Files
Jarvise-project/backend/test/helpers.js
T
BlackAngelTV 31e9619727 feat(backend): stream /api/chat as spec-compliant SSE
Expose the bare `data:`/`[DONE]` contract on the main chat endpoint so
simple clients can consume the stream without parsing named events.
2026-10-05 20:40:12 +02:00

138 lines
3.9 KiB
JavaScript

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { buildApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { createDatabase } from '../src/db/index.js';
import { createOllama } from '../src/services/ollama.js';
import { startMockOllama } from './mock-ollama.js';
/** Starts an isolated instance (in-memory database + mock Ollama) on a free port. */
export async function startServer(options = {}) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jarvise-test-'));
const mock = await startMockOllama(options);
const config = loadConfig({
env: 'test',
jwtSecret: 'test-secret',
dbPath: ':memory:',
ollamaUrl: mock.url,
ollamaModel: 'mock:1',
});
const db = createDatabase(config.dbPath);
const ollama = createOllama(config);
const app = await buildApp({ config, db, ollama });
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address();
return {
app,
db,
mock,
base: `http://127.0.0.1:${port}`,
async close() {
await app.close();
await mock.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
},
};
}
/** Simple JSON request; only sets Content-Type when there is a body. */
export async function api(base, method, apiPath, { token, body, headers = {} } = {}) {
const res = await fetch(base + apiPath, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = text;
}
return { status: res.status, json, headers: res.headers };
}
/** Creates a user and returns its token. */
export async function registerUser(base, email = `u${Date.now()}${Math.random()}@x.io`) {
const res = await api(base, 'POST', '/api/auth/register', {
body: { email, password: 'motdepasse123', name: 'Test' },
});
if (res.status !== 201) throw new Error(`register failed: ${JSON.stringify(res.json)}`);
return { token: res.json.token, user: res.json.user, email };
}
/**
* Consumes an SSE stream and returns each `data:` line verbatim (no JSON parse),
* which is what the `[DONE]` sentinel requires.
*/
export async function readSsePayloads(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const payloads = [];
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
if (!block || block.startsWith(':')) continue;
for (const line of block.split('\n')) {
if (line.startsWith('data: ')) payloads.push(line.slice(6));
}
}
}
return payloads;
}
/**
* Consumes an SSE stream and returns the events as `{ event, data }` objects.
*/
export async function readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const events = [];
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
if (!block || block.startsWith(':')) continue;
let event = 'message';
let data = '';
for (const line of block.split('\n')) {
if (line.startsWith('event: ')) event = line.slice(7).trim();
else if (line.startsWith('data: ')) data += line.slice(6);
}
events.push({ event, data: data ? JSON.parse(data) : null });
}
}
return events;
}