Open History to see the last commit
1import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { pathToFileURL } from 'node:url'
5import { afterAll, describe, expect, it, vi } from 'vitest'
6import { fakeText } from '@tanstack/ai/testing'
7import { defineHarness } from '@tanstack/ai-harness'
8import { memoryPersistence } from '@tanstack/ai-persistence'
9import { EXIT, runCli } from '../src'
10import { loadOptional } from '../src/optional'
11
12// An installed version of @tanstack/ai-acp without harness support: it has
13// no serveAcp function.
14vi.mock('@tanstack/ai-acp/agent', () => ({ serveAcp: undefined }))
15
16const folder = mkdtempSync(join(tmpdir(), 'cli-optional-'))
17afterAll(() => rmSync(folder, { recursive: true, force: true }))
18
19/** The URL of a temp module with `source`. */
20function tempModule(name: string, source: string) {
21 const path = join(folder, name)
22 writeFileSync(path, source)
23 return pathToFileURL(path).href
24}
25
26describe('optional packages', () => {
27 it('loads a module that has the functions', async () => {
28 const path = await loadOptional<{ join: () => string }>('node:path', 'join')
29 expect(typeof path?.join).toBe('function')
30 })
31
32 it('gives undefined for a missing package or a module without the functions', async () => {
33 expect(
34 await loadOptional<{ run: () => void }>(
35 '@tanstack/no-such-package',
36 'run',
37 ),
38 ).toBeUndefined()
39 expect(
40 await loadOptional<{ run: () => void }>(
41 '@tanstack/no-such-package/harness',
42 'run',
43 ),
44 ).toBeUndefined()
45 // An installed package with no harness support.
46 expect(
47 await loadOptional<{ serveAcp: () => void }>('node:path', 'serveAcp'),
48 ).toBeUndefined()
49 })
50
51 it('throws, with the specifier, for a module that fails on import', async () => {
52 const broken = tempModule('broken.mjs', 'throw new Error("boom")\n')
53 await expect(
54 loadOptional<{ run: () => void }>(broken, 'run'),
55 ).rejects.toThrow(`Could not load ${broken}: boom`)
56 })
57
58 it('throws for a missing package that the module imports', async () => {
59 const importer = tempModule(
60 'importer.mjs',
61 'import "@tanstack/no-such-dependency"\n',
62 )
63 await expect(
64 loadOptional<{ run: () => void }>(importer, 'run'),
65 ).rejects.toThrow(`Could not load ${importer}`)
66 })
67
68 it('fails a flag whose package has no harness support, with a clear message', async () => {
69 let stderr = ''
70 const code = await runCli(
71 defineHarness({ name: 'test/optional', adapter: fakeText() }),
72 {
73 argv: ['--acp'],
74 stdout: { write: () => {} },
75 stderr: { write: (chunk) => (stderr += chunk) },
76 persistence: memoryPersistence(),
77 },
78 )
79 expect(code).toBe(EXIT.failed)
80 expect(stderr).toContain(
81 '--acp needs @tanstack/ai-acp with harness support.',
82 )
83 })
84})