@cvr/linear 0.3.0 → 0.5.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,474 +1,445 @@
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 { Comment, Issue, IssueRelation as SdkIssueRelation, User } from "@linear/sdk";
3
+ import { Context, Effect, Layer, Redacted } from "effect";
4
+ import type {
5
+ CreateIssueInput,
6
+ CreatedIssue,
7
+ DownloadedFile,
8
+ IssueComment,
9
+ IssueDetails,
10
+ IssueDetailsOptions,
11
+ IssueReference,
12
+ IssueRelation,
13
+ IssueSelector,
14
+ IssueSummary,
15
+ Project,
16
+ StartedIssue,
17
+ Team,
18
+ UploadUrl,
19
+ Viewer,
20
+ } from "../domain/Linear.js";
21
+ import { fileNameFromContentDisposition } from "../domain/Files.js";
22
+ import type { ConfigError, TokenNotFoundError } from "../lib/errors.js";
23
+ import { InvalidInputError, InvalidTokenError, LinearApiError } from "../lib/errors.js";
24
+ import { succeedUndefined } from "../lib/effect.js";
5
25
  import { ConfigService } from "./Config.js";
6
26
 
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
- }
27
+ type LinearError = ConfigError | InvalidTokenError | LinearApiError | TokenNotFoundError;
19
28
 
20
- export interface IssueReference {
21
- readonly id: string;
22
- readonly identifier: string;
23
- readonly title: string;
24
- readonly url: string;
29
+ interface LinearOperations {
30
+ readonly authenticate: (token: Redacted.Redacted<string>) => Effect.Effect<Viewer, LinearError>;
31
+ readonly getViewer: Effect.Effect<Viewer, LinearError>;
32
+ readonly getTeams: Effect.Effect<readonly Team[], LinearError>;
33
+ readonly getProjects: Effect.Effect<readonly Project[], LinearError>;
34
+ readonly getMyIssues: (filter?: {
35
+ readonly state?: string;
36
+ readonly limit?: number;
37
+ }) => Effect.Effect<readonly IssueSummary[], LinearError>;
38
+ readonly getIssueDetails: (
39
+ id: IssueSelector,
40
+ options: IssueDetailsOptions,
41
+ ) => Effect.Effect<IssueDetails, LinearError>;
42
+ readonly startIssue: (
43
+ id: IssueSelector,
44
+ options: { readonly dryRun: boolean },
45
+ ) => Effect.Effect<StartedIssue, LinearError | InvalidInputError>;
46
+ readonly createIssue: (input: CreateIssueInput) => Effect.Effect<CreatedIssue, LinearError>;
47
+ readonly createComment: (
48
+ issueId: IssueSelector,
49
+ body: string,
50
+ ) => Effect.Effect<{ readonly id: string; readonly url: string }, LinearError>;
51
+ readonly rawQuery: (
52
+ query: string,
53
+ variables: Readonly<Record<string, unknown>>,
54
+ ) => Effect.Effect<unknown, LinearError>;
55
+ readonly downloadFile: (url: UploadUrl) => Effect.Effect<DownloadedFile, LinearError>;
25
56
  }
26
57
 
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
- }>;
70
- }
71
-
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") {
58
+ export class LinearService extends Context.Service<LinearService, LinearOperations>()(
59
+ "@cvr/linear/services/Linear/LinearService",
60
+ ) {
117
61
  static readonly layer = Layer.effect(
118
62
  LinearService,
119
63
  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,
64
+ const config = yield* ConfigService;
65
+ const getClient = yield* Effect.cached(
66
+ config.getToken.pipe(
67
+ Effect.map((token) => new LinearClient({ apiKey: Redacted.value(token) })),
68
+ ),
128
69
  );
129
70
 
130
- const getViewer = Effect.gen(function* () {
131
- const client = yield* getClient;
132
- return yield* Effect.tryPromise({
71
+ const withClient = <A>(
72
+ operation: (client: LinearClient) => PromiseLike<A>,
73
+ ): Effect.Effect<A, LinearError> =>
74
+ getClient.pipe(
75
+ Effect.flatMap((client) =>
76
+ Effect.tryPromise({
77
+ try: () => operation(client),
78
+ catch: toLinearError,
79
+ }),
80
+ ),
81
+ );
82
+
83
+ const authenticate = Effect.fn("LinearService.authenticate")(function* (
84
+ token: Redacted.Redacted<string>,
85
+ ) {
86
+ const client = new LinearClient({ apiKey: Redacted.value(token) });
87
+ const viewer = yield* Effect.tryPromise({
133
88
  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
- },
89
+ catch: toLinearError,
141
90
  });
142
- }).pipe(Effect.withSpan("LinearService.getViewer"));
91
+ yield* config.saveToken(token);
92
+ return toViewer(viewer);
93
+ });
143
94
 
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
- }),
95
+ const getViewer = withClient((client) => client.viewer).pipe(
96
+ Effect.map(toViewer),
97
+ Effect.withSpan("LinearService.getViewer"),
180
98
  );
181
99
 
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
- }),
100
+ const getTeams = withClient((client) => client.teams()).pipe(
101
+ Effect.flatMap(loadAllPages),
102
+ Effect.map((teams) => teams.map(toTeam)),
103
+ Effect.withSpan("LinearService.getTeams"),
202
104
  );
203
105
 
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
- }),
106
+ const getProjects = withClient((client) => client.projects()).pipe(
107
+ Effect.flatMap(loadAllPages),
108
+ Effect.map((projects) => projects.map(toProject)),
109
+ Effect.withSpan("LinearService.getProjects"),
212
110
  );
213
111
 
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
- );
258
-
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
- );
299
-
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;
112
+ const getMyIssues = Effect.fn("LinearService.getMyIssues")(function* (filter?: {
113
+ readonly state?: string;
114
+ readonly limit?: number;
115
+ }) {
116
+ const viewer = yield* withClient((client) => client.viewer);
117
+ const connection = yield* resolveLinearFetch(
118
+ viewer.assignedIssues({
119
+ first: filter?.limit ?? 50,
120
+ filter: toStateFilter(filter?.state),
328
121
  }),
329
- );
122
+ );
123
+ return yield* Effect.forEach(connection.nodes, toIssueSummary, { concurrency: 4 });
124
+ });
330
125
 
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
- );
126
+ const getIssue = (id: IssueSelector) => withClient((client) => client.issue(id));
341
127
 
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,
362
- }),
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
- );
128
+ const getIssueDetails = Effect.fn("LinearService.getIssueDetails")(function* (
129
+ id: IssueSelector,
130
+ options: IssueDetailsOptions,
131
+ ) {
132
+ const issue = yield* getIssue(id);
133
+ const [summary, team, assignee, project, parent, labels] = yield* Effect.all([
134
+ toIssueSummary(issue),
135
+ resolveOptionalFetch(issue.team),
136
+ resolveOptionalFetch(issue.assignee),
137
+ resolveOptionalFetch(issue.project),
138
+ resolveOptionalFetch(issue.parent),
139
+ loadConnection(() => issue.labels()),
140
+ ]);
375
141
 
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
- );
142
+ const children = yield* loadConnectionWhen(options.children, () => issue.children());
143
+ const comments = yield* loadConnectionWhen(options.comments, () => issue.comments());
144
+ const outbound = yield* loadConnectionWhen(options.relations, () => issue.relations());
145
+ const inbound = yield* loadConnectionWhen(options.relations, () =>
146
+ issue.inverseRelations(),
147
+ );
148
+
149
+ const detailedComments = yield* toDetailedComments(comments);
150
+ const relations = yield* toRelations(outbound, inbound);
151
+
152
+ return {
153
+ id: summary.id,
154
+ identifier: summary.identifier,
155
+ title: summary.title,
156
+ url: summary.url,
157
+ branchName: summary.branchName,
158
+ priority: summary.priority,
159
+ state: summary.state,
160
+ description: issue.description ?? undefined,
161
+ team: mapDefined(team, (value) => ({ id: value.id, key: value.key, name: value.name })),
162
+ assignee: mapDefined(assignee, (value) => ({
163
+ id: value.id,
164
+ name: value.name,
165
+ email: value.email,
166
+ })),
167
+ project: mapDefined(project, (value) => ({
168
+ id: value.id,
169
+ name: value.name,
170
+ url: value.url,
171
+ })),
172
+ parent: mapDefined(parent, toIssueReference),
173
+ labels: labels.map((label) => ({ id: label.id, name: label.name })),
174
+ children: children?.map(toIssueReference),
175
+ comments: detailedComments,
176
+ relations,
177
+ } satisfies IssueDetails;
178
+ });
390
179
 
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;
180
+ const startIssue = Effect.fn("LinearService.startIssue")(function* (
181
+ id: IssueSelector,
182
+ options: { readonly dryRun: boolean },
183
+ ) {
184
+ const issue = yield* getIssue(id);
185
+ const team = yield* resolveOptionalFetch(issue.team);
186
+ if (team === undefined) {
187
+ return yield* InvalidInputError.make({
188
+ message: `Issue ${issue.identifier} is not associated with a team`,
189
+ });
190
+ }
191
+ const states = yield* loadConnection(() => team.states());
192
+ const started = states.find(
193
+ (state) => state.type === "started" || state.name.toLowerCase() === "in progress",
194
+ );
195
+ if (started === undefined) {
196
+ return yield* InvalidInputError.make({
197
+ message: `No started state exists for team ${team.key}`,
198
+ });
199
+ }
200
+ if (!options.dryRun) {
201
+ yield* withClient((client) => client.updateIssue(issue.id, { stateId: started.id }));
202
+ }
203
+ return {
204
+ issue: toIssueReference(issue),
205
+ state: { id: started.id, name: started.name, type: started.type },
206
+ branchName: issue.branchName,
207
+ };
208
+ });
209
+
210
+ const resolveParentId = Effect.fn("LinearService.resolveParentId")(function* (
211
+ parent: IssueSelector | undefined,
212
+ ) {
213
+ if (parent === undefined) {
214
+ return undefined;
215
+ }
216
+ const parentIssue = yield* getIssue(parent);
217
+ return parentIssue.id;
218
+ });
219
+
220
+ const createIssue = Effect.fn("LinearService.createIssue")(function* (
221
+ input: CreateIssueInput,
222
+ ) {
223
+ const parentId = yield* resolveParentId(input.parent);
224
+ const payload = yield* withClient((client) =>
225
+ client.createIssue({
226
+ title: input.title,
227
+ teamId: input.teamId,
228
+ description: input.description,
229
+ parentId,
230
+ projectId: input.projectId,
231
+ priority: input.priority,
401
232
  }),
402
- );
233
+ );
234
+ if (payload.issue === undefined) {
235
+ return yield* LinearApiError.make({ message: "Linear did not return the created issue" });
236
+ }
237
+ return toIssueReference(yield* resolveLinearFetch(payload.issue));
238
+ });
239
+
240
+ const createComment = Effect.fn("LinearService.createComment")(function* (
241
+ issueId: IssueSelector,
242
+ body: string,
243
+ ) {
244
+ const payload = yield* withClient((client) => client.createComment({ issueId, body }));
245
+ const comment = yield* resolveOptionalFetch(payload.comment);
246
+ if (comment === undefined) {
247
+ return yield* LinearApiError.make({
248
+ message: "Linear did not return the created comment",
249
+ });
250
+ }
251
+ return { id: comment.id, url: comment.url };
252
+ });
253
+
254
+ const rawQuery = Effect.fn("LinearService.rawQuery")(function* (
255
+ query: string,
256
+ variables: Readonly<Record<string, unknown>>,
257
+ ) {
258
+ const response = yield* withClient((client) =>
259
+ client.client.rawRequest<unknown, Record<string, unknown>>(query, variables),
260
+ );
261
+ return response.data;
262
+ });
263
+
264
+ const downloadFile = Effect.fn("LinearService.downloadFile")(function* (url: UploadUrl) {
265
+ const token = yield* config.getToken;
266
+ return yield* fetchUpload(url, token);
267
+ });
403
268
 
404
269
  return LinearService.of({
270
+ authenticate,
405
271
  getViewer,
406
272
  getTeams,
407
273
  getProjects,
408
- getIssues,
409
274
  getMyIssues,
410
- getIssue,
411
275
  getIssueDetails,
412
- updateIssueState,
276
+ startIssue,
413
277
  createIssue,
414
278
  createComment,
415
279
  rawQuery,
280
+ downloadFile,
416
281
  });
417
282
  }),
418
283
  );
419
284
 
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 },
285
+ static readonly layerTest = (overrides: Partial<LinearOperations> = {}) =>
286
+ Layer.succeed(
287
+ LinearService,
288
+ Object.assign(
289
+ {
290
+ authenticate: (token) =>
291
+ Effect.succeed({
292
+ id: "viewer",
293
+ name: "Test User",
294
+ email: `${Redacted.value(token)}@example.com`,
295
+ admin: false,
296
+ }),
297
+ getViewer: Effect.succeed({
298
+ id: "viewer",
299
+ name: "Test User",
300
+ email: "test@example.com",
301
+ admin: false,
302
+ }),
303
+ getTeams: Effect.succeed([]),
304
+ getProjects: Effect.succeed([]),
305
+ getMyIssues: () => Effect.succeed([]),
306
+ getIssueDetails: (id) =>
307
+ Effect.succeed({
308
+ id,
309
+ identifier: id,
310
+ title: "Test issue",
311
+ url: `https://linear.app/issue/${id}`,
312
+ branchName: id.toLowerCase(),
313
+ priority: { value: 0, label: "No priority" },
454
314
  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
- });
315
+ }),
316
+ startIssue: (id) =>
317
+ Effect.succeed({
318
+ issue: {
319
+ id,
320
+ identifier: id,
321
+ title: "Test issue",
322
+ url: `https://linear.app/issue/${id}`,
323
+ },
324
+ state: { id: "started", name: "In Progress", type: "started" },
325
+ branchName: id.toLowerCase(),
326
+ }),
327
+ createIssue: (input) =>
328
+ Effect.succeed({
329
+ id: "created",
330
+ identifier: "TEST-1",
331
+ title: input.title,
332
+ url: "https://linear.app/issue/TEST-1",
333
+ }),
334
+ createComment: () =>
335
+ Effect.succeed({ id: "comment", url: "https://linear.app/comment/comment" }),
336
+ rawQuery: () => Effect.succeed({}),
337
+ downloadFile: () => Effect.succeed({ bytes: new Uint8Array() }),
338
+ } satisfies LinearOperations,
339
+ overrides,
340
+ ),
341
+ );
465
342
  }
466
343
 
467
- const normalizeIssueId = (input: string): string => {
468
- const match = input.match(/\/issue\/([A-Za-z]+-\d+)(?:\/|$)/);
469
- return match?.[1] ?? input;
344
+ const toLinearError = (error: unknown): InvalidTokenError | LinearApiError => {
345
+ const message = String(error);
346
+ if (message.includes("Authentication") || message.includes("401")) {
347
+ return InvalidTokenError.make({ message: "Invalid API token" });
348
+ }
349
+ return LinearApiError.make({ message });
350
+ };
351
+
352
+ type FetchImplementation = (input: string | URL, init?: RequestInit) => Promise<Response>;
353
+
354
+ const isRedirect = (status: number): boolean => status >= 300 && status < 400;
355
+
356
+ const requestUpload = (
357
+ fetchImplementation: FetchImplementation,
358
+ input: string | URL,
359
+ init: RequestInit,
360
+ ): Effect.Effect<Response, LinearApiError> =>
361
+ Effect.tryPromise({
362
+ try: () => fetchImplementation(input, init),
363
+ catch: (error) => LinearApiError.make({ message: `Download failed: ${String(error)}` }),
364
+ });
365
+
366
+ // Linear serves uploads behind the API key and may redirect to signed storage. The key goes
367
+ // only to the upload host; a redirect is followed without it so it never reaches a third party.
368
+ export const fetchUpload = Effect.fn("LinearService.fetchUpload")(function* (
369
+ url: UploadUrl,
370
+ token: Redacted.Redacted<string>,
371
+ fetchImplementation: FetchImplementation = fetch,
372
+ ) {
373
+ let response = yield* requestUpload(fetchImplementation, url, {
374
+ headers: { Authorization: Redacted.value(token) },
375
+ redirect: "manual",
376
+ });
377
+ const location = response.headers.get("location");
378
+ if (isRedirect(response.status) && location !== null) {
379
+ response = yield* requestUpload(fetchImplementation, new URL(location, url), {
380
+ redirect: "follow",
381
+ });
382
+ }
383
+ if (response.status === 401) {
384
+ return yield* InvalidTokenError.make({ message: "Invalid API token" });
385
+ }
386
+ if (!response.ok) {
387
+ return yield* LinearApiError.make({
388
+ message: `Download failed with HTTP ${response.status} for ${url}`,
389
+ code: String(response.status),
390
+ });
391
+ }
392
+ const body = yield* Effect.tryPromise({
393
+ try: () => response.arrayBuffer(),
394
+ catch: (error) => LinearApiError.make({ message: `Download failed: ${String(error)}` }),
395
+ });
396
+ return {
397
+ bytes: new Uint8Array(body),
398
+ contentType: response.headers.get("content-type") ?? undefined,
399
+ fileName: fileNameFromContentDisposition(response.headers.get("content-disposition")),
400
+ } satisfies DownloadedFile;
401
+ });
402
+
403
+ const mapDefined = <T, U>(value: T | undefined, transform: (value: T) => U): U | undefined => {
404
+ if (value === undefined) {
405
+ return undefined;
406
+ }
407
+ return transform(value);
408
+ };
409
+
410
+ const toViewerStatus = (viewer: User): Viewer["status"] => {
411
+ if (viewer.statusEmoji === undefined && viewer.statusLabel === undefined) {
412
+ return undefined;
413
+ }
414
+ return {
415
+ emoji: viewer.statusEmoji ?? undefined,
416
+ label: viewer.statusLabel ?? undefined,
417
+ };
470
418
  };
471
419
 
420
+ const toViewer = (viewer: User): Viewer => ({
421
+ id: viewer.id,
422
+ name: viewer.name,
423
+ email: viewer.email,
424
+ admin: viewer.admin,
425
+ status: toViewerStatus(viewer),
426
+ });
427
+
428
+ const toTeam = (team: Awaited<ReturnType<LinearClient["team"]>>): Team => ({
429
+ id: team.id,
430
+ key: team.key,
431
+ name: team.name,
432
+ description: team.description ?? undefined,
433
+ });
434
+
435
+ const toProject = (project: Awaited<ReturnType<LinearClient["project"]>>): Project => ({
436
+ id: project.id,
437
+ name: project.name,
438
+ slug: project.slugId,
439
+ state: project.state,
440
+ url: project.url,
441
+ });
442
+
472
443
  const toIssueReference = (issue: Issue): IssueReference => ({
473
444
  id: issue.id,
474
445
  identifier: issue.identifier,
@@ -476,18 +447,143 @@ const toIssueReference = (issue: Issue): IssueReference => ({
476
447
  url: issue.url,
477
448
  });
478
449
 
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
- });
450
+ const toIssueSummary = Effect.fn("LinearService.toIssueSummary")(function* (
451
+ issue: Issue,
452
+ ): Effect.fn.Return<IssueSummary, LinearApiError> {
453
+ const state = yield* resolveOptionalFetch(issue.state);
454
+ return {
455
+ id: issue.id,
456
+ identifier: issue.identifier,
457
+ title: issue.title,
458
+ url: issue.url,
459
+ branchName: issue.branchName,
460
+ priority: { value: issue.priority, label: issue.priorityLabel },
461
+ state: mapDefined(state, (value) => ({ id: value.id, name: value.name, type: value.type })),
462
+ };
463
+ });
488
464
 
489
- const loadConnection = <T>(load: () => PromiseLike<{ readonly nodes: ReadonlyArray<T> }>) =>
465
+ const resolveLinearFetch = <T>(fetch: PromiseLike<T>): Effect.Effect<T, LinearApiError> =>
490
466
  Effect.tryPromise({
491
- try: () => Promise.resolve(load()),
467
+ try: () => fetch,
492
468
  catch: (error) => LinearApiError.make({ message: String(error) }),
493
- }).pipe(Effect.map((connection) => connection.nodes));
469
+ });
470
+
471
+ const resolveOptionalFetch = <T>(
472
+ fetch: PromiseLike<T> | undefined,
473
+ ): Effect.Effect<T | undefined, LinearApiError> => {
474
+ if (fetch === undefined) {
475
+ return succeedUndefined;
476
+ }
477
+ return resolveLinearFetch(fetch);
478
+ };
479
+
480
+ const toStateFilter = (
481
+ state: string | undefined,
482
+ ): { readonly state: { readonly type: { readonly eq: string } } } | undefined => {
483
+ if (state === undefined) {
484
+ return undefined;
485
+ }
486
+ return { state: { type: { eq: state } } };
487
+ };
488
+
489
+ const toCommentAuthor = (author: User | undefined): IssueComment["author"] => {
490
+ if (author === undefined) {
491
+ return undefined;
492
+ }
493
+ return { id: author.id, name: author.name };
494
+ };
495
+
496
+ const toDetailedComments = (
497
+ comments: ReadonlyArray<Comment> | undefined,
498
+ ): Effect.Effect<ReadonlyArray<IssueComment> | undefined, LinearApiError> => {
499
+ if (comments === undefined) {
500
+ return succeedUndefined;
501
+ }
502
+ return Effect.forEach(
503
+ comments,
504
+ (comment) =>
505
+ resolveOptionalFetch(comment.user).pipe(
506
+ Effect.map((author) => ({
507
+ id: comment.id,
508
+ body: comment.body,
509
+ createdAt: comment.createdAt.toISOString(),
510
+ url: comment.url,
511
+ author: toCommentAuthor(author),
512
+ })),
513
+ ),
514
+ { concurrency: 4 },
515
+ );
516
+ };
517
+
518
+ interface RelationWithDirection {
519
+ readonly relation: SdkIssueRelation;
520
+ readonly direction: "outbound" | "inbound";
521
+ }
522
+
523
+ const relatedIssueFetch = (entry: RelationWithDirection): PromiseLike<Issue> | undefined => {
524
+ if (entry.direction === "outbound") {
525
+ return entry.relation.relatedIssue;
526
+ }
527
+ return entry.relation.issue;
528
+ };
529
+
530
+ const toRelations = (
531
+ outbound: ReadonlyArray<SdkIssueRelation> | undefined,
532
+ inbound: ReadonlyArray<SdkIssueRelation> | undefined,
533
+ ): Effect.Effect<ReadonlyArray<IssueRelation> | undefined, LinearApiError> => {
534
+ if (outbound === undefined || inbound === undefined) {
535
+ return succeedUndefined;
536
+ }
537
+ const entries = outbound
538
+ .map<RelationWithDirection>((relation) => ({ relation, direction: "outbound" }))
539
+ .concat(inbound.map((relation) => ({ relation, direction: "inbound" })));
540
+ return Effect.forEach(
541
+ entries,
542
+ Effect.fn("LinearService.resolveRelation")(function* ({ direction, relation }) {
543
+ const related = yield* resolveOptionalFetch(relatedIssueFetch({ direction, relation }));
544
+ if (related === undefined) {
545
+ return undefined;
546
+ }
547
+ return {
548
+ id: relation.id,
549
+ type: relation.type,
550
+ direction,
551
+ issue: toIssueReference(related),
552
+ };
553
+ }),
554
+ { concurrency: 4 },
555
+ ).pipe(
556
+ Effect.map((items) =>
557
+ items.filter((item): item is NonNullable<typeof item> => item !== undefined),
558
+ ),
559
+ );
560
+ };
561
+
562
+ const loadConnectionWhen = <T>(
563
+ enabled: boolean,
564
+ load: () => PromiseLike<PaginatedConnection<T>>,
565
+ ): Effect.Effect<ReadonlyArray<T> | undefined, LinearApiError> => {
566
+ if (!enabled) {
567
+ return succeedUndefined;
568
+ }
569
+ return loadConnection(load);
570
+ };
571
+
572
+ interface PaginatedConnection<T> {
573
+ readonly nodes: ReadonlyArray<T>;
574
+ readonly pageInfo: { readonly hasNextPage: boolean };
575
+ readonly fetchNext: () => PromiseLike<PaginatedConnection<T>>;
576
+ }
577
+
578
+ const loadAllPages = Effect.fn("LinearService.loadAllPages")(function* <T>(
579
+ initial: PaginatedConnection<T>,
580
+ ) {
581
+ let connection = initial;
582
+ while (connection.pageInfo.hasNextPage) {
583
+ connection = yield* resolveLinearFetch(connection.fetchNext());
584
+ }
585
+ return connection.nodes;
586
+ });
587
+
588
+ const loadConnection = <T>(load: () => PromiseLike<PaginatedConnection<T>>) =>
589
+ resolveLinearFetch(load()).pipe(Effect.flatMap(loadAllPages));