I firmly believe in free software. The application I'm making here have capabilities that I've not seen in any system. It presents itself as an opportunity to collaborate on a tool that serves the people rather than corporations. Whose incentives are to help people rather, not make the most money. And whose terms ensure that these freedoms and incentives cannot be taken back or subverted. I license this software under the AGPL.
36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { pipeline } from "node:stream";
|
|
import { addStream, deleteStream } from "~/server/streams";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const session = await getServerSession(event);
|
|
const accountId = session?.account.id;
|
|
|
|
const encoder = new TextEncoder();
|
|
const source = event.headers.get("x-forwarded-for");
|
|
console.log(`starting event stream for ${source}`)
|
|
const stream = new TransformStream<string, Uint8Array>({
|
|
transform(chunk, controller) {
|
|
controller.enqueue(encoder.encode(chunk));
|
|
},
|
|
flush(controller) {
|
|
console.log(`finished event stream for ${source}`);
|
|
deleteStream(stream.writable);
|
|
},
|
|
// @ts-expect-error experimental API
|
|
cancel(reason) {
|
|
console.log(`cancelled event stream for ${source}`);
|
|
deleteStream(stream.writable);
|
|
}
|
|
})
|
|
addStream(stream.writable, session?.id, accountId);
|
|
|
|
// Workaround to properly handle stream errors. See https://github.com/unjs/h3/issues/986
|
|
setHeader(event, "Access-Control-Allow-Origin", "*");
|
|
setHeader(event, "Content-Type", "text/event-stream");
|
|
pipeline(stream.readable as unknown as NodeJS.ReadableStream, event.node.res, (err) => { /* ignore */ });
|
|
event._handled = true;
|
|
});
|