@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 489 lines 18 KB
Raw
1 import { assert, describe, expect, it, layer } from "@alchemy.run/test";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Command from "effect/cli/Command";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
9 import * as Alchemist from "@/Alchemist/index.ts";
10 import { providerCommand } from "@/Cli/commands/provider.ts";
11 import * as Contributions from "@/Contributions.ts";
12 import * as Interaction from "@/Interaction.ts";
13
14 interface Dependency {
15 /** `package.json` of the dependency; omit to leave it uninstalled. */
16 readonly manifest?: object;
17 /** Files beside it, by name. */
18 readonly files?: Readonly<Record<string, string>>;
19 }
20
21 /**
22 * A project in a temp directory, outside the repo, so a dependency's provider
23 * only loads when it's resolved from the dependency itself.
24 */
25 const project = (
26 dependencies: Readonly<Record<string, Dependency>>,
27 options: { readonly directory?: string } = {},
28 ) =>
29 Effect.gen(function* () {
30 const fs = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 if (options.directory !== undefined) {
33 yield* fs.makeDirectory(options.directory, { recursive: true });
34 }
35 const root = yield* fs.makeTempDirectoryScoped({
36 prefix: "alchemy-provider-",
37 directory: options.directory,
38 });
39 yield* fs.writeFileString(
40 path.join(root, "package.json"),
41 JSON.stringify({
42 name: "project",
43 dependencies: Object.fromEntries(Object.keys(dependencies).map((name) => [name, "*"])),
44 }),
45 );
46 for (const [name, dependency] of Object.entries(dependencies)) {
47 if (dependency.manifest === undefined) continue;
48 const directory = path.join(root, "node_modules", name);
49 yield* fs.makeDirectory(directory, { recursive: true });
50 yield* fs.writeFileString(
51 path.join(directory, "package.json"),
52 JSON.stringify({ name, type: "module", ...dependency.manifest }),
53 );
54 for (const [file, contents] of Object.entries(dependency.files ?? {})) {
55 yield* fs.writeFileString(path.join(directory, file), contents);
56 }
57 }
58 return root;
59 });
60
61 const contributingPackage = (name: string, provider: string): Dependency => ({
62 manifest: {
63 exports: { "./Contributions": "./Contributions.js" },
64 alchemy: { contributes: [`${name}/Contributions`] },
65 },
66 files: { "Contributions.js": provider },
67 });
68
69 describe("Contributions.load", { tags: ["unit", "local"] }, () =>
70 layer(NodeServices.layer)((it) => {
71 it.effect("loads a dependency's providers", () =>
72 Effect.gen(function* () {
73 const root = yield* project({
74 "fake-provider": contributingPackage(
75 "fake-provider",
76 `export default { name: "fake", stateStores: { fake: { description: "Fake store" } } };`,
77 ),
78 });
79 const providers = yield* Contributions.load(root);
80 const names = providers.map((provider) => provider.name);
81 expect(names).toContain("fake");
82 expect(
83 providers.find((provider) => provider.name === "fake")?.stateStores?.fake?.description,
84 ).toBe("Fake store");
85 }).pipe(Effect.scoped),
86 );
87
88 it.effect("skips dependencies without providers and ones not installed", () =>
89 Effect.gen(function* () {
90 const root = yield* project({
91 "plain-package": { manifest: { exports: { ".": "./index.js" } } },
92 "not-installed": {},
93 });
94 const own = yield* Contributions.load(yield* project({}));
95 const providers = yield* Contributions.load(root);
96 expect(providers.map((provider) => provider.name)).toEqual(
97 own.map((provider) => provider.name),
98 );
99 }).pipe(Effect.scoped),
100 );
101
102 it.effect("a dependency's provider replaces alchemy's own of the same name", () =>
103 Effect.gen(function* () {
104 const root = yield* project({
105 "aws-package": contributingPackage(
106 "aws-package",
107 `export default { name: "aws", from: "aws-package" };`,
108 ),
109 });
110 const aws = (yield* Contributions.load(root)).filter((provider) => provider.name === "aws");
111 expect(aws).toHaveLength(1);
112 expect(aws[0]).toMatchObject({ from: "aws-package" });
113 }).pipe(Effect.scoped),
114 );
115
116 it.effect(
117 "merges the dev environment providers contribute",
118 () =>
119 Effect.gen(function* () {
120 const path = yield* Path.Path;
121 // Imports `effect`, so the project lives under this package.
122 const devEnvProvider = (name: string, env: Record<string, string>) =>
123 contributingPackage(
124 name,
125 `import * as Effect from "effect/Effect";
126 export default { name: ${JSON.stringify(name)}, devEnv: Effect.succeed(Effect.succeed(${JSON.stringify(env)})) };`,
127 );
128 const root = yield* project(
129 {
130 "env-one": devEnvProvider("env-one", { ONE: "1" }),
131 "env-two": devEnvProvider("env-two", { TWO: "2" }),
132 },
133 { directory: path.resolve(import.meta.dirname, "../.alchemy/test-providers") },
134 );
135 const env = yield* inDirectory(root, Contributions.devEnv());
136 expect(env).toMatchObject({ ONE: "1", TWO: "2" });
137 }).pipe(Effect.scoped),
138 // Exclusive: changes the process's working directory.
139 { exclusive: true },
140 );
141
142 it.effect("skips a second dependency provider with a taken name", () =>
143 Effect.gen(function* () {
144 const root = yield* project({
145 "first-acme": contributingPackage(
146 "first-acme",
147 `export default { name: "acme", from: "first" };`,
148 ),
149 "second-acme": contributingPackage(
150 "second-acme",
151 `export default { name: "acme", from: "second" };`,
152 ),
153 });
154 const acme = (yield* Contributions.load(root)).filter(
155 (provider) => provider.name === "acme",
156 );
157 expect(acme).toHaveLength(1);
158 expect(acme[0]).toMatchObject({ from: "first" });
159 }).pipe(Effect.scoped),
160 );
161
162 it.effect("skips a provider that fails to load, keeping the others", () =>
163 Effect.gen(function* () {
164 const root = yield* project({
165 "no-default": contributingPackage(
166 "no-default",
167 `export const provider = { name: "nope" };`,
168 ),
169 "fake-provider": contributingPackage("fake-provider", `export default { name: "fake" };`),
170 });
171 const names = (yield* Contributions.load(root)).map((provider) => provider.name);
172 expect(names).toContain("fake");
173 expect(names).not.toContain("nope");
174 }).pipe(Effect.scoped),
175 );
176 it.effect("resolves a dependency's provider with import conditions", () =>
177 Effect.gen(function* () {
178 const root = yield* project({
179 "import-only": {
180 manifest: {
181 exports: { "./Contributions": { import: "./Contributions.js" } },
182 alchemy: { contributes: ["import-only/Contributions"] },
183 },
184 files: { "Contributions.js": `export default { name: "import-only" };` },
185 },
186 dual: {
187 manifest: {
188 exports: {
189 "./Contributions": { require: "./Contributions.cjs", import: "./Contributions.js" },
190 },
191 alchemy: { contributes: ["dual/Contributions"] },
192 },
193 files: {
194 "Contributions.js": `export default { name: "dual-esm" };`,
195 "Contributions.cjs": `module.exports = { default: { name: "dual-cjs" } };`,
196 },
197 },
198 });
199 const names = (yield* Contributions.load(root)).map((provider) => provider.name);
200 expect(names).toContain("import-only");
201 expect(names).toContain("dual-esm");
202 expect(names).not.toContain("dual-cjs");
203 }).pipe(Effect.scoped),
204 );
205
206 it.effect("discovers a provider declared by an ancestor package.json", () =>
207 Effect.gen(function* () {
208 const fs = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const root = yield* project({
211 "fake-provider": contributingPackage("fake-provider", `export default { name: "fake" };`),
212 });
213 const workspace = path.join(root, "apps", "infra");
214 yield* fs.makeDirectory(workspace, { recursive: true });
215 yield* fs.writeFileString(
216 path.join(workspace, "package.json"),
217 JSON.stringify({ name: "infra" }),
218 );
219 const names = (yield* Contributions.load(workspace)).map((provider) => provider.name);
220 expect(names).toContain("fake");
221 }).pipe(Effect.scoped),
222 );
223
224 it.effect("discovers an installed @alchemy.run package the project doesn't list", () =>
225 Effect.gen(function* () {
226 const fs = yield* FileSystem.FileSystem;
227 const path = yield* Path.Path;
228 const root = yield* project({});
229 const directory = path.join(root, "node_modules", "@alchemy.run", "fake");
230 yield* fs.makeDirectory(directory, { recursive: true });
231 yield* fs.writeFileString(
232 path.join(directory, "package.json"),
233 JSON.stringify({
234 name: "@alchemy.run/fake",
235 type: "module",
236 exports: { "./Contributions": "./Contributions.js" },
237 alchemy: { contributes: ["@alchemy.run/fake/Contributions"] },
238 }),
239 );
240 yield* fs.writeFileString(
241 path.join(directory, "Contributions.js"),
242 `export default { name: "fake" };`,
243 );
244 const names = (yield* Contributions.load(root)).map((provider) => provider.name);
245 expect(names).toContain("fake");
246 }).pipe(Effect.scoped),
247 );
248
249 it.effect("skips a provider whose specifier names another package", () =>
250 Effect.gen(function* () {
251 const root = yield* project({
252 borrower: {
253 manifest: { alchemy: { contributes: ["fake-provider/Contributions"] } },
254 },
255 });
256 const own = yield* Contributions.load(yield* project({}));
257 const providers = yield* Contributions.load(root);
258 expect(providers.map((provider) => provider.name)).toEqual(
259 own.map((provider) => provider.name),
260 );
261 }).pipe(Effect.scoped),
262 );
263
264 const storeNames = (dependencies: Record<string, string>) =>
265 Effect.gen(function* () {
266 const root = yield* project(
267 Object.fromEntries(
268 Object.entries(dependencies).map(([name, source]) => [
269 name,
270 contributingPackage(name, source),
271 ]),
272 ),
273 );
274 return yield* inDirectory(root, Contributions.stateStores());
275 });
276
277 it.effect(
278 "a provider contributes several state stores",
279 () =>
280 Effect.gen(function* () {
281 const stores = yield* storeNames({
282 "multi-store": `export default { name: "multi", stateStores: {
283 "multi-kv": { description: "KV" },
284 "multi-sql": { description: "SQL" },
285 } };`,
286 });
287 expect(stores.get("multi-kv")?.provider.name).toBe("multi");
288 expect(stores.get("multi-sql")?.store.description).toBe("SQL");
289 }).pipe(Effect.scoped),
290 // Exclusive: changes the process's working directory.
291 { exclusive: true },
292 );
293
294 it.effect(
295 "two providers contributing one state store name is an error",
296 () =>
297 Effect.gen(function* () {
298 const error = yield* Effect.flip(
299 storeNames({
300 "first-store": `export default { name: "first", stateStores: { kv: { description: "KV" } } };`,
301 "second-store": `export default { name: "second", stateStores: { kv: { description: "KV" } } };`,
302 }),
303 );
304 expect(contributionErrorMessage(error)).toBe(
305 "second and first both contribute a state store named kv",
306 );
307 }).pipe(Effect.scoped),
308 { exclusive: true },
309 );
310
311 it.effect(
312 "a state store named after a backend alchemy reserves is an error",
313 () =>
314 Effect.gen(function* () {
315 const error = yield* Effect.flip(
316 storeNames({
317 "local-store": `export default { name: "other", stateStores: { local: { description: "Local" } } };`,
318 }),
319 );
320 expect(contributionErrorMessage(error)).toBe(
321 "other and alchemy both contribute a state store named local",
322 );
323 }).pipe(Effect.scoped),
324 { exclusive: true },
325 );
326 }),
327 );
328
329 /** The message of the `ContributionError` a lifecycle route failed with. */
330 const contributionErrorMessage = (error: unknown) => {
331 assert(error instanceof Contributions.ContributionError);
332 return error.message;
333 };
334
335 /** Run with the process in `directory`, as the CLI would run in a project. */
336 const inDirectory = <A, E, R>(directory: string, effect: Effect.Effect<A, E, R>) =>
337 Effect.acquireUseRelease(
338 Effect.sync(() => {
339 const previous = process.cwd();
340 process.chdir(directory);
341 return previous;
342 }),
343 () => effect,
344 (previous) => Effect.sync(() => process.chdir(previous)),
345 );
346
347 declare global {
348 var __scopedStoreState: "open" | "closed" | undefined;
349 }
350
351 /**
352 * A provider whose state store holds a resource its layer's finalizer closes.
353 * It imports `effect` and alchemy's `State`, so it lives under this package.
354 */
355 const scopedStoreContributions = Effect.gen(function* () {
356 const path = yield* Path.Path;
357 const state = path.resolve(import.meta.dirname, "../src/State/State.ts");
358 return contributingPackage(
359 "scoped-store",
360 `import * as Effect from "effect/Effect";
361 import * as Layer from "effect/Layer";
362 import { State } from ${JSON.stringify(state)};
363
364 const layer = Layer.effect(
365 State,
366 Effect.acquireRelease(
367 Effect.sync(() => {
368 globalThis.__scopedStoreState = "open";
369 return Effect.succeed({
370 listStacks: () =>
371 globalThis.__scopedStoreState === "open"
372 ? Effect.succeed(["open"])
373 : Effect.die(new Error("the store's client is closed")),
374 });
375 }),
376 () => Effect.sync(() => void (globalThis.__scopedStoreState = "closed")),
377 ),
378 );
379
380 export default {
381 name: "scoped-store",
382 stateStores: {
383 "scoped-store": { description: "Scoped", load: Effect.succeed({ layer: () => layer }) },
384 },
385 };
386 `,
387 );
388 });
389
390 describe("Alchemist.State lifecycle", { tags: ["unit", "local"] }, () =>
391 layer(Alchemist.layer())((it) => {
392 it.effect(
393 "a store's resources stay open until the caller's scope closes",
394 () =>
395 Effect.gen(function* () {
396 const path = yield* Path.Path;
397 const root = yield* project(
398 { "scoped-store": yield* scopedStoreContributions },
399 { directory: path.resolve(import.meta.dirname, "../.alchemy/test-providers") },
400 );
401 const stacks = yield* inDirectory(
402 root,
403 Effect.scoped(
404 Effect.flatMap(
405 Alchemist.State.store({ type: "provider", backend: "scoped-store" }),
406 (store) => store.listStacks(),
407 ),
408 ),
409 );
410 expect(stacks).toEqual(["open"]);
411 expect(globalThis.__scopedStoreState).toBe("closed");
412 }).pipe(Effect.scoped),
413 // Exclusive: changes the process's working directory.
414 { exclusive: true },
415 );
416
417 it.effect("rejects an unknown backend", () =>
418 Effect.gen(function* () {
419 const error = yield* Effect.flip(
420 Alchemist.State.bootstrap({ type: "provider", backend: "nope" }),
421 );
422 // The available stores depend on the @alchemy.run packages installed
423 // around the repo, so only the stable parts are pinned.
424 const message = contributionErrorMessage(error);
425 expect(message).toContain("Unknown state backend 'nope'. Available: local, configured");
426 expect(message).toContain("Install the package that provides it.");
427 }),
428 );
429
430 it.effect("rejects an operation the backend doesn't have", () =>
431 Effect.gen(function* () {
432 const error = yield* Effect.flip(
433 Alchemist.State.logs({ type: "provider", backend: "aws" }),
434 );
435 expect(contributionErrorMessage(error)).toBe("State backend 'aws' does not support logs.");
436 }),
437 );
438 }),
439 );
440
441 const cliContributions = (
442 name: string,
443 load: Contributions.Lazy<Contributions.AnyCommand>,
444 ): Contributions.Contributions =>
445 Contributions.make({ name, cli: { provider: { description: `${name} commands`, load } } });
446
447 const brokenCli = cliContributions(
448 "broken",
449 Effect.fail(new Contributions.ContributionError({ message: "broken CLI failed to import" })),
450 );
451 const workingCli = cliContributions(
452 "working",
453 Effect.succeed(Command.make("working", {}, () => Effect.void)),
454 );
455
456 describe("alchemy provider", { tags: ["unit", "local"] }, () => {
457 it.live("a provider whose CLI fails to load doesn't block another's", () =>
458 Effect.gen(function* () {
459 const command = yield* Effect.promise(() => providerCommand([brokenCli, workingCli]));
460 const run = (args: ReadonlyArray<string>) =>
461 Command.runWith(command, { version: "test" })(args).pipe(
462 Effect.provide(Layer.mergeAll(Alchemist.layer(), Interaction.layerNonInteractive())),
463 );
464 yield* run(["working"]);
465 const error = yield* Effect.flip(run(["broken"]));
466 expect(String(error)).toContain("broken CLI failed to import");
467 }),
468 );
469 });
470
471 describe("Contributions contract", { tags: ["unit", "local"] }, () => {
472 it("rejects a field requiring a service no host provides", () => {
473 class PrivateClient extends Context.Service<PrivateClient, { readonly id: string }>()(
474 "PrivateClient",
475 ) {}
476 const provider = Contributions.make({
477 name: "needs-private-client",
478 // @ts-expect-error PrivateClient is not a host service; the provider must supply it.
479 auth: Effect.succeed(
480 Layer.effectDiscard(
481 Effect.gen(function* () {
482 yield* PrivateClient;
483 }),
484 ),
485 ),
486 });
487 expect(provider.name).toBe("needs-private-client");
488 });
489 });