The best way to control Claude Code, Codex and more from any computer or phone

main
ts 145 lines 5.62 KB
Raw
1 import { ConfigError } from "effect/Config";
2 import * as ConfigProvider from "effect/ConfigProvider";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
7 import * as Option from "effect/Option";
8 import { ProcessEnv } from "../Secrets/ProcessEnv.ts";
9 import { resolveSecretsOption } from "../Secrets/Provider.ts";
10 import type { StackSecrets, StackServices } from "../Stack.ts";
11
12 /**
13 * Command-line settings that shape a stack's configuration.
14 *
15 * @internal
16 */
17 export interface StackConfigOverrides {
18 /**
19 * The `--env-file` flag: the file the CLI reads instead of
20 * `.env`. A stack that declares its own `secrets` cannot be combined with
21 * it; the list is the single place that decides what loads.
22 */
23 readonly envFile?: string;
24 /** The `--profile` flag. */
25 readonly profile?: string;
26 }
27
28 /** @internal */
29 export const StackConfigOverrides = Context.Reference<StackConfigOverrides>(
30 "Alchemy/StackConfigOverrides",
31 { defaultValue: () => ({}) },
32 );
33
34 /** Report a secrets provider's own failure as the ConfigError a stack fails with. */
35 const toConfigError = (error: unknown) =>
36 error instanceof ConfigError
37 ? error
38 : new ConfigError(
39 new ConfigProvider.SourceError({
40 message: error instanceof Error ? error.message : String(error),
41 cause: error,
42 }),
43 );
44
45 /**
46 * Build the ConfigProvider a stack runs under from its `secrets` list.
47 * When omitted, leave the caller's configuration unchanged.
48 *
49 * Each provider is a layer that requires the configuration assembled so far
50 * and provides the merged result, so the list folds with `Layer.provide`:
51 * later providers override earlier ones. With an explicit list, `ALCHEMY_PROFILE` is taken
52 * from `--profile` or the real process environment only, never from a
53 * provider, so a dotenv file or a secrets manager cannot redirect which
54 * credentials every other provider uses.
55 *
56 * @internal
57 */
58 export const stackConfigLayer = (
59 secrets?: StackSecrets,
60 ): Layer.Layer<never, ConfigError, StackServices> =>
61 secrets === undefined
62 ? Layer.empty
63 : Layer.effect(
64 ConfigProvider.ConfigProvider,
65 Effect.gen(function* () {
66 const overrides = yield* StackConfigOverrides;
67 if (overrides.envFile !== undefined) {
68 return yield* Effect.fail(
69 new ConfigError(
70 new ConfigProvider.SourceError({
71 message: `--env-file cannot be combined with a stack that declares \`secrets\`. Add Secrets.DotEnv({ path: "${overrides.envFile}" }) to the list instead, or drop the flag.`,
72 }),
73 ),
74 );
75 }
76
77 const declared = yield* resolveSecretsOption(secrets);
78
79 // Every list ends with the shell unless the user placed (or disabled) it.
80 const entries = Array.isArray(declared) ? [...declared] : [declared];
81 const shellListed = entries.some(
82 (entry) => "_tag" in entry && entry._tag === "alchemy/SecretProvider::ProcessEnv",
83 );
84 if (!shellListed) entries.push(ProcessEnv());
85
86 // `ALCHEMY_PROFILE` is answered from `--profile` or the real shell,
87 // never from a provider. Every provider is built on a pinned view (so
88 // its credentials resolve against the right profile) and the stack
89 // gets a pinned view of the final result.
90 const profile =
91 overrides.profile ??
92 (yield* Effect.sync(() => process.env.ALCHEMY_PROFILE || undefined));
93 const pinned = ConfigProvider.fromEnv({
94 env: profile === undefined ? {} : { ALCHEMY_PROFILE: profile },
95 });
96 const pin = (provider: ConfigProvider.ConfigProvider) =>
97 ConfigProvider.make((path) =>
98 (path[0] === "ALCHEMY_PROFILE" ? pinned : provider).load(path),
99 );
100
101 const chain = entries.reduce<Layer.Layer<never, unknown, StackServices>>(
102 (below, entry) =>
103 ("layer" in entry ? entry.layer : entry).pipe(
104 // A reused entry must merge with this position's configuration,
105 // not return the result memoized at its first position.
106 Layer.fresh,
107 Layer.provide(
108 ConfigProvider.layer(Effect.map(ConfigProvider.ConfigProvider, pin)).pipe(
109 Layer.provide(below),
110 ),
111 ),
112 ),
113 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
114 );
115 const context = yield* Layer.build(chain).pipe(Effect.mapError(toConfigError));
116 return pin(Context.get(context, ConfigProvider.ConfigProvider));
117 }),
118 );
119
120 /**
121 * The ConfigProvider a CLI command runs under before any stack is loaded:
122 * an explicit `--env-file` overrides the process environment. Without that
123 * flag, the process environment overrides an optional `.env` file.
124 */
125 export const loadConfigProvider = Effect.fn("loadConfigProvider")(function* (
126 envFile: Option.Option<string>,
127 ) {
128 const fs = yield* FileSystem.FileSystem;
129
130 let path: string | undefined;
131 if (Option.isSome(envFile)) {
132 path = envFile.value;
133 } else if (yield* fs.exists(".env")) {
134 path = ".env";
135 }
136
137 // `fromEnv` snapshots `process.env` when called, so build it here rather
138 // than once at module load.
139 const shell = ConfigProvider.fromEnv();
140 if (path === undefined) return shell;
141 const dotEnv = yield* ConfigProvider.fromDotEnv({ path });
142 return Option.isSome(envFile)
143 ? ConfigProvider.orElse(dotEnv, shell)
144 : ConfigProvider.orElse(shell, dotEnv);
145 });