@cvr/linear 0.3.0 → 0.4.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.
@@ -1,415 +1,306 @@
1
- import { Context, Effect, Layer } from "effect";
2
1
  import { LinearClient } from "@linear/sdk";
3
- import type { Issue, Project, Team, User } from "@linear/sdk";
4
- import { LinearApiError, InvalidTokenError, TokenNotFoundError } from "../lib/errors.js";
2
+ import type { Issue, IssueRelation as SdkIssueRelation, User } from "@linear/sdk";
3
+ import { Context, Effect, Layer, Redacted } from "effect";
4
+ import type {
5
+ CreateIssueInput,
6
+ CreatedIssue,
7
+ IssueDetails,
8
+ IssueDetailsOptions,
9
+ IssueReference,
10
+ IssueSelector,
11
+ IssueSummary,
12
+ Project,
13
+ StartedIssue,
14
+ Team,
15
+ Viewer,
16
+ } from "../domain/Linear.js";
17
+ import type { ConfigError, TokenNotFoundError } from "../lib/errors.js";
18
+ import { InvalidInputError, InvalidTokenError, LinearApiError } from "../lib/errors.js";
5
19
  import { ConfigService } from "./Config.js";
6
20
 
7
- export interface IssueFilter {
8
- readonly teamId?: string;
9
- readonly state?: "triage" | "backlog" | "unstarted" | "started" | "completed" | "canceled";
10
- readonly assigneeId?: string;
11
- readonly limit?: number;
12
- }
13
-
14
- export interface IssueDetailsOptions {
15
- readonly comments: boolean;
16
- readonly children: boolean;
17
- readonly relations: boolean;
18
- }
19
-
20
- export interface IssueReference {
21
- readonly id: string;
22
- readonly identifier: string;
23
- readonly title: string;
24
- readonly url: string;
25
- }
21
+ type LinearError = ConfigError | InvalidTokenError | LinearApiError | TokenNotFoundError;
26
22
 
27
- export interface IssueDetails extends IssueReference {
28
- readonly description?: string;
29
- readonly branchName: string;
30
- readonly priority: {
31
- readonly value: number;
32
- readonly label: string;
33
- };
34
- readonly state?: {
35
- readonly id: string;
36
- readonly name: string;
37
- readonly type: string;
38
- };
39
- readonly team?: {
40
- readonly id: string;
41
- readonly key: string;
42
- readonly name: string;
43
- };
44
- readonly assignee?: {
45
- readonly id: string;
46
- readonly name: string;
47
- readonly email: string;
48
- };
49
- readonly project?: {
50
- readonly id: string;
51
- readonly name: string;
52
- readonly url: string;
53
- };
54
- readonly parent?: IssueReference;
55
- readonly labels: ReadonlyArray<{ readonly id: string; readonly name: string }>;
56
- readonly children?: ReadonlyArray<IssueReference>;
57
- readonly comments?: ReadonlyArray<{
58
- readonly id: string;
59
- readonly body: string;
60
- readonly createdAt: string;
61
- readonly url: string;
62
- readonly author?: { readonly id: string; readonly name: string };
63
- }>;
64
- readonly relations?: ReadonlyArray<{
65
- readonly id: string;
66
- readonly type: string;
67
- readonly direction: "outbound" | "inbound";
68
- readonly issue: IssueReference;
69
- }>;
23
+ interface LinearOperations {
24
+ readonly authenticate: (token: Redacted.Redacted<string>) => Effect.Effect<Viewer, LinearError>;
25
+ readonly getViewer: Effect.Effect<Viewer, LinearError>;
26
+ readonly getTeams: Effect.Effect<readonly Team[], LinearError>;
27
+ readonly getProjects: Effect.Effect<readonly Project[], LinearError>;
28
+ readonly getMyIssues: (filter?: {
29
+ readonly state?: string;
30
+ readonly limit?: number;
31
+ }) => Effect.Effect<readonly IssueSummary[], LinearError>;
32
+ readonly getIssueDetails: (
33
+ id: IssueSelector,
34
+ options: IssueDetailsOptions,
35
+ ) => Effect.Effect<IssueDetails, LinearError>;
36
+ readonly startIssue: (
37
+ id: IssueSelector,
38
+ options: { readonly dryRun: boolean },
39
+ ) => Effect.Effect<StartedIssue, LinearError | InvalidInputError>;
40
+ readonly createIssue: (input: CreateIssueInput) => Effect.Effect<CreatedIssue, LinearError>;
41
+ readonly createComment: (
42
+ issueId: IssueSelector,
43
+ body: string,
44
+ ) => Effect.Effect<{ readonly id: string; readonly url: string }, LinearError>;
45
+ readonly rawQuery: (
46
+ query: string,
47
+ variables: Readonly<Record<string, unknown>>,
48
+ ) => Effect.Effect<unknown, LinearError>;
70
49
  }
71
50
 
72
- export class LinearService extends Context.Service<
73
- LinearService,
74
- {
75
- readonly getViewer: Effect.Effect<
76
- User,
77
- LinearApiError | InvalidTokenError | TokenNotFoundError
78
- >;
79
- readonly getTeams: Effect.Effect<readonly Team[], LinearApiError | TokenNotFoundError>;
80
- readonly getProjects: Effect.Effect<readonly Project[], LinearApiError | TokenNotFoundError>;
81
- readonly getIssues: (
82
- filter: IssueFilter,
83
- ) => Effect.Effect<readonly Issue[], LinearApiError | TokenNotFoundError>;
84
- readonly getIssue: (id: string) => Effect.Effect<Issue, LinearApiError | TokenNotFoundError>;
85
- readonly getIssueDetails: (
86
- id: string,
87
- options: IssueDetailsOptions,
88
- ) => Effect.Effect<IssueDetails, LinearApiError | TokenNotFoundError>;
89
- readonly getMyIssues: (filter?: {
90
- state?: string;
91
- }) => Effect.Effect<readonly Issue[], LinearApiError | TokenNotFoundError>;
92
- readonly updateIssueState: (
93
- issueId: string,
94
- stateId: string,
95
- ) => Effect.Effect<void, LinearApiError | TokenNotFoundError>;
96
- readonly createIssue: (input: {
97
- title: string;
98
- teamId: string;
99
- description?: string;
100
- parentId?: string;
101
- projectId?: string;
102
- priority?: number;
103
- }) => Effect.Effect<Issue, LinearApiError | TokenNotFoundError>;
104
- readonly createComment: (
105
- issueId: string,
106
- body: string,
107
- ) => Effect.Effect<
108
- { readonly id: string; readonly url: string },
109
- LinearApiError | TokenNotFoundError
110
- >;
111
- readonly rawQuery: (
112
- query: string,
113
- variables: Readonly<Record<string, unknown>>,
114
- ) => Effect.Effect<unknown, LinearApiError | TokenNotFoundError>;
115
- }
116
- >()("@cvr/linear/services/Linear/LinearService") {
51
+ export class LinearService extends Context.Service<LinearService, LinearOperations>()(
52
+ "@cvr/linear/services/Linear/LinearService",
53
+ ) {
117
54
  static readonly layer = Layer.effect(
118
55
  LinearService,
119
56
  Effect.gen(function* () {
120
- const configService = yield* ConfigService;
121
-
122
- // Lazy client creation - token is loaded when first API call is made
123
- const getClient = configService.getToken.pipe(
124
- Effect.catchTag("ConfigError", (e) => TokenNotFoundError.make({ message: e.message })),
125
- Effect.map((token) => new LinearClient({ apiKey: token })),
126
- Effect.cached,
127
- Effect.runSync,
57
+ const config = yield* ConfigService;
58
+ const getClient = yield* Effect.cached(
59
+ config.getToken.pipe(
60
+ Effect.map((token) => new LinearClient({ apiKey: Redacted.value(token) })),
61
+ ),
128
62
  );
129
63
 
130
- const getViewer = Effect.gen(function* () {
131
- const client = yield* getClient;
132
- return yield* Effect.tryPromise({
64
+ const withClient = <A>(
65
+ operation: (client: LinearClient) => PromiseLike<A>,
66
+ ): Effect.Effect<A, LinearError> =>
67
+ getClient.pipe(
68
+ Effect.flatMap((client) =>
69
+ Effect.tryPromise({
70
+ try: () => Promise.resolve(operation(client)),
71
+ catch: toLinearError,
72
+ }),
73
+ ),
74
+ );
75
+
76
+ const authenticate = Effect.fn("LinearService.authenticate")(function* (
77
+ token: Redacted.Redacted<string>,
78
+ ) {
79
+ const client = new LinearClient({ apiKey: Redacted.value(token) });
80
+ const viewer = yield* Effect.tryPromise({
133
81
  try: () => client.viewer,
134
- catch: (e) => {
135
- const msg = String(e);
136
- if (msg.includes("Authentication") || msg.includes("401")) {
137
- return InvalidTokenError.make({ message: "Invalid API token" });
138
- }
139
- return LinearApiError.make({ message: msg });
140
- },
82
+ catch: toLinearError,
141
83
  });
142
- }).pipe(Effect.withSpan("LinearService.getViewer"));
84
+ yield* config.saveToken(token);
85
+ return toViewer(viewer);
86
+ });
143
87
 
144
- const getTeams = Effect.gen(function* () {
145
- const client = yield* getClient;
146
- const connection = yield* Effect.tryPromise({
147
- try: () => client.teams(),
148
- catch: (e) => LinearApiError.make({ message: String(e) }),
149
- });
150
- return connection.nodes;
151
- }).pipe(Effect.withSpan("LinearService.getTeams"));
152
-
153
- const getProjects = Effect.gen(function* () {
154
- const client = yield* getClient;
155
- const connection = yield* Effect.tryPromise({
156
- try: () => client.projects(),
157
- catch: (error) => LinearApiError.make({ message: String(error) }),
158
- });
159
- return connection.nodes;
160
- }).pipe(Effect.withSpan("LinearService.getProjects"));
161
-
162
- const getIssues = Effect.fn("LinearService.getIssues")((filter: IssueFilter) =>
163
- Effect.gen(function* () {
164
- const client = yield* getClient;
165
- const connection = yield* Effect.tryPromise({
166
- try: () =>
167
- client.issues({
168
- first: filter.limit ?? 50,
169
- filter: {
170
- team: filter.teamId !== undefined ? { id: { eq: filter.teamId } } : undefined,
171
- state: filter.state !== undefined ? { type: { eq: filter.state } } : undefined,
172
- assignee:
173
- filter.assigneeId !== undefined ? { id: { eq: filter.assigneeId } } : undefined,
174
- },
175
- }),
176
- catch: (e) => LinearApiError.make({ message: String(e) }),
177
- });
178
- return connection.nodes;
179
- }),
88
+ const getViewer = withClient((client) => client.viewer).pipe(
89
+ Effect.map(toViewer),
90
+ Effect.withSpan("LinearService.getViewer"),
180
91
  );
181
92
 
182
- const getMyIssues = Effect.fn("LinearService.getMyIssues")((filter?: { state?: string }) =>
183
- Effect.gen(function* () {
184
- const client = yield* getClient;
185
- const viewer = yield* Effect.tryPromise({
186
- try: () => client.viewer,
187
- catch: (e) => LinearApiError.make({ message: String(e) }),
188
- });
189
- const connection = yield* Effect.tryPromise({
190
- try: () =>
191
- viewer.assignedIssues({
192
- first: 50,
193
- filter:
194
- filter?.state !== undefined
195
- ? { state: { type: { eq: filter.state } } }
196
- : undefined,
197
- }),
198
- catch: (e) => LinearApiError.make({ message: String(e) }),
199
- });
200
- return connection.nodes;
201
- }),
93
+ const getTeams = withClient((client) => client.teams()).pipe(
94
+ Effect.flatMap(loadAllPages),
95
+ Effect.map((teams) => teams.map(toTeam)),
96
+ Effect.withSpan("LinearService.getTeams"),
202
97
  );
203
98
 
204
- const getIssue = Effect.fn("LinearService.getIssue")((id: string) =>
205
- Effect.gen(function* () {
206
- const client = yield* getClient;
207
- return yield* Effect.tryPromise({
208
- try: () => client.issue(id),
209
- catch: (e) => LinearApiError.make({ message: String(e) }),
210
- });
211
- }),
99
+ const getProjects = withClient((client) => client.projects()).pipe(
100
+ Effect.flatMap(loadAllPages),
101
+ Effect.map((projects) => projects.map(toProject)),
102
+ Effect.withSpan("LinearService.getProjects"),
212
103
  );
213
104
 
214
- const getIssueDetails = Effect.fn("LinearService.getIssueDetails")(
215
- (id: string, options: IssueDetailsOptions) =>
216
- Effect.gen(function* () {
217
- const issue = yield* getIssue(normalizeIssueId(id));
218
- const [state, team, assignee, project, parent, labels] = yield* Effect.all([
219
- resolveLinearFetch(issue.state),
220
- resolveLinearFetch(issue.team),
221
- resolveLinearFetch(issue.assignee),
222
- resolveLinearFetch(issue.project),
223
- resolveLinearFetch(issue.parent),
224
- loadConnection(() => issue.labels()),
225
- ]);
226
-
227
- const children = options.children
228
- ? yield* loadConnection(() => issue.children())
229
- : undefined;
230
- const comments = options.comments
231
- ? yield* loadConnection(() => issue.comments())
232
- : undefined;
233
- const outboundRelations = options.relations
234
- ? yield* loadConnection(() => issue.relations())
235
- : undefined;
236
- const inboundRelations = options.relations
237
- ? yield* loadConnection(() => issue.inverseRelations())
238
- : undefined;
239
-
240
- const detailedComments =
241
- comments === undefined
242
- ? undefined
243
- : yield* Effect.forEach(
244
- comments,
245
- (comment) =>
246
- resolveLinearFetch(comment.user).pipe(
247
- Effect.map((author) => ({
248
- id: comment.id,
249
- body: comment.body,
250
- createdAt: comment.createdAt.toISOString(),
251
- url: comment.url,
252
- author:
253
- author === undefined ? undefined : { id: author.id, name: author.name },
254
- })),
255
- ),
256
- { concurrency: 4 },
257
- );
105
+ const getMyIssues = Effect.fn("LinearService.getMyIssues")(function* (filter?: {
106
+ readonly state?: string;
107
+ readonly limit?: number;
108
+ }) {
109
+ const viewer = yield* withClient((client) => client.viewer);
110
+ const connection = yield* resolveLinearFetch(
111
+ viewer.assignedIssues({
112
+ first: filter?.limit ?? 50,
113
+ filter:
114
+ filter?.state === undefined ? undefined : { state: { type: { eq: filter.state } } },
115
+ }),
116
+ );
117
+ return yield* Effect.forEach(connection.nodes, toIssueSummary, { concurrency: 4 });
118
+ });
258
119
 
259
- const relations =
260
- outboundRelations === undefined || inboundRelations === undefined
261
- ? undefined
262
- : yield* Effect.forEach(
263
- outboundRelations
264
- .map(
265
- (
266
- relation,
267
- ): {
268
- readonly relation: typeof relation;
269
- readonly direction: "outbound" | "inbound";
270
- } => ({ relation, direction: "outbound" }),
271
- )
272
- .concat(
273
- inboundRelations.map((relation) => ({
274
- relation,
275
- direction: "inbound" as const,
276
- })),
277
- ),
278
- ({ direction, relation }) =>
279
- resolveLinearFetch(
280
- direction === "outbound" ? relation.relatedIssue : relation.issue,
281
- ).pipe(
282
- Effect.flatMap((relatedIssue) =>
283
- relatedIssue === undefined
284
- ? Effect.succeed(undefined)
285
- : Effect.succeed({
286
- id: relation.id,
287
- type: relation.type,
288
- direction,
289
- issue: toIssueReference(relatedIssue),
290
- }),
291
- ),
292
- ),
293
- { concurrency: 4 },
294
- ).pipe(
295
- Effect.map((items) =>
296
- items.filter((item): item is NonNullable<typeof item> => item !== undefined),
297
- ),
298
- );
120
+ const getIssue = (id: IssueSelector) => withClient((client) => client.issue(id));
299
121
 
300
- return {
301
- id: issue.id,
302
- identifier: issue.identifier,
303
- title: issue.title,
304
- url: issue.url,
305
- description: issue.description ?? undefined,
306
- branchName: issue.branchName,
307
- priority: { value: issue.priority, label: issue.priorityLabel },
308
- state:
309
- state === undefined
310
- ? undefined
311
- : { id: state.id, name: state.name, type: state.type },
312
- team:
313
- team === undefined ? undefined : { id: team.id, key: team.key, name: team.name },
314
- assignee:
315
- assignee === undefined
316
- ? undefined
317
- : { id: assignee.id, name: assignee.name, email: assignee.email },
318
- project:
319
- project === undefined
320
- ? undefined
321
- : { id: project.id, name: project.name, url: project.url },
322
- parent: parent === undefined ? undefined : toIssueReference(parent),
323
- labels: labels.map((label) => ({ id: label.id, name: label.name })),
324
- children: children?.map(toIssueReference),
325
- comments: detailedComments,
326
- relations,
327
- } satisfies IssueDetails;
328
- }),
329
- );
122
+ const getIssueDetails = Effect.fn("LinearService.getIssueDetails")(function* (
123
+ id: IssueSelector,
124
+ options: IssueDetailsOptions,
125
+ ) {
126
+ const issue = yield* getIssue(id);
127
+ const [summary, team, assignee, project, parent, labels] = yield* Effect.all([
128
+ toIssueSummary(issue),
129
+ resolveOptionalFetch(issue.team),
130
+ resolveOptionalFetch(issue.assignee),
131
+ resolveOptionalFetch(issue.project),
132
+ resolveOptionalFetch(issue.parent),
133
+ loadConnection(() => issue.labels()),
134
+ ]);
330
135
 
331
- const updateIssueState = Effect.fn("LinearService.updateIssueState")(
332
- (issueId: string, stateId: string) =>
333
- Effect.gen(function* () {
334
- const client = yield* getClient;
335
- yield* Effect.tryPromise({
336
- try: () => client.updateIssue(issueId, { stateId }),
337
- catch: (e) => LinearApiError.make({ message: String(e) }),
338
- });
339
- }),
340
- );
136
+ const children = options.children
137
+ ? yield* loadConnection(() => issue.children())
138
+ : undefined;
139
+ const comments = options.comments
140
+ ? yield* loadConnection(() => issue.comments())
141
+ : undefined;
142
+ const outbound = options.relations
143
+ ? yield* loadConnection(() => issue.relations())
144
+ : undefined;
145
+ const inbound = options.relations
146
+ ? yield* loadConnection(() => issue.inverseRelations())
147
+ : undefined;
148
+
149
+ const detailedComments =
150
+ comments === undefined
151
+ ? undefined
152
+ : yield* Effect.forEach(
153
+ comments,
154
+ (comment) =>
155
+ resolveOptionalFetch(comment.user).pipe(
156
+ Effect.map((author) => ({
157
+ id: comment.id,
158
+ body: comment.body,
159
+ createdAt: comment.createdAt.toISOString(),
160
+ url: comment.url,
161
+ author:
162
+ author === undefined ? undefined : { id: author.id, name: author.name },
163
+ })),
164
+ ),
165
+ { concurrency: 4 },
166
+ );
341
167
 
342
- const createIssue = Effect.fn("LinearService.createIssue")(
343
- (input: {
344
- title: string;
345
- teamId: string;
346
- description?: string;
347
- parentId?: string;
348
- projectId?: string;
349
- priority?: number;
350
- }) =>
351
- Effect.gen(function* () {
352
- const client = yield* getClient;
353
- const payload = yield* Effect.tryPromise({
354
- try: () =>
355
- client.createIssue({
356
- title: input.title,
357
- teamId: input.teamId,
358
- description: input.description,
359
- parentId: input.parentId,
360
- projectId: input.projectId,
361
- priority: input.priority,
168
+ const relations =
169
+ outbound === undefined || inbound === undefined
170
+ ? undefined
171
+ : yield* Effect.forEach(
172
+ outbound
173
+ .map<{
174
+ readonly relation: SdkIssueRelation;
175
+ readonly direction: "outbound" | "inbound";
176
+ }>((relation) => ({ relation, direction: "outbound" }))
177
+ .concat(inbound.map((relation) => ({ relation, direction: "inbound" }))),
178
+ Effect.fn("LinearService.resolveRelation")(function* ({ direction, relation }) {
179
+ const related = yield* resolveOptionalFetch(
180
+ direction === "outbound" ? relation.relatedIssue : relation.issue,
181
+ );
182
+ return related === undefined
183
+ ? undefined
184
+ : {
185
+ id: relation.id,
186
+ type: relation.type,
187
+ direction,
188
+ issue: toIssueReference(related),
189
+ };
362
190
  }),
363
- catch: (e) => LinearApiError.make({ message: String(e) }),
364
- });
365
- const issueFetch = payload.issue;
366
- if (issueFetch === undefined) {
367
- return yield* LinearApiError.make({ message: "Failed to create issue" });
368
- }
369
- return yield* Effect.tryPromise({
370
- try: () => issueFetch,
371
- catch: (e) => LinearApiError.make({ message: String(e) }),
372
- });
373
- }),
374
- );
191
+ { concurrency: 4 },
192
+ ).pipe(
193
+ Effect.map((items) =>
194
+ items.filter((item): item is NonNullable<typeof item> => item !== undefined),
195
+ ),
196
+ );
375
197
 
376
- const createComment = Effect.fn("LinearService.createComment")(
377
- (issueId: string, body: string) =>
378
- Effect.gen(function* () {
379
- const client = yield* getClient;
380
- const payload = yield* Effect.tryPromise({
381
- try: () => client.createComment({ issueId: normalizeIssueId(issueId), body }),
382
- catch: (error) => LinearApiError.make({ message: String(error) }),
383
- });
384
- const comment = yield* resolveLinearFetch(payload.comment);
385
- return comment === undefined
386
- ? yield* LinearApiError.make({ message: "Linear did not return the created comment" })
387
- : { id: comment.id, url: comment.url };
388
- }),
389
- );
198
+ return {
199
+ id: summary.id,
200
+ identifier: summary.identifier,
201
+ title: summary.title,
202
+ url: summary.url,
203
+ branchName: summary.branchName,
204
+ priority: summary.priority,
205
+ state: summary.state,
206
+ description: issue.description ?? undefined,
207
+ team: team === undefined ? undefined : { id: team.id, key: team.key, name: team.name },
208
+ assignee:
209
+ assignee === undefined
210
+ ? undefined
211
+ : { id: assignee.id, name: assignee.name, email: assignee.email },
212
+ project:
213
+ project === undefined
214
+ ? undefined
215
+ : { id: project.id, name: project.name, url: project.url },
216
+ parent: parent === undefined ? undefined : toIssueReference(parent),
217
+ labels: labels.map((label) => ({ id: label.id, name: label.name })),
218
+ children: children?.map(toIssueReference),
219
+ comments: detailedComments,
220
+ relations,
221
+ } satisfies IssueDetails;
222
+ });
390
223
 
391
- const rawQuery = Effect.fn("LinearService.rawQuery")(
392
- (query: string, variables: Readonly<Record<string, unknown>>) =>
393
- Effect.gen(function* () {
394
- const client = yield* getClient;
395
- const response = yield* Effect.tryPromise({
396
- try: () =>
397
- client.client.rawRequest<unknown, Record<string, unknown>>(query, variables),
398
- catch: (error) => LinearApiError.make({ message: String(error) }),
399
- });
400
- return response.data;
224
+ const startIssue = Effect.fn("LinearService.startIssue")(function* (
225
+ id: IssueSelector,
226
+ options: { readonly dryRun: boolean },
227
+ ) {
228
+ const issue = yield* getIssue(id);
229
+ const team = yield* resolveOptionalFetch(issue.team);
230
+ if (team === undefined) {
231
+ return yield* InvalidInputError.make({
232
+ message: `Issue ${issue.identifier} is not associated with a team`,
233
+ });
234
+ }
235
+ const states = yield* loadConnection(() => team.states());
236
+ const started = states.find(
237
+ (state) => state.type === "started" || state.name.toLowerCase() === "in progress",
238
+ );
239
+ if (started === undefined) {
240
+ return yield* InvalidInputError.make({
241
+ message: `No started state exists for team ${team.key}`,
242
+ });
243
+ }
244
+ if (!options.dryRun) {
245
+ yield* withClient((client) => client.updateIssue(issue.id, { stateId: started.id }));
246
+ }
247
+ return {
248
+ issue: toIssueReference(issue),
249
+ state: { id: started.id, name: started.name, type: started.type },
250
+ branchName: issue.branchName,
251
+ };
252
+ });
253
+
254
+ const createIssue = Effect.fn("LinearService.createIssue")(function* (
255
+ input: CreateIssueInput,
256
+ ) {
257
+ const parentId =
258
+ input.parent === undefined ? undefined : (yield* getIssue(input.parent)).id;
259
+ const payload = yield* withClient((client) =>
260
+ client.createIssue({
261
+ title: input.title,
262
+ teamId: input.teamId,
263
+ description: input.description,
264
+ parentId,
265
+ projectId: input.projectId,
266
+ priority: input.priority,
401
267
  }),
402
- );
268
+ );
269
+ if (payload.issue === undefined) {
270
+ return yield* LinearApiError.make({ message: "Linear did not return the created issue" });
271
+ }
272
+ return toIssueReference(yield* resolveLinearFetch(payload.issue));
273
+ });
274
+
275
+ const createComment = Effect.fn("LinearService.createComment")(function* (
276
+ issueId: IssueSelector,
277
+ body: string,
278
+ ) {
279
+ const payload = yield* withClient((client) => client.createComment({ issueId, body }));
280
+ const comment = yield* resolveOptionalFetch(payload.comment);
281
+ return comment === undefined
282
+ ? yield* LinearApiError.make({ message: "Linear did not return the created comment" })
283
+ : { id: comment.id, url: comment.url };
284
+ });
285
+
286
+ const rawQuery = Effect.fn("LinearService.rawQuery")(function* (
287
+ query: string,
288
+ variables: Readonly<Record<string, unknown>>,
289
+ ) {
290
+ const response = yield* withClient((client) =>
291
+ client.client.rawRequest<unknown, Record<string, unknown>>(query, variables),
292
+ );
293
+ return response.data;
294
+ });
403
295
 
404
296
  return LinearService.of({
297
+ authenticate,
405
298
  getViewer,
406
299
  getTeams,
407
300
  getProjects,
408
- getIssues,
409
301
  getMyIssues,
410
- getIssue,
411
302
  getIssueDetails,
412
- updateIssueState,
303
+ startIssue,
413
304
  createIssue,
414
305
  createComment,
415
306
  rawQuery,
@@ -417,58 +308,100 @@ export class LinearService extends Context.Service<
417
308
  }),
418
309
  );
419
310
 
420
- static readonly layerTest = (options?: {
421
- viewer?: User;
422
- teams?: readonly Team[];
423
- issues?: readonly Issue[];
424
- }) =>
425
- Layer.succeed(LinearService, {
426
- getViewer:
427
- options?.viewer !== undefined
428
- ? Effect.succeed(options.viewer)
429
- : Effect.fail(LinearApiError.make({ message: "No viewer in test" })),
430
- getTeams: Effect.succeed(options?.teams ?? []),
431
- getProjects: Effect.succeed([]),
432
- getIssues: (_filter) => Effect.succeed(options?.issues ?? []),
433
- getMyIssues: (_filter) => Effect.succeed(options?.issues ?? []),
434
- getIssue: (id) => {
435
- const issue = options?.issues?.find((i) => i.id === id || i.identifier === id);
436
- return issue !== undefined
437
- ? Effect.succeed(issue)
438
- : Effect.fail(LinearApiError.make({ message: `Issue ${id} not found` }));
439
- },
440
- getIssueDetails: (id, _options) => {
441
- const issue = options?.issues?.find(
442
- (candidate) => candidate.id === id || candidate.identifier === id,
443
- );
444
- return issue === undefined
445
- ? Effect.fail(LinearApiError.make({ message: `Issue ${id} not found` }))
446
- : Effect.succeed({
447
- id: issue.id,
448
- identifier: issue.identifier,
449
- title: issue.title,
450
- url: issue.url,
451
- description: issue.description ?? undefined,
452
- branchName: issue.branchName,
453
- priority: { value: issue.priority, label: issue.priorityLabel },
311
+ static readonly layerTest = (overrides: Partial<LinearOperations> = {}) =>
312
+ Layer.succeed(
313
+ LinearService,
314
+ Object.assign(
315
+ {
316
+ authenticate: (token) =>
317
+ Effect.succeed({
318
+ id: "viewer",
319
+ name: "Test User",
320
+ email: `${Redacted.value(token)}@example.com`,
321
+ admin: false,
322
+ }),
323
+ getViewer: Effect.succeed({
324
+ id: "viewer",
325
+ name: "Test User",
326
+ email: "test@example.com",
327
+ admin: false,
328
+ }),
329
+ getTeams: Effect.succeed([]),
330
+ getProjects: Effect.succeed([]),
331
+ getMyIssues: () => Effect.succeed([]),
332
+ getIssueDetails: (id) =>
333
+ Effect.succeed({
334
+ id,
335
+ identifier: id,
336
+ title: "Test issue",
337
+ url: `https://linear.app/issue/${id}`,
338
+ branchName: id.toLowerCase(),
339
+ priority: { value: 0, label: "No priority" },
454
340
  labels: [],
455
- });
456
- },
457
- updateIssueState: (_issueId, _stateId) => Effect.void,
458
- createIssue: (_input) =>
459
- Effect.fail(LinearApiError.make({ message: "Not implemented in test" })),
460
- createComment: (_issueId, _body) =>
461
- Effect.fail(LinearApiError.make({ message: "Not implemented in test" })),
462
- rawQuery: (_query, _variables) =>
463
- Effect.fail(LinearApiError.make({ message: "Not implemented in test" })),
464
- });
341
+ }),
342
+ startIssue: (id) =>
343
+ Effect.succeed({
344
+ issue: {
345
+ id,
346
+ identifier: id,
347
+ title: "Test issue",
348
+ url: `https://linear.app/issue/${id}`,
349
+ },
350
+ state: { id: "started", name: "In Progress", type: "started" },
351
+ branchName: id.toLowerCase(),
352
+ }),
353
+ createIssue: (input) =>
354
+ Effect.succeed({
355
+ id: "created",
356
+ identifier: "TEST-1",
357
+ title: input.title,
358
+ url: "https://linear.app/issue/TEST-1",
359
+ }),
360
+ createComment: () =>
361
+ Effect.succeed({ id: "comment", url: "https://linear.app/comment/comment" }),
362
+ rawQuery: () => Effect.succeed({}),
363
+ } satisfies LinearOperations,
364
+ overrides,
365
+ ),
366
+ );
465
367
  }
466
368
 
467
- const normalizeIssueId = (input: string): string => {
468
- const match = input.match(/\/issue\/([A-Za-z]+-\d+)(?:\/|$)/);
469
- return match?.[1] ?? input;
369
+ const toLinearError = (error: unknown): InvalidTokenError | LinearApiError => {
370
+ const message = String(error);
371
+ return message.includes("Authentication") || message.includes("401")
372
+ ? InvalidTokenError.make({ message: "Invalid API token" })
373
+ : LinearApiError.make({ message });
470
374
  };
471
375
 
376
+ const toViewer = (viewer: User): Viewer => ({
377
+ id: viewer.id,
378
+ name: viewer.name,
379
+ email: viewer.email,
380
+ admin: viewer.admin,
381
+ status:
382
+ viewer.statusEmoji === undefined && viewer.statusLabel === undefined
383
+ ? undefined
384
+ : {
385
+ emoji: viewer.statusEmoji ?? undefined,
386
+ label: viewer.statusLabel ?? undefined,
387
+ },
388
+ });
389
+
390
+ const toTeam = (team: Awaited<ReturnType<LinearClient["team"]>>): Team => ({
391
+ id: team.id,
392
+ key: team.key,
393
+ name: team.name,
394
+ description: team.description ?? undefined,
395
+ });
396
+
397
+ const toProject = (project: Awaited<ReturnType<LinearClient["project"]>>): Project => ({
398
+ id: project.id,
399
+ name: project.name,
400
+ slug: project.slugId,
401
+ state: project.state,
402
+ url: project.url,
403
+ });
404
+
472
405
  const toIssueReference = (issue: Issue): IssueReference => ({
473
406
  id: issue.id,
474
407
  identifier: issue.identifier,
@@ -476,18 +409,47 @@ const toIssueReference = (issue: Issue): IssueReference => ({
476
409
  url: issue.url,
477
410
  });
478
411
 
479
- const resolveLinearFetch = <T>(
480
- fetch: PromiseLike<T> | undefined,
481
- ): Effect.Effect<T | undefined, LinearApiError> =>
482
- fetch === undefined
483
- ? Effect.succeed<T | undefined>(undefined)
484
- : Effect.tryPromise({
485
- try: () => Promise.resolve(fetch),
486
- catch: (error) => LinearApiError.make({ message: String(error) }),
487
- });
412
+ const toIssueSummary = Effect.fn("LinearService.toIssueSummary")(function* (
413
+ issue: Issue,
414
+ ): Effect.fn.Return<IssueSummary, LinearApiError> {
415
+ const state = yield* resolveOptionalFetch(issue.state);
416
+ return {
417
+ id: issue.id,
418
+ identifier: issue.identifier,
419
+ title: issue.title,
420
+ url: issue.url,
421
+ branchName: issue.branchName,
422
+ priority: { value: issue.priority, label: issue.priorityLabel },
423
+ state: state === undefined ? undefined : { id: state.id, name: state.name, type: state.type },
424
+ };
425
+ });
488
426
 
489
- const loadConnection = <T>(load: () => PromiseLike<{ readonly nodes: ReadonlyArray<T> }>) =>
427
+ const resolveLinearFetch = <T>(fetch: PromiseLike<T>): Effect.Effect<T, LinearApiError> =>
490
428
  Effect.tryPromise({
491
- try: () => Promise.resolve(load()),
429
+ try: () => Promise.resolve(fetch),
492
430
  catch: (error) => LinearApiError.make({ message: String(error) }),
493
- }).pipe(Effect.map((connection) => connection.nodes));
431
+ });
432
+
433
+ const resolveOptionalFetch = <T>(
434
+ fetch: PromiseLike<T> | undefined,
435
+ ): Effect.Effect<T | undefined, LinearApiError> =>
436
+ fetch === undefined ? Effect.succeed(undefined) : resolveLinearFetch(fetch);
437
+
438
+ interface PaginatedConnection<T> {
439
+ readonly nodes: ReadonlyArray<T>;
440
+ readonly pageInfo: { readonly hasNextPage: boolean };
441
+ readonly fetchNext: () => PromiseLike<PaginatedConnection<T>>;
442
+ }
443
+
444
+ const loadAllPages = Effect.fn("LinearService.loadAllPages")(function* <T>(
445
+ initial: PaginatedConnection<T>,
446
+ ) {
447
+ let connection = initial;
448
+ while (connection.pageInfo.hasNextPage) {
449
+ connection = yield* resolveLinearFetch(connection.fetchNext());
450
+ }
451
+ return connection.nodes;
452
+ });
453
+
454
+ const loadConnection = <T>(load: () => PromiseLike<PaginatedConnection<T>>) =>
455
+ resolveLinearFetch(load()).pipe(Effect.flatMap(loadAllPages));