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

index.test.ts

171 lines5.5 KB

1import { mkdtemp, readFile, rm } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5import type { ResolvedConfig } from 'vite'
6​
7import { modelschemas } from './index.ts'
8import type { ModelschemasOptions } from './index.ts'
9​
10const HASH_A = 'a'.repeat(64)
11const HASH_B = 'b'.repeat(64)
12​
13const TYPES_BODY = [
14 '// @generated by modelschemas typegen v1',
15 'export type JsonSchema = { readonly [key: string]: unknown }',
16 'export const anthropicV1MessagesRequestSchema: JsonSchema = {}',
17 'export interface AnthropicV1MessagesRequest { model: string }',
18 '',
19].join('\n')
20​
21/** Minimal fake of the live service for one input-only chat endpoint. */
22function fakeService() {
23 let requests = 0
24 const fetchImpl: typeof fetch = (input, init) => {
25 requests++
26 const { pathname, searchParams } = new URL(String(input))
27 const headers = new Headers(init?.headers)
28 if (pathname === '/v1/schemas/anthropic') {
29 return Promise.resolve(
30 Response.json({
31 provider: 'anthropic',
32 activities: { chat: ['v1/messages'] },
33 }),
34 )
35 }
36 if (pathname === '/v1/schemas/anthropic/chat/v1/messages') {
37 if (searchParams.get('kind') === 'output') {
38 return Promise.resolve(
39 Response.json(
40 { error: { code: 'unknown_schema', message: 'no output' } },
41 { status: 404 },
42 ),
43 )
44 }
45 const etag = `"${HASH_A}-types-v1-exact"`
46 if (headers.get('if-none-match') === etag) {
47 return Promise.resolve(new Response(null, { status: 304 }))
48 }
49 return Promise.resolve(new Response(TYPES_BODY, { headers: { etag } }))
50 }
51 if (pathname === '/v1/changes') {
52 return Promise.resolve(
53 Response.json({
54 changes: [
55 {
56 type: 'schema.updated',
57 subjectId: 'anthropic/v1/messages',
58 summary: 'Updated input schema for /v1/messages',
59 payload: { kind: 'input', contentHash: HASH_B },
60 },
61 ],
62 nextCursor: null,
63 }),
64 )
65 }
66 return Promise.resolve(
67 Response.json(
68 { error: { code: 'not_found', message: pathname } },
69 { status: 404 },
70 ),
71 )
72 }
73 return { fetchImpl, requestCount: () => requests }
75​
76let outDir: string
77​
78beforeEach(async () => {
79 outDir = await mkdtemp(join(tmpdir(), 'modelschemas-vite-'))
80})
81​
82afterEach(async () => {
83 await rm(outDir, { recursive: true, force: true })
84})
85​
86interface FakeLogger {
87 info: ReturnType<typeof vi.fn>
88 warn: ReturnType<typeof vi.fn>
90​
91function drive(pluginOptions: ModelschemasOptions, command: 'serve' | 'build') {
92 const plugin = modelschemas(pluginOptions)
93 const logger: FakeLogger = { info: vi.fn(), warn: vi.fn() }
94 const config = { command, root: '/tmp', logger } as unknown as ResolvedConfig
95 const configResolved = plugin.configResolved as (c: ResolvedConfig) => void
96 configResolved(config)
97 const buildStart = plugin.buildStart as () => Promise<void>
98 return { run: buildStart, logger }
100​
101function options(
102 fetchImpl: typeof fetch,
103 overrides: Partial<ModelschemasOptions> = {},
104): ModelschemasOptions {
105 return {
106 baseUrl: 'https://svc.test',
107 outDir, // absolute — root is ignored
108 selections: ['anthropic'],
109 fetchImpl,
110 ...overrides,
111 }
113​
114describe('serve mode', () => {
115 it('pulls missing modules, then reports (not applies) upstream updates', async () => {
116 const { fetchImpl } = fakeService()
117 const { run, logger } = drive(options(fetchImpl), 'serve')
118 await run()
119​
120 const file = await readFile(
121 join(outDir, 'anthropic', 'v1-messages.request.ts'),
122 'utf8',
123 )
124 expect(file).toContain('AnthropicV1MessagesRequest')
125​
126 // The fake changes feed reports HASH_B upstream vs HASH_A pulled —
127 // surfaced as a log, file untouched.
128 const messages = logger.info.mock.calls.map((c) => String(c[0]))
129 expect(messages.some((m) => m.includes('update(s) available'))).toBe(true)
130 expect(file).not.toContain(HASH_B)
131 })
132​
133 it('generated modules are import-clean: no imports, no side effects, no barrel', async () => {
134 const { fetchImpl } = fakeService()
135 const { run } = drive(options(fetchImpl), 'serve')
136 await run()
137​
138 const file = await readFile(
139 join(outDir, 'anthropic', 'v1-messages.request.ts'),
140 'utf8',
141 )
142 // No top-level statement other than pure exports (tree-shakeable, no
143 // side effects) — declaration keywords at column 0 must be export-led.
144 expect(file).not.toMatch(
145 /^(import|const|let|var|function|class|console|if|for|while)\b/m,
146 )
147 expect(file).toMatch(/^export (type|const|interface) /m)
148 // And no barrel: nothing re-exported from elsewhere.
149 expect(file).not.toMatch(/export \* from|export \{[^}]*\} from/)
150 })
151})
152​
153describe('build mode', () => {
154 it('fails with remediation when nothing was pulled, without touching the network', async () => {
155 const { fetchImpl, requestCount } = fakeService()
156 const { run } = drive(options(fetchImpl), 'build')
157 await expect(run()).rejects.toThrow(/modelschemas pull/)
158 expect(requestCount()).toBe(0)
159 })
160​
161 it('passes offline once the committed files match the manifest', async () => {
162 const { fetchImpl } = fakeService()
163 const serve = drive(options(fetchImpl), 'serve')
164 await serve.run()
165​
166 const offline = fakeService()
167 const build = drive(options(offline.fetchImpl), 'build')
168 await expect(build.run()).resolves.toBeUndefined()
169 expect(offline.requestCount()).toBe(0)
170 })
171})