@cvr/linear 0.4.0 → 0.5.1

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,78 +1,89 @@
1
- import { Argument, Command, Flag, Prompt } from "effect/unstable/cli";
1
+ import { Argument, Command, Flag, Prompt } from "effect/cli";
2
2
  import { Console, Effect, Option } from "effect";
3
3
  import type { IssueDetails } from "../domain/Linear.js";
4
- import { parseIssueSelector, validateText } from "../domain/Input.js";
4
+ import { extractUploadLinks, uniqueByUrl } from "../domain/Files.js";
5
+ import { parseIssueSelector, parseUploadUrl, validateText } from "../domain/Input.js";
6
+ import { saveDownloads } from "../lib/downloads.js";
7
+ import { succeedUndefined } from "../lib/effect.js";
5
8
  import { InvalidInputError, NoIssuesError } from "../lib/errors.js";
6
- import { jsonFlag } from "../lib/flags.js";
9
+ import { jsonFlag, outputDirFlag, overwriteFlag } from "../lib/flags.js";
10
+ import { logSavedFiles } from "./file.js";
7
11
  import { encodeJson } from "../lib/json.js";
8
12
  import { LinearService } from "../services/Linear.js";
9
13
  import { ConfigService } from "../services/Config.js";
10
14
 
11
15
  // Options
12
- const stateOption = Flag.string("state").pipe(
16
+ const stateOption = Flag.String("state").pipe(
13
17
  Flag.withAlias("s"),
14
18
  Flag.withDescription("Filter by state type (started, unstarted, backlog, etc.)"),
15
19
  Flag.optional,
16
20
  );
17
21
 
18
- const limitOption = Flag.integer("limit").pipe(
22
+ const limitOption = Flag.Int("limit").pipe(
19
23
  Flag.withAlias("n"),
20
24
  Flag.withDefault(20),
21
25
  Flag.withDescription("Number of issues to show"),
22
26
  );
23
27
 
24
- const commentsOption = Flag.boolean("comments").pipe(
28
+ const commentsOption = Flag.Boolean("comments").pipe(
29
+ Flag.withDefault(false),
25
30
  Flag.withDescription("Include issue comments"),
26
31
  );
27
32
 
28
- const childrenOption = Flag.boolean("children").pipe(Flag.withDescription("Include sub-issues"));
33
+ const childrenOption = Flag.Boolean("children").pipe(
34
+ Flag.withDefault(false),
35
+ Flag.withDescription("Include sub-issues"),
36
+ );
29
37
 
30
- const relationsOption = Flag.boolean("relations").pipe(
38
+ const relationsOption = Flag.Boolean("relations").pipe(
39
+ Flag.withDefault(false),
31
40
  Flag.withDescription("Include inbound and outbound issue relations"),
32
41
  );
33
42
 
34
- const titleOption = Flag.string("title").pipe(
43
+ const titleOption = Flag.String("title").pipe(
35
44
  Flag.withDescription("Issue title; enables non-interactive creation"),
36
45
  Flag.optional,
37
46
  );
38
47
 
39
- const descriptionOption = Flag.string("description").pipe(
48
+ const descriptionOption = Flag.String("description").pipe(
40
49
  Flag.withDescription("Issue description in Markdown"),
41
50
  Flag.optional,
42
51
  );
43
52
 
44
- const teamOption = Flag.string("team").pipe(
53
+ const teamOption = Flag.String("team").pipe(
45
54
  Flag.withDescription("Team key or UUID"),
46
55
  Flag.optional,
47
56
  );
48
57
 
49
- const parentOption = Flag.string("parent").pipe(
58
+ const parentOption = Flag.String("parent").pipe(
50
59
  Flag.withDescription("Parent issue identifier or UUID"),
51
60
  Flag.optional,
52
61
  );
53
62
 
54
- const projectOption = Flag.string("project").pipe(
63
+ const projectOption = Flag.String("project").pipe(
55
64
  Flag.withDescription("Project name, slug, or UUID"),
56
65
  Flag.optional,
57
66
  );
58
67
 
59
- const priorityOption = Flag.integer("priority").pipe(
68
+ const priorityOption = Flag.Int("priority").pipe(
60
69
  Flag.withDescription("Priority from 0 (none) to 4 (low)"),
61
70
  Flag.optional,
62
71
  );
63
72
 
64
- const dryRunOption = Flag.boolean("dry-run").pipe(
73
+ const dryRunOption = Flag.Boolean("dry-run").pipe(
74
+ Flag.withDefault(false),
65
75
  Flag.withDescription("Validate and print the mutation without writing"),
66
76
  );
67
77
 
68
- const interactiveOption = Flag.boolean("interactive").pipe(
78
+ const interactiveOption = Flag.Boolean("interactive").pipe(
79
+ Flag.withDefault(false),
69
80
  Flag.withDescription("Allow prompts when required input is missing"),
70
81
  );
71
82
 
72
- const bodyOption = Flag.string("body").pipe(Flag.withDescription("Comment body in Markdown"));
83
+ const bodyOption = Flag.String("body").pipe(Flag.withDescription("Comment body in Markdown"));
73
84
 
74
85
  // Args
75
- const issueIdsArg = Argument.string("id").pipe(
86
+ const issueIdsArg = Argument.String("id").pipe(
76
87
  Argument.withDescription("Issue ID, URL, or identifier (repeat for bulk reads)"),
77
88
  Argument.variadic(),
78
89
  );
@@ -94,7 +105,7 @@ export const issueListCommand = Command.make(
94
105
  const issues = yield* linear.getMyIssues({ state: stateFilter, limit });
95
106
 
96
107
  if (issues.length === 0) {
97
- yield* Console.log(json ? "[]" : "No issues found.");
108
+ yield* logEmptyList(json, "No issues found.");
98
109
  return;
99
110
  }
100
111
 
@@ -151,10 +162,11 @@ export const issueViewCommand = Command.make(
151
162
  "Issue identifier required in non-interactive mode. Usage: linear issue view ISSUE-123 --json",
152
163
  });
153
164
  }
154
- const selectedIds = yield* Effect.forEach(
155
- ids.length === 0 ? [yield* selectIssue] : ids,
156
- parseIssueSelector,
157
- );
165
+ let requestedIds: ReadonlyArray<string> = ids;
166
+ if (requestedIds.length === 0) {
167
+ requestedIds = [yield* selectIssue];
168
+ }
169
+ const selectedIds = yield* Effect.forEach(requestedIds, parseIssueSelector);
158
170
  const linear = yield* LinearService;
159
171
  const details = yield* Effect.forEach(
160
172
  selectedIds,
@@ -182,7 +194,7 @@ export const issueViewCommand = Command.make(
182
194
  );
183
195
 
184
196
  // linear issue start [id] - Start working on an issue
185
- const optionalIssueIdArg = Argument.string("id").pipe(
197
+ const optionalIssueIdArg = Argument.String("id").pipe(
186
198
  Argument.withDescription("Issue ID, URL, or identifier"),
187
199
  Argument.optional,
188
200
  );
@@ -198,13 +210,15 @@ export const issueStartCommand = Command.make(
198
210
  ({ id, dryRun, json, interactive }) =>
199
211
  Effect.gen(function* () {
200
212
  const selectedIssue = yield* Option.match(id, {
201
- onNone: () =>
202
- interactive
203
- ? selectIssue
204
- : InvalidInputError.make({
205
- message:
206
- "Issue identifier required in non-interactive mode. Usage: linear issue start ISSUE-123 --dry-run",
207
- }),
213
+ onNone: () => {
214
+ if (interactive) {
215
+ return selectIssue;
216
+ }
217
+ return InvalidInputError.make({
218
+ message:
219
+ "Issue identifier required in non-interactive mode. Usage: linear issue start ISSUE-123 --dry-run",
220
+ });
221
+ },
208
222
  onSome: Effect.succeed,
209
223
  });
210
224
  const issueId = yield* parseIssueSelector(selectedIssue);
@@ -284,17 +298,19 @@ export const issueCreateCommand = Command.make(
284
298
  const requestedTeam = Option.getOrUndefined(team) ?? linearConfig.teamId;
285
299
  const teamId = yield* resolveTeamId(teams, requestedTeam, isInteractive);
286
300
  const issueTitle = yield* Option.match(title, {
287
- onNone: () => Prompt.text({ message: "Issue title" }),
301
+ onNone: () => Prompt.String({ message: "Issue title" }),
288
302
  onSome: Effect.succeed,
289
303
  });
290
304
  const issueDescription = yield* Option.match(description, {
291
- onNone: () =>
292
- isInteractive
293
- ? Prompt.text({
294
- message: "Description (optional, press Enter to skip)",
295
- default: "",
296
- })
297
- : Effect.succeed(""),
305
+ onNone: () => {
306
+ if (isInteractive) {
307
+ return Prompt.String({
308
+ message: "Description (optional, press Enter to skip)",
309
+ default: "",
310
+ });
311
+ }
312
+ return Effect.succeed("");
313
+ },
298
314
  onSome: Effect.succeed,
299
315
  });
300
316
  const validatedTitle = yield* validateText({
@@ -314,16 +330,16 @@ export const issueCreateCommand = Command.make(
314
330
  }
315
331
 
316
332
  const projectSelector = Option.getOrUndefined(project);
317
- const projectId =
318
- projectSelector === undefined
319
- ? undefined
320
- : yield* resolveProjectId(yield* linear.getProjects, projectSelector);
333
+ let projectId: string | undefined = undefined;
334
+ if (projectSelector !== undefined) {
335
+ projectId = yield* resolveProjectId(yield* linear.getProjects, projectSelector);
336
+ }
321
337
  const input = {
322
338
  title: validatedTitle,
323
339
  teamId,
324
- description: validatedDescription.length === 0 ? undefined : validatedDescription,
340
+ description: emptyToUndefined(validatedDescription),
325
341
  parent: yield* Option.match(parent, {
326
- onNone: () => Effect.succeed(undefined),
342
+ onNone: () => succeedUndefined,
327
343
  onSome: parseIssueSelector,
328
344
  }),
329
345
  projectId,
@@ -365,7 +381,7 @@ export const issueCreateCommand = Command.make(
365
381
  export const issueCommentCommand = Command.make(
366
382
  "comment",
367
383
  {
368
- id: Argument.string("id").pipe(Argument.withDescription("Issue ID, URL, or identifier")),
384
+ id: Argument.String("id").pipe(Argument.withDescription("Issue ID, URL, or identifier")),
369
385
  body: bodyOption,
370
386
  dryRun: dryRunOption,
371
387
  json: jsonFlag,
@@ -411,6 +427,69 @@ export const issueCommentCommand = Command.make(
411
427
  ]),
412
428
  );
413
429
 
430
+ const downloadOption = Flag.Boolean("download").pipe(
431
+ Flag.withDefault(false),
432
+ Flag.withDescription("Save every listed file into --output-dir"),
433
+ );
434
+
435
+ // linear issue files <id> - List (and optionally download) files uploaded to an issue
436
+ export const issueFilesCommand = Command.make(
437
+ "files",
438
+ {
439
+ id: Argument.String("id").pipe(Argument.withDescription("Issue ID, URL, or identifier")),
440
+ download: downloadOption,
441
+ outputDir: outputDirFlag,
442
+ overwrite: overwriteFlag,
443
+ json: jsonFlag,
444
+ },
445
+ ({ id, download, outputDir, overwrite, json }) =>
446
+ Effect.gen(function* () {
447
+ const issueId = yield* parseIssueSelector(id);
448
+ const linear = yield* LinearService;
449
+ const details = yield* linear.getIssueDetails(issueId, {
450
+ comments: true,
451
+ children: false,
452
+ relations: false,
453
+ });
454
+ const files = uniqueByUrl([
455
+ ...extractUploadLinks(details.description, "description"),
456
+ ...(details.comments ?? []).flatMap((comment) =>
457
+ extractUploadLinks(comment.body, comment.id),
458
+ ),
459
+ ]);
460
+
461
+ if (!download) {
462
+ if (json) {
463
+ yield* Console.log(encodeJson(files));
464
+ return;
465
+ }
466
+ if (files.length === 0) {
467
+ yield* Console.log(`No files found on ${details.identifier}.`);
468
+ return;
469
+ }
470
+ for (const issueFile of files) {
471
+ yield* Console.log(`${issueFile.name}\t${issueFile.source}\t${issueFile.url}`);
472
+ }
473
+ return;
474
+ }
475
+
476
+ const requests = yield* Effect.forEach(files, (issueFile) =>
477
+ parseUploadUrl(issueFile.url).pipe(Effect.map((url) => ({ url, name: issueFile.name }))),
478
+ );
479
+ const savedFiles = yield* saveDownloads({ requests, outputDir, overwrite });
480
+ yield* logSavedFiles(savedFiles, json);
481
+ }),
482
+ ).pipe(
483
+ Command.withDescription("List files uploaded to an issue's description and comments"),
484
+ Command.withExamples([
485
+ { command: "linear issue files ENG-123 --json", description: "List uploads as JSON" },
486
+ {
487
+ command: "linear issue files ENG-123 --download --output-dir ./files --json",
488
+ description: "Save every upload under its Markdown name",
489
+ },
490
+ ]),
491
+ );
492
+
414
493
  // Combined issue command with subcommands
415
494
  export const issue = Command.make("issue", {}, () =>
416
495
  Console.log("Use 'linear issue list' to list issues. See --help for more."),
@@ -422,6 +501,7 @@ export const issue = Command.make("issue", {}, () =>
422
501
  issueStartCommand,
423
502
  issueCreateCommand,
424
503
  issueCommentCommand,
504
+ issueFilesCommand,
425
505
  ]),
426
506
  );
427
507
 
@@ -429,8 +509,10 @@ export const issue = Command.make("issue", {}, () =>
429
509
 
430
510
  const selectIssue = Effect.gen(function* () {
431
511
  const linear = yield* LinearService;
432
- const issues = yield* linear.getMyIssues({ state: "started" });
433
- const allIssues = issues.length > 0 ? issues : yield* linear.getMyIssues({ state: "unstarted" });
512
+ let allIssues = yield* linear.getMyIssues({ state: "started" });
513
+ if (allIssues.length === 0) {
514
+ allIssues = yield* linear.getMyIssues({ state: "unstarted" });
515
+ }
434
516
 
435
517
  if (allIssues.length === 0) {
436
518
  return yield* NoIssuesError.default;
@@ -443,7 +525,7 @@ const selectIssue = Effect.gen(function* () {
443
525
  description: candidate.state?.name ?? "Unknown state",
444
526
  }));
445
527
 
446
- const selected = yield* Prompt.select({
528
+ const selected = yield* Prompt.Select({
447
529
  message: "Select an issue",
448
530
  choices,
449
531
  });
@@ -496,7 +578,7 @@ const renderIssueDetails = Effect.fn("IssueCommand.renderDetails")(function* (
496
578
  });
497
579
 
498
580
  function selectTeam(teams: readonly { id: string; key: string; name: string }[]) {
499
- return Prompt.select({
581
+ return Prompt.Select({
500
582
  message: "Select a team",
501
583
  choices: teams.map((team) => ({
502
584
  title: `${team.key}: ${team.name}`,
@@ -515,19 +597,24 @@ const resolveTeamId = Effect.fn("IssueCommand.resolveTeamId")(function* (
515
597
  const selected = teams.find(
516
598
  (team) => team.id === selector || team.key.toLowerCase() === normalized,
517
599
  );
518
- return selected === undefined
519
- ? yield* InvalidInputError.make({ message: `Unknown team: ${selector}` })
520
- : selected.id;
600
+ if (selected === undefined) {
601
+ return yield* InvalidInputError.make({ message: `Unknown team: ${selector}` });
602
+ }
603
+ return selected.id;
521
604
  }
522
605
  if (teams.length === 1) {
523
606
  const [team] = teams;
524
- return team === undefined
525
- ? yield* InvalidInputError.make({ message: "No team available" })
526
- : team.id;
607
+ if (team === undefined) {
608
+ return yield* InvalidInputError.make({ message: "No team available" });
609
+ }
610
+ return team.id;
611
+ }
612
+ if (interactive) {
613
+ return yield* selectTeam(teams);
527
614
  }
528
- return interactive
529
- ? yield* selectTeam(teams)
530
- : yield* InvalidInputError.make({ message: "--team is required when multiple teams exist" });
615
+ return yield* InvalidInputError.make({
616
+ message: "--team is required when multiple teams exist",
617
+ });
531
618
  });
532
619
 
533
620
  const resolveProjectId = Effect.fn("IssueCommand.resolveProjectId")(function* (
@@ -541,9 +628,10 @@ const resolveProjectId = Effect.fn("IssueCommand.resolveProjectId")(function* (
541
628
  project.name.toLowerCase() === normalized ||
542
629
  project.slug.toLowerCase() === normalized,
543
630
  );
544
- return selected === undefined
545
- ? yield* InvalidInputError.make({ message: `Unknown project: ${selector}` })
546
- : selected.id;
631
+ if (selected === undefined) {
632
+ return yield* InvalidInputError.make({ message: `Unknown project: ${selector}` });
633
+ }
634
+ return selected.id;
547
635
  });
548
636
 
549
637
  const toCreatedIssue = (created: {
@@ -559,7 +647,24 @@ const toCreatedIssue = (created: {
559
647
  });
560
648
 
561
649
  function truncate(str: string, len: number): string {
562
- return str.length > len ? str.slice(0, len - 1) + "…" : str;
650
+ if (str.length > len) {
651
+ return str.slice(0, len - 1) + "…";
652
+ }
653
+ return str;
654
+ }
655
+
656
+ function emptyToUndefined(value: string): string | undefined {
657
+ if (value.length === 0) {
658
+ return undefined;
659
+ }
660
+ return value;
661
+ }
662
+
663
+ function logEmptyList(json: boolean, message: string): Effect.Effect<void> {
664
+ if (json) {
665
+ return Console.log("[]");
666
+ }
667
+ return Console.log(message);
563
668
  }
564
669
 
565
670
  function getPriorityIcon(priority: number): string {
@@ -1,5 +1,5 @@
1
1
  import { Console, Effect } from "effect";
2
- import { Command } from "effect/unstable/cli";
2
+ import { Command } from "effect/cli";
3
3
  import { jsonFlag } from "../lib/flags.js";
4
4
  import { encodeJson } from "../lib/json.js";
5
5
  import { LinearService } from "../services/Linear.js";
@@ -1,4 +1,4 @@
1
- import { Command } from "effect/unstable/cli";
1
+ import { Command } from "effect/cli";
2
2
  import { Console, Effect } from "effect";
3
3
  import { jsonFlag } from "../lib/flags.js";
4
4
  import { encodeJson } from "../lib/json.js";
@@ -11,7 +11,11 @@ export const teamListCommand = Command.make("list", { json: jsonFlag }, ({ json
11
11
  const teams = yield* linear.getTeams;
12
12
 
13
13
  if (teams.length === 0) {
14
- yield* Console.log(json ? "[]" : "No teams found.");
14
+ if (json) {
15
+ yield* Console.log("[]");
16
+ } else {
17
+ yield* Console.log("No teams found.");
18
+ }
15
19
  return;
16
20
  }
17
21
 
@@ -34,9 +38,7 @@ export const teamListCommand = Command.make("list", { json: jsonFlag }, ({ json
34
38
  for (const team of teams) {
35
39
  const key = team.key;
36
40
  const name = team.name;
37
- const description =
38
- team.description !== undefined && team.description !== null ? ` - ${team.description}` : "";
39
- yield* Console.log(` ${key.padEnd(8)} ${name}${description}`);
41
+ yield* Console.log(` ${key.padEnd(8)} ${name}${formatDescription(team.description)}`);
40
42
  }
41
43
 
42
44
  yield* Console.log("");
@@ -53,3 +55,10 @@ export const teamListCommand = Command.make("list", { json: jsonFlag }, ({ json
53
55
  export const team = Command.make("team", {}, () =>
54
56
  Console.log("Use 'linear team list' to list teams. See --help for more."),
55
57
  ).pipe(Command.withDescription("Manage Linear teams"), Command.withSubcommands([teamListCommand]));
58
+
59
+ function formatDescription(description: string | null | undefined): string {
60
+ if (description === undefined || description === null) {
61
+ return "";
62
+ }
63
+ return ` - ${description}`;
64
+ }
@@ -0,0 +1,81 @@
1
+ import { Result } from "effect";
2
+ import { IssueFile } from "./Linear.js";
3
+
4
+ // Markdown links and images whose target is a Linear upload: `[name](url)` or `![name](url)`.
5
+ const uploadLinkPattern = /!?\[([^\]]*)\]\(<?(https:\/\/uploads\.linear\.app\/[^)\s>]+)>?\)/g;
6
+
7
+ export const extractUploadLinks = (
8
+ markdown: string | undefined,
9
+ source: string,
10
+ ): ReadonlyArray<IssueFile> => {
11
+ if (markdown === undefined) {
12
+ return [];
13
+ }
14
+ return Array.from(markdown.matchAll(uploadLinkPattern), (match) =>
15
+ IssueFile.make({ name: match[1] ?? "", url: match[2] ?? "", source }),
16
+ );
17
+ };
18
+
19
+ /** Keeps the first link to each URL. */
20
+ export const uniqueByUrl = (files: ReadonlyArray<IssueFile>): ReadonlyArray<IssueFile> => {
21
+ const seenUrls = new Set<string>();
22
+ return files.filter((file) => {
23
+ if (seenUrls.has(file.url)) {
24
+ return false;
25
+ }
26
+ seenUrls.add(file.url);
27
+ return true;
28
+ });
29
+ };
30
+
31
+ const unsafeFileNameCharacters = /[^A-Za-z0-9._ ()-]/g;
32
+
33
+ /** A plain file name that cannot leave the output directory. */
34
+ export const toSafeFileName = (candidate: string): string => {
35
+ const baseName = candidate.split(/[/\\]/).pop() ?? "";
36
+ const cleaned = baseName
37
+ .replace(unsafeFileNameCharacters, "_")
38
+ .replace(/^[.\s]+/, "")
39
+ .trim();
40
+ if (cleaned.length === 0) {
41
+ return "download";
42
+ }
43
+ return cleaned;
44
+ };
45
+
46
+ const splitExtension = (
47
+ fileName: string,
48
+ ): { readonly stem: string; readonly extension: string } => {
49
+ const dotIndex = fileName.lastIndexOf(".");
50
+ if (dotIndex <= 0) {
51
+ return { stem: fileName, extension: "" };
52
+ }
53
+ return { stem: fileName.slice(0, dotIndex), extension: fileName.slice(dotIndex) };
54
+ };
55
+
56
+ /** `report.pdf`, then `report-2.pdf`, `report-3.pdf`, ... for names already taken in this run. */
57
+ export const withUniqueSuffix = (fileName: string, takenNames: ReadonlySet<string>): string => {
58
+ if (!takenNames.has(fileName)) {
59
+ return fileName;
60
+ }
61
+ const { stem, extension } = splitExtension(fileName);
62
+ let counter = 2;
63
+ while (takenNames.has(`${stem}-${counter}${extension}`)) {
64
+ counter += 1;
65
+ }
66
+ return `${stem}-${counter}${extension}`;
67
+ };
68
+
69
+ const contentDispositionFileName = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i;
70
+
71
+ export const fileNameFromContentDisposition = (header: string | null): string | undefined => {
72
+ const match = header?.match(contentDispositionFileName);
73
+ if (match?.[1] === undefined) {
74
+ return undefined;
75
+ }
76
+ const rawName = match[1];
77
+ return Result.getOrElse(
78
+ Result.try(() => decodeURIComponent(rawName)),
79
+ () => rawName,
80
+ );
81
+ };
@@ -1,5 +1,5 @@
1
1
  import { Effect } from "effect";
2
- import { IssueSelector } from "./Linear.js";
2
+ import { IssueSelector, UploadUrl } from "./Linear.js";
3
3
  import { InvalidInputError } from "../lib/errors.js";
4
4
 
5
5
  const issueIdentifierPattern = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
@@ -53,3 +53,16 @@ export const validateText = Effect.fn("Input.validateText")(function* (options:
53
53
  }
54
54
  return options.value;
55
55
  });
56
+
57
+ const uploadHost = "uploads.linear.app";
58
+
59
+ // The stored token is sent with the download, so only Linear's own upload host is accepted.
60
+ export const parseUploadUrl = Effect.fn("Input.parseUploadUrl")(function* (input: string) {
61
+ const url = URL.parse(input);
62
+ if (url === null || url.protocol !== "https:" || url.hostname !== uploadHost) {
63
+ return yield* InvalidInputError.make({
64
+ message: `Invalid upload URL: ${input}. Expected https://${uploadHost}/...`,
65
+ });
66
+ }
67
+ return UploadUrl.make(url.href);
68
+ });
@@ -3,6 +3,9 @@ import { Schema } from "effect";
3
3
  export const IssueSelector = Schema.String.pipe(Schema.brand("IssueSelector"));
4
4
  export type IssueSelector = Schema.Schema.Type<typeof IssueSelector>;
5
5
 
6
+ export const UploadUrl = Schema.String.pipe(Schema.brand("UploadUrl"));
7
+ export type UploadUrl = Schema.Schema.Type<typeof UploadUrl>;
8
+
6
9
  export class ViewerStatus extends Schema.Class<ViewerStatus>("ViewerStatus")({
7
10
  emoji: Schema.optional(Schema.String),
8
11
  label: Schema.optional(Schema.String),
@@ -45,7 +48,7 @@ export class IssueState extends Schema.Class<IssueState>("IssueState")({
45
48
  }) {}
46
49
 
47
50
  export class IssuePriority extends Schema.Class<IssuePriority>("IssuePriority")({
48
- value: Schema.Number,
51
+ value: Schema.Finite,
49
52
  label: Schema.String,
50
53
  }) {}
51
54
 
@@ -132,3 +135,24 @@ export interface CreateIssueInput {
132
135
  readonly projectId?: string;
133
136
  readonly priority?: number;
134
137
  }
138
+
139
+ export class IssueFile extends Schema.Class<IssueFile>("IssueFile")({
140
+ name: Schema.String,
141
+ url: Schema.String,
142
+ /** `description`, or the ID of the comment that links the file. */
143
+ source: Schema.String,
144
+ }) {}
145
+
146
+ export class SavedFile extends Schema.Class<SavedFile>("SavedFile")({
147
+ url: Schema.String,
148
+ path: Schema.String,
149
+ bytes: Schema.Finite,
150
+ contentType: Schema.optional(Schema.String),
151
+ }) {}
152
+
153
+ export interface DownloadedFile {
154
+ readonly bytes: Uint8Array;
155
+ readonly contentType?: string;
156
+ /** From the `Content-Disposition` header, when the server sends one. */
157
+ readonly fileName?: string;
158
+ }
@@ -0,0 +1,71 @@
1
+ import { Effect, FileSystem, Path } from "effect";
2
+ import { toSafeFileName, withUniqueSuffix } from "../domain/Files.js";
3
+ import { SavedFile } from "../domain/Linear.js";
4
+ import type { DownloadedFile, UploadUrl } from "../domain/Linear.js";
5
+ import { LinearService } from "../services/Linear.js";
6
+ import { FileWriteError, InvalidInputError } from "./errors.js";
7
+
8
+ export interface DownloadRequest {
9
+ readonly url: UploadUrl;
10
+ /** The name the Markdown link gave the file, when there is one. */
11
+ readonly name?: string;
12
+ }
13
+
14
+ const toFileWriteError = (error: unknown): FileWriteError =>
15
+ FileWriteError.make({ message: String(error) });
16
+
17
+ const nonEmpty = (value: string | undefined): string | undefined => {
18
+ if (value === undefined || value.trim().length === 0) {
19
+ return undefined;
20
+ }
21
+ return value;
22
+ };
23
+
24
+ const preferredFileName = (request: DownloadRequest, download: DownloadedFile): string =>
25
+ nonEmpty(request.name) ??
26
+ nonEmpty(download.fileName) ??
27
+ new URL(request.url).pathname.split("/").pop() ??
28
+ "download";
29
+
30
+ export const saveDownloads = Effect.fn("saveDownloads")(function* (options: {
31
+ readonly requests: ReadonlyArray<DownloadRequest>;
32
+ readonly outputDir: string;
33
+ readonly overwrite: boolean;
34
+ }) {
35
+ const fileSystem = yield* FileSystem.FileSystem;
36
+ const path = yield* Path.Path;
37
+ const linear = yield* LinearService;
38
+
39
+ yield* fileSystem
40
+ .makeDirectory(options.outputDir, { recursive: true })
41
+ .pipe(Effect.mapError(toFileWriteError));
42
+
43
+ const takenNames = new Set<string>();
44
+ const savedFiles: Array<SavedFile> = [];
45
+ for (const request of options.requests) {
46
+ const download = yield* linear.downloadFile(request.url);
47
+ const fileName = withUniqueSuffix(
48
+ toSafeFileName(preferredFileName(request, download)),
49
+ takenNames,
50
+ );
51
+ takenNames.add(fileName);
52
+ const target = path.join(options.outputDir, fileName);
53
+
54
+ const exists = yield* fileSystem.exists(target).pipe(Effect.mapError(toFileWriteError));
55
+ if (exists && !options.overwrite) {
56
+ return yield* InvalidInputError.make({
57
+ message: `${target} already exists. Pass --overwrite to replace it.`,
58
+ });
59
+ }
60
+ yield* fileSystem.writeFile(target, download.bytes).pipe(Effect.mapError(toFileWriteError));
61
+ savedFiles.push(
62
+ SavedFile.make({
63
+ url: request.url,
64
+ path: target,
65
+ bytes: download.bytes.byteLength,
66
+ contentType: download.contentType,
67
+ }),
68
+ );
69
+ }
70
+ return savedFiles;
71
+ });
@@ -0,0 +1,9 @@
1
+ import { Effect } from "effect";
2
+
3
+ /**
4
+ * An Effect that yields absent optional data.
5
+ *
6
+ * Typed as `undefined` rather than `void` because these values populate
7
+ * `Schema.optional` fields, whose encoded type is `T | undefined`.
8
+ */
9
+ export const succeedUndefined: Effect.Effect<undefined> = Effect.as(Effect.void, undefined);