Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

combinators.test.ts

81 lines2.5 KB

1import { describe, expect, it, vi } from 'vitest'
2import { aggregate, cache, dedupe, filter } from '../src/combinators'
3import { inlineSkill } from '../src/sources/inline'
4import type { SkillMetadata, SkillSource } from '../src/types'
5​
6const alpha = inlineSkill({
7 name: 'alpha',
8 description: 'a',
9 instructions: 'A',
10})
11const beta = inlineSkill({ name: 'beta', description: 'b', instructions: 'B' })
12const alpha2 = inlineSkill({
13 name: 'alpha',
14 description: 'a2',
15 instructions: 'A2',
16})
17​
18describe('aggregate', () => {
19 it('concatenates in order and routes load() to the owner', async () => {
20 const s = aggregate([alpha, beta])
21 expect((await s.list()).map((x) => x.name)).toEqual(['alpha', 'beta'])
22 expect(await s.load('beta')).toBe('B')
23 })
24})
25​
26describe('dedupe', () => {
27 it('keeps the first occurrence and warns on collision', async () => {
28 const warn = vi.fn()
29 const s = dedupe(aggregate([alpha, alpha2]), warn)
30 const list = await s.list()
31 expect(list).toHaveLength(1)
32 expect(warn).toHaveBeenCalledWith('alpha')
33 })
34})
35​
36describe('filter', () => {
37 it('hides rejected skills', async () => {
38 const s = filter(aggregate([alpha, beta]), (m) => m.name !== 'beta')
39 expect((await s.list()).map((x) => x.name)).toEqual(['alpha'])
40 })
41​
42 it('rejects load and readResource of a hidden skill', async () => {
43 const s = filter(aggregate([alpha, beta]), (m) => m.name !== 'beta')
44 await expect(s.load('beta')).rejects.toThrow('no skill named "beta"')
45 await expect(s.readResource?.('beta', 'references/x.md')).rejects.toThrow(
46 'no skill named "beta"',
47 )
48 })
49})
50​
51describe('cache', () => {
52 it('serves concurrent list() from a single underlying fetch', async () => {
53 let calls = 0
54 const underlying: SkillSource = {
55 list: () => {
56 calls++
57 const meta: SkillMetadata = { name: 'alpha', description: 'a' }
58 return Promise.resolve([meta])
59 },
60 load: () => Promise.resolve('A'),
61 }
62 const s = cache(underlying)
63 await Promise.all([s.list(), s.list(), s.list()])
64 expect(calls).toBe(1)
65 })
66​
67 it('clears cached load() when list() refreshes', async () => {
68 let body = 'A'
69 const underlying: SkillSource = {
70 list: () => Promise.resolve([{ name: 'alpha', description: 'a' }]),
71 load: () => Promise.resolve(body),
72 }
73 const s = cache(underlying, { refreshInterval: 1 })
74 await s.list()
75 expect(await s.load('alpha')).toBe('A')
76 body = 'B'
77 await new Promise((r) => setTimeout(r, 5))
78 await s.list()
79 expect(await s.load('alpha')).toBe('B')
80 })
81})