@cvr/linear 0.1.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.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # Linear CLI
2
+
3
+ A command-line interface for [Linear](https://linear.app) built with Bun and Effect TypeScript.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # Clone and build
9
+ git clone <repo>
10
+ cd linear
11
+ bun install
12
+ bun run build
13
+
14
+ # Add to PATH (symlink to ~/.local/bin)
15
+ bun run link
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```bash
21
+ # Authenticate (required first)
22
+ linear auth
23
+
24
+ # Check current user
25
+ linear auth whoami
26
+
27
+ # List your issues
28
+ linear issue list
29
+
30
+ # Start working on an issue
31
+ linear issue start ABC-123
32
+
33
+ # View issue details
34
+ linear issue view ABC-123
35
+
36
+ # Create a new issue
37
+ linear issue create
38
+
39
+ # List teams
40
+ linear team list
41
+ ```
42
+
43
+ ## Commands
44
+
45
+ ### Authentication
46
+
47
+ | Command | Description |
48
+ |---------|-------------|
49
+ | `linear auth` | Authenticate with Linear (opens browser for API key) |
50
+ | `linear auth whoami` | Show current user info |
51
+
52
+ ### Issues
53
+
54
+ | Command | Description |
55
+ |---------|-------------|
56
+ | `linear issue list` | List your assigned issues |
57
+ | `linear issue view [id]` | View issue details (interactive picker if no ID) |
58
+ | `linear issue start [id]` | Start working on an issue |
59
+ | `linear issue create` | Create a new issue |
60
+
61
+ ### Teams
62
+
63
+ | Command | Description |
64
+ |---------|-------------|
65
+ | `linear team list` | List all teams |
66
+
67
+ ## Configuration
68
+
69
+ - **Token**: `~/.config/linear/token`
70
+ - **Global config**: `~/.config/linear/config.toml`
71
+ - **Project config**: `.linear.toml` in repo root
72
+
73
+ ### Project Config Example
74
+
75
+ Create a `.linear.toml` in your project root to set defaults:
76
+
77
+ ```toml
78
+ team_id = "ENG"
79
+ ```
80
+
81
+ ### Environment Variables
82
+
83
+ - `LINEAR_API_KEY`: Alternative to config file token
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ # Install dependencies
89
+ bun install
90
+
91
+ # Run tests
92
+ bun run test
93
+
94
+ # Build binary
95
+ bun run build
96
+
97
+ # Run without building
98
+ bun run src/main.ts --help
99
+ ```
100
+
101
+ ## Architecture
102
+
103
+ Built with:
104
+ - **[Bun](https://bun.sh)**: Fast JavaScript runtime with native compilation
105
+ - **[Effect](https://effect.website)**: TypeScript library for type-safe, composable code
106
+ - **[@effect/cli](https://github.com/Effect-TS/effect/tree/main/packages/cli)**: CLI framework with prompts and argument parsing
107
+ - **[@linear/sdk](https://github.com/linear/linear)**: Official Linear GraphQL SDK
108
+
109
+ ## Credits
110
+
111
+ Inspired by [schpet/linear-cli](https://github.com/schpet/linear-cli) - the original Linear CLI built with Deno and Cliffy.
112
+
113
+ ## License
114
+
115
+ MIT
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@cvr/linear",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "bin": {
6
+ "linear": "./bin/linear"
7
+ },
8
+ "files": [
9
+ "src",
10
+ "bin",
11
+ "tsconfig.json"
12
+ ],
13
+ "scripts": {
14
+ "build": "bun build ./src/main.ts --compile --outfile bin/linear",
15
+ "postinstall": "bun run build",
16
+ "prepublishOnly": "rm -rf bin",
17
+ "test": "vitest run",
18
+ "test:watch": "vitest",
19
+ "link": "ln -sf $(pwd)/bin/linear ~/.local/bin/linear",
20
+ "prepare": "effect-language-service patch",
21
+ "version": "changeset version",
22
+ "release": "changeset publish"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/cevr/linear-cli.git"
30
+ },
31
+ "engines": {
32
+ "bun": ">=1.0.0"
33
+ },
34
+ "dependencies": {
35
+ "effect": "^3.12.7",
36
+ "@effect/cli": "^0.56.6",
37
+ "@effect/platform": "^0.87.0",
38
+ "@effect/platform-bun": "^0.87.0",
39
+ "@linear/sdk": "^29.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@changesets/changelog-github": "^0.5.0",
43
+ "@changesets/cli": "^2.27.0",
44
+ "@effect/language-service": "^0.65.0",
45
+ "@effect/vitest": "^0.27.0",
46
+ "@types/bun": "latest",
47
+ "typescript": "^5.7.3",
48
+ "vitest": "^2.1.8"
49
+ }
50
+ }
@@ -0,0 +1,69 @@
1
+ import { Command } from "@effect/cli"
2
+ import { Console, Effect } from "effect"
3
+ import { ConfigService } from "../services/Config.js"
4
+ import { LinearService } from "../services/Linear.js"
5
+ import { BrowserService } from "../services/Browser.js"
6
+ import { StdinService } from "../services/Stdin.js"
7
+
8
+ const LINEAR_API_KEY_URL = "https://linear.app/settings/account/security"
9
+
10
+ // linear auth - Interactive authentication flow
11
+ export const authCommand = Command.make("auth", {}, () =>
12
+ Effect.gen(function* () {
13
+ const browser = yield* BrowserService
14
+ const config = yield* ConfigService
15
+ const stdin = yield* StdinService
16
+
17
+ yield* Console.log(`\nTo authenticate, you'll need a Linear API key.`)
18
+ yield* Console.log(`Opening: ${LINEAR_API_KEY_URL}\n`)
19
+
20
+ // Open browser
21
+ yield* browser.open(LINEAR_API_KEY_URL).pipe(
22
+ Effect.catchAll(() =>
23
+ Console.log(`Could not open browser. Please visit the URL manually.`)
24
+ )
25
+ )
26
+
27
+ // Simple prompt using readline
28
+ const token = yield* stdin.readLine("Paste your API key: ")
29
+
30
+ // Validate token by making an API call
31
+ yield* Console.log("\nValidating token...")
32
+
33
+ // Save token first so LinearService can use it
34
+ yield* config.saveToken(token)
35
+
36
+ // Now validate with the saved token
37
+ const linear = yield* LinearService
38
+ const viewer = yield* linear.getViewer.pipe(
39
+ Effect.catchTag("InvalidTokenError", (e) =>
40
+ Effect.gen(function* () {
41
+ yield* Console.error(`\nError: ${e.message}`)
42
+ yield* Console.error("Please try again with a valid API key.")
43
+ return yield* Effect.die(e)
44
+ })
45
+ )
46
+ )
47
+
48
+ yield* Console.log(`\nAuthenticated as ${viewer.name} (${viewer.email})`)
49
+ })
50
+ )
51
+
52
+ // linear auth whoami - Show current user
53
+ export const whoamiCommand = Command.make("whoami", {}, () =>
54
+ Effect.gen(function* () {
55
+ const linear = yield* LinearService
56
+ const viewer = yield* linear.getViewer
57
+
58
+ yield* Console.log(`\nLogged in as:`)
59
+ yield* Console.log(` Name: ${viewer.name}`)
60
+ yield* Console.log(` Email: ${viewer.email}`)
61
+ yield* Console.log(` Admin: ${viewer.admin ? "Yes" : "No"}`)
62
+ if (viewer.statusLabel) {
63
+ yield* Console.log(` Status: ${viewer.statusEmoji ?? ""} ${viewer.statusLabel}`)
64
+ }
65
+ })
66
+ )
67
+
68
+ // Combined auth command with subcommands
69
+ export const auth = authCommand.pipe(Command.withSubcommands([whoamiCommand]))
@@ -0,0 +1,330 @@
1
+ import { Args, Command, Options, Prompt } from "@effect/cli"
2
+ import { Console, Effect, Option } from "effect"
3
+ import { LinearService } from "../services/Linear.js"
4
+ import { ConfigService } from "../services/Config.js"
5
+
6
+ // Options
7
+ const stateOption = Options.text("state").pipe(
8
+ Options.withAlias("s"),
9
+ Options.withDescription("Filter by state type (started, unstarted, backlog, etc.)"),
10
+ Options.optional
11
+ )
12
+
13
+ const teamOption = Options.text("team").pipe(
14
+ Options.withAlias("t"),
15
+ Options.withDescription("Filter by team key or ID"),
16
+ Options.optional
17
+ )
18
+
19
+ const limitOption = Options.integer("limit").pipe(
20
+ Options.withAlias("n"),
21
+ Options.withDefault(20),
22
+ Options.withDescription("Number of issues to show")
23
+ )
24
+
25
+ // Args
26
+ const issueIdArg = Args.text({ name: "id" }).pipe(
27
+ Args.withDescription("Issue ID or identifier (e.g., ABC-123)"),
28
+ Args.optional
29
+ )
30
+
31
+ // linear issue list - List issues
32
+ export const issueListCommand = Command.make(
33
+ "list",
34
+ { state: stateOption, team: teamOption, limit: limitOption },
35
+ ({ state, team, limit }) =>
36
+ Effect.gen(function* () {
37
+ const linear = yield* LinearService
38
+
39
+ const stateFilter = Option.getOrUndefined(state) as any
40
+ const issues = yield* linear.getMyIssues({ state: stateFilter })
41
+
42
+ if (issues.length === 0) {
43
+ yield* Console.log("No issues found.")
44
+ return
45
+ }
46
+
47
+ yield* Console.log("\nYour Issues:\n")
48
+
49
+ const displayed = issues.slice(0, limit)
50
+ for (const issue of displayed) {
51
+ const state = yield* Effect.tryPromise({
52
+ try: () => issue.state,
53
+ catch: () => null,
54
+ })
55
+ const stateName = state?.name ?? "Unknown"
56
+ const priority = issue.priority ?? 0
57
+ const priorityIcon = getPriorityIcon(priority)
58
+
59
+ yield* Console.log(
60
+ ` ${priorityIcon} ${issue.identifier.padEnd(10)} ${stateName.padEnd(12)} ${truncate(issue.title, 50)}`
61
+ )
62
+ }
63
+
64
+ if (issues.length > limit) {
65
+ yield* Console.log(`\n ... and ${issues.length - limit} more`)
66
+ }
67
+
68
+ yield* Console.log("")
69
+ })
70
+ )
71
+
72
+ // linear issue view [id] - View issue details
73
+ export const issueViewCommand = Command.make(
74
+ "view",
75
+ { id: issueIdArg },
76
+ ({ id }) =>
77
+ Effect.gen(function* () {
78
+ const linear = yield* LinearService
79
+
80
+ // If no ID provided, prompt for selection
81
+ const issueId = yield* Option.match(id, {
82
+ onNone: () => selectIssue(linear),
83
+ onSome: (id) => Effect.succeed(id),
84
+ })
85
+
86
+ const issue = yield* linear.getIssue(issueId)
87
+ const state = yield* Effect.tryPromise({
88
+ try: () => issue.state,
89
+ catch: () => null,
90
+ })
91
+ const assignee = yield* Effect.tryPromise({
92
+ try: () => issue.assignee,
93
+ catch: () => null,
94
+ })
95
+ const team = yield* Effect.tryPromise({
96
+ try: () => issue.team,
97
+ catch: () => null,
98
+ })
99
+
100
+ yield* Console.log("")
101
+ yield* Console.log(`${issue.identifier}: ${issue.title}`)
102
+ yield* Console.log(`${"─".repeat(60)}`)
103
+ yield* Console.log(`State: ${state?.name ?? "Unknown"}`)
104
+ yield* Console.log(`Team: ${team?.name ?? "Unknown"}`)
105
+ yield* Console.log(`Priority: ${getPriorityLabel(issue.priority ?? 0)}`)
106
+ yield* Console.log(`Assignee: ${assignee?.name ?? "Unassigned"}`)
107
+ yield* Console.log(`URL: ${issue.url}`)
108
+
109
+ if (issue.description) {
110
+ yield* Console.log(`\nDescription:\n${issue.description}`)
111
+ }
112
+
113
+ yield* Console.log("")
114
+ })
115
+ )
116
+
117
+ // linear issue start [id] - Start working on an issue
118
+ export const issueStartCommand = Command.make(
119
+ "start",
120
+ { id: issueIdArg },
121
+ ({ id }) =>
122
+ Effect.gen(function* () {
123
+ const linear = yield* LinearService
124
+
125
+ // If no ID provided, prompt for selection
126
+ const issueId = yield* Option.match(id, {
127
+ onNone: () => selectIssue(linear),
128
+ onSome: (id) => Effect.succeed(id),
129
+ })
130
+
131
+ const issue = yield* linear.getIssue(issueId)
132
+ const team = yield* Effect.tryPromise({
133
+ try: () => issue.team,
134
+ catch: () => null,
135
+ })
136
+
137
+ // Get the "Started" state for this team
138
+ const states = yield* Effect.tryPromise({
139
+ try: async () => {
140
+ if (!team) return []
141
+ const connection = await team.states()
142
+ return connection.nodes
143
+ },
144
+ catch: () => [],
145
+ })
146
+
147
+ const startedState = states.find(
148
+ (s) => s.type === "started" || s.name.toLowerCase() === "in progress"
149
+ )
150
+
151
+ if (startedState) {
152
+ yield* linear.updateIssueState(issue.id, startedState.id)
153
+ yield* Console.log(`\nStarted: ${issue.identifier} - ${issue.title}`)
154
+ yield* Console.log(`State changed to: ${startedState.name}`)
155
+ } else {
156
+ yield* Console.log(`\nCould not find a "started" state for this issue's team.`)
157
+ }
158
+
159
+ // Show branch name for git
160
+ if (issue.branchName) {
161
+ yield* Console.log(`\nBranch name: ${issue.branchName}`)
162
+ }
163
+
164
+ yield* Console.log("")
165
+ })
166
+ )
167
+
168
+ // linear issue create - Create a new issue
169
+ export const issueCreateCommand = Command.make("create", {}, () =>
170
+ Effect.gen(function* () {
171
+ const linear = yield* LinearService
172
+ const config = yield* ConfigService
173
+ const linearConfig = yield* config.getConfig
174
+
175
+ // Get teams for selection
176
+ const teams = yield* linear.getTeams
177
+
178
+ if (teams.length === 0) {
179
+ yield* Console.error("No teams found. Cannot create issue.")
180
+ return
181
+ }
182
+
183
+ // Select team (or use default from config)
184
+ let teamId: string
185
+
186
+ if (linearConfig.teamId) {
187
+ const team = teams.find(
188
+ (t) => t.id === linearConfig.teamId || t.key === linearConfig.teamId
189
+ )
190
+ if (team) {
191
+ teamId = team.id
192
+ yield* Console.log(`Using team from config: ${team.name}`)
193
+ } else {
194
+ teamId = yield* selectTeam(teams)
195
+ }
196
+ } else if (teams.length === 1) {
197
+ teamId = teams[0].id
198
+ yield* Console.log(`Using team: ${teams[0].name}`)
199
+ } else {
200
+ teamId = yield* selectTeam(teams)
201
+ }
202
+
203
+ // Prompt for title
204
+ const title = yield* Prompt.text({
205
+ message: "Issue title",
206
+ })
207
+
208
+ // Prompt for description (optional)
209
+ const description = yield* Prompt.text({
210
+ message: "Description (optional, press Enter to skip)",
211
+ default: "",
212
+ })
213
+
214
+ // Create the issue
215
+ const issue = yield* linear.createIssue({
216
+ title,
217
+ teamId,
218
+ description: description || undefined,
219
+ })
220
+
221
+ yield* Console.log(`\nCreated: ${issue.identifier} - ${issue.title}`)
222
+ yield* Console.log(`URL: ${issue.url}`)
223
+ yield* Console.log("")
224
+ })
225
+ )
226
+
227
+ // Combined issue command with subcommands
228
+ export const issue = Command.make("issue", {}, () =>
229
+ Console.log("Use 'linear issue list' to list issues. See --help for more.")
230
+ ).pipe(
231
+ Command.withSubcommands([
232
+ issueListCommand,
233
+ issueViewCommand,
234
+ issueStartCommand,
235
+ issueCreateCommand,
236
+ ])
237
+ )
238
+
239
+ // Helper functions
240
+
241
+ function selectIssue(
242
+ linear: Context.Tag.Service<typeof LinearService>
243
+ ): Effect.Effect<string, any, any> {
244
+ return Effect.gen(function* () {
245
+ const issues = yield* linear.getMyIssues({ state: "started" })
246
+ const allIssues =
247
+ issues.length > 0
248
+ ? issues
249
+ : yield* linear.getMyIssues({ state: "unstarted" })
250
+
251
+ if (allIssues.length === 0) {
252
+ yield* Console.error("No issues found to select from.")
253
+ return yield* Effect.die("No issues")
254
+ }
255
+
256
+ // Build choices with state info
257
+ const choices = yield* Effect.all(
258
+ allIssues.slice(0, 20).map((issue) =>
259
+ Effect.gen(function* () {
260
+ const state = yield* Effect.tryPromise({
261
+ try: () => issue.state,
262
+ catch: () => null,
263
+ })
264
+ return {
265
+ title: `${issue.identifier}: ${truncate(issue.title, 40)}`,
266
+ value: issue.identifier,
267
+ description: state?.name ?? "Unknown state",
268
+ }
269
+ })
270
+ )
271
+ )
272
+
273
+ const selected = yield* Prompt.select({
274
+ message: "Select an issue",
275
+ choices,
276
+ })
277
+
278
+ return selected
279
+ })
280
+ }
281
+
282
+ function selectTeam(
283
+ teams: readonly { id: string; key: string; name: string }[]
284
+ ): Effect.Effect<string, any, any> {
285
+ return Prompt.select({
286
+ message: "Select a team",
287
+ choices: teams.map((team) => ({
288
+ title: `${team.key}: ${team.name}`,
289
+ value: team.id,
290
+ })),
291
+ })
292
+ }
293
+
294
+ function truncate(str: string, len: number): string {
295
+ return str.length > len ? str.slice(0, len - 1) + "…" : str
296
+ }
297
+
298
+ function getPriorityIcon(priority: number): string {
299
+ switch (priority) {
300
+ case 0:
301
+ return "○" // No priority
302
+ case 1:
303
+ return "⬆" // Urgent
304
+ case 2:
305
+ return "↑" // High
306
+ case 3:
307
+ return "─" // Medium
308
+ case 4:
309
+ return "↓" // Low
310
+ default:
311
+ return "○"
312
+ }
313
+ }
314
+
315
+ function getPriorityLabel(priority: number): string {
316
+ switch (priority) {
317
+ case 0:
318
+ return "No priority"
319
+ case 1:
320
+ return "Urgent"
321
+ case 2:
322
+ return "High"
323
+ case 3:
324
+ return "Medium"
325
+ case 4:
326
+ return "Low"
327
+ default:
328
+ return "Unknown"
329
+ }
330
+ }
@@ -0,0 +1,32 @@
1
+ import { Command } from "@effect/cli"
2
+ import { Console, Effect } from "effect"
3
+ import { LinearService } from "../services/Linear.js"
4
+
5
+ // linear team list - List all teams
6
+ export const teamListCommand = Command.make("list", {}, () =>
7
+ Effect.gen(function* () {
8
+ const linear = yield* LinearService
9
+ const teams = yield* linear.getTeams
10
+
11
+ if (teams.length === 0) {
12
+ yield* Console.log("No teams found.")
13
+ return
14
+ }
15
+
16
+ yield* Console.log("\nTeams:\n")
17
+
18
+ for (const team of teams) {
19
+ const key = team.key
20
+ const name = team.name
21
+ const description = team.description ? ` - ${team.description}` : ""
22
+ yield* Console.log(` ${key.padEnd(8)} ${name}${description}`)
23
+ }
24
+
25
+ yield* Console.log("")
26
+ })
27
+ )
28
+
29
+ // Combined team command with subcommands
30
+ export const team = Command.make("team", {}, () =>
31
+ Console.log("Use 'linear team list' to list teams. See --help for more.")
32
+ ).pipe(Command.withSubcommands([teamListCommand]))
@@ -0,0 +1,50 @@
1
+ import { Schema } from "effect"
2
+
3
+ export class ConfigError extends Schema.TaggedError<ConfigError>()(
4
+ "ConfigError",
5
+ {
6
+ message: Schema.String,
7
+ }
8
+ ) {}
9
+
10
+ export class LinearApiError extends Schema.TaggedError<LinearApiError>()(
11
+ "LinearApiError",
12
+ {
13
+ message: Schema.String,
14
+ code: Schema.optional(Schema.String),
15
+ }
16
+ ) {}
17
+
18
+ export class BrowserError extends Schema.TaggedError<BrowserError>()(
19
+ "BrowserError",
20
+ {
21
+ message: Schema.String,
22
+ }
23
+ ) {}
24
+
25
+ export class TokenNotFoundError extends Schema.TaggedError<TokenNotFoundError>()(
26
+ "TokenNotFoundError",
27
+ {
28
+ message: Schema.String,
29
+ }
30
+ ) {
31
+ static readonly default = TokenNotFoundError.make({
32
+ message: "No token found. Run 'linear auth' to authenticate.",
33
+ })
34
+ }
35
+
36
+ export class InvalidTokenError extends Schema.TaggedError<InvalidTokenError>()(
37
+ "InvalidTokenError",
38
+ {
39
+ message: Schema.String,
40
+ }
41
+ ) {}
42
+
43
+ export const AppError = Schema.Union(
44
+ ConfigError,
45
+ LinearApiError,
46
+ BrowserError,
47
+ TokenNotFoundError,
48
+ InvalidTokenError
49
+ )
50
+ export type AppError = typeof AppError.Type
package/src/main.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { Command } from "@effect/cli"
2
+ import { BunContext, BunRuntime } from "@effect/platform-bun"
3
+ import { Console, Effect, Layer } from "effect"
4
+ import { auth } from "./commands/auth.js"
5
+ import { team } from "./commands/team.js"
6
+ import { issue } from "./commands/issue.js"
7
+ import { ConfigService } from "./services/Config.js"
8
+ import { LinearService } from "./services/Linear.js"
9
+ import { BrowserService } from "./services/Browser.js"
10
+ import { StdinService } from "./services/Stdin.js"
11
+ import { TokenNotFoundError } from "./lib/errors.js"
12
+
13
+ // Root command
14
+ const linear = Command.make("linear", {}, () =>
15
+ Console.log("Linear CLI - Use --help to see available commands")
16
+ ).pipe(Command.withSubcommands([auth, team, issue]))
17
+
18
+ // Build the CLI runner
19
+ const cli = Command.run(linear, {
20
+ name: "linear",
21
+ version: "0.1.0",
22
+ })
23
+
24
+ // Layer composition:
25
+ // - BunContext provides FileSystem, Path, Terminal
26
+ // - ConfigService depends on FileSystem, Path
27
+ // - LinearService depends on ConfigService
28
+ // - BrowserService is standalone
29
+
30
+ // Build layers with dependencies
31
+ const MainLayer = StdinService.layer.pipe(
32
+ Layer.provideMerge(BrowserService.layer),
33
+ Layer.provideMerge(LinearService.layer),
34
+ Layer.provideMerge(ConfigService.layer),
35
+ Layer.provideMerge(BunContext.layer)
36
+ )
37
+
38
+ // Run the CLI
39
+ cli(process.argv).pipe(
40
+ Effect.catchTag("TokenNotFoundError", (e) =>
41
+ Console.error(`Error: ${e.message}`)
42
+ ),
43
+ Effect.catchTag("LinearApiError", (e) =>
44
+ Console.error(`Linear API Error: ${e.message}`)
45
+ ),
46
+ Effect.catchTag("ConfigError", (e) =>
47
+ Console.error(`Config Error: ${e.message}`)
48
+ ),
49
+ Effect.catchTag("InvalidTokenError", (e) =>
50
+ Console.error(`Authentication Error: ${e.message}`)
51
+ ),
52
+ Effect.provide(MainLayer),
53
+ BunRuntime.runMain
54
+ )
@@ -0,0 +1,23 @@
1
+ import { Context, Effect, Layer } from "effect"
2
+ import { BrowserError } from "../lib/errors.js"
3
+
4
+ export class BrowserService extends Context.Tag("@linear/BrowserService")<
5
+ BrowserService,
6
+ {
7
+ readonly open: (url: string) => Effect.Effect<void, BrowserError>
8
+ }
9
+ >() {
10
+ // macOS-only implementation using `open` command
11
+ static readonly layer = Layer.succeed(BrowserService, {
12
+ open: (url) =>
13
+ Effect.tryPromise({
14
+ try: () => Bun.$`open ${url}`.quiet(),
15
+ catch: (e) => BrowserError.make({ message: String(e) }),
16
+ }).pipe(Effect.asVoid),
17
+ })
18
+
19
+ // No-op layer for testing
20
+ static readonly testLayer = Layer.succeed(BrowserService, {
21
+ open: (_url) => Effect.void,
22
+ })
23
+ }
@@ -0,0 +1,166 @@
1
+ import { Context, Effect, Layer, Option } from "effect"
2
+ import { FileSystem, Path } from "@effect/platform"
3
+ import { ConfigError, TokenNotFoundError } from "../lib/errors.js"
4
+
5
+ // Config structure for .linear.toml
6
+ export interface LinearConfig {
7
+ readonly teamId?: string
8
+ readonly workspace?: string
9
+ readonly issueSort?: "manual" | "priority"
10
+ }
11
+
12
+ export class ConfigService extends Context.Tag("@linear/ConfigService")<
13
+ ConfigService,
14
+ {
15
+ readonly getToken: Effect.Effect<string, TokenNotFoundError | ConfigError>
16
+ readonly saveToken: (token: string) => Effect.Effect<void, ConfigError>
17
+ readonly getConfig: Effect.Effect<LinearConfig, ConfigError>
18
+ }
19
+ >() {
20
+ static readonly layer = Layer.effect(
21
+ ConfigService,
22
+ Effect.gen(function* () {
23
+ const fs = yield* FileSystem.FileSystem
24
+ const path = yield* Path.Path
25
+
26
+ const homeDir = process.env.HOME ?? ""
27
+ const configDir = path.join(homeDir, ".config", "linear")
28
+ const tokenPath = path.join(configDir, "token")
29
+ const configPath = path.join(configDir, "config.toml")
30
+
31
+ const ensureConfigDir = Effect.gen(function* () {
32
+ const exists = yield* fs.exists(configDir)
33
+ if (!exists) {
34
+ yield* fs.makeDirectory(configDir, { recursive: true })
35
+ }
36
+ }).pipe(
37
+ Effect.catchAll((e) =>
38
+ ConfigError.make({ message: `Failed to create config directory: ${e}` })
39
+ )
40
+ )
41
+
42
+ const getToken = Effect.gen(function* () {
43
+ // 1. Try config file first
44
+ const fileToken = yield* Effect.tryPromise({
45
+ try: () => Bun.file(tokenPath).text(),
46
+ catch: () => null,
47
+ }).pipe(Effect.option)
48
+
49
+ if (Option.isSome(fileToken) && fileToken.value.trim()) {
50
+ return fileToken.value.trim()
51
+ }
52
+
53
+ // 2. Try env var
54
+ const envToken = process.env.LINEAR_API_KEY
55
+ if (envToken) {
56
+ return envToken
57
+ }
58
+
59
+ // 3. Error
60
+ return yield* TokenNotFoundError.default
61
+ }).pipe(Effect.withSpan("ConfigService.getToken"))
62
+
63
+ const saveToken = (token: string) =>
64
+ Effect.gen(function* () {
65
+ yield* ensureConfigDir
66
+ yield* Effect.tryPromise({
67
+ try: () => Bun.write(tokenPath, token.trim()),
68
+ catch: (e) => ConfigError.make({ message: `Failed to save token: ${e}` }),
69
+ })
70
+ }).pipe(Effect.withSpan("ConfigService.saveToken"))
71
+
72
+ const getConfig = Effect.gen(function* () {
73
+ // Try project config first (.linear.toml in cwd or git root)
74
+ const projectConfig = yield* loadProjectConfig(fs, path)
75
+ if (Option.isSome(projectConfig)) {
76
+ return projectConfig.value
77
+ }
78
+
79
+ // Fall back to global config
80
+ const globalConfig = yield* loadTomlConfig(configPath)
81
+ return globalConfig
82
+ }).pipe(Effect.withSpan("ConfigService.getConfig"))
83
+
84
+ return ConfigService.of({
85
+ getToken,
86
+ saveToken,
87
+ getConfig,
88
+ })
89
+ })
90
+ )
91
+
92
+ static readonly testLayer = (options?: {
93
+ token?: string
94
+ config?: LinearConfig
95
+ }) =>
96
+ Layer.succeed(ConfigService, {
97
+ getToken:
98
+ options?.token != null
99
+ ? Effect.succeed(options.token)
100
+ : Effect.fail(TokenNotFoundError.default),
101
+ saveToken: (_token) => Effect.void,
102
+ getConfig: Effect.succeed(options?.config ?? {}),
103
+ })
104
+ }
105
+
106
+ function loadTomlConfig(
107
+ filePath: string
108
+ ): Effect.Effect<LinearConfig, ConfigError> {
109
+ return Effect.tryPromise({
110
+ try: async () => {
111
+ const file = Bun.file(filePath)
112
+ const exists = await file.exists()
113
+ if (!exists) return {}
114
+
115
+ const content = await file.text()
116
+ // Simple TOML parsing for our use case
117
+ const config: LinearConfig = {}
118
+ for (const line of content.split("\n")) {
119
+ const trimmed = line.trim()
120
+ if (trimmed.startsWith("#") || !trimmed.includes("=")) continue
121
+
122
+ const [key, ...rest] = trimmed.split("=")
123
+ const value = rest.join("=").trim().replace(/^["']|["']$/g, "")
124
+
125
+ switch (key.trim()) {
126
+ case "team_id":
127
+ config.teamId = value
128
+ break
129
+ case "workspace":
130
+ config.workspace = value
131
+ break
132
+ case "issue_sort":
133
+ if (value === "manual" || value === "priority") {
134
+ config.issueSort = value
135
+ }
136
+ break
137
+ }
138
+ }
139
+ return config
140
+ },
141
+ catch: (e) => ConfigError.make({ message: `Failed to load config: ${e}` }),
142
+ })
143
+ }
144
+
145
+ function loadProjectConfig(
146
+ fs: FileSystem.FileSystem,
147
+ path: Path.Path
148
+ ): Effect.Effect<Option.Option<LinearConfig>, ConfigError> {
149
+ return Effect.gen(function* () {
150
+ const cwd = process.cwd()
151
+ const candidates = [
152
+ path.join(cwd, ".linear.toml"),
153
+ path.join(cwd, "linear.toml"),
154
+ ]
155
+
156
+ for (const candidate of candidates) {
157
+ const exists = yield* fs.exists(candidate)
158
+ if (exists) {
159
+ const config = yield* loadTomlConfig(candidate)
160
+ return Option.some(config)
161
+ }
162
+ }
163
+
164
+ return Option.none()
165
+ })
166
+ }
@@ -0,0 +1,192 @@
1
+ import { Context, Effect, Layer, Option, Ref } from "effect"
2
+ import { LinearClient, Issue, User, Team } from "@linear/sdk"
3
+ import { LinearApiError, InvalidTokenError, TokenNotFoundError } from "../lib/errors.js"
4
+ import { ConfigService } from "./Config.js"
5
+
6
+ export interface IssueFilter {
7
+ readonly teamId?: string
8
+ readonly state?: "triage" | "backlog" | "unstarted" | "started" | "completed" | "canceled"
9
+ readonly assigneeId?: string
10
+ readonly limit?: number
11
+ }
12
+
13
+ export class LinearService extends Context.Tag("@linear/LinearService")<
14
+ LinearService,
15
+ {
16
+ readonly getViewer: Effect.Effect<User, LinearApiError | InvalidTokenError | TokenNotFoundError>
17
+ readonly getTeams: Effect.Effect<readonly Team[], LinearApiError | TokenNotFoundError>
18
+ readonly getIssues: (filter: IssueFilter) => Effect.Effect<readonly Issue[], LinearApiError | TokenNotFoundError>
19
+ readonly getIssue: (id: string) => Effect.Effect<Issue, LinearApiError | TokenNotFoundError>
20
+ readonly getMyIssues: (filter?: { state?: string }) => Effect.Effect<readonly Issue[], LinearApiError | TokenNotFoundError>
21
+ readonly updateIssueState: (issueId: string, stateId: string) => Effect.Effect<void, LinearApiError | TokenNotFoundError>
22
+ readonly createIssue: (input: {
23
+ title: string
24
+ teamId: string
25
+ description?: string
26
+ }) => Effect.Effect<Issue, LinearApiError | TokenNotFoundError>
27
+ }
28
+ >() {
29
+ static readonly layer = Layer.effect(
30
+ LinearService,
31
+ Effect.gen(function* () {
32
+ const configService = yield* ConfigService
33
+
34
+ // Cache the client once token is loaded
35
+ const clientRef = yield* Ref.make<LinearClient | null>(null)
36
+
37
+ // Get or create client lazily
38
+ const getClient = Effect.gen(function* () {
39
+ const cached = yield* Ref.get(clientRef)
40
+ if (cached) return cached
41
+
42
+ const token = yield* configService.getToken
43
+ const client = new LinearClient({ apiKey: token })
44
+ yield* Ref.set(clientRef, client)
45
+ return client
46
+ })
47
+
48
+ const getViewer = Effect.gen(function* () {
49
+ const client = yield* getClient
50
+ const viewer = yield* Effect.tryPromise({
51
+ try: () => client.viewer,
52
+ catch: (e) => {
53
+ const msg = String(e)
54
+ if (msg.includes("Authentication") || msg.includes("401")) {
55
+ return InvalidTokenError.make({ message: "Invalid API token" })
56
+ }
57
+ return LinearApiError.make({ message: msg })
58
+ },
59
+ })
60
+ return viewer
61
+ })
62
+
63
+ const getTeams = Effect.gen(function* () {
64
+ const client = yield* getClient
65
+ const teams = yield* Effect.tryPromise({
66
+ try: async () => {
67
+ const connection = await client.teams()
68
+ return connection.nodes
69
+ },
70
+ catch: (e) => LinearApiError.make({ message: String(e) }),
71
+ })
72
+ return teams
73
+ })
74
+
75
+ const getIssues = (filter: IssueFilter) =>
76
+ Effect.gen(function* () {
77
+ const client = yield* getClient
78
+ const issues = yield* Effect.tryPromise({
79
+ try: async () => {
80
+ const connection = await client.issues({
81
+ first: filter.limit ?? 50,
82
+ filter: {
83
+ team: filter.teamId ? { id: { eq: filter.teamId } } : undefined,
84
+ state: filter.state ? { type: { eq: filter.state } } : undefined,
85
+ assignee: filter.assigneeId
86
+ ? { id: { eq: filter.assigneeId } }
87
+ : undefined,
88
+ },
89
+ })
90
+ return connection.nodes
91
+ },
92
+ catch: (e) => LinearApiError.make({ message: String(e) }),
93
+ })
94
+ return issues
95
+ })
96
+
97
+ const getMyIssues = (filter?: { state?: string }) =>
98
+ Effect.gen(function* () {
99
+ const client = yield* getClient
100
+ const issues = yield* Effect.tryPromise({
101
+ try: async () => {
102
+ const viewer = await client.viewer
103
+ const connection = await viewer.assignedIssues({
104
+ first: 50,
105
+ filter: filter?.state
106
+ ? { state: { type: { eq: filter.state } } }
107
+ : undefined,
108
+ })
109
+ return connection.nodes
110
+ },
111
+ catch: (e) => LinearApiError.make({ message: String(e) }),
112
+ })
113
+ return issues
114
+ })
115
+
116
+ const getIssue = (id: string) =>
117
+ Effect.gen(function* () {
118
+ const client = yield* getClient
119
+ const issue = yield* Effect.tryPromise({
120
+ try: () => client.issue(id),
121
+ catch: (e) => LinearApiError.make({ message: String(e) }),
122
+ })
123
+ return issue
124
+ })
125
+
126
+ const updateIssueState = (issueId: string, stateId: string) =>
127
+ Effect.gen(function* () {
128
+ const client = yield* getClient
129
+ yield* Effect.tryPromise({
130
+ try: () => client.updateIssue(issueId, { stateId }),
131
+ catch: (e) => LinearApiError.make({ message: String(e) }),
132
+ })
133
+ })
134
+
135
+ const createIssue = (input: {
136
+ title: string
137
+ teamId: string
138
+ description?: string
139
+ }) =>
140
+ Effect.gen(function* () {
141
+ const client = yield* getClient
142
+ const result = yield* Effect.tryPromise({
143
+ try: async () => {
144
+ const payload = await client.createIssue({
145
+ title: input.title,
146
+ teamId: input.teamId,
147
+ description: input.description,
148
+ })
149
+ const issue = await payload.issue
150
+ if (!issue) throw new Error("Failed to create issue")
151
+ return issue
152
+ },
153
+ catch: (e) => LinearApiError.make({ message: String(e) }),
154
+ })
155
+ return result
156
+ })
157
+
158
+ return LinearService.of({
159
+ getViewer,
160
+ getTeams,
161
+ getIssues,
162
+ getMyIssues,
163
+ getIssue,
164
+ updateIssueState,
165
+ createIssue,
166
+ })
167
+ })
168
+ )
169
+
170
+ static readonly testLayer = (options?: {
171
+ viewer?: User
172
+ teams?: readonly Team[]
173
+ issues?: readonly Issue[]
174
+ }) =>
175
+ Layer.succeed(LinearService, {
176
+ getViewer: options?.viewer
177
+ ? Effect.succeed(options.viewer)
178
+ : Effect.fail(LinearApiError.make({ message: "No viewer in test" })),
179
+ getTeams: Effect.succeed(options?.teams ?? []),
180
+ getIssues: (_filter) => Effect.succeed(options?.issues ?? []),
181
+ getMyIssues: (_filter) => Effect.succeed(options?.issues ?? []),
182
+ getIssue: (id) => {
183
+ const issue = options?.issues?.find((i) => i.id === id || (i as any).identifier === id)
184
+ return issue
185
+ ? Effect.succeed(issue)
186
+ : Effect.fail(LinearApiError.make({ message: `Issue ${id} not found` }))
187
+ },
188
+ updateIssueState: (_issueId, _stateId) => Effect.void,
189
+ createIssue: (_input) =>
190
+ Effect.fail(LinearApiError.make({ message: "Not implemented in test" })),
191
+ })
192
+ }
@@ -0,0 +1,34 @@
1
+ import { Context, Effect, Layer } from "effect"
2
+
3
+ /**
4
+ * Simple stdin reading service that works with Bun compiled binaries.
5
+ * Uses Node's readline API which Bun supports.
6
+ */
7
+ export class StdinService extends Context.Tag("StdinService")<
8
+ StdinService,
9
+ {
10
+ readonly readLine: (prompt: string) => Effect.Effect<string>
11
+ }
12
+ >() {
13
+ static readonly layer = Layer.succeed(StdinService, {
14
+ readLine: (prompt) =>
15
+ Effect.async<string>((resume) => {
16
+ // Use Node's readline API (Bun compatible)
17
+ const readline = require("node:readline")
18
+ const rl = readline.createInterface({
19
+ input: process.stdin,
20
+ output: process.stdout,
21
+ })
22
+
23
+ rl.question(prompt, (answer: string) => {
24
+ rl.close()
25
+ resume(Effect.succeed(answer))
26
+ })
27
+ }),
28
+ })
29
+
30
+ static readonly testLayer = (input: string) =>
31
+ Layer.succeed(StdinService, {
32
+ readLine: (_prompt) => Effect.succeed(input),
33
+ })
34
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "moduleDetection": "force",
7
+ "verbatimModuleSyntax": true,
8
+ "esModuleInterop": true,
9
+ "strict": true,
10
+ "exactOptionalPropertyTypes": true,
11
+ "noUnusedLocals": true,
12
+ "noImplicitOverride": true,
13
+ "skipLibCheck": true,
14
+ "declaration": true,
15
+ "declarationMap": true,
16
+ "sourceMap": true,
17
+ "outDir": "dist",
18
+ "rootDir": "src",
19
+ "types": ["bun-types"],
20
+ "plugins": [
21
+ {
22
+ "name": "@effect/language-service"
23
+ }
24
+ ]
25
+ },
26
+ "include": ["src/**/*"],
27
+ "exclude": ["node_modules", "dist", "bin"]
28
+ }