Open History to see the last commit
1import { requestUrl } from '#/lib/text.ts'
2import { describe, expect, it } from 'vitest'
3
4import { findDanglingRefs } from '#/server/ingest/bundle.ts'
5import { classifyAndBundle } from '#/server/ingest/sync.ts'
6import type { OpenApiDocument } from '../types.ts'
7import { provider } from './stability.ts'
8import { STABILITY_PRICING_URL } from '../stability-pricing.ts'
9
10const SPEC_URL = 'https://api.stability.ai/v2alpha/openapi'
11const ENGINES_URL = 'https://api.stability.ai/v1/engines/list'
12
13const FIXTURE_SPEC: OpenApiDocument = {
14 openapi: '3.0.1',
15 info: { title: 'StabilityAI REST API', version: 'v2beta' },
16 servers: [{ url: 'https://api.stability.ai' }],
17 paths: {
18 '/v2beta/stable-image/generate/ultra': {
19 post: {
20 summary: 'Stable Image Ultra',
21 requestBody: {
22 content: {
23 'multipart/form-data': {
24 schema: {
25 type: 'object',
26 required: ['prompt'],
27 properties: {
28 prompt: { type: 'string' },
29 output_format: {
30 type: 'string',
31 enum: ['jpeg', 'png', 'webp'],
32 },
33 },
34 },
35 },
36 },
37 },
38 responses: {
39 '200': {
40 content: {
41 'application/json': {
42 schema: {
43 type: 'object',
44 properties: {
45 image: { type: 'string' },
46 finish_reason: { type: 'string' },
47 seed: { type: 'number' },
48 },
49 },
50 },
51 },
52 },
53 },
54 },
55 },
56 '/v2beta/audio/stable-audio-2/text-to-audio': {
57 post: {
58 summary: 'Text-to-Audio',
59 requestBody: {
60 content: {
61 'multipart/form-data': {
62 schema: {
63 type: 'object',
64 required: ['prompt'],
65 properties: { prompt: { type: 'string' } },
66 },
67 },
68 },
69 },
70 responses: {
71 '200': {
72 content: {
73 'application/json': {
74 schema: {
75 type: 'object',
76 properties: { audio: { type: 'string' } },
77 },
78 },
79 },
80 },
81 },
82 },
83 },
84 '/v2beta/3d/stable-fast-3d': {
85 post: {
86 summary: 'Stable Fast 3D',
87 requestBody: {
88 content: {
89 'multipart/form-data': {
90 schema: {
91 type: 'object',
92 properties: { image: { type: 'string' } },
93 },
94 },
95 },
96 },
97 responses: { '200': { description: 'model/gltf-binary' } },
98 },
99 },
100 },
101}
102
103async function withFetch<T>(
104 handler: (url: string, init?: RequestInit) => Response,
105 run: () => Promise<T>,
106): Promise<{ result: T; urls: Array<string> }> {
107 const original = globalThis.fetch
108 const urls: Array<string> = []
109 globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
110 const href = requestUrl(input)
111 urls.push(href)
112 return Promise.resolve(handler(href, init))
113 }
114 try {
115 return { result: await run(), urls }
116 } finally {
117 globalThis.fetch = original
118 }
119}
120
121describe('stability classify', () => {
122 it('maps image and audio generation paths and drops platform ones', () => {
123 expect(provider.classify('/v2beta/stable-image/generate/ultra', {})).toBe(
124 'image',
125 )
126 expect(provider.classify('/v2beta/stable-image/upscale/fast', {})).toBe(
127 'image',
128 )
129 expect(provider.classify('/v2beta/stable-image/edit/inpaint', {})).toBe(
130 'image',
131 )
132 expect(
133 provider.classify('/v2alpha/generation/stable-image/upscale', {}),
134 ).toBe('image')
135 expect(
136 provider.classify('/v2beta/audio/stable-audio-2/text-to-audio', {}),
137 ).toBe('audio')
138 expect(provider.classify('/v2beta/results/{id}', {})).toBeNull()
139 expect(
140 provider.classify(
141 '/v2beta/stable-image/upscale/creative/result/{id}',
142 {},
143 ),
144 ).toBeNull()
145 expect(provider.classify('/v2beta/audio/results/{id}', {})).toBeNull()
146 expect(provider.classify('/v2beta/3d/stable-fast-3d', {})).toBeNull()
147 expect(provider.classify('/v1/user/account', {})).toBeNull()
148 expect(provider.classify('/v1/engines/list', {})).toBeNull()
149 })
150})
151
152describe('stability listModels', () => {
153 it('skips with an empty catalog when the secret is absent', async () => {
154 const result = await provider.listModels({})
155 expect(result.models).toEqual([])
156 expect(result.skipped).toBe(
157 'stability: STABILITY_API_KEY not set — skipped',
158 )
159 })
160
161 it('maps engines/list entries without calling a live host', async () => {
162 const { result, urls } = await withFetch(
163 (url) => {
164 if (url === STABILITY_PRICING_URL) {
165 return new Response(
166 '1 credit = \\$0.01.\n\n| Service | Description | Price (credits) |\n| - | - | - |\n| [Stable Image Ultra](/api-reference/generate/stable-image-ultra) | Flagship | 8 |\n',
167 )
168 }
169 expect(url).toBe(ENGINES_URL)
170 return new Response(
171 JSON.stringify([
172 {
173 id: 'stable-diffusion-xl-1024-v1-0',
174 name: 'Stable Diffusion XL 1.0',
175 type: 'PICTURE',
176 },
177 { id: 'stable-audio', name: 'Stable Audio', type: 'AUDIO' },
178 ]),
179 )
180 },
181 () => provider.listModels({ STABILITY_API_KEY: 'test-key' }),
182 )
183 expect(urls).toEqual([ENGINES_URL, STABILITY_PRICING_URL])
184 expect(result.skipped).toBeUndefined()
185 expect(result.docsFailures).toEqual({ failed: 0, skipped: 0, first: [] })
186 expect(result.models).toEqual([
187 {
188 rawId: 'stable-diffusion-xl-1024-v1-0',
189 displayName: 'Stable Diffusion XL 1.0',
190 activity: 'image',
191 },
192 {
193 rawId: 'stable-audio',
194 displayName: 'Stable Audio',
195 activity: 'audio',
196 },
197 ])
198 })
199
200 it('keeps the listing and reports the pricing page when it prices nothing', async () => {
201 const { result } = await withFetch(
202 (url) => {
203 if (url === STABILITY_PRICING_URL) {
204 return new Response('<!DOCTYPE html><html></html>')
205 }
206 expect(url).toBe(ENGINES_URL)
207 return new Response(
208 JSON.stringify([
209 {
210 id: 'stable-diffusion-xl-1024-v1-0',
211 name: 'Stable Diffusion XL 1.0',
212 type: 'PICTURE',
213 },
214 ]),
215 )
216 },
217 () => provider.listModels({ STABILITY_API_KEY: 'test-key' }),
218 )
219 expect(result.models).toEqual([
220 {
221 rawId: 'stable-diffusion-xl-1024-v1-0',
222 displayName: 'Stable Diffusion XL 1.0',
223 activity: 'image',
224 absent: { pricing: 'unavailable' },
225 },
226 ])
227 expect(result.docsFailures?.failed).toBe(1)
228 expect(result.docsFailures?.first[0]).toMatchObject({
229 source: STABILITY_PRICING_URL,
230 error: 'stability pricing page: parsed 0 model rows',
231 })
232 })
233})
234
235describe('stability fetchSpec', () => {
236 it('loads the public spec keylessly and bundles generation POSTs', async () => {
237 const { result: fetched, urls } = await withFetch(
238 (url) => {
239 expect(url).toBe(SPEC_URL)
240 return new Response(JSON.stringify(FIXTURE_SPEC))
241 },
242 () => provider.fetchSpec({}),
243 )
244 expect(urls).toEqual([SPEC_URL])
245 expect(fetched.outputStrategy).toBe('post-200')
246 expect(fetched.sources[0]?.url).toBe(SPEC_URL)
247 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
248
249 const { endpoints, warnings } = classifyAndBundle(provider, fetched)
250 expect(warnings).toEqual([])
251 expect(
252 endpoints
253 .map((e): [string, string] => [e.dbId, e.activity])
254 .sort(([aId, aAct], [bId, bAct]) =>
255 aId < bId
256 ? -1
257 : aId > bId
258 ? 1
259 : aAct < bAct
260 ? -1
261 : aAct > bAct
262 ? 1
263 : 0,
264 ),
265 ).toEqual([
266 ['stability/v2beta/audio/stable-audio-2/text-to-audio', 'audio'],
267 ['stability/v2beta/stable-image/generate/ultra', 'image'],
268 ])
269 for (const endpoint of endpoints) {
270 expect(endpoint.input, endpoint.dbId).toBeDefined()
271 expect(endpoint.output, endpoint.dbId).toBeDefined()
272 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
273 if (endpoint.output) expect(findDanglingRefs(endpoint.output)).toEqual([])
274 }
275 })
276})
277
278describe('stability seed metadata', () => {
279 it('exports the adapter contract fields', () => {
280 expect(provider.id).toBe('stability')
281 expect(provider.displayName).toBe('Stability AI')
282 expect(provider.authEnvVar).toBe('STABILITY_API_KEY')
283 expect(provider.specSourceUrl).toBe(SPEC_URL)
284 expect(provider.modelsEndpoint).toBe(ENGINES_URL)
285 expect(provider.defaultDerivation).toBe('upstream-spec')
286 })
287})