linear-api 0.1.0

Unofficial async Rust client for the Linear GraphQL API (API-key auth)
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Projects, project statuses, and project milestones.
//!
//! Access through [`LinearClient::projects`]:
//!
//! ```no_run
//! # async fn example() -> linear_api::Result<()> {
//! let client = linear_api::LinearClient::from_env()?;
//! let page = client
//!     .projects()
//!     .list(linear_api::projects::ListProjectsRequest::builder().build())
//!     .await?;
//! for project in &page.nodes {
//!     println!("{} ({:?})", project.name, project.status.status_type);
//! }
//! # Ok(()) }
//! ```
//!
//! Naming note: Linear has both a mutation `projectUpdate` (updates a
//! `Project`) and an entity type `ProjectUpdate` (a status post). This module
//! implements the former as [`ProjectsService::update`]; status posts are out
//! of scope here.

use bon::Builder;
use serde::{Deserialize, Serialize};

use crate::client::LinearClient;
use crate::error::{Error, Result};
use crate::filter::ProjectFilter;
use crate::ids::{ProjectId, ProjectMilestoneId, ProjectStatusId, TeamId, UserId};
use crate::pagination::{Page, PageInfo};
use crate::types::{
    PaginationOrderBy, Priority, ProjectHealth, ProjectStatusType, TeamRef, TimelessDate,
    Undefinable, UserRef, ensure_success,
};

/// The canonical `Project` selection, together with the Ref fragments it
/// spreads. Appended to every document that returns full projects.
macro_rules! project_fragments {
    () => {
        concat!(
            " fragment ProjectFields on Project { id name slugId url description content",
            " status { id name type } health priority progress startDate targetDate",
            " lead { ...UserRefFields } teams(first: 25) { nodes { ...TeamRefFields } }",
            " createdAt updatedAt completedAt canceledAt archivedAt }",
            " fragment UserRefFields on User { id name displayName }",
            " fragment TeamRefFields on Team { id key name }"
        )
    };
}

/// The canonical `ProjectMilestone` selection.
macro_rules! milestone_fragment {
    () => {
        concat!(
            " fragment MilestoneFields on ProjectMilestone",
            " { id name description targetDate sortOrder }"
        )
    };
}

const PROJECT_LIST: &str = concat!(
    "query ProjectList($filter: ProjectFilter, $first: Int, $after: String,",
    " $includeArchived: Boolean, $orderBy: PaginationOrderBy) {",
    " projects(filter: $filter, first: $first, after: $after,",
    " includeArchived: $includeArchived, orderBy: $orderBy) {",
    " nodes { ...ProjectFields }",
    " pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }",
    project_fragments!()
);

const PROJECT_GET: &str = concat!(
    "query ProjectGet($id: String!) { project(id: $id) { ...ProjectFields } }",
    project_fragments!()
);

const PROJECT_CREATE: &str = concat!(
    "mutation ProjectCreate($input: ProjectCreateInput!) {",
    " projectCreate(input: $input) { success project { ...ProjectFields } } }",
    project_fragments!()
);

const UPDATE_PROJECT: &str = concat!(
    "mutation UpdateProject($id: String!, $input: ProjectUpdateInput!) {",
    " projectUpdate(id: $id, input: $input) { success project { ...ProjectFields } } }",
    project_fragments!()
);

const PROJECT_ARCHIVE: &str =
    "mutation ProjectArchive($id: String!) { projectArchive(id: $id) { success } }";

const PROJECT_STATUSES: &str =
    "query ProjectStatuses { projectStatuses(first: 50) { nodes { id name type } } }";

const PROJECT_MILESTONES: &str = concat!(
    "query ProjectMilestones($id: String!, $first: Int, $after: String) {",
    " project(id: $id) { projectMilestones(first: $first, after: $after) {",
    " nodes { ...MilestoneFields }",
    " pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } } }",
    milestone_fragment!()
);

const PROJECT_MILESTONE_CREATE: &str = concat!(
    "mutation ProjectMilestoneCreate($input: ProjectMilestoneCreateInput!) {",
    " projectMilestoneCreate(input: $input) {",
    " success projectMilestone { ...MilestoneFields } } }",
    milestone_fragment!()
);

const PROJECT_MILESTONE_UPDATE: &str = concat!(
    "mutation ProjectMilestoneUpdate($id: String!, $input: ProjectMilestoneUpdateInput!) {",
    " projectMilestoneUpdate(id: $id, input: $input) {",
    " success projectMilestone { ...MilestoneFields } } }",
    milestone_fragment!()
);

const PROJECT_MILESTONE_DELETE: &str = concat!(
    "mutation ProjectMilestoneDelete($id: String!) {",
    " projectMilestoneDelete(id: $id) { success } }"
);

pub(crate) const DOCUMENTS: &[(&str, &str)] = &[
    ("ProjectList", PROJECT_LIST),
    ("ProjectGet", PROJECT_GET),
    ("ProjectCreate", PROJECT_CREATE),
    ("UpdateProject", UPDATE_PROJECT),
    ("ProjectArchive", PROJECT_ARCHIVE),
    ("ProjectStatuses", PROJECT_STATUSES),
    ("ProjectMilestones", PROJECT_MILESTONES),
    ("ProjectMilestoneCreate", PROJECT_MILESTONE_CREATE),
    ("ProjectMilestoneUpdate", PROJECT_MILESTONE_UPDATE),
    ("ProjectMilestoneDelete", PROJECT_MILESTONE_DELETE),
];

/// A Linear project.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Project {
    /// Project ID.
    pub id: ProjectId,
    /// Project name.
    pub name: String,
    /// URL slug identifier, e.g. `"sdk-v1-8f2a1c0d3b4e"`.
    pub slug_id: String,
    /// Canonical URL of the project in the Linear app.
    pub url: String,
    /// Short description (empty string when unset).
    pub description: String,
    /// Long-form markdown content, when set.
    pub content: Option<String>,
    /// Current project status.
    pub status: ProjectStatus,
    /// Health as of the latest project update, when reported.
    pub health: Option<ProjectHealth>,
    /// Project priority.
    pub priority: Priority,
    /// Completion progress in `0.0..=1.0`.
    pub progress: f64,
    /// Planned start date.
    pub start_date: Option<TimelessDate>,
    /// Planned target date.
    pub target_date: Option<TimelessDate>,
    /// Project lead, when assigned.
    pub lead: Option<UserRef>,
    /// Teams the project belongs to (first 25).
    #[serde(deserialize_with = "crate::types::nodes")]
    pub teams: Vec<TeamRef>,
    /// When the project was created.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    /// When the project was last updated.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// When the project was completed, if it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub completed_at: Option<time::OffsetDateTime>,
    /// When the project was canceled, if it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub canceled_at: Option<time::OffsetDateTime>,
    /// When the project was archived, if it was.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub archived_at: Option<time::OffsetDateTime>,
}

/// A workspace-level project status (the column a project sits in).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectStatus {
    /// Project status ID.
    pub id: ProjectStatusId,
    /// Status name, e.g. `"In Progress"`.
    pub name: String,
    /// Status category.
    #[serde(rename = "type")]
    pub status_type: ProjectStatusType,
}

/// A milestone within a project.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectMilestone {
    /// Milestone ID.
    pub id: ProjectMilestoneId,
    /// Milestone name.
    pub name: String,
    /// Milestone description, when set.
    pub description: Option<String>,
    /// Target date, when set.
    pub target_date: Option<TimelessDate>,
    /// Sort order within the project.
    pub sort_order: f64,
}

/// Request parameters for [`ProjectsService::list`] /
/// [`ProjectsService::list_stream`]. Serialized directly as the operation's
/// GraphQL variables.
///
/// ```
/// use linear_api::ProjectFilter;
/// use linear_api::projects::ListProjectsRequest;
///
/// let request = ListProjectsRequest::builder()
///     .filter(ProjectFilter::builder().build())
///     .first(25)
///     .build();
/// assert_eq!(request.first, Some(25));
/// ```
#[derive(Debug, Clone, Default, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ListProjectsRequest {
    /// Filter to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<ProjectFilter>,
    /// Page size (server default 50).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first: Option<i32>,
    /// Cursor to resume after (from
    /// [`PageInfo::end_cursor`](crate::PageInfo)).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub after: Option<String>,
    /// Whether to include archived projects (server default `false`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_archived: Option<bool>,
    /// Pagination sort order (server default `createdAt`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_by: Option<PaginationOrderBy>,
}

/// Input for [`ProjectsService::create`].
///
/// ```
/// use linear_api::TeamId;
/// use linear_api::projects::ProjectCreateInput;
///
/// let input = ProjectCreateInput::builder()
///     .name("SDK v1".to_owned())
///     .team_ids(vec![TeamId::new("team-1")])
///     .target_date("2026-09-01".parse().unwrap())
///     .build();
/// assert_eq!(input.name, "SDK v1");
/// ```
#[derive(Debug, Clone, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectCreateInput {
    /// Project name (required).
    pub name: String,
    /// Teams the project belongs to (required).
    pub team_ids: Vec<TeamId>,
    /// Short description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Long-form markdown content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Initial project status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_id: Option<ProjectStatusId>,
    /// Project lead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lead_id: Option<UserId>,
    /// Project members.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub member_ids: Option<Vec<UserId>>,
    /// Project priority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<Priority>,
    /// Planned start date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_date: Option<TimelessDate>,
    /// Planned target date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_date: Option<TimelessDate>,
    /// Icon color as a hex string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// Icon name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
}

/// Input for [`ProjectsService::update`]. All fields are optional; the
/// [`Undefinable`] fields distinguish *leave unchanged* (default) from
/// *clear* ([`Undefinable::Null`]) from *set*.
///
/// ```
/// use linear_api::Undefinable;
/// use linear_api::projects::ProjectUpdateInput;
///
/// let input = ProjectUpdateInput::builder()
///     .name("SDK v1 (renamed)".to_owned())
///     .lead_id(Undefinable::Null) // clear the lead
///     .build();
/// assert_eq!(input.lead_id, Undefinable::Null);
/// ```
#[derive(Debug, Clone, Default, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectUpdateInput {
    /// New project name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New short description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// New project status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_id: Option<ProjectStatusId>,
    /// New project priority.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<Priority>,
    /// New set of teams.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub team_ids: Option<Vec<TeamId>>,
    /// Long-form markdown content.
    ///
    /// Live-verified server quirk: Linear **ignores both `null` and the
    /// empty string** for this document-backed field — neither
    /// [`Undefinable::Null`] nor `""` clears it; only non-empty values
    /// update it.
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub content: Undefinable<String>,
    /// Project lead (clearable).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub lead_id: Undefinable<UserId>,
    /// Planned start date (clearable).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub start_date: Undefinable<TimelessDate>,
    /// Planned target date (clearable).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub target_date: Undefinable<TimelessDate>,
}

/// Input for [`ProjectsService::create_milestone`].
///
/// ```
/// use linear_api::ProjectId;
/// use linear_api::projects::ProjectMilestoneCreateInput;
///
/// let input = ProjectMilestoneCreateInput::builder()
///     .project_id(ProjectId::new("proj-1"))
///     .name("M1".to_owned())
///     .build();
/// assert_eq!(input.name, "M1");
/// ```
#[derive(Debug, Clone, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectMilestoneCreateInput {
    /// Project the milestone belongs to (required).
    pub project_id: ProjectId,
    /// Milestone name (required).
    pub name: String,
    /// Milestone description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Target date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_date: Option<TimelessDate>,
    /// Sort order within the project.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_order: Option<f64>,
}

/// Input for [`ProjectsService::update_milestone`].
///
/// ```
/// use linear_api::Undefinable;
/// use linear_api::projects::ProjectMilestoneUpdateInput;
///
/// let input = ProjectMilestoneUpdateInput::builder()
///     .target_date(Undefinable::Null) // clear the target date
///     .build();
/// assert_eq!(input.target_date, Undefinable::Null);
/// ```
#[derive(Debug, Clone, Default, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectMilestoneUpdateInput {
    /// New milestone name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New sort order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_order: Option<f64>,
    /// Milestone description.
    ///
    /// Live-verified server quirk: Linear **ignores both `null` and the
    /// empty string** for this document-backed field — neither
    /// [`Undefinable::Null`] nor `""` clears it; only non-empty values
    /// update it.
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub description: Undefinable<String>,
    /// Target date (clearable).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub target_date: Undefinable<TimelessDate>,
}

/// A GraphQL connection as returned on the wire; converted to [`Page`].
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Connection<T> {
    nodes: Vec<T>,
    page_info: PageInfo,
}

impl<T> From<Connection<T>> for Page<T> {
    fn from(connection: Connection<T>) -> Self {
        Page {
            nodes: connection.nodes,
            page_info: connection.page_info,
        }
    }
}

/// Service for projects, project statuses, and project milestones. Obtain
/// via [`LinearClient::projects`].
#[derive(Clone, Copy)]
pub struct ProjectsService<'a> {
    client: &'a LinearClient,
}

impl LinearClient {
    /// Projects, project statuses, and project milestones.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let statuses = client.projects().statuses().await?;
    /// # Ok(()) }
    /// ```
    pub fn projects(&self) -> ProjectsService<'_> {
        ProjectsService { client: self }
    }
}

impl<'a> ProjectsService<'a> {
    /// Fetches one page of projects.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use linear_api::projects::ListProjectsRequest;
    ///
    /// let page = client
    ///     .projects()
    ///     .list(ListProjectsRequest::builder().first(50).build())
    ///     .await?;
    /// println!("{} projects, more: {}", page.nodes.len(), page.page_info.has_next_page);
    /// # Ok(()) }
    /// ```
    pub async fn list(&self, request: ListProjectsRequest) -> Result<Page<Project>> {
        #[derive(Deserialize)]
        struct Data {
            projects: Connection<Project>,
        }
        let data: Data = self
            .client
            .query("ProjectList", PROJECT_LIST, request)
            .await?;
        Ok(data.projects.into())
    }

    /// Lazily streams every project matching `request` across pages,
    /// starting from `request.after` when set (the cursor then advances page
    /// by page). See [`crate::paginate`] for the complexity trade-offs.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use futures::TryStreamExt;
    /// use linear_api::projects::ListProjectsRequest;
    ///
    /// let projects: Vec<_> = client
    ///     .projects()
    ///     .list_stream(ListProjectsRequest::builder().first(50).build())
    ///     .try_collect()
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub fn list_stream(
        &self,
        request: ListProjectsRequest,
    ) -> impl futures::Stream<Item = Result<Project>> + 'a {
        let service = *self;
        crate::pagination::paginate(move |after| {
            let mut request = request.clone();
            // The first call keeps a caller-seeded `request.after`; later
            // calls advance to each page's end cursor.
            if after.is_some() {
                request.after = after;
            }
            async move { service.list(request).await }
        })
    }

    /// Fetches a single project by ID. Linear also resolves slug IDs (the
    /// identifier from the project URL) passed as a [`ProjectId`].
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// let id = linear_api::ProjectId::new("sdk-v1-8f2a1c0d3b4e");
    /// let project = client.projects().get(&id).await?;
    /// println!("{} — {:.0}% done", project.name, project.progress * 100.0);
    /// # Ok(()) }
    /// ```
    pub async fn get(&self, id: &ProjectId) -> Result<Project> {
        #[derive(Deserialize)]
        struct Data {
            project: Project,
        }
        let data: Data = self
            .client
            .query(
                "ProjectGet",
                PROJECT_GET,
                serde_json::json!({ "id": id.as_str() }),
            )
            .await?;
        Ok(data.project)
    }

    /// Creates a project.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use linear_api::TeamId;
    /// use linear_api::projects::ProjectCreateInput;
    ///
    /// let project = client
    ///     .projects()
    ///     .create(
    ///         ProjectCreateInput::builder()
    ///             .name("SDK v1".to_owned())
    ///             .team_ids(vec![TeamId::new("team-1")])
    ///             .build(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn create(&self, input: ProjectCreateInput) -> Result<Project> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
            project: Option<Project>,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectCreate")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "ProjectCreate",
                PROJECT_CREATE,
                serde_json::json!({ "input": input }),
            )
            .await?;
        ensure_success("ProjectCreate", data.payload.success)?;
        data.payload.project.ok_or(Error::MissingData {
            operation: "ProjectCreate",
        })
    }

    /// Updates a project (Linear's `projectUpdate` **mutation**, not the
    /// `ProjectUpdate` status-post entity). [`Undefinable`] fields on the
    /// input distinguish leave-unchanged from clear from set.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use linear_api::Undefinable;
    /// use linear_api::projects::ProjectUpdateInput;
    ///
    /// let id = linear_api::ProjectId::new("proj-1");
    /// let project = client
    ///     .projects()
    ///     .update(
    ///         &id,
    ///         ProjectUpdateInput::builder()
    ///             .target_date("2026-10-01".parse::<linear_api::TimelessDate>().unwrap())
    ///             .lead_id(Undefinable::Null) // clear the lead
    ///             .build(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn update(&self, id: &ProjectId, input: ProjectUpdateInput) -> Result<Project> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
            project: Option<Project>,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectUpdate")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "UpdateProject",
                UPDATE_PROJECT,
                serde_json::json!({ "id": id.as_str(), "input": input }),
            )
            .await?;
        ensure_success("UpdateProject", data.payload.success)?;
        data.payload.project.ok_or(Error::MissingData {
            operation: "UpdateProject",
        })
    }

    /// Archives a project.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// let id = linear_api::ProjectId::new("proj-1");
    /// client.projects().archive(&id).await?;
    /// # Ok(()) }
    /// ```
    pub async fn archive(&self, id: &ProjectId) -> Result<()> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectArchive")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "ProjectArchive",
                PROJECT_ARCHIVE,
                serde_json::json!({ "id": id.as_str() }),
            )
            .await?;
        ensure_success("ProjectArchive", data.payload.success)
    }

    /// Fetches the workspace's project statuses (a single page of up to 50 —
    /// workspaces define a handful).
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// for status in client.projects().statuses().await? {
    ///     println!("{} ({:?})", status.name, status.status_type);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn statuses(&self) -> Result<Vec<ProjectStatus>> {
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectStatuses", deserialize_with = "crate::types::nodes")]
            statuses: Vec<ProjectStatus>,
        }
        let data: Data = self
            .client
            .query("ProjectStatuses", PROJECT_STATUSES, serde_json::json!({}))
            .await?;
        Ok(data.statuses)
    }

    /// Fetches every milestone of a project, draining pagination internally
    /// (pages of 50, capped at 250 milestones).
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// let id = linear_api::ProjectId::new("proj-1");
    /// for milestone in client.projects().milestones(&id).await? {
    ///     println!("{} (order {})", milestone.name, milestone.sort_order);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn milestones(&self, id: &ProjectId) -> Result<Vec<ProjectMilestone>> {
        #[derive(Deserialize)]
        struct ProjectNode {
            #[serde(rename = "projectMilestones")]
            milestones: Connection<ProjectMilestone>,
        }
        #[derive(Deserialize)]
        struct Data {
            project: ProjectNode,
        }
        let service = *self;
        let id = id.clone();
        crate::pagination::collect_all(
            move |after| {
                let id = id.clone();
                async move {
                    let data: Data = service
                        .client
                        .query(
                            "ProjectMilestones",
                            PROJECT_MILESTONES,
                            serde_json::json!({ "id": id.as_str(), "first": 50, "after": after }),
                        )
                        .await?;
                    Ok(data.project.milestones.into())
                }
            },
            Some(250),
        )
        .await
    }

    /// Creates a milestone within a project.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use linear_api::projects::ProjectMilestoneCreateInput;
    ///
    /// let milestone = client
    ///     .projects()
    ///     .create_milestone(
    ///         ProjectMilestoneCreateInput::builder()
    ///             .project_id(linear_api::ProjectId::new("proj-1"))
    ///             .name("M1 — Read path".to_owned())
    ///             .build(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn create_milestone(
        &self,
        input: ProjectMilestoneCreateInput,
    ) -> Result<ProjectMilestone> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
            #[serde(rename = "projectMilestone")]
            milestone: Option<ProjectMilestone>,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectMilestoneCreate")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "ProjectMilestoneCreate",
                PROJECT_MILESTONE_CREATE,
                serde_json::json!({ "input": input }),
            )
            .await?;
        ensure_success("ProjectMilestoneCreate", data.payload.success)?;
        data.payload.milestone.ok_or(Error::MissingData {
            operation: "ProjectMilestoneCreate",
        })
    }

    /// Updates a milestone.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// use linear_api::Undefinable;
    /// use linear_api::projects::ProjectMilestoneUpdateInput;
    ///
    /// let id = linear_api::ProjectMilestoneId::new("ms-1");
    /// let milestone = client
    ///     .projects()
    ///     .update_milestone(
    ///         &id,
    ///         ProjectMilestoneUpdateInput::builder()
    ///             .name("M1 — Read path (done)".to_owned())
    ///             .target_date(Undefinable::Null) // clear the target date
    ///             .build(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn update_milestone(
        &self,
        id: &ProjectMilestoneId,
        input: ProjectMilestoneUpdateInput,
    ) -> Result<ProjectMilestone> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
            #[serde(rename = "projectMilestone")]
            milestone: Option<ProjectMilestone>,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectMilestoneUpdate")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "ProjectMilestoneUpdate",
                PROJECT_MILESTONE_UPDATE,
                serde_json::json!({ "id": id.as_str(), "input": input }),
            )
            .await?;
        ensure_success("ProjectMilestoneUpdate", data.payload.success)?;
        data.payload.milestone.ok_or(Error::MissingData {
            operation: "ProjectMilestoneUpdate",
        })
    }

    /// Deletes a milestone.
    ///
    /// ```no_run
    /// # async fn example() -> linear_api::Result<()> {
    /// # let client = linear_api::LinearClient::from_env()?;
    /// let id = linear_api::ProjectMilestoneId::new("ms-1");
    /// client.projects().delete_milestone(&id).await?;
    /// # Ok(()) }
    /// ```
    pub async fn delete_milestone(&self, id: &ProjectMilestoneId) -> Result<()> {
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
        }
        #[derive(Deserialize)]
        struct Data {
            #[serde(rename = "projectMilestoneDelete")]
            payload: Payload,
        }
        let data: Data = self
            .client
            .mutation(
                "ProjectMilestoneDelete",
                PROJECT_MILESTONE_DELETE,
                serde_json::json!({ "id": id.as_str() }),
            )
            .await?;
        ensure_success("ProjectMilestoneDelete", data.payload.success)
    }
}