The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { HttpNeonClient, withSslmode } from './neon'
const uri = 'postgresql://[email protected]/db'
const base = 'https://neon.example.test/api/v2'
describe('hosted App Neon requests', () => {
const client = new HttpNeonClient('test-token', 'org', 'region', base)
let fetcher: jest.SpiedFunction<typeof fetch>
const response = (status: number, data: unknown = {}) =>
fetcher.mockResolvedValueOnce(Response.json(data, { status }))
const requests = () =>
fetcher.mock.calls.map(([url, init]) => ({
path: String(url).slice(base.length),
method: init?.method,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
}))
beforeEach(() => {
fetcher = jest.spyOn(global, 'fetch').mockRejectedValue(new Error('unexpected request'))
})
afterEach(() => {
jest.restoreAllMocks()
jest.useRealTimers()
})
test('creates the named project and schema branch and preserves its original history on restore', async () => {
response(201, { project: { id: 'p' }, branch: { id: 'main' }, connection_uris: [{ connection_uri: uri }] })
expect(await client.createProject('mc-app')).toEqual({
projectId: 'p',
mainBranchId: 'main',
host: 'main.example.test',
connectionUri: uri,
})
response(201, { branch: { id: 'staging' } })
expect(await client.createBranch('p', 'preview', 'main', 'schema-only')).toEqual({
branchId: 'staging',
logicalSizeBytes: null,
})
response(200, { branch: { id: 'staging', logical_size: 2048 } })
expect((await client.getBranch('p', 'staging')).logicalSizeBytes).toBe(2048)
response(200)
await client.restoreBranch('p', 'staging', '2025-12-25T12:00:00Z', 'before-rollback')
expect(requests()).toEqual([
{
path: '/projects',
method: 'POST',
body: { project: { name: 'mc-app', org_id: 'org', region_id: 'region', pg_version: 17 } },
},
{
path: '/projects/p/branches',
method: 'POST',
body: {
branch: { name: 'preview', parent_id: 'main', init_source: 'schema-only' },
endpoints: [{ type: 'read_write' }],
},
},
{ path: '/projects/p/branches/staging', method: 'GET' },
{
path: '/projects/p/branches/staging/restore',
method: 'POST',
body: {
source_branch_id: 'staging',
source_timestamp: '2025-12-25T12:00:00Z',
preserve_under_name: 'before-rollback',
},
},
])
expect(fetcher.mock.calls[0][1]?.headers).toMatchObject({ authorization: 'Bearer test-token' })
})
test('recovers an ambiguous create by exact project and branch names without repeating the create', async () => {
response(502)
response(200, {
projects: [
{ id: 'other', name: 'mc-app-copy' },
{ id: 'p', name: 'mc-app' },
],
})
response(200, { branches: [{ id: 'preview' }, { id: 'main', default: true }] })
response(200, { uri })
expect(await client.createProject('mc-app')).toMatchObject({
projectId: 'p',
mainBranchId: 'main',
connectionUri: uri,
})
response(409)
response(200, {
branches: [
{ id: 'other', name: 'preview-copy' },
{ id: 'br', name: 'preview' },
],
})
expect(await client.createBranch('p', 'preview', null, 'parent-data')).toEqual({
branchId: 'br',
logicalSizeBytes: null,
})
expect(requests().map((r) => [r.method, r.path])).toEqual([
['POST', '/projects'],
['GET', '/projects?org_id=org&search=mc-app'],
['GET', '/projects/p/branches'],
['GET', '/projects/p/connection_uri?branch_id=main&database_name=neondb&role_name=neondb_owner'],
['POST', '/projects/p/branches'],
['GET', '/projects/p/branches'],
])
})
test('returns the original create error for a missing recovery candidate or a rejected create', async () => {
response(503)
response(200, { projects: [] })
await expect(client.createProject('absent')).rejects.toMatchObject({ status: 503 })
response(409)
response(200, { branches: [] })
await expect(client.createBranch('p', 'missing', null, 'parent-data')).rejects.toMatchObject({ status: 409 })
response(422)
await expect(client.createBranch('p', 'bad', null, 'parent-data')).rejects.toMatchObject({ status: 422 })
response(201, { project: { id: 'p' }, connection_uris: [] })
await expect(client.createProject('invalid')).rejects.toThrow('no branch or connection URI')
})
test('waits for a locked role creation and for the granted role to reach compute', async () => {
jest.useFakeTimers()
response(423)
response(201, { operations: [{ id: 'op' }] })
response(200, { operation: { status: 'running' } })
response(200, { operation: { status: 'finished' } })
const created = client.createRole('p', 'b', 'read only')
await jest.runAllTimersAsync()
expect(await created).toBe('created')
expect(requests().map((r) => r.path)).toEqual([
'/projects/p/branches/b/roles',
'/projects/p/branches/b/roles',
'/projects/p/operations/op',
'/projects/p/operations/op',
])
response(409)
expect(await client.createRole('p', 'b', 'reader')).toBe('exists')
response(200, { role: { name: 'read only', authentication_method: 'no_login' } })
expect(await client.getRole('p', 'b', 'read only')).toEqual({ name: 'read only', authMethod: 'no_login' })
response(200, { password: 'temporary-role-value' })
expect(await client.revealRolePassword('p', 'b', 'read only')).toBe('temporary-role-value')
expect(requests().at(-1)?.path).toBe('/projects/p/branches/b/roles/read%20only/reveal_password')
response(200, { operations: [{ id: 'delete' }] })
response(200, { operation: { status: 'failed', error: 'compute offline' } })
await expect(client.deleteRole('p', 'b', 'reader')).rejects.toThrow('compute offline')
})
test('idempotent cleanup accepts absent resources and propagates permission failures', async () => {
response(404)
expect(await client.getRole('p', 'b', 'reader')).toBeNull()
for (const remove of [
() => client.deleteRole('p', 'b', 'reader'),
() => client.deleteBranch('p', 'b'),
() => client.deleteProject('p'),
]) {
response(404)
await expect(remove()).resolves.toBeUndefined()
response(403)
await expect(remove()).rejects.toMatchObject({ status: 403 })
}
response(403)
await expect(client.getRole('p', 'b', 'reader')).rejects.toMatchObject({ status: 403 })
})
test('requires platform configuration before provider calls and preserves explicit TLS choices', async () => {
await expect(new HttpNeonClient('', 'org', 'region').getBranch('p', 'b')).rejects.toThrow('NEON_API_KEY')
await expect(new HttpNeonClient('key', '', 'region').createProject('p')).rejects.toThrow('NEON_ORG_ID')
expect(fetcher).not.toHaveBeenCalled()
for (const [query, mode] of [
['', 'verify-full'],
['?sslmode=require', 'verify-full'],
['?sslmode=verify-ca', 'verify-ca'],
]) {
expect(new URL(withSslmode(uri + query)).searchParams.get('sslmode')).toBe(mode)
}
})
test('bounds role operation polling and propagates provider refusal before polling', async () => {
response(403)
await expect(client.createRole('p', 'b', 'reader')).rejects.toMatchObject({ status: 403 })
expect(fetcher).toHaveBeenCalledTimes(1)
jest.useFakeTimers()
response(201, { operations: [{ id: 'slow' }] })
fetcher.mockImplementation(async () => Response.json({ operation: { status: 'running' } }))
const stopped = expect(client.createRole('p', 'b', 'reader')).rejects.toMatchObject({
status: 504,
message: expect.stringContaining('operation slow still running'),
})
await jest.runAllTimersAsync()
await stopped
})
test('returns provider metadata defaults and finishes role changes without operation IDs', async () => {
response(200, { role: { name: 'reader' } })
expect(await client.getRole('p', 'b', 'reader')).toEqual({ name: 'reader', authMethod: 'password' })
response(200, { branch: { id: 'b' } })
expect(await client.getBranch('p', 'b')).toEqual({ branchId: 'b', logicalSizeBytes: null })
response(201)
expect(await client.createRole('p', 'b', 'reader')).toBe('created')
response(200)
await client.deleteRole('p', 'b', 'reader')
expect(requests().at(-1)).toMatchObject({ method: 'DELETE', path: '/projects/p/branches/b/roles/reader' })
})
test('recovers from a lost response using the first branch when the provider has no default', async () => {
fetcher.mockRejectedValueOnce(new Error('socket closed'))
response(200, { projects: [{ id: 'p', name: 'orders' }] })
response(200, { branches: [{ id: 'original' }, { id: 'preview' }] })
response(200, { uri })
expect(await client.createProject('orders')).toMatchObject({ projectId: 'p', mainBranchId: 'original' })
response(409)
response(200, { projects: [{ id: 'p', name: 'empty' }] })
response(200, { branches: [] })
await expect(client.createProject('empty')).rejects.toMatchObject({ status: 409 })
response(403)
await expect(client.createProject('denied')).rejects.toMatchObject({ status: 403 })
expect(requests().at(-1)?.method).toBe('POST')
})
test('returns a body transfer failure and identifies cancelled operations without provider details', async () => {
const interrupted = new Error('body stream closed')
const partial = new Response(
new ReadableStream({
start(controller) {
controller.error(interrupted)
},
}),
)
fetcher.mockResolvedValueOnce(partial)
await expect(client.createProject('incomplete')).rejects.toBe(interrupted)
expect(fetcher).toHaveBeenCalledTimes(1)
response(201, { operations: [{ id: 'skip' }, { id: 'cancelled' }] })
response(200, { operation: { status: 'skipped' } })
response(200, { operation: { status: 'cancelled' } })
await expect(client.createRole('p', 'b', 'reader')).rejects.toMatchObject({
status: 500,
message: expect.stringContaining('operation cancelled cancelled'),
})
})
})