chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,143 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise compiled Content Mapper aliases across native typing and runtime. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { createClient } from '../dist/index.js'
import { transformSpec } from '../dist/tooling/transform.js'
import '../dist/tooling/register.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const operation = {
'x-client-path': ['enterprise', 'access', 'getEnvironmentApi'],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: {
description: 'OK',
content: {
'application/json': {
schema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } },
},
},
},
},
}
const spec = {
openapi: '3.1.0',
paths: {
'/environments/{id}': { get: operation },
'/pets': { get: { responses: { 204: { description: 'Empty' } } } },
},
}
test('explicit client paths preserve HTTP methods, defaults, error maps, query keys and inferred types', async () => {
const directory = mkdtempSync(join(import.meta.dirname, '.aliases-'))
const file = join(directory, 'spec.openapi')
try {
writeFileSync(file, JSON.stringify(spec))
writeFileSync(
`${file}.config.ts`,
`export type Context = object; export default { queryKeyPrefix: ['console'] };`,
)
writeFileSync(
`${file}.queries.ts`,
`const defaults = { queryOptions: { staleTime: 42 } }; export { defaults as 'GET /environments/{id}' };`,
)
writeFileSync(
`${file}.errors.ts`,
`const errors = { DENIED: { status: 403 } }; export { errors as 'GET /environments/{id}' };`,
)
const { api, query } = await import(pathToFileURL(file).href)
const requests = []
const client = createClient({
baseUrl: 'https://example.test',
fetch: async (url, init) => {
requests.push({ url: String(url), method: init.method })
return Response.json({ id: 'a/b' })
},
})
assert.deepEqual(
await api.enterprise.access.getEnvironmentApi({ params: { id: 'a/b' } }, { client }),
{ id: 'a/b' },
)
assert.deepEqual(requests, [{ url: 'https://example.test/environments/a%2Fb', method: 'GET' }])
const options = query.enterprise.access.getEnvironmentApi.queryOptions({
input: { params: { id: 'a' } },
})
assert.equal(options.staleTime, 42)
assert.deepEqual(options.queryKey[0], ['console', 'enterprise', 'access', 'getEnvironmentApi'])
assert.equal(typeof api.pets.get, 'function')
const denied = createClient({
baseUrl: 'https://example.test',
fetch: async () => Response.json({ code: 'DENIED' }, { status: 403 }),
})
await assert.rejects(
api.enterprise.access.getEnvironmentApi({ params: { id: 'a' } }, { client: denied }),
(error) => error.code === 'DENIED' && error.defined === true,
)
writeFileSync(
join(directory, 'consumer.ts'),
`
import { api, query } from './spec.openapi';
import type { Inputs, Outputs } from './spec.openapi';
import { safe } from '@orpc/client';
const input: Inputs['enterprise']['access']['getEnvironmentApi'] = { params: { id: 'a' } };
const output: Outputs['enterprise']['access']['getEnvironmentApi'] = { id: 'a' };
// @ts-expect-error type maps follow the explicit client path too
type OriginalPath = Outputs['environments']['byId']['get'];
const [error, data, defined] = await safe(api.enterprise.access.getEnvironmentApi({ params: { id: 'a' } }));
if (defined) { const code: 'DENIED' = error.code; }
if (data) { const id: string = data.id; }
query.enterprise.access.getEnvironmentApi.queryOptions({ input: { params: { id: 'a' } } });
// @ts-expect-error A custom member still requires the documented path parameter.
api.enterprise.access.getEnvironmentApi();
// @ts-expect-error Renamed operations are not also exposed under their URL path.
api.environments.byId.get({ params: { id: 'a' } });
`,
)
writeFileSync(
join(directory, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
},
contentMappers: [{ package: root, extensions: ['.openapi'] }],
include: ['consumer.ts'],
}),
)
const result = spawnSync(
process.execPath,
[join(root, 'node_modules/typescript/bin/tsc'), '--runExternalCode', '-p', directory],
{ encoding: 'utf8', timeout: 60000 },
)
assert.equal(result.status, 0, result.stdout + result.stderr)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('client paths reject collisions and unsafe namespace members', () => {
for (const path of [
[],
['key'],
['then'],
['constructor'],
['pets', 'get'],
['pets'],
['pets', 'get', 'child'],
]) {
const source = structuredClone(spec)
source.paths['/environments/{id}'].get['x-client-path'] = path
assert(
transformSpec(JSON.stringify(source), 'test.openapi').diagnostics?.length,
JSON.stringify(path),
)
}
})
@@ -0,0 +1,286 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Integration tests exercise the built package in native Node, including its module hooks. */
import assert from 'node:assert/strict'
import { Buffer } from 'node:buffer'
import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { gzipSync } from 'node:zlib'
import { build } from 'vite'
import { parse, stringify } from 'yaml'
import { openapi } from '../dist/tooling/vite.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const fixture = parse(readFileSync(join(root, 'examples/petstore/pets.openapi.yaml'), 'utf8'))
test('sidecar star re-exports use Vite aliases and TypeScript extension resolution', async () => {
const dir = mkdtempSync(join(root, 'test/.sidecar-resolve-'))
try {
writeFileSync(
join(dir, 'api.openapi'),
JSON.stringify({
openapi: '3.1.0',
paths: { '/pets': { get: { responses: { 200: { description: 'OK' } } } } },
}),
)
writeFileSync(join(dir, 'api.openapi.queries.ts'), "export * from './defaults.js';")
writeFileSync(join(dir, 'defaults.ts'), "export * from '@policies';")
writeFileSync(
join(dir, 'policies.ts'),
"const policy = {queryOptions: {staleTime: 42}}; export {policy as 'GET /pets'};",
)
writeFileSync(join(dir, 'api.openapi.errors.ts'), "export * from './errors.js';")
writeFileSync(
join(dir, 'errors.ts'),
"const errors = {CONFLICT: {status: 409}}; export {errors as 'GET /pets'};",
)
writeFileSync(
join(dir, 'entry.ts'),
`
import {createClient} from '@dify/openapi-content-mapper';
import {api, query} from './api.openapi';
export const staleTime = query.pets.get.queryOptions().staleTime;
export async function fail() {
const client = createClient({baseUrl: 'https://example.test', fetch: async () => Response.json({code: 'CONFLICT'}, {status: 409})});
return api.pets.get(undefined, {client}).catch(error => ({code: error.code, defined: error.defined}));
}`,
)
await build({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [openapi()],
resolve: { alias: { '@policies': join(dir, 'policies.ts') } },
build: { lib: { entry: join(dir, 'entry.ts'), formats: ['es'], fileName: () => 'entry.js' } },
})
const result = await import(pathToFileURL(join(dir, 'dist/entry.js')).href)
assert.equal(result.staleTime, 42)
assert.deepEqual(await result.fail(), { code: 'CONFLICT', defined: true })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
for (const mode of ['api', 'query'])
test(`${mode}: error chunks are shared per document and stay lazy with distinct maps`, async () => {
const dir = mkdtempSync(join(root, 'test/.shared-errors-'))
const loaded = `error-sidecars:${dir}`
globalThis[loaded] = []
try {
writeFileSync(join(dir, 'shared.ts'), `export const errorCode = index => 'ERROR_' + index;`)
for (const document of ['console', 'marketplace']) {
const paths = {}
const maps = [
`import { errorCode } from './shared'; globalThis[${JSON.stringify(loaded)}].push('${document}');`,
]
for (let index = 0; index < 20; index++) {
paths[`/operation${index}`] = { get: { responses: { 200: { description: 'OK' } } } }
maps.push(
`const map${index} = { [errorCode(${index})]: { status: 409 } }; export { map${index} as 'GET /operation${index}' };`,
)
}
writeFileSync(join(dir, `${document}.openapi`), JSON.stringify({ openapi: '3.1.0', paths }))
writeFileSync(join(dir, `${document}.openapi.errors.ts`), maps.join('\n'))
}
writeFileSync(
join(dir, 'entry.ts'),
`
import { createClient } from '@dify/openapi-content-mapper';
export { errorCode } from './shared';
import { ${mode} as console } from './console.openapi';
import { ${mode} as marketplace } from './marketplace.openapi';
export async function run(document, index, code) {
const client = createClient({ baseUrl: 'https://example.test', fetch: async () =>
code ? Response.json({ code }, { status: 409 }) : Response.json({ ok: true }) });
const operation = (document === 'console' ? console : marketplace)['operation' + index].get;
try {
return await ${mode === 'api' ? 'operation(undefined, { client })' : 'operation.call(undefined, { client })'};
} catch (error) { return { code: error.code, defined: error.defined }; }
}
`,
)
const result = await build({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [openapi()],
build: {
minify: true,
rolldownOptions: { preserveEntrySignatures: 'allow-extension' },
lib: { entry: join(dir, 'entry.ts'), formats: ['es'], fileName: 'entry' },
},
})
const chunks = (Array.isArray(result) ? result : [result])
.flatMap((output) => output.output)
.filter((file) => file.type === 'chunk')
const errorChunks = chunks.filter((chunk) =>
Object.keys(chunk.modules).some((id) => id.includes('?openapi-errors=')),
)
assert.equal(errorChunks.length, 2, 'Forty operations need only one error chunk per document')
for (const chunk of errorChunks) {
const documents = new Set(
Object.keys(chunk.modules)
.filter((id) => id.includes('?openapi-errors='))
.map((id) => id.split('?')[0]),
)
assert.equal(documents.size, 1, 'Independent documents must not share error chunks')
}
const entry = chunks.find((chunk) => chunk.isEntry)
const initial = new Set()
const visit = (file) => {
if (initial.has(file)) return
initial.add(file)
chunks.find((chunk) => chunk.fileName === file)?.imports.forEach(visit)
}
visit(entry.fileName)
assert(errorChunks.every((chunk) => !initial.has(chunk.fileName)))
const { run } = await import(pathToFileURL(join(dir, 'dist', entry.fileName)).href)
assert.deepEqual(globalThis[loaded], [])
assert.deepEqual(await run('console', 0), { ok: true })
assert.deepEqual(globalThis[loaded], [], 'Success must not load error validators')
assert.deepEqual(await run('console', 0, 'ERROR_0'), { code: 'ERROR_0', defined: true })
assert.deepEqual(await run('console', 1, 'ERROR_0'), { code: 'ERROR_0', defined: false })
assert.deepEqual(await run('console', 1, 'ERROR_1'), { code: 'ERROR_1', defined: true })
assert.deepEqual(globalThis[loaded], ['console'])
assert.deepEqual(await run('marketplace', 0, 'ERROR_0'), { code: 'ERROR_0', defined: true })
assert.deepEqual(globalThis[loaded], ['console', 'marketplace'])
} finally {
delete globalThis[loaded]
rmSync(dir, { recursive: true, force: true })
}
})
for (const mode of ['nested', 'query'])
test(`${mode}: Vite browser bundle drops 1,000 unused operations and all schema metadata`, async (t) => {
const dir = mkdtempSync(join(root, 'test/.bundle-'))
try {
async function bundle(spec, extension = 'yaml') {
const file = `api.${extension}`
if (extension === 'openapi') {
writeFileSync(join(dir, 'original.json'), JSON.stringify(spec))
symlinkSync('original.json', join(dir, file))
} else writeFileSync(join(dir, file), stringify(spec))
writeFileSync(
join(dir, 'entry.ts'),
mode === 'nested'
? `import { api } from './${file}'; export const getPet = api.pets.byPetId.get;`
: `import { query } from './${file}'; export const getPet = query.pets.byPetId.get.queryOptions;`,
)
const result = await build({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [openapi()],
build: {
write: false,
minify: true,
lib: { entry: join(dir, 'entry.ts'), formats: ['es'] },
},
})
return (Array.isArray(result) ? result : [result])
.flatMap((output) => output.output)
.filter((file) => file.type === 'chunk')
.map((file) => file.code)
.join('\n')
}
const small = await bundle(fixture)
const large = structuredClone(fixture)
large.info.description = 'SCHEMA_METADATA_MUST_DISAPPEAR'.repeat(2000)
for (let i = 0; i < 1000; i++)
large.paths[`/pets/UNUSED_ENDPOINT_${i}`] = {
get: {
operationId: `unused${i}`,
responses: {
200: {
description: 'unused',
content: { 'application/json': { schema: { type: 'string' } } },
},
},
},
}
const output = await bundle(large)
assert(!output.includes('UNUSED_ENDPOINT_'))
assert(!output.includes('SCHEMA_METADATA_MUST_DISAPPEAR'))
assert(!output.includes('components'))
assert(!output.includes('YAMLParseError'))
assert(!output.includes('parseDocument'))
assert(output.includes('/pets/{petId}'))
assert.equal(
output.length,
small.length,
'Adding unused operations must not increase the bundle',
)
assert(Buffer.byteLength(output) < 30000, `Unexpected runtime size: ${output.length}`)
const json = await bundle(fixture, 'openapi')
const stripBundleComments = (code) => code.replace(/^\/\/.*$/gm, '')
assert.equal(
stripBundleComments(json),
stripBundleComments(small),
'JSON and YAML must produce equivalent runtime code',
)
t.diagnostic(
`One operation: ${Buffer.byteLength(output)} bytes, ${gzipSync(output).length} bytes gzip; unchanged with 1,000 extra operations`,
)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
for (const mode of ['api', 'query'])
test(`${mode}: unused operation policies and error validators are removed`, async () => {
const dir = mkdtempSync(join(root, 'test/.policies-bundle-'))
try {
async function bundle(count) {
const spec = structuredClone(fixture)
const defaults = [
`const used = { queryOptions: { staleTime: 1234 } }; export { used as 'GET /pets/{petId}' };`,
]
const errors = [
`const used = { NOT_FOUND: { status: 404 } }; export { used as 'GET /pets/{petId}' };`,
]
for (let i = 0; i < count; i++) {
const path = `/UNUSED_OPERATION_${i}`
spec.paths[path] = { get: { responses: { 200: { description: 'OK' } } } }
defaults.push(
`const policy${i} = { queryOptions: { meta: { marker: 'UNUSED_POLICY_${i}' } } }; export { policy${i} as ${JSON.stringify(`GET ${path}`)} };`,
)
errors.push(
`const errors${i} = { UNUSED: { status: 400, message: 'UNUSED_VALIDATOR_${i}' } }; export { errors${i} as ${JSON.stringify(`GET ${path}`)} };`,
)
}
writeFileSync(join(dir, 'api.openapi'), JSON.stringify(spec))
writeFileSync(join(dir, 'api.openapi.queries.ts'), defaults.join('\n'))
writeFileSync(join(dir, 'api.openapi.errors.ts'), errors.join('\n'))
writeFileSync(
join(dir, 'entry.ts'),
`import { ${mode} } from './api.openapi'; export const operation = ${mode}.pets.byPetId.get${mode === 'query' ? '.queryOptions' : ''};`,
)
const result = await build({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [openapi()],
build: {
write: false,
minify: true,
rolldownOptions: { preserveEntrySignatures: 'allow-extension' },
lib: { entry: join(dir, 'entry.ts'), formats: ['es'] },
},
})
return (Array.isArray(result) ? result : [result])
.flatMap((r) => r.output)
.filter((f) => f.type === 'chunk')
.map((f) => f.code)
.join('\n')
}
const small = await bundle(0)
const large = await bundle(1000)
assert.equal(large, small)
assert(!large.includes('UNUSED_'))
if (mode === 'query') assert(large.includes('1234'))
else assert(!large.includes('1234'), 'API calls do not retain query defaults')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,65 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise generated descriptors through the real command cache. */
import assert from 'node:assert/strict'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { test } from 'node:test'
import { generateCompatibilitySources } from '../../contracts/scripts/generate-compatibility-sources.ts'
import { inspectSource, resolveDocument } from '../dist/tooling/source.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
test('generated Community sources refresh cached types after sibling Python dependency changes', async (t) => {
const repo = mkdtempSync(resolve(import.meta.dirname, '.compatibility-sources-'))
t.after(() => rmSync(repo, { recursive: true, force: true }))
function write(path, content) {
const file = join(repo, path)
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, content)
return file
}
for (const file of [
'packages/contracts/api-documents.ts',
'packages/contracts/typescript-generation.ts',
'packages/contracts/package.json',
'packages/contracts/generated/api/web/types.gen.ts',
'pnpm-lock.yaml',
'api/schema.py',
'api/pyproject.toml',
'api/uv.lock',
'dify-agent/pyproject.toml',
])
write(file, file.endsWith('.json') ? '{}' : '')
const modelPath = 'dify-agent/src/dify_agent/protocol/knowledge_fs.py'
const model = write(modelPath, 'class KnowledgeFsCitation: pass\n')
write(
'packages/contracts/scripts/export-compatibility-types.ts',
`
import { appendFileSync, readFileSync } from 'node:fs';
appendFileSync('exports.log', '1');
const source = readFileSync(${JSON.stringify(modelPath)}, 'utf8');
console.log(JSON.stringify({typescript: 'export type Source = ' + JSON.stringify(source) + ';'}));
`,
)
const contracts = join(repo, 'packages/contracts')
const output = join(repo, 'packages/openapi-content-mapper/contracts')
await generateCompatibilitySources(contracts, output)
const file = join(output, 'web.openapi-types')
const content = readFileSync(file, 'utf8')
const before = inspectSource(content, file)
assert(before.dependencies.includes(model))
const first = resolveDocument(content, file)
assert.deepEqual(resolveDocument(content, file), first)
assert.equal(readFileSync(join(repo, 'exports.log'), 'utf8'), '1')
write(modelPath, 'class KnowledgeFsCitation: extra: str\n')
const edited = inspectSource(content, file)
assert.notEqual(edited.identity, before.identity)
assert.match(JSON.parse(resolveDocument(content, file).content).typescript, /extra: str/)
assert.equal(readFileSync(join(repo, 'exports.log'), 'utf8'), '11')
const added = write('dify-agent/src/dify_agent/protocol/new_model.py', 'class NewModel: pass\n')
const addedIdentity = inspectSource(content, file).identity
assert.notEqual(addedIdentity, edited.identity)
rmSync(added)
assert.notEqual(inspectSource(content, file).identity, addedIdentity)
const metadata = write('dify-agent/pyproject.toml', '[project]\nversion = "2"\n')
assert(inspectSource(content, file).dependencies.includes(metadata))
assert.notEqual(inspectSource(content, file).identity, edited.identity)
})
@@ -0,0 +1,135 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise public native imports, query callbacks and Standard Schema error validation. */
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { isDefinedError, ORPCError, safe } from '@orpc/client'
import { MutationObserver, QueryClient } from '@tanstack/query-core'
import { createClient } from '../dist/index.js'
import '../dist/tooling/register.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
test('operation defaults preserve keys, overrides and awaited mutation callbacks; errors stay typed and validated', async () => {
const dir = mkdtempSync(join(import.meta.dirname, '.compat-'))
try {
const file = join(dir, 'api.openapi')
writeFileSync(
file,
JSON.stringify({
openapi: '3.1.0',
paths: {
'/pets': {
get: { responses: { 200: { description: 'ok' } } },
post: { responses: { 200: { description: 'ok' } } },
},
},
}),
)
writeFileSync(
`${file}.config.ts`,
`
import { createClient } from '@dify/openapi-content-mapper';
export type Context = { silent?: boolean };
export default { createClient: () => createClient({ baseUrl: 'https://example.test', fetch: async () => Response.json({ id: 1 }) }) };
`,
)
writeFileSync(
`${file}.queries.ts`,
`
const read = { queryOptions: { staleTime: 1234, retry: false, context: { silent: true } } };
const write = { mutationOptions: { onSettled: (_data, _error, _input, _result, context) => context.client.invalidateQueries({ queryKey: [['pets'], {}] }) } };
export { read as 'GET /pets', write as 'POST /pets' };
`,
)
writeFileSync(
`${file}.errors.ts`,
`
const errors = { CONFLICT: { status: 409, data: { '~standard': {
version: 1, vendor: 'fixture', validate(value) {
return typeof value?.revision === 'number'
? { value: { revision: value.revision } }
: { issues: [{ message: 'revision must be a number' }] };
},
} } } };
export { errors as 'POST /pets' };
`,
)
const { api, query } = await import(pathToFileURL(file).href)
const client = createClient({
baseUrl: 'https://example.test',
fetch: async () => Response.json({ id: 1 }),
})
const defaults = query.pets.get.queryOptions()
assert.equal(defaults.staleTime, 1234)
assert.equal(defaults.retry, false)
assert.deepEqual(defaults.queryKey, [['pets', 'get'], { type: 'query' }])
assert.equal(query.pets.get.queryOptions({ staleTime: 9 }).staleTime, 9)
assert.deepEqual(query.pets.get.queryKey({ queryKey: ['custom'] }), ['custom'])
assert.deepEqual(query.pets.post.mutationKey({ mutationKey: ['custom-write'] }), [
'custom-write',
])
const cache = new QueryClient()
let release
let invalidated = false
const callbackStarted = Promise.withResolvers()
cache.invalidateQueries = async () => {
invalidated = true
callbackStarted.resolve()
await new Promise((resolve) => {
release = resolve
})
}
const observer = new MutationObserver(cache, query.pets.post.mutationOptions())
let settled = false
const pending = observer.mutate().then(() => {
settled = true
})
await callbackStarted.promise
assert.equal(settled, false)
assert.equal(observer.getCurrentResult().status, 'pending')
release()
await pending
assert.equal(settled, true)
invalidated = false
await new MutationObserver(
cache,
query.pets.post.mutationOptions({ onSettled: () => {} }),
).mutate()
assert.equal(invalidated, false, 'caller callbacks replace defaults, as in oRPC')
cache.clear()
for (const [status, data, defined] of [
[409, { revision: 2, extra: true }, true],
[400, { revision: 2 }, false],
[409, { revision: 'bad' }, false],
]) {
client.setConfig({
fetch: async () => {
throw new ORPCError('CONFLICT', { status, data })
},
})
const [error, , isDefined] = await safe(api.pets.post(undefined, { client }))
assert.equal(isDefined, defined)
assert.equal(isDefinedError(error), defined)
if (defined)
assert.deepEqual(error.data, { revision: 2 }, 'validated data strips undeclared properties')
}
client.setConfig({
fetch: async () => Response.json({ code: 'CONFLICT', revision: 3 }, { status: 409 }),
})
const [error, , defined] = await safe(api.pets.post(undefined, { client }))
assert.equal(defined, true)
assert.equal(error.data.revision, 3)
const failure = new TypeError('Network failed')
client.setConfig({
fetch: async () => {
throw failure
},
})
await assert.rejects(api.pets.post(undefined, { client }), (error) => error === failure)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,196 @@
/* oxlint-disable vitest/no-import-node-test -- Verify actual package exports with the native compiler and language server. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { rpcProcess } from './rpc.mjs'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
for (const moduleResolution of ['NodeNext', 'Bundler']) {
test(`contract subpaths have typed LSP diagnostics without paths or sources options (${moduleResolution})`, async (t) => {
const dir = mkdtempSync(join(root, 'test/.subpaths-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const source = [
"import type { EnvironmentDeployment, RuntimeState } from '@dify/openapi-content-mapper/enterprise-app-deploy';",
'export function environmentId(deployment: EnvironmentDeployment): string {',
' return deployment.environment.id;',
'}',
'export type RuntimeStates = typeof RuntimeState;',
"export const state: RuntimeState = 'RUNTIME_STATE_RUNNING';",
].join('\n')
writeFileSync(join(dir, 'index.ts'), source)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
target: 'ES2022',
module: moduleResolution === 'Bundler' ? 'ESNext' : 'NodeNext',
moduleResolution,
},
contentMappers: [
{
package: root,
extensions: ['.openapi-types'],
},
],
include: ['index.ts'],
}),
)
const compiled = spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], {
encoding: 'utf8',
timeout: 30000,
})
assert.ifError(compiled.error)
assert.equal(compiled.status, 0, compiled.stdout + compiled.stderr)
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)
const uri = pathToFileURL(join(dir, 'index.ts')).href
try {
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(dir).href,
initializationOptions: { runExternalCode: true },
workspaceFolders: [{ uri: pathToFileURL(dir).href, name: 'subpath-consumer' }],
capabilities: {
general: { positionEncodings: ['utf-16'] },
textDocument: {
diagnostic: { dynamicRegistration: false },
hover: { contentFormat: ['plaintext'] },
},
},
})
rpc.notify('initialized', {})
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
const diagnostics = await rpc.request('textDocument/diagnostic', {
textDocument: { uri },
})
// CLI type checking alone misses TS7016 when the server reports it as a hint.
assert.deepEqual(diagnostics.items, [], JSON.stringify(diagnostics))
const hover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 0, character: source.indexOf('EnvironmentDeployment') },
})
assert.match(JSON.stringify(hover), /environment: DeploymentEnvironment/)
rpc.notify('textDocument/didChange', {
textDocument: { uri, version: 2 },
contentChanges: [
{
text: `${source}\nexport const invalid: EnvironmentDeployment = { environment: 123 };`,
},
],
})
const invalid = await rpc.request('textDocument/diagnostic', {
textDocument: { uri },
})
assert(invalid.items.some((item) => item.code === 2322 && item.severity === 1))
assert(!invalid.items.some((item) => item.code === 7016))
} finally {
rpc.close()
}
})
}
test('automatically registered package sources refresh LSP and incremental types after input changes', async (t) => {
const dir = mkdtempSync(join(root, 'test/.bundled-sources-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const mapper = join(dir, 'mapper')
const contracts = join(mapper, 'contracts')
mkdirSync(contracts, { recursive: true })
cpSync(join(root, 'dist'), join(mapper, 'dist'), { recursive: true })
const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
writeFileSync(
join(mapper, 'package.json'),
JSON.stringify({ name: 'fixture-mapper', type: 'module', typescript: manifest.typescript }),
)
const schema = join(mapper, 'schema.txt')
writeFileSync(schema, 'string')
writeFileSync(
join(mapper, 'export.mjs'),
`import {readFileSync} from 'node:fs';
process.stdout.write(JSON.stringify({typescript: 'export type Model = {name: ' + readFileSync('schema.txt', 'utf8') + '};'}));`,
)
writeFileSync(
join(contracts, 'shared.json'),
JSON.stringify({
cwd: '..',
command: ['node', 'export.mjs'],
inputs: ['schema.txt', 'export.mjs'],
}),
)
writeFileSync(
join(contracts, 'model.openapi-types'),
JSON.stringify({ extends: './shared.json' }),
)
writeFileSync(join(contracts, 'model.d.ts'), "export type * from './model.openapi-types';")
const source = [
"import type {Model} from './mapper/contracts/model.d.ts';",
'export function name(model: Model): string { return model.name; }',
].join('\n')
writeFileSync(join(dir, 'index.ts'), source)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: { strict: true, noEmit: true, incremental: true, module: 'NodeNext' },
contentMappers: [{ package: mapper, extensions: ['.openapi-types'] }],
include: ['index.ts'],
}),
)
const compile = () =>
spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], {
encoding: 'utf8',
timeout: 30000,
})
const first = compile()
assert.ifError(first.error)
assert.equal(first.status, 0, first.stdout + first.stderr)
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)
try {
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(dir).href,
initializationOptions: { runExternalCode: true },
capabilities: {
general: { positionEncodings: ['utf-16'] },
textDocument: {
diagnostic: { dynamicRegistration: false },
hover: { contentFormat: ['plaintext'] },
},
},
})
rpc.notify('initialized', {})
const uri = pathToFileURL(join(dir, 'index.ts')).href
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
const hover = () =>
rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 0, character: source.indexOf('Model') },
})
assert.match(JSON.stringify(await hover()), /name: string/)
writeFileSync(schema, 'number')
rpc.notify('workspace/didChangeWatchedFiles', {
changes: [{ uri: pathToFileURL(schema).href, type: 2 }],
})
assert.match(JSON.stringify(await hover()), /name: number/)
const diagnostics = await rpc.request('textDocument/diagnostic', { textDocument: { uri } })
assert(diagnostics.items.some((item) => item.code === 2322))
const changed = compile()
assert.ifError(changed.error)
assert.notEqual(changed.status, 0)
assert.match(changed.stdout + changed.stderr, /number.*string/)
} finally {
rpc.close()
}
})
@@ -0,0 +1,39 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise byte framing used by the external compiler process. */
import assert from 'node:assert/strict'
import { Buffer } from 'node:buffer'
import { test } from 'node:test'
import { readFrames } from '../dist/tooling/framing.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
function frame(payload) {
return Buffer.from(`Content-Length: ${Buffer.byteLength(payload)}\r\n\r\n${payload}`)
}
async function* chunks(input, size) {
for (let offset = 0; offset < input.length; offset += size)
yield input.subarray(offset, offset + size)
}
async function collect(input, size) {
const result = []
for await (const payload of readFrames(chunks(input, size))) result.push(payload.toString())
return result
}
test('frames preserve byte lengths across fragmented headers, Unicode and coalesced requests', async () => {
const payloads = ['{"text":"中文 🐱"}', '', '{"id":2}', 'next']
const input = Buffer.concat(payloads.map(frame))
for (const size of [1, 7, input.length]) assert.deepEqual(await collect(input, size), payloads)
const large = '文'.repeat(1024 * 1024)
assert.deepEqual(await collect(frame(large), 4096), [large])
})
test('frames reject invalid sizes, oversized headers and truncated input', async () => {
for (const input of [
'Content-Length: -1\r\n\r\n',
'Content-Length: 67108865\r\n\r\n',
'Content-Length: 1.5\r\n\r\n',
'Content-Length: 3\r\n\r\nx',
'Content-Length:',
'x'.repeat(8193),
])
await assert.rejects(collect(Buffer.from(input), 31), /content mapper (frame|header)/)
})
@@ -0,0 +1,154 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Verify the loader's module graph and watch invalidation against the built package. */
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { test } from 'node:test'
import loader from '../dist/tooling/loader.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
function runLoader(context) {
return new Promise((resolve, reject) => {
loader.call({
getResolve: () => async () => {
throw new Error('Unexpected re-export')
},
...context,
async: () => (error, source) => (error ? reject(error) : resolve(source)),
})
})
}
test('loader namespaces use a tiny resource and invalidate when the source document changes', async () => {
const directory = mkdtempSync(join(root, 'test/.loader-&-'))
const file = join(directory, 'spec.json')
const runtime = join(directory, 'runtime.js')
const dependencies = new Set()
const spec = {
openapi: '3.1.0',
info: { title: 'Loader', version: '1' },
paths: { '/pets': { get: { responses: { 200: { description: 'OK' } } } } },
}
const context = {
resourcePath: file,
resourceQuery: '',
getOptions: () => ({ runtime: './runtime.js' }),
addDependency: (file) => dependencies.add(file),
}
try {
writeFileSync(file, JSON.stringify(spec))
writeFileSync(runtime, 'export default {};')
const entry = await runLoader(context)
const rootModule = JSON.parse(entry.match(/export \* from (.+);/)[1])
const namespacePath = join(root, 'dist/tooling/openapi-namespace.js')
const namespaceEntry = await runLoader({
...context,
resourcePath: namespacePath,
getOptions: () => ({}),
resourceQuery: rootModule.slice(rootModule.indexOf('?')),
})
const apiModule = JSON.parse(namespaceEntry.match(/export \* as api from (.+);/)[1])
assert.equal(
resolve(dirname(namespacePath), apiModule.split('?')[0]),
join(root, 'dist/tooling/openapi-namespace.js'),
)
const query = new URLSearchParams(apiModule.slice(apiModule.indexOf('?')))
assert.equal(query.get('openapi-document'), file)
assert.equal(query.get('openapi-router'), '[]')
query.set('openapi-router', JSON.stringify(['pets']))
const namespaceContext = {
...context,
resourcePath: namespacePath,
getOptions: () => ({}),
resourceQuery: `?${query}`,
}
const before = await runLoader(namespaceContext)
assert(before.includes('as "get"'))
const runtimeImport = JSON.parse(before.match(/import runtime from (.+);/)[1])
assert.equal(resolve(dirname(namespaceContext.resourcePath), runtimeImport), runtime)
assert(dependencies.has(file))
assert(dependencies.has(runtime))
spec.paths['/pets'].delete = { responses: { 204: { description: 'Deleted' } } }
writeFileSync(file, JSON.stringify(spec))
const after = await runLoader(namespaceContext)
assert(after.includes('as "delete"'))
assert.notEqual(after, before)
const errors = `${file}.errors.ts`
writeFileSync(errors, 'const errors = {}; export { errors as "GET /pets" };')
const configured = await runLoader(namespaceContext)
assert(configured.includes('openapi-errors='))
assert(dependencies.has(errors))
const errorQuery = new URLSearchParams(query)
errorQuery.delete('openapi-router')
errorQuery.set('openapi-errors', JSON.stringify(['pets', 'get']))
const errorModule = await runLoader({ ...namespaceContext, resourceQuery: `?${errorQuery}` })
assert(errorModule.includes('"GET /pets" as errors'))
const errorImport = JSON.parse(errorModule.match(/from (.+);/)[1])
assert.equal(resolve(dirname(namespacePath), errorImport), errors)
writeFileSync(errors, 'const errors = {}; export { errors as "DELETE /pets" };')
const changed = await runLoader(namespaceContext)
assert.notEqual(changed, configured)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
test('loader resolves logical sidecar re-exports and invalidates when their sources change', async () => {
const directory = mkdtempSync(join(root, 'test/.loader-sidecars-'))
const file = join(directory, 'physical.json')
const logical = join(directory, 'logical.openapi')
const namespacePath = join(root, 'dist/tooling/openapi-namespace.js')
const dependencies = new Set()
const resolutions = []
const context = {
resourcePath: namespacePath,
resourceQuery: `?${new URLSearchParams({ 'openapi-document': file, 'openapi-query': JSON.stringify(['pets']) })}`,
getOptions: () => ({ sidecars: './logical.openapi' }),
addDependency: (file) => dependencies.add(file),
getResolve: (options) => async (context, request) => {
assert.deepEqual(options, { dependencyType: 'esm' })
assert.equal(context, directory)
resolutions.push(request)
return resolve(context, request.replace(/\.js$/, '.ts'))
},
}
try {
writeFileSync(
file,
JSON.stringify({
openapi: '3.1.0',
info: { title: 'Logical sidecars', version: '1' },
paths: { '/pets': { get: { responses: { 200: { description: 'OK' } } } } },
}),
)
writeFileSync(`${logical}.queries.ts`, "export * from './defaults.js';")
writeFileSync(
join(directory, 'defaults.ts'),
'const defaults = { queryOptions: { staleTime: 42 } }; export { defaults as "GET /pets" };',
)
writeFileSync(`${logical}.errors.ts`, "export * from './errors.js';")
writeFileSync(
join(directory, 'errors.ts'),
'const errors = { CONFLICT: { status: 409 } }; export { errors as "GET /pets" };',
)
const [selected, concurrent] = await Promise.all([runLoader(context), runLoader(context)])
assert.equal(concurrent, selected)
assert.deepEqual(resolutions.sort(), ['./defaults.js', './errors.js'])
assert(selected.includes('"GET /pets" as operation0Defaults'))
assert(selected.includes('openapi-errors='))
assert(dependencies.has(`${logical}.queries.ts`))
assert(dependencies.has(`${logical}.errors.ts`))
assert(dependencies.has(join(directory, 'defaults.ts')))
assert(dependencies.has(join(directory, 'errors.ts')))
writeFileSync(join(directory, 'errors.ts'), 'export {};')
const changed = await runLoader(context)
assert(!changed.includes('openapi-errors='))
assert(changed.includes('"GET /pets" as operation0Defaults'))
const withoutSidecars = await runLoader({ ...context, getOptions: () => ({}) })
assert(!withoutSidecars.includes('operation0Defaults'))
assert(!withoutSidecars.includes('openapi-errors='))
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
@@ -0,0 +1,122 @@
/* oxlint-disable vitest/no-import-node-test -- Integration tests exercise the built package in native Node, including its module hooks. */
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { parseDocument } from 'yaml'
import { rpcProcess } from './rpc.mjs'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
test('native TS 7.1 LSP: operation completions, hover, definition into YAML, live schema updates', async () => {
const dir = mkdtempSync(join(root, 'test/.lsp-'))
const specDocument = parseDocument(
readFileSync(join(root, 'examples/petstore/pets.openapi.yaml'), 'utf8'),
)
specDocument.setIn(['paths', '/pets/{petId}', 'get', 'x-source-location'], {
file: './backend.py',
line: 7,
})
const spec = specDocument.toString()
const source = [
"import { api, query } from './pets.yaml';",
'// SDK inferred by the content mapper',
'const pet = await api.pets.byPetId.get({ params: { petId: 1 } });',
'pet.name;',
'query.pets.byPetId.get.queryOptions({input: {params: {petId: 1}}});',
'api.pets.byPetId.',
].join('\n')
writeFileSync(join(dir, 'pets.yaml'), spec)
writeFileSync(join(dir, 'index.ts'), source)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
module: 'NodeNext',
target: 'ES2022',
skipLibCheck: true,
},
contentMappers: [{ package: root, extensions: ['.yaml'] }],
include: ['*.ts'],
}),
)
const rpc = rpcProcess(
process.execPath,
[join(root, 'node_modules/typescript/bin/tsc'), '--lsp', '--stdio'],
root,
)
const uri = pathToFileURL(join(dir, 'index.ts')).href
const specUri = pathToFileURL(join(dir, 'pets.yaml')).href
try {
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(root).href,
initializationOptions: { runExternalCode: true },
workspaceFolders: [{ uri: pathToFileURL(root).href, name: 'openapi-content-mapper' }],
capabilities: {
general: { positionEncodings: ['utf-16'] },
textDocument: { hover: { contentFormat: ['plaintext'] } },
},
})
rpc.notify('initialized', {})
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
const completions = await rpc.request('textDocument/completion', {
textDocument: { uri },
position: { line: 5, character: source.split('\n')[5].length },
})
const labels = (completions.items ?? completions).map((item) => item.label)
assert(labels.includes('get'), JSON.stringify(completions))
assert(labels.includes('delete'))
const hover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 3, character: 5 },
})
assert.match(JSON.stringify(hover), /name.*string/)
const methodHover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 2, character: source.split('\n')[2].indexOf('.get') + 2 },
})
assert.match(JSON.stringify(methodHover), /Open backend implementation/)
assert.match(JSON.stringify(methodHover), /backend.py#L7/)
const definitions = await rpc.request('textDocument/definition', {
textDocument: { uri },
position: { line: 2, character: source.split('\n')[2].indexOf('.get') + 2 },
})
assert.match(JSON.stringify(definitions), /pets.yaml/)
const queryDefinition = await rpc.request('textDocument/definition', {
textDocument: { uri },
position: { line: 4, character: source.split('\n')[4].indexOf('.get') + 2 },
})
assert.match(JSON.stringify(queryDefinition), /pets.yaml/)
const queryHover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 4, character: source.split('\n')[4].indexOf('.get') + 2 },
})
assert.match(JSON.stringify(queryHover), /backend.py#L7/)
rpc.notify('textDocument/didOpen', {
textDocument: { uri: specUri, languageId: 'yaml', version: 1, text: spec },
})
const changed = parseDocument(spec)
changed.setIn(['components', 'schemas', 'Pet', 'properties', 'name', 'type'], 'number')
rpc.notify('textDocument/didChange', {
textDocument: { uri: specUri, version: 2 },
contentChanges: [{ text: changed.toString() }],
})
const changedHover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 3, character: 5 },
})
assert.match(JSON.stringify(changedHover), /name.*number/)
await rpc.request('shutdown')
rpc.notify('exit')
} finally {
rpc.close()
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,94 @@
/* oxlint-disable vitest/no-import-node-test -- Exercise the mapper's disposable disk cache directly. */
import assert from 'node:assert/strict'
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
/* oxlint-disable antfu/no-import-dist -- Verify the emitted modules used by the external compiler process. */
import { createCachedTransform } from '../dist/tooling/mapper-cache.js'
import { transformSpec } from '../dist/tooling/transform.js'
/* oxlint-enable antfu/no-import-dist */
/* oxlint-enable vitest/no-import-node-test */
const spec = 'openapi: 3.1.0\npaths: {}'
test('mapper cache survives instances and invalidates on content, location, implementation and sidecars', async () => {
const dir = mkdtempSync(join(tmpdir(), 'openapi-cache-test-'))
try {
const cache = join(dir, 'cache')
const file = join(dir, 'spec.yaml')
let calls = 0
const transform = (content, fileName) => {
calls++
return transformSpec(content, fileName)
}
const first = createCachedTransform(cache, 'v1', transform)
const expected = JSON.parse(await first(spec, file))
assert.equal(calls, 1)
const second = createCachedTransform(cache, 'v1', transform)
assert.deepEqual(JSON.parse(await second(spec, file)), expected)
assert.equal(calls, 1)
await second(`${spec}\n# moved source positions`, file)
assert.equal(calls, 2)
await second(spec, join(dir, 'other.yaml'))
assert.equal(calls, 3)
const next = createCachedTransform(cache, 'v2', transform)
await next(spec, file)
assert.equal(calls, 4)
writeFileSync(`${file}.config.ts`, 'export type Context = { token: string }')
const configured = JSON.parse(await next(spec, file))
assert.match(configured.text, /spec\.yaml\.config\.ts/)
assert.equal(calls, 5)
rmSync(`${file}.config.ts`)
assert.doesNotMatch(JSON.parse(await next(spec, file)).text, /spec\.yaml\.config\.ts/)
assert.equal(calls, 6)
assert(readdirSync(cache).every((name) => name.endsWith('.cache')))
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
test('corrupt caches, incomplete writes and unavailable cache directories cannot break mapping', async () => {
const dir = mkdtempSync(join(tmpdir(), 'openapi-cache-test-'))
try {
const file = join(dir, 'spec.yaml')
const cache = join(dir, 'cache')
const cached = createCachedTransform(cache, 'v1')
const expected = await cached(spec, file)
const entry = join(cache, readdirSync(cache)[0])
const original = readFileSync(entry, 'utf8')
for (const corrupt of [
'{',
original.slice(0, 100),
original.replace('"text":', '"broken":'),
`${original} `,
`wrong-key${original.slice(9)}`,
original.replace(/\n/, ' '),
]) {
writeFileSync(entry, corrupt)
assert.equal(await cached(spec, file), expected)
}
const blocked = join(dir, 'not-a-directory')
writeFileSync(blocked, '')
assert.equal(await createCachedTransform(blocked, 'v1')(spec, file), expected)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
test('diagnostics are not cached and document revisions reuse a bounded set of slots', async () => {
const dir = mkdtempSync(join(tmpdir(), 'openapi-cache-test-'))
try {
const cache = join(dir, 'cache')
const cached = createCachedTransform(cache, 'v1')
const file = join(dir, 'spec.yaml')
assert(JSON.parse(await cached('openapi: [', file)).diagnostics)
assert.deepEqual(readdirSync(dir), [])
for (let version = 0; version < 3; version++) await cached(`${spec}\n# ${version}`, file)
assert.equal(readdirSync(cache).length, 1)
for (let i = 0; i < 70; i++) await cached(spec, join(dir, `${i}.yaml`))
assert.equal(readdirSync(cache).length, 64)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,78 @@
const json = (kind) => ({
schema: {
type: 'object',
required: ['kind'],
properties: { kind: { const: kind } },
},
})
const post = (content, required = true) => ({
post: {
requestBody: { required, content },
responses: { 204: { description: 'Done' } },
},
})
const binary = { type: 'string', format: 'binary' }
export const mediaSpec = {
openapi: '3.1.0',
paths: {
'/wildcard': {
get: { responses: { 200: { content: { '*/*': { schema: binary } } } } },
},
'/text-wildcard': {
get: { responses: { 200: { content: { 'text/*': { schema: { type: 'string' } } } } } },
},
'/mixed': post({
// Deliberately put vendor JSON first: the default must not depend on key order.
'application/vnd.example+json': json('vendor'),
'application/json': json('standard'),
'multipart/form-data': json('form'),
}),
'/vendors': post({
'application/vnd.first+json': json('first'),
'application/vnd.second+json': json('second'),
}),
'/optional-vendors': post(
{
'application/vnd.first+json': json('first'),
'application/vnd.second+json': json('second'),
},
false,
),
'/single': post({ 'application/vnd.example+json': json('single') }),
'/binary': {
get: {
responses: {
200: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['inline', 'referenced'],
properties: {
inline: binary,
referenced: { $ref: '#/components/schemas/Binary' },
},
},
},
},
},
},
},
},
'/vendor-binary': {
get: {
responses: {
200: {
content: {
'application/vnd.example+json': {
schema: { $ref: '#/components/schemas/Binary' },
},
},
},
},
},
},
},
components: { schemas: { Binary: binary } },
}
@@ -0,0 +1,49 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Native integration with the built mapper and editor navigation adapter. */
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { compileRuntime, transformSpec } from '../dist/tooling/transform.js'
import { backendLocations } from '../vscode/locations.cjs'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
test('backend links survive Markdown-sensitive filenames without entering runtime modules', () => {
const spec = JSON.stringify({
openapi: '3.1.0',
info: { title: 'navigation', version: '1' },
paths: {
'/pets': {
get: {
'x-source-location': { file: './back end(1)*/handler.py', line: 12 },
responses: { 204: { description: 'OK' } },
},
},
},
})
const result = transformSpec(spec, '/project/spec.openapi')
assert.equal(result.diagnostics, undefined)
assert.deepEqual(backendLocations([{ value: result.text }]), [
{
uri: 'file:///project/back%20end%281%29%2A/handler.py',
line: 12,
},
])
assert.doesNotMatch(
compileRuntime(spec, '/project/spec.openapi')(['pets']),
/handler.py|x-source-location|Open backend/,
)
})
test('navigation ignores missing, malformed, unrelated and non-file links and deduplicates origins', () => {
const link = '[Open backend implementation](file:///project/backend.py#L9)'
assert.deepEqual(
backendLocations([
{ value: `${link}\n${link}` },
'[Unrelated](file:///project/other.py#L9)',
'[Open backend implementation](https://example.com/backend.py#L9)',
'[Open backend implementation](file:///project/backend.py#L0)',
'[Open backend implementation](file:///project/backend.py#L99999999999999999)',
'[Open backend implementation](file:///project/backend.py?query=x#L9)',
'ordinary hover without metadata',
]),
[{ uri: 'file:///project/backend.py', line: 9 }],
)
})
@@ -0,0 +1,70 @@
import { Buffer } from 'node:buffer'
import { spawn } from 'node:child_process'
export function rpcProcess(command, args, cwd, timeoutMs = 15000) {
const child = spawn(command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] })
let stderr = ''
let buffer = Buffer.alloc(0)
let sequence = 0
const pending = new Map()
child.stderr.on('data', (chunk) => {
stderr += chunk
})
child.on('exit', (code) => {
for (const { reject } of pending.values())
reject(new Error(`RPC process exited (${code}): ${stderr}`))
})
function write(message) {
const bytes = Buffer.from(JSON.stringify(message))
child.stdin.write(`Content-Length: ${bytes.length}\r\n\r\n`)
child.stdin.write(bytes)
}
child.stdout.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk])
while (true) {
const end = buffer.indexOf('\r\n\r\n')
if (end < 0) return
const length = Number(/Content-Length:\s*(\d+)/i.exec(buffer.subarray(0, end).toString())[1])
if (buffer.length < end + 4 + length) return
const message = JSON.parse(buffer.subarray(end + 4, end + 4 + length).toString())
buffer = buffer.subarray(end + 4 + length)
if (message.method && message.id !== undefined) {
const result =
message.method === 'workspace/configuration' ? message.params.items.map(() => null) : null
write({ jsonrpc: '2.0', id: message.id, result })
} else if (pending.has(message.id)) {
const { resolve, reject } = pending.get(message.id)
pending.delete(message.id)
message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result)
}
}
})
return {
notify(method, params) {
write({ jsonrpc: '2.0', method, params })
},
request(method, params) {
const id = ++sequence
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pending.delete(id)
reject(new Error(`Timed out: ${method}\n${stderr}`))
}, timeoutMs)
pending.set(id, {
resolve: (value) => {
clearTimeout(timeout)
resolve(value)
},
reject: (error) => {
clearTimeout(timeout)
reject(error)
},
})
write({ jsonrpc: '2.0', id, method, params })
})
},
close() {
child.kill()
},
}
}
@@ -0,0 +1,422 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Integration tests exercise the built package in native Node, including its module hooks. */
import assert from 'node:assert/strict'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
import { QueryClient } from '@tanstack/query-core'
import { invokeRpcOperation } from '../dist/client.js'
import { ApiError, createClient, client as defaultClient } from '../dist/index.js'
import { describeOperations } from '../dist/operation.js'
import { createQueryKey, createQueryOperation } from '../dist/query-runtime.js'
import { compileRuntime, transformSpec } from '../dist/tooling/transform.js'
import { mediaSpec } from './media.mjs'
import '../dist/tooling/register.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const { api, query: generatedQuery } = await import('../examples/petstore/pets.openapi.yaml')
const pet = { id: 1, name: 'Mochi', status: 'available' }
test('wildcard response media preserve Blob types, specific matches and HTTP errors', async () => {
const response = (...media) => ({ content: Object.fromEntries(media.map((type) => [type, {}])) })
const operation = describeOperations({
openapi: '3.1.0',
paths: {
'/files': {
get: {
operationId: 'file',
responses: {
'2XX': { $ref: '#/components/responses/File' },
201: response('application/json', '*/*'),
202: response('text/*', '*/*'),
203: response('application/*', '*/*'),
206: response('text/plain'),
},
},
},
},
components: { responses: { File: response('*/*') } },
}).get('file')
let reply
const client = createClient({ baseUrl: 'https://example.test', fetch: async () => reply })
for (const [status, contentType, expected] of [
[200, 'text/plain', 'blob'],
[200, 'application/json', 'blob'],
[200, 'text/event-stream', 'blob'],
[201, 'application/json', 'json'],
[201, 'text/plain', 'blob'],
[202, 'text/event-stream', 'text'],
[203, 'application/json', 'blob'],
[206, 'text/plain', 'text'],
]) {
reply = new Response('123', { status, headers: { 'content-type': contentType } })
const value = await client.request(operation)
if (expected === 'blob') {
assert(value instanceof Blob, `${status} ${contentType}`)
assert.equal(await value.text(), '123')
} else assert.equal(value, expected === 'json' ? 123 : '123')
}
reply = Response.json({ code: 'DENIED' }, { status: 403 })
await assert.rejects(client.request(operation), (error) => {
assert(error instanceof ApiError)
assert.deepEqual(error.data, { code: 'DENIED' })
return true
})
})
test('document sidecar automatically binds only API and query exports in Node', async () => {
const dir = await mkdtemp(join(import.meta.dirname, '.config-'))
try {
const file = join(dir, 'api.openapi')
await writeFile(
file,
JSON.stringify({
openapi: '3.1.0',
paths: {
...Object.fromEntries(
['then', 'api', 'query', 'default'].map((operationId, index) => [
index ? `/pets/${operationId}` : '/pets',
{ get: { operationId, responses: { 200: { description: 'OK' } } } },
]),
),
},
}),
)
await writeFile(
`${file}.config.ts`,
`
import { createClient } from '@dify/openapi-content-mapper';
export type Context = { user?: string };
export default {
queryKeyPrefix: ['app'],
createClient: ({ context }) => createClient({
baseUrl: 'https://bound.test',
fetch: async (url) => Response.json({ url: String(url), user: context?.user }),
}),
};
`,
)
const bound = await import(pathToFileURL(file).href)
assert.deepEqual(Object.keys(bound), ['api', 'query'])
assert.equal((await bound.api.pets.get()).url, 'https://bound.test/pets')
assert.equal(
(await bound.api.pets.get(undefined, { context: { user: 'alice' } })).user,
'alice',
)
const options = bound.query.pets.get.queryOptions({ input: {}, context: { user: 'bob' } })
assert.equal((await options.queryFn({ signal: new AbortController().signal })).user, 'bob')
assert.deepEqual(bound.query.pets.key(), [['app', 'pets'], {}])
} finally {
await rm(dir, { recursive: true, force: true })
}
})
test('document configuration shares transport and keys without leaking per-call context', async () => {
const operation = { method: 'get', path: '/pets' }
const seen = []
const errors = []
const config = {
queryKeyPrefix: ['console'],
createClient: ({ context, signal }) =>
createClient({
baseUrl: `https://${context.user}.example.test`,
fetch: async (url, init) => {
seen.push([String(url), init.signal === signal])
return Response.json(pet)
},
}),
onError: (error) => errors.push(error),
}
const query = createQueryOperation(operation, ['pets', 'get'], config)
const controller = new AbortController()
await Promise.all([
invokeRpcOperation(
operation,
{},
{ context: { user: 'alice' }, signal: controller.signal },
config,
),
query.queryOptions({ context: { user: 'bob' } }).queryFn({ signal: controller.signal }),
invokeRpcOperation(operation, {}, { context: { user: 'carol' } }, config),
])
assert.deepEqual(seen.map(([url]) => url).sort(), [
'https://alice.example.test/pets',
'https://bob.example.test/pets',
'https://carol.example.test/pets',
])
assert(seen.every(([, forwarded]) => forwarded))
assert.deepEqual(createQueryKey([], config)(), [['console'], {}])
assert.deepEqual(query.queryKey()[0], ['console', 'pets', 'get'])
const failure = new Error('failed')
const override = createClient({
baseUrl: 'https://override.test',
fetch: async () => {
throw failure
},
})
await assert.rejects(
invokeRpcOperation(operation, {}, { client: override }, config),
(error) => error === failure,
)
assert.deepEqual(errors, [failure])
})
test('nested client sends params/query/body, headers and cancellation through Fetch', async () => {
const calls = []
const client = createClient({
baseUrl: 'https://example.test/v1',
headers: { Authorization: 'Bearer test-only' },
fetch: async (url, init) => {
calls.push({ url: String(url), ...init })
if (init.method === 'DELETE') return new Response(null, { status: 204 })
return Response.json(pet)
},
})
const controller = new AbortController()
assert.deepEqual(
await api.pets.byPetId.get({ params: { petId: 1 } }, { client, signal: controller.signal }),
pet,
)
assert.equal(calls[0].url, 'https://example.test/v1/pets/1')
assert.equal(calls[0].headers.get('authorization'), 'Bearer test-only')
assert.equal(calls[0].signal, controller.signal)
await api.pets.get({ query: { status: 'available', limit: 0 } }, { client })
assert.match(calls[1].url, /limit=0/)
assert.match(calls[1].url, /status=available/)
await api.pets.post({ body: { name: '雪团' } }, { client, headers: { 'X-Test': '1' } })
assert.equal(calls[2].body, '{"name":"雪团"}')
assert.equal(calls[2].headers.get('content-type'), 'application/json')
assert.equal(calls[2].headers.get('x-test'), '1')
assert.equal(await api.pets.byPetId.delete({ params: { petId: 1 } }, { client }), undefined)
await assert.rejects(api.pets.byPetId.get({}, { client }), /Missing required path/)
await assert.rejects(api.pets.post({}, { client }), /Missing required request body/)
assert.equal(calls.length, 4, 'Missing required input must fail before sending a request')
})
test('HTTP errors preserve status and payload; abort errors are not swallowed', async () => {
const client = createClient({
baseUrl: 'https://example.test',
fetch: async () => Response.json({ message: 'Missing' }, { status: 404 }),
})
await assert.rejects(api.pets.byPetId.get({ params: { petId: 1 } }, { client }), (error) => {
assert(error instanceof ApiError)
assert.equal(error.response.status, 404)
assert.deepEqual(error.data, { message: 'Missing' })
return true
})
client.setConfig({
fetch: async (_url, init) => {
init.signal.throwIfAborted()
return Response.json(pet)
},
})
const reason = new Error('cancelled')
await assert.rejects(
api.pets.byPetId.get({ params: { petId: 1 } }, { client, signal: AbortSignal.abort(reason) }),
(error) => error === reason,
)
})
test('OpenAPI serializers escape path segments, encode query arrays/objects, and apply parameter overrides', async () => {
const spec = {
openapi: '3.1.0',
paths: {
'/files/{key}': {
parameters: [
{ name: 'key', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'tag', in: 'query', required: true },
],
get: {
operationId: 'getFile',
parameters: [
{ name: 'tag', in: 'query', required: false },
{ name: 'filter', in: 'query', style: 'deepObject', explode: true },
{ name: 'x-tags', in: 'header', style: 'simple' },
],
responses: { 200: { description: 'ok' } },
},
},
},
}
const operation = describeOperations(spec).get('getFile')
let observed
const client = createClient({
baseUrl: 'https://example.test/base/',
fetch: async (url, options) => {
observed = { url, options }
return new Response('ok', { headers: { 'Content-Type': 'text/plain' } })
},
})
assert.equal(
await client.request(operation, {
path: { key: 'a/b c' },
query: { tag: ['one&two', 'three'], filter: { active: false } },
header: { 'x-tags': ['a', 'b'] },
}),
'ok',
)
assert.equal(observed.url.pathname, '/base/files/a%2Fb%20c')
assert.deepEqual(observed.url.searchParams.getAll('tag'), ['one&two', 'three'])
assert.equal(observed.url.searchParams.get('filter[active]'), 'false')
assert.equal(observed.options.headers.get('x-tags'), 'a,b')
await client.request(operation, { path: { key: 'ok' } })
})
test('existing oRPC TanStack Query helpers infer and execute nested calls', async () => {
const before = defaultClient.getConfig()
defaultClient.setConfig({
baseUrl: 'https://example.test',
fetch: async () => Response.json(pet),
})
const queryClient = new QueryClient()
try {
const query = createTanstackQueryUtils(api)
const options = query.pets.byPetId.get.queryOptions({ input: { params: { petId: 1 } } })
assert.deepEqual(await queryClient.fetchQuery(options), pet)
assert.deepEqual(queryClient.getQueryData(options.queryKey), pet)
const generatedOptions = generatedQuery.pets.byPetId.get.queryOptions({
input: { params: { petId: 1 } },
})
assert.deepEqual(await queryClient.fetchQuery(generatedOptions), pet)
assert.deepEqual(generatedQuery.pets.key(), query.pets.key())
assert.deepEqual(generatedQuery.pets.byPetId.get.key(), query.pets.byPetId.get.key())
} finally {
defaultClient.setConfig({ baseUrl: undefined, fetch: undefined, headers: undefined, ...before })
queryClient.clear()
}
})
test('mapper and runtime reject the same invalid documents and route names', () => {
const operation = (id) => ({ operationId: id, responses: { 200: { description: 'ok' } } })
for (const [spec, expected] of [
[
{
openapi: '3.1.0',
paths: {
'/x': {
get: { ...operation('x'), responses: { 200: { $ref: 'remote.yaml#/Response' } } },
},
},
},
/Only local JSON Pointer/,
],
[
{
openapi: '3.1.0',
paths: { '/x': { get: operation('a') }, '/x/get': { get: operation('b') } },
},
/collides with an existing member/,
],
[
{ openapi: '3.1.0', paths: { '/x': { get: operation('a'), post: operation('a') } } },
/Duplicate operationId/,
],
[
{ openapi: '3.1.0', paths: {}, components: { schemas: { X: { $ref: '#/missing' } } } },
/Unresolved reference/,
],
['openapi: 3.1.0\npaths: {}\nx-value: .inf', /non-finite numbers/],
['openapi: 3.1.0\npaths: {}\n? [complex, key]\n: value', /keys must be strings or numbers/],
['openapi: 3.1.0\npaths: {}\nx-value: &value {}\nx-alias: *value', /alias/i],
]) {
const content = typeof spec === 'string' ? spec : JSON.stringify(spec)
const result = transformSpec(content, 'spec.openapi')
assert.match(result.diagnostics[0].messageText, expected)
assert.throws(() => compileRuntime(content, 'spec.openapi'), expected)
}
})
test('nested typed headers reach Fetch alongside transport headers without filling schema defaults', async () => {
const calls = []
const client = createClient({
baseUrl: 'https://example.test',
headers: { Authorization: 'Bearer shared' },
fetch: async (url, init) => {
calls.push({ url, ...init })
return Response.json({})
},
})
const operation = {
method: 'post',
path: '/settings',
parameters: [
{ in: 'header', name: 'Idempotency-Key', required: true, style: 'simple', explode: false },
{ in: 'header', name: 'X-Tags', required: false, style: 'simple', explode: false },
],
}
const result = await invokeRpcOperation(
operation,
{ headers: { 'Idempotency-Key': 'key', 'X-Tags': ['a', 'b'] } },
{ client, headers: { 'X-Transport': 'extra' } },
)
assert.equal(calls[0].headers.get('Idempotency-Key'), 'key')
assert.equal(calls[0].headers.get('X-Tags'), 'a,b')
assert.equal(calls[0].headers.get('Authorization'), 'Bearer shared')
assert.equal(calls[0].headers.get('X-Transport'), 'extra')
assert.deepEqual(result, {})
await assert.rejects(invokeRpcOperation(operation, {}, { client }), /Missing required header/)
})
test('request media defaults agree with types and JSON responses preserve wire values', async () => {
const operations = [...describeOperations(mediaSpec).values()]
const operation = (path) => operations.find((operation) => operation.path === path)
const calls = []
const client = createClient({
baseUrl: 'https://example.test',
fetch: async (_url, init) => {
calls.push(init)
return Response.json({ inline: 'inline', referenced: 'referenced' })
},
})
await client.request(operation('/mixed'), { body: { kind: 'standard' } })
assert.equal(calls.at(-1).headers.get('content-type'), 'application/json')
await client.request(operation('/mixed'), {
body: { kind: 'vendor' },
contentType: 'application/vnd.example+json',
})
assert.equal(calls.at(-1).headers.get('content-type'), 'application/vnd.example+json')
assert.equal(calls.at(-1).body, '{"kind":"vendor"}')
await client.request(operation('/single'), { body: { kind: 'single' } })
assert.equal(calls.at(-1).headers.get('content-type'), 'application/vnd.example+json')
await assert.rejects(
client.request(operation('/vendors'), { body: { kind: 'second' } }),
/content type/,
)
await assert.rejects(client.request(operation('/vendors')), /Missing required request body/)
assert.equal(calls.length, 3, 'Ambiguous media and missing bodies fail before sending')
await client.request(operation('/vendors'), {
body: { kind: 'second' },
contentType: 'application/vnd.second+json',
})
assert.equal(calls.at(-1).headers.get('content-type'), 'application/vnd.second+json')
assert.deepEqual(await client.request(operation('/binary')), {
inline: 'inline',
referenced: 'referenced',
})
})
test('downloads preserve filenames, encoded names, media type and bytes', async () => {
const bytes = new Uint8Array([0x50, 0x4b, 0x00, 0xff])
for (const [disposition, name] of [
['attachment; filename="agent.ifpkg"', 'agent.ifpkg'],
['attachment; filename="fallback.zip"; filename*=UTF-8\'\'%E7%9F%A5%E8%AF%86.zip', '知识.zip'],
['attachment', 'blob'],
]) {
const client = createClient({
baseUrl: 'https://example.test',
fetch: async () =>
new Response(bytes, {
headers: {
'content-type': 'application/zip',
'content-disposition': disposition,
},
}),
})
const result = await client.request({ method: 'get', path: '/download' })
assert(result instanceof File)
assert.equal(result.name, name)
assert.equal(result.type, 'application/zip')
assert.deepEqual(new Uint8Array(await result.arrayBuffer()), bytes)
}
})
@@ -0,0 +1,326 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise command sources through the real compiler and adapters. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { setTimeout as delay } from 'node:timers/promises'
import { pathToFileURL } from 'node:url'
import { build, createServer } from 'vite'
import loader from '../dist/tooling/loader.js'
import { inspectSource, resolveDocument } from '../dist/tooling/source.js'
import { openapi } from '../dist/tooling/vite.js'
import { rpcProcess } from './rpc.mjs'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
function fixture(t) {
const directory = mkdtempSync(join(root, 'test/.source-'))
t.after(() => rmSync(directory, { recursive: true, force: true }))
mkdirSync(join(directory, 'unwatched'))
const file = join(directory, 'pets.openapi-source')
const schema = join(directory, 'schema.txt')
writeFileSync(schema, 'string')
writeFileSync(
join(directory, 'export.mjs'),
`
import { readFileSync, appendFileSync } from 'node:fs';
appendFileSync('unwatched/calls', '1');
console.error('Exporter diagnostic');
console.log(JSON.stringify({openapi:'3.1.0',info:{title:'Pets',version:'1'},paths:{
'/pets':{get:{'x-source-location':{file:'./backend.py',line:7},responses:{200:{description:'OK',content:{'application/json':{schema:{type:readFileSync('schema.txt','utf8')}}}}}}},
'/unused':{get:{responses:{204:{description:'OK'}}}}
},components:{schemas:{Pet:{type:readFileSync('schema.txt','utf8')}}}}));
`,
)
const content = JSON.stringify({
command: ['node', 'export.mjs'],
inputs: ['export.mjs', '*.txt'],
})
writeFileSync(file, content)
const config = {
compilerOptions: {
strict: true,
noEmit: true,
incremental: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
},
contentMappers: [
{
package: root,
extensions: ['.openapi-source'],
options: { sources: ['./pets.openapi-source'] },
},
],
include: ['*.ts'],
}
writeFileSync(join(directory, 'tsconfig.json'), JSON.stringify(config))
return { directory, file, content, schema, config }
}
test('command sources stay in memory, cache by backend inputs, and do not cache failed exports', (t) => {
const { directory, file, content, schema } = fixture(t)
const before = inspectSource(content, file)
const first = resolveDocument(content, file)
assert.equal(
JSON.parse(first.content).paths['/pets'].get.responses[200].content['application/json'].schema
.type,
'string',
)
assert(first.dependencies.includes(schema))
writeFileSync(join(directory, 'unrelated.log'), 'Not an exporter input')
assert.equal(inspectSource(content, file).identity, before.identity)
assert.deepEqual(resolveDocument(content, file), first)
assert.equal(readFileSync(join(directory, 'unwatched/calls'), 'utf8'), '1')
writeFileSync(schema, 'number')
assert.notEqual(inspectSource(content, file).identity, before.identity)
assert.notEqual(resolveDocument(content, file).content, first.content)
const identity = inspectSource(content, file).identity
writeFileSync(join(directory, 'new.txt'), 'new source')
assert.notEqual(inspectSource(content, file).identity, identity)
writeFileSync(join(directory, 'export.mjs'), "console.error('export failed');process.exit(1);")
assert.throws(() => resolveDocument(content, file), /export failed/)
writeFileSync(join(directory, 'export.mjs'), "console.log('not JSON');")
assert.throws(() => resolveDocument(content, file), /JSON/)
writeFileSync(join(directory, 'export.mjs'), `console.log(${JSON.stringify(first.content)});`)
assert.equal(resolveDocument(content, file).content.trim(), first.content.trim())
})
test('excluded inputs do not invalidate contracts; optional inputs track creation, edits and removal', (t) => {
const { directory, file } = fixture(t)
mkdirSync(join(directory, 'tests'))
const ignored = join(directory, 'tests/schema.txt')
writeFileSync(ignored, 'unrelated')
const content = JSON.stringify({
command: ['node', 'export.mjs'],
inputs: ['**/*.txt', 'export.mjs'],
exclude: ['tests/**'],
optionalInputs: ['.env'],
})
const first = inspectSource(content, file)
assert(!first.dependencies.includes(ignored))
writeFileSync(ignored, 'another test')
assert.equal(inspectSource(content, file).identity, first.identity)
const env = join(directory, '.env')
assert(first.dependencies.includes(env))
writeFileSync(env, 'SETTING=one')
const created = inspectSource(content, file)
assert.notEqual(created.identity, first.identity)
writeFileSync(env, 'SETTING=two')
assert.notEqual(inspectSource(content, file).identity, created.identity)
rmSync(env)
assert.equal(inspectSource(content, file).identity, first.identity)
})
test('TS incremental checks invalidate when backend input changes without touching the descriptor', (t) => {
const { directory, schema, config } = fixture(t)
writeFileSync(
join(directory, 'index.ts'),
`import { api } from './pets.openapi-source';
import type { Schemas, Inputs, Outputs } from './pets.openapi-source';
const input: Inputs['pets']['get'] = undefined;
const result: string = await api.pets.get(input);
const schema: string = null! as Schemas['Pet'];
const output: string = null! as Outputs['pets']['get'];`,
)
const compile = () =>
spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', directory], {
encoding: 'utf8',
})
const first = compile()
assert.equal(first.status, 0, first.stdout + first.stderr)
writeFileSync(schema, 'number')
const changed = compile()
assert.notEqual(changed.status, 0)
assert.match(changed.stdout + changed.stderr, /number.*string/)
config.contentMappers[0].options.sources = []
writeFileSync(join(directory, 'tsconfig.json'), JSON.stringify(config))
const untracked = compile()
assert.notEqual(untracked.status, 0)
assert.match(untracked.stdout + untracked.stderr, /options.sources/)
})
test('Node, Vite and the Next loader consume the same command source and track its inputs', async (t) => {
const { directory, file, schema } = fixture(t)
const consumer = join(directory, 'consumer.mjs')
writeFileSync(
consumer,
"import { api } from './pets.openapi-source'; export const load = api.pets.get;",
)
const node = spawnSync(
process.execPath,
[
'--import',
join(root, 'dist/tooling/register.js'),
'--input-type=module',
'-e',
`
import { load } from ${JSON.stringify(pathToFileURL(consumer).href)};
globalThis.fetch = async () => new Response(JSON.stringify('pet'), {headers:{'content-type':'application/json'}});
if (await load(undefined, {client: (await import('@dify/openapi-content-mapper')).createClient({baseUrl:'https://example.com'})}) !== 'pet') throw new Error('Wrong response');
`,
],
{ cwd: root, encoding: 'utf8' },
)
assert.equal(node.status, 0, node.stderr)
const bundled = await build({
configFile: false,
root: directory,
logLevel: 'silent',
plugins: [openapi()],
build: { write: false, lib: { entry: consumer, formats: ['es'] }, minify: false },
})
const code = (Array.isArray(bundled) ? bundled : [bundled])
.flatMap((output) => output.output)
.filter((item) => item.type === 'chunk')
.map((item) => item.code)
.join('\n')
assert(code.includes('/pets'))
assert(!code.includes('/unused'))
assert(!code.includes('export.mjs'))
const dependencies = new Set()
const run = () =>
new Promise((resolve, reject) =>
loader.call({
resourcePath: join(root, 'dist/tooling/openapi-namespace.js'),
resourceQuery: `?${new URLSearchParams({ 'openapi-document': file, 'openapi-router': '[]' })}`,
getOptions: () => ({}),
getResolve: () => async () => {
throw new Error('Unexpected resolution')
},
addDependency: (file) => dependencies.add(file),
async: () => (error, code) => (error ? reject(error) : resolve(code)),
}),
)
const before = await run()
assert(before.includes('pets'))
assert(dependencies.has(schema))
const exporter = join(directory, 'export.mjs')
writeFileSync(exporter, readFileSync(exporter, 'utf8').replace("'/pets'", "'/animals'"))
const after = await run()
assert(after.includes('animals'))
assert(!after.includes('"pets"'))
})
for (const external of [false, true]) {
test(`Vite refreshes command sources for input additions and removals (${external ? 'outside' : 'inside'} root)`, async (t) => {
const { directory, file, content } = fixture(t)
writeFileSync(file, JSON.stringify({ ...JSON.parse(content), optionalInputs: ['backend.env'] }))
const exporter = join(directory, 'export.mjs')
writeFileSync(
exporter,
readFileSync(exporter, 'utf8')
.replace('readFileSync, appendFileSync', 'readFileSync, appendFileSync, existsSync')
.replace(
"'/pets':",
"[existsSync('backend.env') ? '/configured' : existsSync('extra.txt') ? '/animals' : '/pets']:",
),
)
const frontend = external ? join(directory, 'frontend') : directory
mkdirSync(frontend, { recursive: true })
writeFileSync(
join(frontend, 'entry.ts'),
`export { api } from '${external ? '..' : '.'}/pets.openapi-source'`,
)
const server = await createServer({
configFile: false,
root: frontend,
logLevel: 'silent',
plugins: [openapi()],
server: { port: 0, fs: { allow: [directory] } },
})
t.after(() => server.close())
// New files created during the initial scan are ignored by Chokidar.
const watcherReady = new Promise((resolve) => server.watcher.once('ready', resolve))
await server.listen()
await watcherReady
await server.transformRequest('/entry.ts')
const specUrl = external ? `/@fs${file}` : '/pets.openapi-source'
await server.transformRequest(specUrl)
const url = `${specUrl}?openapi-router=%5B%5D`
assert.match((await server.transformRequest(url)).code, /pets/)
if (external) {
// External dependencies are discovered on first import, after root readiness.
// Wait until the recursively watched child has actually been scanned.
const deadline = Date.now() + 10000
while (!server.watcher.getWatched()[join(directory, 'unwatched')]?.includes('calls')) {
assert(Date.now() < deadline, 'External dependency watcher did not become ready')
await delay(10)
}
}
async function changeInput(input, mutate, expected) {
const send = server.ws.send.bind(server.ws)
let timeout
const refreshed = new Promise((resolve, reject) => {
timeout = setTimeout(
() => reject(new Error(`No Vite reload after changing ${input}`)),
10000,
)
server.ws.send = (...args) => {
if (args[0]?.type === 'full-reload' && args[0].triggeredBy === input) resolve()
return send(...args)
}
})
try {
mutate()
await refreshed
assert.match((await server.transformRequest(url)).code, expected)
} finally {
clearTimeout(timeout)
server.ws.send = send
}
}
const extra = join(directory, 'extra.txt')
await changeInput(extra, () => writeFileSync(extra, 'new backend route'), /animals/)
await changeInput(extra, () => rmSync(extra), /pets/)
const env = join(directory, 'backend.env')
await changeInput(env, () => writeFileSync(env, 'SETTING=value'), /configured/)
await changeInput(env, () => rmSync(env), /pets/)
})
}
test('the language server refreshes command-source hover types after backend changes', async (t) => {
const { directory, schema } = fixture(t)
const source =
"import { api } from './pets.openapi-source';\nconst pet = await api.pets.get();\npet;"
writeFileSync(join(directory, 'index.ts'), source)
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)
t.after(() => rpc.close())
const uri = pathToFileURL(join(directory, 'index.ts')).href
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(directory).href,
initializationOptions: { runExternalCode: true },
capabilities: {
general: { positionEncodings: ['utf-16'] },
textDocument: { hover: { contentFormat: ['plaintext'] } },
},
})
rpc.notify('initialized', {})
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
const hover = () =>
rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 2, character: 1 },
})
assert.match(JSON.stringify(await hover()), /pet: string/)
const methodHover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 1, character: source.split('\n')[1].indexOf('.get') + 2 },
})
assert.match(JSON.stringify(methodHover), /Open backend implementation/)
assert.match(JSON.stringify(methodHover), /backend.py#L7/)
writeFileSync(schema, 'number')
rpc.notify('workspace/didChangeWatchedFiles', {
changes: [{ uri: pathToFileURL(schema).href, type: 2 }],
})
assert.match(JSON.stringify(await hover()), /pet: number/)
await rpc.request('shutdown')
rpc.notify('exit')
})
@@ -0,0 +1,131 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Compare projected and full virtual documents with the native compiler. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { transformSpec } from '../dist/tooling/transform.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
test('projection preserves structural refs, escaped pointers, literal payloads and binary media types', () => {
const spec = {
openapi: '3.1.0',
info: { title: 'not a type', version: '1' },
paths: { '/pets': { $ref: '#/components/schemas/Path' } },
components: {
schemas: {
Path: {
parameters: [{ $ref: '#/extra/1' }],
get: { $ref: '#/operations/get' },
post: {
requestBody: { $ref: '#/bodies/input' },
responses: { 201: { $ref: '#/responses/pet' } },
},
},
'Pet/~': {
type: 'object',
required: ['name', 'file', 'next', 'literal'],
properties: {
name: { type: 'string' },
file: { type: 'string', format: 'binary' },
next: { anyOf: [{ $ref: '#/components/schemas/Pet~1~0' }, { type: 'null' }] },
literal: { const: { description: 'keep', properties: ['yes'] } },
},
},
},
},
extra: ['unused array slot', { $ref: '#/parameters/query' }],
parameters: { query: { name: 'limit', in: 'query', schema: { type: 'integer' } } },
operations: {
get: {
parameters: [{ name: 'limit', in: 'query', required: true, schema: { type: 'string' } }],
responses: { 200: { $ref: '#/responses/pet' }, 204: { description: 'No content' } },
},
},
bodies: {
input: {
required: true,
content: {
'application/json': { schema: { $ref: '#/components/schemas/Pet~1~0' } },
'multipart/form-data': { schema: { $ref: '#/components/schemas/Pet~1~0' } },
},
},
},
responses: {
pet: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['pet', 'literal', 'impossible'],
properties: {
pet: { $ref: '#/components/schemas/Pet~1~0' },
literal: { const: { description: ['keep', { enum: true }] } },
impossible: false,
},
},
},
},
},
},
}
const dir = mkdtempSync(join(root, 'test/.projection-'))
try {
const projected = transformSpec(JSON.stringify(spec), join(dir, 'spec.openapi'))
assert.equal(projected.diagnostics, undefined)
const commandSource = transformSpec(JSON.stringify(spec), join(dir, 'spec.openapi-source'))
assert.equal(commandSource.text, projected.text)
assert.deepEqual(commandSource.mappings, [])
const declarationEnd = projected.text.indexOf(';\n')
const document = JSON.parse(
projected.text.slice('declare const document: '.length, declarationEnd),
)
assert.equal(document.info, undefined)
assert.equal(document.components.schemas['Pet/~'], undefined)
assert(document.components.schemas.Path)
assert.deepEqual(document.extra, [null, { $ref: '#/parameters/query' }])
const full = `declare const document: ${JSON.stringify(spec)};\n${projected.text.slice(declarationEnd + 2)}`
writeFileSync(join(dir, 'full.ts'), full)
writeFileSync(join(dir, 'projected.ts'), projected.text)
writeFileSync(
join(dir, 'index.ts'),
`
import { api as full, query as fullQuery } from './full.js';
import { api, query } from './projected.js';
const forward: typeof full = api;
const backward: typeof api = full;
const queryForward: typeof fullQuery = query;
const queryBackward: typeof query = fullQuery;
// @ts-expect-error operation parameter overrides path-level number
api.pets.get({query:{limit:1}});
api.pets.get({query:{limit:'1'}});
`,
)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
},
include: ['*.ts'],
}),
)
const result = spawnSync(
process.execPath,
[join(root, 'node_modules/typescript/bin/tsc'), '-p', dir],
{
encoding: 'utf8',
timeout: 30000,
},
)
assert.ifError(result.error)
assert.equal(result.status, 0, result.stdout + result.stderr)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,175 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise type-only command sources through the real compiler. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { inspectSource, resolveDocument, sourceProject } from '../dist/tooling/source.js'
import { transformSpec } from '../dist/tooling/transform.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
test('package sources merge with explicit sources and track shared inputs and module additions', (t) => {
const dir = mkdtempSync(join(import.meta.dirname, '.package-sources-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const bundled = join(dir, 'contracts')
mkdirSync(join(bundled, 'console'), { recursive: true })
const input = join(dir, 'schema.txt')
writeFileSync(input, 'string')
const config = {
command: ['node', '-e', 'throw new Error("Registration must not run exporters")'],
cwd: '..',
inputs: ['schema.txt'],
}
const shared = join(bundled, 'shared.json')
writeFileSync(shared, JSON.stringify(config))
const descriptor = JSON.stringify({ extends: '../shared.json', args: ['first'] })
const first = join(bundled, 'console/first.openapi-types')
writeFileSync(first, descriptor)
const custom = join(dir, 'custom.openapi-types')
writeFileSync(custom, JSON.stringify({ ...config, cwd: '.' }))
const configPath = join(dir, 'tsconfig.json')
const options = { sources: ['./custom.openapi-types'] }
const inspect = () => sourceProject(configPath, options, bundled)
const initial = inspect()
assert.deepEqual([...initial.registered].sort(), [first, custom].sort())
for (const file of [bundled, join(bundled, 'console'), first, shared, input, custom])
assert(initial.watchedFiles.includes(file), file)
writeFileSync(input, 'number')
const changed = inspect()
assert.notEqual(changed.configIdentity, initial.configIdentity)
writeFileSync(shared, JSON.stringify({ ...config, timeoutMs: 10000 }))
assert.notEqual(inspect().configIdentity, changed.configIdentity)
const added = join(bundled, 'console/second.openapi-types')
writeFileSync(added, descriptor)
assert(inspect().registered.has(added))
rmSync(first)
assert(!inspect().registered.has(first))
const standalone = sourceProject(configPath, options, join(dir, 'missing-contracts'))
assert.deepEqual([...standalone.registered], [custom])
})
test('thin type sources inherit cwd and watched inputs and invalidate when shared configuration changes', (t) => {
const dir = mkdtempSync(join(import.meta.dirname, '.inherited-source-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
mkdirSync(join(dir, 'modules'))
writeFileSync(join(dir, 'input.txt'), 'string')
writeFileSync(
join(dir, 'export.mjs'),
`
process.stdout.write(JSON.stringify({typescript: 'export type Module = ' + JSON.stringify(process.argv[2]) + ';'}));
`,
)
const base = join(dir, 'base.json')
const config = { command: ['node', 'export.mjs'], inputs: ['input.txt', 'export.mjs'] }
writeFileSync(base, JSON.stringify(config))
const file = join(dir, 'modules/types.openapi-types')
const content = JSON.stringify({ extends: '../base.json', args: ['datasets'] })
writeFileSync(file, content)
const inspected = inspectSource(content, file)
assert.equal(inspected.cwd, dir)
assert.deepEqual(inspected.command, ['node', 'export.mjs', 'datasets'])
assert(inspected.dependencies.includes(base))
assert(inspected.dependencies.includes(join(dir, 'input.txt')))
assert.match(resolveDocument(content, file).content, /datasets/)
const before = sourceProject(join(dir, 'tsconfig.json'), {
sources: ['./modules/*.openapi-types'],
})
writeFileSync(base, JSON.stringify({ ...config, timeoutMs: 10000 }))
const after = sourceProject(join(dir, 'tsconfig.json'), {
sources: ['./modules/*.openapi-types'],
})
assert.notEqual(after.configIdentity, before.configIdentity)
assert.notEqual(inspectSource(content, file).identity, inspected.identity)
writeFileSync(base, JSON.stringify({ extends: './modules/types.openapi-types' }))
assert.throws(() => inspectSource(content, file), /Circular source descriptor/)
assert.throws(() => inspectSource('{"extends":42}', file), /extends must be/)
assert.throws(() => inspectSource('{"extends":"../missing.json"}', file), /ENOENT/)
})
test('type sources track inputs, preserve named exports, and invalidate incremental checks', (t) => {
const dir = mkdtempSync(join(import.meta.dirname, '.type-source-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
mkdirSync(join(dir, 'sources'))
writeFileSync(join(dir, 'schema.txt'), 'string')
writeFileSync(
join(dir, 'export.mjs'),
`
import {readFileSync} from 'node:fs';
process.stdout.write(JSON.stringify({typescript:
'export type Model = {name: ' + readFileSync('schema.txt', 'utf8') + '};' +
'export type GetData = {path: {id: string}; url: "/pets/{id}"};' +
'export type GetResponses = {200: Model; 204: void};' +
'export type GetResponse = GetResponses[keyof GetResponses];' +
'export type GetErrors = {404: {code: "missing"}; default: {message: string}};' +
'export type GetError = GetErrors[keyof GetErrors];'
}));`,
)
const descriptor = JSON.stringify({
cwd: '..',
command: ['node', 'export.mjs'],
inputs: ['schema.txt', 'export.mjs'],
})
const source = join(dir, 'sources/types.openapi-types')
writeFileSync(source, descriptor)
const config = {
compilerOptions: {
strict: true,
noEmit: true,
incremental: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
},
contentMappers: [
{
package: root,
extensions: ['.openapi-types'],
options: { sources: ['./sources/*.openapi-types'] },
},
],
include: ['check.ts'],
}
const configPath = join(dir, 'tsconfig.json')
writeFileSync(configPath, JSON.stringify(config))
writeFileSync(
join(dir, 'check.ts'),
`
import type {Model, GetData, GetResponses, GetResponse, GetErrors, GetError} from './sources/types.openapi-types';
const name: string = (null! as Model).name;
const input: GetData = {path: {id: 'a'}, url: '/pets/{id}'};
const response: GetResponse = null! as GetResponses[200];
const error: GetError = null! as GetErrors[404];
// @ts-expect-error legacy envelopes do not accept params
const wrong: GetData = {params: {id: 'a'}, url: '/pets/{id}'};
// @ts-expect-error status-indexed response maps are retained
type MissingStatus = GetResponses[201];
`,
)
const compile = () =>
spawnSync(process.execPath, [compiler, '--runExternalCode', '-p', dir], { encoding: 'utf8' })
const first = compile()
assert.equal(first.status, 0, first.stdout + first.stderr)
const before = sourceProject(configPath, config.contentMappers[0].options)
assert(before.registered.has(source))
writeFileSync(join(dir, 'schema.txt'), 'number')
assert.notEqual(
sourceProject(configPath, config.contentMappers[0].options).configIdentity,
before.configIdentity,
)
const changed = compile()
assert.notEqual(changed.status, 0)
assert.match(changed.stdout + changed.stderr, /number.*string/)
writeFileSync(join(dir, 'sources/new.openapi-types'), descriptor)
assert.equal(sourceProject(configPath, config.contentMappers[0].options).registered.size, 2)
config.contentMappers[0].options.sources = []
writeFileSync(configPath, JSON.stringify(config))
const unregistered = compile()
assert.notEqual(unregistered.status, 0)
assert.match(unregistered.stdout + unregistered.stderr, /options.sources/)
writeFileSync(join(dir, 'export.mjs'), 'process.stdout.write(JSON.stringify({typescript: ""}))')
assert.throws(() => resolveDocument(readFileSync(source, 'utf8'), source), /non-empty typescript/)
assert(transformSpec('{"typescript":42}', source).diagnostics)
})
@@ -0,0 +1,722 @@
/* oxlint-disable vitest/no-import-node-test -- Integration tests exercise the built package in native Node, including its module hooks. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { parse, parseDocument } from 'yaml'
import { mediaSpec } from './media.mjs'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
const yaml = readFileSync(join(root, 'examples/petstore/pets.openapi.yaml'), 'utf8')
test('document configuration types context for both the API and query namespaces', () => {
project(
{
'pets.yaml': yaml,
'pets.yaml.config.ts': `
import type { RuntimeConfig } from '@dify/openapi-content-mapper';
export type Context = { silent?: boolean };
const runtime: RuntimeConfig<Context> = {
queryKeyPrefix: ['console'],
createClient: ({context}) => {
const silent: boolean | undefined = context?.silent;
// @ts-expect-error the runtime factory uses the same context contract as callers
const wrong: number = context?.silent;
throw new Error('Type-check only');
},
};
export default runtime;
`,
'index.ts': `
import { api, query } from './pets.yaml';
await api.pets.get(undefined, { context: { silent: true } });
query.pets.get.queryOptions({ input: {}, context: { silent: true } });
query.pets.get.queryOptions();
query.pets.get.queryOptions({ staleTime: Infinity });
query.pets.get.queryKey();
// @ts-expect-error required path input cannot be omitted
query.pets.byPetId.get.queryOptions();
// @ts-expect-error context is inferred from the document configuration
api.pets.get(undefined, { context: { silent: 'yes' } });
// @ts-expect-error query helpers preserve that same context
query.pets.get.queryOptions({ input: {}, context: { silent: 'yes' } });
// @ts-expect-error query helpers retain operation inputs alongside the context
query.pets.byPetId.get.queryOptions({ input: { params: { petId: 'wrong' } }, context: { silent: true } });
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
)
})
function project(files, run, compilerOptions = {}) {
const dir = mkdtempSync(join(root, 'test/.tmp-'))
try {
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
moduleResolution: 'NodeNext',
types: ['node'],
lib: ['ES2022', 'DOM'],
...compilerOptions,
},
contentMappers: [{ package: root, extensions: ['.yaml', '.yml', '.openapi'] }],
include: ['*.ts'],
}),
)
for (const [file, content] of Object.entries(files)) writeFileSync(join(dir, file), content)
run(dir, (...flags) => {
const result = spawnSync(
process.execPath,
[compiler, '-p', dir, '--runExternalCode', '--pretty', 'false', ...flags],
{ cwd: root, encoding: 'utf8', timeout: 20000 },
)
assert.ifError(result.error)
return { status: result.status, output: result.stdout + result.stderr }
})
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
for (const [extension, content] of [
['yaml', yaml],
['openapi', JSON.stringify(parse(yaml))],
]) {
test(`TS 7.1 ${extension}: accurate SDK types, rejected invalid calls, no generated files`, () => {
project(
{
[`pets.${extension}`]: content,
'index.ts': `
import { api, query } from './pets.${extension}';
import type { Schemas, Inputs, Outputs } from './pets.${extension}';
import * as document from './pets.${extension}';
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
const inputMatches: Equal<Inputs['pets']['post'], Parameters<typeof api.pets.post>[0]> = true;
const outputMatches: Equal<Outputs['pets']['byPetId']['get'], Awaited<ReturnType<typeof api.pets.byPetId.get>>> = true;
const schemaMatches: Equal<Schemas['Pet'], Outputs['pets']['byPetId']['get']> = true;
const create: Inputs['pets']['post']['body'] = {name: 'Mochi'};
const optionalInput: Inputs['pets']['get'] = undefined;
const deletedOutput: Outputs['pets']['byPetId']['delete'] = undefined;
// @ts-expect-error required inputs cannot be omitted
const missingInput: Inputs['pets']['post'] = undefined;
// @ts-expect-error inline bodies retain required fields
const missingName: Inputs['pets']['post']['body'] = {};
// @ts-expect-error unknown schema names are rejected
type UnknownSchema = Schemas['Missing'];
// @ts-expect-error type exports are not runtime values
document.Schemas;
// @ts-expect-error operation IDs are not exports
document.getPet;
import { createTanstackQueryUtils } from '@orpc/tanstack-query';
const wrappedQuery = createTanstackQueryUtils(api);
const fromWrapped: typeof query.pets.byPetId.get = wrappedQuery.pets.byPetId.get;
const toWrapped: typeof wrappedQuery.pets.byPetId.get = query.pets.byPetId.get;
// The document helpers also preserve optional inputs that generic client inference loses.
query.pets.get.queryOptions();
const generatedOptions = query.pets.byPetId.get.queryOptions({ input: { params: { petId: 1 } } });
const generatedKey = query.pets.key();
// @ts-expect-error generated query helpers retain parameter types
query.pets.byPetId.get.queryOptions({ input: { params: { petId: 'wrong' } } });
const queryOptions = wrappedQuery.pets.byPetId.get.queryOptions({ input: { params: { petId: 1 } } });
type QueryResult = Awaited<ReturnType<typeof queryOptions.queryFn>>;
const queryName: string = (null! as QueryResult).name;
// @ts-expect-error wrapped query helpers retain required parameter types
wrappedQuery.pets.byPetId.get.queryOptions({ input: { params: { petId: 'wrong' } } });
const pet = await api.pets.byPetId.get({ params: { petId: 1 } });
const name: string = pet.name;
const id: number = pet.id;
const state: 'available' | 'adopted' = pet.status;
const nickname: string | null | undefined = pet.nickname;
const pets = await api.pets.get();
const item: typeof pet = pets[0]!;
const created: typeof pet = await api.pets.post({ body: { name: 'Mochi' } });
const deleted: void = await api.pets.byPetId.delete({ params: { petId: 1 } });
await api.pets.get({ query: { limit: 10, status: 'available' } });
type IsAny<T> = 0 extends (1 & T) ? true : false;
const notAny: IsAny<typeof pet> = false;
// @ts-expect-error response must not silently become any
const wrong: number = pet.name;
// @ts-expect-error no invented response fields
pet.missing;
// @ts-expect-error required path group
api.pets.byPetId.get();
// @ts-expect-error required path parameter
api.pets.byPetId.get({ params: {} });
// @ts-expect-error integer parameter
api.pets.byPetId.get({ params: { petId: '1' } });
// @ts-expect-error unknown operation
api.unknown();
// @ts-expect-error enum values retained from file
api.pets.get({ query: { status: 'lost' } });
// @ts-expect-error no undeclared query arguments
api.pets.get({ query: { invented: true } });
// @ts-expect-error required body
api.pets.post();
// @ts-expect-error required property in body
api.pets.post({ body: {} });
// @ts-expect-error no body on GET
api.pets.get({ body: {} });
`,
},
(dir, check) => {
const before = readdirSync(dir)
const result = check()
assert.equal(result.status, 0, result.output)
assert.deepEqual(readdirSync(dir), before)
},
)
})
}
test('public schemas include unused recursive models, escaped names and JSON wire types', () => {
const binary = { type: 'string', format: 'binary' }
const spec = {
openapi: '3.1.0',
paths: {
'/upload': {
post: {
requestBody: {
required: true,
content: {
'application/json': { schema: { $ref: '#/components/schemas/File' } },
'multipart/form-data': { schema: { $ref: '#/components/schemas/File' } },
},
},
responses: { 204: { description: 'Done' } },
},
},
},
components: {
schemas: {
File: { type: 'object', required: ['data'], properties: { data: binary } },
'A/B~C': { type: 'integer' },
// Public export names cannot collide with schema names.
Schemas: { type: 'boolean' },
Unused: {
type: 'object',
required: ['value', 'children'],
properties: {
value: { $ref: '#/components/schemas/A~1B~0C' },
children: { type: 'array', items: { $ref: '#/components/schemas/Unused' } },
},
},
},
},
}
project(
{
'spec.openapi': JSON.stringify(spec),
'empty.openapi': JSON.stringify({ openapi: '3.1.0', paths: {} }),
'index.ts': `
import type { Schemas, Inputs, Outputs } from './spec.openapi';
import type { Schemas as EmptySchemas, Inputs as EmptyInputs, Outputs as EmptyOutputs } from './empty.openapi';
type IsNever<T> = [T] extends [never] ? true : false;
const emptySchemas: IsNever<keyof EmptySchemas> = true;
const emptyInputs: IsNever<keyof EmptyInputs> = true;
const emptyOutputs: IsNever<keyof EmptyOutputs> = true;
const escaped: Schemas['A/B~C'] = 1;
const collision: Schemas['Schemas'] = true;
const jsonFile: Schemas['File'] = {data: 'base64'};
const json: Inputs['upload']['post'] = {body: jsonFile};
const form: Inputs['upload']['post'] = {body: {data: new Blob()}, contentType: 'multipart/form-data'};
// @ts-expect-error schema models use JSON strings, not multipart Blob values
const wrongModel: Schemas['File'] = {data: new Blob()};
// @ts-expect-error the request body must match its media type
const wrongForm: Inputs['upload']['post'] = {body: jsonFile, contentType: 'multipart/form-data'};
// @ts-expect-error JSON is the default media type
const wrongJson: Inputs['upload']['post'] = {body: {data: new Blob()}};
const nothing: Outputs['upload']['post'] = undefined;
type Descend<T, D extends unknown[] = []> = D['length'] extends 60 ? T : T extends {children: (infer C)[]} ? Descend<C, [...D, unknown]> : never;
const deep: number = (null! as Descend<Schemas['Unused']>).value;
// @ts-expect-error unused recursive schemas remain precise beyond inference depth limits
const wrongDeep: string = (null! as Descend<Schemas['Unused']>).value;
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
)
})
test('compatibility modules retain existing contracts imports, names and request structure', () => {
const spec = {
openapi: '3.1.0',
paths: {
'/tags': {
get: {
parameters: [
{
in: 'query',
name: 'type',
required: true,
schema: { $ref: '#/components/schemas/TagType' },
},
{ in: 'query', name: 'keyword', schema: { type: 'string' } },
],
responses: {
200: {
content: {
'application/json': {
schema: {
type: 'array',
items: { $ref: '#/components/schemas/console_TagResponse' },
},
},
},
},
},
},
},
'/tags/{tag_id}': {
delete: {
parameters: [{ in: 'path', name: 'tag_id', required: true, schema: { type: 'string' } }],
responses: { 204: { description: 'Done' } },
},
},
},
components: {
schemas: {
TagType: { type: 'string', enum: ['app', 'knowledge', 'skill', 'snippet'] },
console_TagResponse: {
type: 'object',
required: ['id', 'name'],
properties: {
id: { type: 'string' },
name: { type: 'string' },
binding_count: { type: ['string', 'null'] },
type: { type: ['string', 'null'] },
},
},
},
},
}
project(
{
'console.openapi': JSON.stringify(spec),
'tags.types.ts': `
import type { Schemas, Inputs, Outputs } from './console.openapi';
export type TagResponse = Schemas['console_TagResponse'];
export type GetTagsResponse = Outputs['tags']['get'];
export type GetTagsData = {
body?: never;
path?: never;
query: Inputs['tags']['get']['query'];
url: '/tags';
};
export type DeleteTagsByTagIdData = {
body?: never;
path: Inputs['tags']['byTagId']['delete']['params'];
query?: never;
url: '/tags/{tag_id}';
};
`,
'index.ts': `
import type * as Previous from ${JSON.stringify(join(root, '../contracts/generated/api/console/tags/types.gen.ts'))};
import type { TagResponse, GetTagsData, GetTagsResponse, DeleteTagsByTagIdData } from '@dify/contracts/api/console/tags/types.gen';
const tag: TagResponse = null! as Previous.TagResponse;
const oldTag: Previous.TagResponse = null! as TagResponse;
const input: GetTagsData = null! as Previous.GetTagsData;
const oldInput: Previous.GetTagsData = null! as GetTagsData;
const output: GetTagsResponse = null! as Previous.GetTagsResponse;
const oldOutput: Previous.GetTagsResponse = null! as GetTagsResponse;
const deletion: DeleteTagsByTagIdData = null! as Previous.DeleteTagsByTagIdData;
const oldDeletion: Previous.DeleteTagsByTagIdData = null! as DeleteTagsByTagIdData;
// @ts-expect-error legacy request types still require url
const missingUrl: GetTagsData = {query: {type: 'app'}};
// @ts-expect-error legacy request types retain path rather than params
const renamedPath: DeleteTagsByTagIdData = {params: {tag_id: 'id'}, url: '/tags/{tag_id}'};
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
{ paths: { '@dify/contracts/api/console/tags/types.gen': ['./tags.types.ts'] } },
)
})
test('schema changes invalidate types on the next native compilation', () => {
project(
{
'pets.yaml': yaml,
'index.ts': `
import { api } from './pets.yaml';
const pet = await api.pets.byPetId.get({params: {petId: 1}});
const id: number = pet.id;
`,
},
(dir, check) => {
assert.equal(check().status, 0)
const changed = parseDocument(yaml)
changed.setIn(['components', 'schemas', 'Pet', 'properties', 'id', 'type'], 'string')
writeFileSync(join(dir, 'pets.yaml'), changed.toString())
const result = check()
assert.notEqual(result.status, 0)
assert.match(result.output, /Type 'string' is not assignable to type 'number'/)
},
)
})
test('unused operations do not eagerly instantiate API or query signatures', () => {
const instantiations = []
for (const count of [0, 1000]) {
const spec = parse(yaml)
for (let i = 0; i < count; i++) {
spec.paths[`/unused-${i}`] = {
get: {
parameters: [{ name: 'id', in: 'query', required: true, schema: { type: 'integer' } }],
responses: {
200: {
content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet' } } },
},
},
},
}
}
project(
{
'spec.openapi': JSON.stringify(spec),
'index.ts': `import { api, query } from './spec.openapi';
const name: string = (await api.pets.byPetId.get({params: {petId: 1}})).name;
query.pets.byPetId.get.queryOptions({input: {params: {petId: 1}}});`,
},
(_dir, check) => {
const result = check('--extendedDiagnostics')
assert.equal(result.status, 0, result.output)
const match = result.output.match(/Instantiations:\s+(\d+)/)
assert(match, result.output)
instantiations.push(Number(match[1]))
},
)
}
assert(instantiations[1] - instantiations[0] < 1000, JSON.stringify(instantiations))
})
test('cached mapper output follows sidecar additions, edits and removals', () => {
project(
{
'pets.yaml': yaml,
'index.ts': `import { api } from './pets.yaml';
api.pets.get(undefined, {context: {token: 'secret'}});`,
},
(dir, check) => {
assert.equal(check().status, 0)
const sidecar = join(dir, 'pets.yaml.config.ts')
writeFileSync(sidecar, 'export type Context = { token: number };')
assert.notEqual(check().status, 0)
writeFileSync(sidecar, 'export type Context = { token: string };')
const edited = check()
assert.equal(edited.status, 0, edited.output)
rmSync(sidecar)
const removed = check()
assert.equal(removed.status, 0, removed.output)
},
)
})
test('invalid specs and unresolved refs are compiler diagnostics, not any', () => {
for (const content of [
'openapi: [',
yaml.replace('#/components/schemas/Pet', '#/components/schemas/Missing'),
]) {
project(
{ 'bad.yaml': content, 'index.ts': "import * as spec from './bad.yaml'; export { spec };" },
(_dir, check) => {
const result = check()
assert.notEqual(result.status, 0)
assert.match(result.output, /1001/)
assert.match(result.output, /bad.yaml/)
},
)
}
})
test('schema composition, nullable, parameter overrides, dictionaries and escaped references', () => {
const spec = parse(yaml)
spec.components.schemas['A/B~C'] = { type: 'integer' }
spec.components.schemas.Pet = {
allOf: [
{
type: 'object',
required: ['id'],
properties: { id: { $ref: '#/components/schemas/A~1B~0C' } },
},
{
type: 'object',
required: ['choice', 'dictionary', 'nullable'],
properties: {
choice: { oneOf: [{ const: 'yes' }, { type: 'integer' }] },
dictionary: { type: 'object', additionalProperties: { type: 'number' } },
nullable: { type: 'string', nullable: true },
},
},
],
}
spec.paths['/pets/{petId}'].get.parameters = [
{ name: 'petId', in: 'path', required: true, schema: { type: 'string' } },
]
spec.paths['/literal'] = {
get: {
responses: {
200: {
content: {
'application/json': { schema: { const: { name: 'fixed', values: [1, true] } } },
},
},
},
},
}
project(
{
'spec.openapi': JSON.stringify(spec),
'index.ts': `
import { api } from './spec.openapi';
const pet = await api.pets.byPetId.get({params: {petId: 'abc'}});
const id: number = pet.id;
const choice: 'yes' | number = pet.choice;
const nullable: string | null = pet.nullable;
const dict: number | undefined = pet.dictionary.a;
const literal = await api.literal.get();
const fixed: 'fixed' = literal.name;
const first: 1 = literal.values[0];
// @ts-expect-error literal objects retain their original readonly semantics
literal.name = 'fixed';
// @ts-expect-error nested literal tuples remain readonly too
literal.values.push(1);
// @ts-expect-error operation-level parameter overrides path-level parameter
api.pets.byPetId.get({params: {petId: 1}});
// @ts-expect-error composition retains actual types
const wrong: boolean = pet.choice;
`,
},
(_dir, check) => {
const result = check()
assert.equal(result.status, 0, result.output)
},
)
})
test('nested API and query types do not require operationId', () => {
const spec = parse(yaml)
for (const item of Object.values(spec.paths)) {
for (const operation of Object.values(item)) {
if (operation && typeof operation === 'object' && !Array.isArray(operation))
delete operation.operationId
}
}
project(
{
'spec.openapi': JSON.stringify(spec),
'index.ts': `
import { api, query } from './spec.openapi';
const pet = await api.pets.byPetId.get({params: {petId: 1}});
const name: string = pet.name;
query.pets.byPetId.get.queryOptions({input: {params: {petId: 1}}});
// @ts-expect-error input still checked without operationId
api.pets.byPetId.get({params: {petId: 'wrong'}});
`,
},
(_dir, check) => {
const result = check()
assert.equal(result.status, 0, result.output)
},
)
})
test('recursive references remain precise; oRPC headers, dictionaries and void are preserved', () => {
const reference = (name) => ({ $ref: `#/components/schemas/${name}` })
const spec = {
openapi: '3.1.0',
paths: {
'/tree': {
get: {
responses: { 200: { content: { 'application/json': { schema: reference('Tree') } } } },
},
},
'/json': {
post: {
requestBody: {
required: true,
content: { 'application/json': { schema: reference('Json') } },
},
responses: { 204: { description: 'Done' } },
},
},
'/settings': {
post: {
parameters: [
{ in: 'header', name: 'Idempotency-Key', required: true, schema: { type: 'string' } },
],
requestBody: {
required: true,
content: { 'application/json': { schema: reference('Settings') } },
},
responses: {
200: { content: { 'application/json': { schema: reference('Settings') } } },
},
},
},
},
components: {
schemas: {
Tree: {
type: 'object',
required: ['name', 'children'],
properties: {
name: { type: 'string' },
children: { type: 'array', items: reference('Tree') },
},
},
Json: {
anyOf: [
{ type: ['string', 'number', 'boolean', 'null'] },
{ type: 'array', items: reference('Json') },
{ type: 'object', additionalProperties: reference('Json') },
],
},
Settings: {
type: 'object',
properties: { enabled: { type: 'boolean', default: true }, prompt: { type: 'string' } },
additionalProperties: reference('Json'),
},
},
},
}
project(
{
'spec.openapi': JSON.stringify(spec),
'check.ts': `
import { api } from './spec.openapi';
type Tree = Awaited<ReturnType<typeof api.tree.get>>;
type Descend<T, Depth extends unknown[] = []> = Depth['length'] extends 60 ? T : T extends {children: (infer Child)[]} ? Descend<Child, [...Depth, unknown]> : never;
const deepName: string = (null! as Descend<Tree>).name;
// @ts-expect-error deep recursive fields must not become any/unknown
const wrongName: number = (null! as Descend<Tree>).name;
type Json = Parameters<typeof api.json.post>[0]['body'];
type Nest<T, Depth extends unknown[] = []> = Depth['length'] extends 60 ? T : {next: Nest<T, [...Depth, unknown]>};
const good: Json = null! as Nest<string>;
type JsonDescend<T, Depth extends unknown[] = []> = Depth['length'] extends 60 ? T : JsonDescend<Extract<T, Record<string, unknown>>[string], [...Depth, unknown]>;
// @ts-expect-error JSON leaves still reject functions after 60 reference traversals
const bad: JsonDescend<Json> = () => {};
// @ts-expect-error nested functions cannot enter a JSON request
api.json.post({body: {nested: {callback: () => {}}}});
const empty: void = await api.json.post({body: {nested: [null, false, {a: 1}]}});
await api.settings.post({headers: {'Idempotency-Key': 'key'}, body: {prompt: 'hello', custom: [1, null]}});
// @ts-expect-error typed dictionaries do not permit undefined values
await api.settings.post({headers: {'Idempotency-Key': 'key'}, body: {custom: undefined}});
// @ts-expect-error the required request header cannot be omitted
await api.settings.post({body: {}});
// @ts-expect-error nested API uses the oRPC plural headers key
await api.settings.post({header: {'Idempotency-Key': 'key'}, body: {}});
const settings = await api.settings.post({headers: {'Idempotency-Key': 'key'}, body: {}});
const enabled: boolean | undefined = settings.enabled;
// @ts-expect-error a schema default does not guarantee the HTTP response contains a value
const guaranteed: boolean = settings.enabled;
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
)
})
test('JSON responses use wire strings and request media selects a matching body', () => {
project(
{
'media.openapi': JSON.stringify(mediaSpec),
'index.ts': `
import { api, query } from './media.openapi';
const wildcard: Blob = await api.wildcard.get();
await wildcard.arrayBuffer();
const textWildcard: string = await api.textWildcard.get();
// @ts-expect-error a binary wildcard cannot promise decoded text
const wrongWildcard: string = await api.wildcard.get();
const response = await api.binary.get();
const inline: string = response.inline;
const referenced: string = response.referenced;
const vendorBinary: string = await api.vendorBinary.get();
// @ts-expect-error JSON decoding does not construct Blob instances
const blob: Blob = response.referenced;
// @ts-expect-error inline JSON binary schemas also remain strings
response.inline.arrayBuffer();
await api.mixed.post({body: {kind: 'standard'}});
await api.mixed.post({body: {kind: 'vendor'}, contentType: 'application/vnd.example+json'});
await api.mixed.post({body: {kind: 'form'}, contentType: 'multipart/form-data'});
// @ts-expect-error only the application/json branch may omit its media type
api.mixed.post({body: {kind: 'vendor'}});
// @ts-expect-error content type and body must belong to the same branch
api.mixed.post({body: {kind: 'vendor'}, contentType: 'application/json'});
// @ts-expect-error multipart remains explicit when JSON is also declared
api.mixed.post({body: {kind: 'form'}});
await api.single.post({body: {kind: 'single'}});
await api.optionalVendors.post();
// @ts-expect-error an optional body still requires a media type when provided
api.optionalVendors.post({body: {kind: 'second'}});
await api.vendors.post({body: {kind: 'first'}, contentType: 'application/vnd.first+json'});
// @ts-expect-error multiple vendor types have no implicit default
api.vendors.post({body: {kind: 'second'}});
query.mixed.post.queryOptions({input: {body: {kind: 'vendor'}, contentType: 'application/vnd.example+json'}});
// @ts-expect-error query helpers preserve the same media/body discrimination
query.mixed.post.queryOptions({input: {body: {kind: 'vendor'}}});
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
)
})
test('API and query errors narrow to the selected operation map, including re-exports', () => {
project(
{
'pets.yaml': yaml,
'errors.ts': `
import { type } from '@orpc/contract';
export const conflicts = { CONFLICT: { status: 409, data: type<{ revision: number }>() } };
`,
'pets.yaml.errors.ts': `export { conflicts as 'GET /pets' } from './errors.js';`,
'index.ts': `
import { safe } from '@orpc/client';
import { api, query } from './pets.yaml';
const [error, , defined] = await safe(api.pets.get());
if (defined) {
const code: 'CONFLICT' = error.code;
const revision: number = error.data.revision;
// @ts-expect-error other error payloads must not leak into this operation
error.data.reason;
}
query.pets.get.queryOptions({ input: {}, retry: (_count, failure) => {
if (failure instanceof Error && 'defined' in failure && failure.defined) {
const code: 'CONFLICT' = failure.code;
const revision: number = failure.data.revision;
}
return false;
} });
const [other, , otherDefined] = await safe(api.pets.byPetId.get({ params: { petId: 1 } }));
if (otherDefined) {
// @ts-expect-error this operation has no documented conflict
other.data.revision;
}
`,
},
(_dir, compile) => {
const result = compile()
assert.equal(result.status, 0, result.output)
},
)
})
@@ -0,0 +1,90 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Exercise the built adapter inside a real Vite development server. */
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { createServer } from 'vite'
import { parse, stringify } from 'yaml'
import { openapi } from '../dist/tooling/vite.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const fixture = parse(readFileSync(join(root, 'examples/petstore/pets.openapi.yaml'), 'utf8'))
for (const extension of ['yaml', 'openapi']) {
test(`Vite dev ${extension}: nested virtual modules refresh after the source changes`, async () => {
const dir = mkdtempSync(join(root, 'test/.dev-'))
let server
try {
const file = join(dir, extension === 'yaml' ? 'api.yaml' : 'source.json')
const spec = structuredClone(fixture)
spec.servers = [{ url: 'https://before.test' }]
const save = () =>
writeFileSync(file, extension === 'yaml' ? stringify(spec) : JSON.stringify(spec))
save()
if (extension === 'openapi') symlinkSync('source.json', join(dir, 'api.openapi'))
writeFileSync(join(dir, 'entry.ts'), `export { api, query } from './api.${extension}';`)
server = await createServer({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [
openapi(),
{
name: 'downstream-source-map',
transform(code, id) {
if (!id.includes('?openapi-')) return
return { code, map: { version: 3, sources: [id], names: [], mappings: 'AAAA' } }
},
},
],
server: {
port: 0,
watch: { awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 10 } },
},
})
await server.listen()
await server.transformRequest('/entry.ts')
const main = await server.transformRequest(`/api.${extension}`)
assert.match(main.code, /openapi-router/)
const urls = ['router', 'query'].map(
(kind) =>
`/api.${extension}?openapi-${kind}=${encodeURIComponent(JSON.stringify(['pets', 'byPetId']))}`,
)
for (const url of urls) {
const transformed = await server.transformRequest(url)
assert.match(transformed.code, /before\.test/)
assert.equal(
transformed.map.mappings,
'',
'Virtual namespaces must not embed the source specification',
)
}
const refreshed = new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('No Vite reload after spec edit')), 10000)
const send = server.ws.send.bind(server.ws)
server.ws.send = (...args) => {
if (
args[0]?.type === 'full-reload' &&
[file, join(dir, 'api.openapi')].includes(args[0].triggeredBy)
) {
clearTimeout(timeout)
resolve()
}
return send(...args)
}
})
spec.servers[0].url = 'https://after.test'
save()
await refreshed
for (const url of urls) {
const transformed = await server.transformRequest(url)
assert.match(transformed.code, /after\.test/)
assert.doesNotMatch(transformed.code, /before\.test/)
}
} finally {
await server?.close()
rmSync(dir, { recursive: true, force: true })
}
})
}