@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,18 +1,20 @@
1
- import { Config, Context, Effect, FileSystem, Layer, Option, Path } from "effect";
1
+ import { parse } from "toml";
2
+ import { Config, Context, Effect, FileSystem, Layer, Option, Path, Redacted, Schema } from "effect";
2
3
  import { ConfigError, TokenNotFoundError } from "../lib/errors.js";
3
4
 
4
- // Config structure for .linear.toml
5
- export interface LinearConfig {
6
- readonly teamId?: string;
7
- readonly workspace?: string;
8
- readonly issueSort?: "manual" | "priority";
9
- }
5
+ export class LinearConfig extends Schema.Class<LinearConfig>("LinearConfig")({
6
+ teamId: Schema.optional(Schema.String),
7
+ }) {}
8
+
9
+ class LinearConfigFile extends Schema.Class<LinearConfigFile>("LinearConfigFile")({
10
+ team_id: Schema.optional(Schema.String),
11
+ }) {}
10
12
 
11
13
  export class ConfigService extends Context.Service<
12
14
  ConfigService,
13
15
  {
14
- readonly getToken: Effect.Effect<string, TokenNotFoundError | ConfigError>;
15
- readonly saveToken: (token: string) => Effect.Effect<void, ConfigError>;
16
+ readonly getToken: Effect.Effect<Redacted.Redacted<string>, TokenNotFoundError | ConfigError>;
17
+ readonly saveToken: (token: Redacted.Redacted<string>) => Effect.Effect<void, ConfigError>;
16
18
  readonly getConfig: Effect.Effect<LinearConfig, ConfigError>;
17
19
  }
18
20
  >()("@cvr/linear/services/Config/ConfigService") {
@@ -21,144 +23,143 @@ export class ConfigService extends Context.Service<
21
23
  Effect.gen(function* () {
22
24
  const fs = yield* FileSystem.FileSystem;
23
25
  const path = yield* Path.Path;
24
-
25
26
  const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
26
- const envToken = yield* Config.string("LINEAR_API_KEY").pipe(Config.option);
27
+ const envToken = yield* Config.redacted("LINEAR_API_KEY").pipe(Config.option);
27
28
  const configDir = path.join(homeDir, ".config", "linear");
28
29
  const tokenPath = path.join(configDir, "token");
29
30
  const configPath = path.join(configDir, "config.toml");
30
31
 
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.catch((e) =>
38
- Effect.fail(ConfigError.make({ message: `Failed to create config directory: ${e}` })),
32
+ const ensureConfigDir = fs
33
+ .makeDirectory(configDir, { recursive: true })
34
+ .pipe(
35
+ Effect.mapError((error) =>
36
+ ConfigError.make({ message: `Failed to create config directory: ${error}` }),
37
+ ),
38
+ );
39
+
40
+ const getToken = readTokenFile(fs, tokenPath).pipe(
41
+ Effect.flatMap(
42
+ Option.match({
43
+ onSome: Effect.succeed,
44
+ onNone: () =>
45
+ Option.match(envToken, {
46
+ onSome: Effect.succeed,
47
+ onNone: () => TokenNotFoundError.default,
48
+ }),
49
+ }),
39
50
  ),
51
+ Effect.withSpan("ConfigService.getToken"),
40
52
  );
41
53
 
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().length > 0) {
50
- return fileToken.value.trim();
51
- }
52
-
53
- // 2. Try env var
54
- if (Option.isSome(envToken)) {
55
- return envToken.value;
56
- }
57
-
58
- // 3. Error
59
- return yield* TokenNotFoundError.default;
60
- }).pipe(Effect.withSpan("ConfigService.getToken"));
61
-
62
- const saveToken = Effect.fn("ConfigService.saveToken")((token: string) =>
63
- Effect.gen(function* () {
64
- yield* ensureConfigDir;
65
- yield* Effect.tryPromise({
66
- try: () => Bun.write(tokenPath, token.trim()),
67
- catch: (e) => ConfigError.make({ message: `Failed to save token: ${e}` }),
68
- });
69
- }),
70
- );
54
+ const saveToken = Effect.fn("ConfigService.saveToken")(function* (
55
+ token: Redacted.Redacted<string>,
56
+ ) {
57
+ yield* ensureConfigDir;
58
+ yield* fs
59
+ .writeFileString(tokenPath, Redacted.value(token).trim(), { mode: 0o600 })
60
+ .pipe(
61
+ Effect.mapError((error) =>
62
+ ConfigError.make({ message: `Failed to save token: ${error}` }),
63
+ ),
64
+ );
65
+ });
71
66
 
72
67
  const getConfig = Effect.gen(function* () {
73
- // Try project config first (.linear.toml in cwd or git root)
74
- const projectConfig = yield* loadProjectConfig(path);
75
- if (Option.isSome(projectConfig)) {
76
- return projectConfig.value;
68
+ const cwd = path.resolve(".");
69
+ for (const candidate of [path.join(cwd, ".linear.toml"), path.join(cwd, "linear.toml")]) {
70
+ const projectConfig = yield* readConfigFile(fs, candidate);
71
+ if (Option.isSome(projectConfig)) {
72
+ return projectConfig.value;
73
+ }
77
74
  }
78
75
 
79
- // Fall back to global config
80
- const globalConfig = yield* loadTomlConfig(configPath);
81
- return globalConfig;
76
+ return Option.getOrElse(yield* readConfigFile(fs, configPath), () => new LinearConfig({}));
82
77
  }).pipe(Effect.withSpan("ConfigService.getConfig"));
83
78
 
84
- return ConfigService.of({
85
- getToken,
86
- saveToken,
87
- getConfig,
88
- });
79
+ return ConfigService.of({ getToken, saveToken, getConfig });
89
80
  }),
90
81
  );
91
82
 
92
83
  static readonly layerTest = (options?: { token?: string; config?: LinearConfig }) =>
93
84
  Layer.succeed(ConfigService, {
94
- getToken:
95
- options?.token != null
96
- ? Effect.succeed(options.token)
97
- : Effect.fail(TokenNotFoundError.default),
98
- saveToken: (_token) => Effect.void,
99
- getConfig: Effect.succeed(options?.config ?? {}),
85
+ getToken: makeTestGetToken(options?.token),
86
+ saveToken: () => Effect.void,
87
+ getConfig: Effect.succeed(options?.config ?? new LinearConfig({})),
100
88
  });
101
89
  }
102
90
 
103
- const loadTomlConfig = Effect.fn("ConfigService.loadTomlConfig")((filePath: string) =>
104
- Effect.tryPromise({
105
- try: async () => {
106
- const file = Bun.file(filePath);
107
- const exists = await file.exists();
108
- if (!exists) return {};
109
-
110
- const content = await file.text();
111
- // Simple TOML parsing for our use case
112
- let teamId: string | undefined;
113
- let workspace: string | undefined;
114
- let issueSort: "manual" | "priority" | undefined;
115
-
116
- for (const line of content.split("\n")) {
117
- const trimmed = line.trim();
118
- if (trimmed.startsWith("#") || !trimmed.includes("=")) continue;
119
-
120
- const [key, ...rest] = trimmed.split("=");
121
- const value = rest
122
- .join("=")
123
- .trim()
124
- .replace(/^["']|["']$/g, "");
125
-
126
- switch (key?.trim()) {
127
- case "team_id":
128
- teamId = value;
129
- break;
130
- case "workspace":
131
- workspace = value;
132
- break;
133
- case "issue_sort":
134
- if (value === "manual" || value === "priority") {
135
- issueSort = value;
136
- }
137
- break;
138
- }
139
- }
140
- return { teamId, workspace, issueSort } as LinearConfig;
141
- },
142
- catch: (e) => ConfigError.make({ message: `Failed to load config: ${e}` }),
143
- }),
144
- );
145
-
146
- const loadProjectConfig = Effect.fn("ConfigService.loadProjectConfig")((pathService: Path.Path) =>
147
- Effect.gen(function* () {
148
- const cwd = process.cwd();
149
- const candidates = [
150
- pathService.join(cwd, ".linear.toml"),
151
- pathService.join(cwd, "linear.toml"),
152
- ];
153
-
154
- for (const candidate of candidates) {
155
- const exists = yield* Effect.promise(() => Bun.file(candidate).exists());
156
- if (exists) {
157
- const config = yield* loadTomlConfig(candidate);
158
- return Option.some(config);
91
+ const readTokenFile = (
92
+ fs: Context.Service.Shape<typeof FileSystem.FileSystem>,
93
+ tokenPath: string,
94
+ ): Effect.Effect<Option.Option<Redacted.Redacted<string>>, ConfigError> =>
95
+ fs.exists(tokenPath).pipe(
96
+ Effect.mapError((error) =>
97
+ ConfigError.make({ message: `Failed to inspect token file: ${error}` }),
98
+ ),
99
+ Effect.flatMap((exists) => {
100
+ if (!exists) {
101
+ return Effect.succeed(Option.none());
159
102
  }
160
- }
103
+ return fs.readFileString(tokenPath).pipe(
104
+ Effect.mapError((error) =>
105
+ ConfigError.make({ message: `Failed to read token file: ${error}` }),
106
+ ),
107
+ Effect.map((token) => token.trim()),
108
+ Effect.map(toOptionalToken),
109
+ );
110
+ }),
111
+ );
161
112
 
113
+ const toOptionalToken = (token: string): Option.Option<Redacted.Redacted<string>> => {
114
+ if (token.length === 0) {
162
115
  return Option.none();
163
- }),
164
- );
116
+ }
117
+ return Option.some(Redacted.make(token));
118
+ };
119
+
120
+ const makeTestGetToken = (
121
+ token: string | undefined,
122
+ ): Effect.Effect<Redacted.Redacted<string>, TokenNotFoundError> => {
123
+ if (token === undefined) {
124
+ return Effect.fail(TokenNotFoundError.default);
125
+ }
126
+ return Effect.succeed(Redacted.make(token));
127
+ };
128
+
129
+ const readConfigFile = Effect.fn("ConfigService.readConfigFile")(function* (
130
+ fs: Context.Service.Shape<typeof FileSystem.FileSystem>,
131
+ filePath: string,
132
+ ): Effect.fn.Return<Option.Option<LinearConfig>, ConfigError> {
133
+ const exists = yield* fs
134
+ .exists(filePath)
135
+ .pipe(
136
+ Effect.mapError((error) =>
137
+ ConfigError.make({ message: `Failed to inspect ${filePath}: ${error}` }),
138
+ ),
139
+ );
140
+ if (!exists) {
141
+ return Option.none();
142
+ }
143
+
144
+ const content = yield* fs
145
+ .readFileString(filePath)
146
+ .pipe(
147
+ Effect.mapError((error) =>
148
+ ConfigError.make({ message: `Failed to read ${filePath}: ${error}` }),
149
+ ),
150
+ );
151
+ const parsed = yield* Effect.try({
152
+ try: () => parse(content),
153
+ catch: (error) => ConfigError.make({ message: `Failed to parse ${filePath}: ${error}` }),
154
+ });
155
+ const decoded = yield* Schema.decodeUnknownEffect(LinearConfigFile)(parsed).pipe(
156
+ Effect.mapError((error) =>
157
+ ConfigError.make({ message: `Invalid Linear config in ${filePath}: ${error}` }),
158
+ ),
159
+ );
160
+ return Option.some(
161
+ new LinearConfig({
162
+ teamId: decoded.team_id,
163
+ }),
164
+ );
165
+ });