Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(pii): preserve custom event names and apply stream PII sanitization fixes (#3056)

dangeReisc711ac62a793
diff --git a/src/lib/piiSanitizer.ts b/src/lib/piiSanitizer.ts
index 5306488bbc..33f750ef61 100644
--- a/src/lib/piiSanitizer.ts
+++ b/src/lib/piiSanitizer.ts
@@ -22,7 +22,7 @@ type PiiMode = typeof VALID_MODES[number];
const getMode = (): PiiMode => {
const value = resolveFeatureFlag("PII_RESPONSE_SANITIZATION_MODE");
if (value === "" || value === undefined || value === null) return "redact";
- if (value === "false") return "off";
+ if (String(value) === "false") return "off";
if ((VALID_MODES as readonly any[]).includes(value)) return value as PiiMode;
console.error(`[PII] Invalid PII_RESPONSE_SANITIZATION_MODE: "${value}", defaulting to "redact"`);
return "redact";
@@ -88,7 +88,7 @@ const PII_PATTERNS: PIIPattern[] = [
},
{
name: "ipv6_address",
- regex: /(?<=^|[^A-Za-z0-9])(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}(?=$|[^A-Za-z0-9])/g,
+ regex: /(?<=^|[^A-Za-z0-9:])(?:[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4}){7}|(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}|::|[0-9a-fA-F]{1,4}::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){2}:(?:[0-9a-fA-F]{1,4}:){0,4}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){3}:(?:[0-9a-fA-F]{1,4}:){0,3}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){4}:(?:[0-9a-fA-F]{1,4}:){0,2}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){5}:(?:[0-9a-fA-F]{1,4}:){0,1}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){6}:[0-9a-fA-F]{1,4})(?=$|[^A-Za-z0-9])(?!:[0-9a-fA-F:])/g,
replacement: "[IP_REDACTED]",
severity: "low",
},
diff --git a/src/lib/sseTextTransform.ts b/src/lib/sseTextTransform.ts
index ebdb12fd93..cc692ae6c3 100644
--- a/src/lib/sseTextTransform.ts
+++ b/src/lib/sseTextTransform.ts
@@ -52,11 +52,16 @@ export function createSseTextTransform(
let isJsonStream = false;
let flushed = false;
let errored = false;
+ let currentEventLine = "";
+ let lastEventLine = "";
const handleLine = (line: string, controller: TransformStreamDefaultController) => {
const trimmed = line.trim();
if (trimmed === "" || line.startsWith(":")) {
// Pass comments and empty lines through unchanged
+ if (trimmed === "") {
+ currentEventLine = "";
+ }
controller.enqueue(encoder.encode(line + "\n"));
return;
}
@@ -71,7 +76,10 @@ export function createSseTextTransform(
if (flushedValue) {
const prefix = lastPrefix || "data: ";
const payload = typeof flushedValue === "string" ? flushedValue : JSON.stringify(flushedValue);
- controller.enqueue(encoder.encode(prefix + payload + "\n"));
+ if (lastEventLine) {
+ controller.enqueue(encoder.encode(lastEventLine + "\n"));
+ }
+ controller.enqueue(encoder.encode(prefix + payload + "\n\n"));
}
flushed = true;
}
@@ -90,6 +98,10 @@ export function createSseTextTransform(
const isStopSignal = checkIfStopSignal(json);
const isSnapshot = checkIfSnapshot(json);
+ if (!isStopSignal && !isSnapshot) {
+ lastEventLine = currentEventLine;
+ }
+
const METADATA_KEYS = [
"id", "model", "object", "created", "finish_reason", "finishReason",
"role", "type", "index", "stop_reason", "stop_sequence",
@@ -146,7 +158,10 @@ export function createSseTextTransform(
const prefix = lastPrefix || "data: ";
const payload = typeof flushedValue === "string" ? flushedValue : JSON.stringify(flushedValue);
// Only enqueue if the flushed value actually has content (onFlush usually returns null if buffer is empty now)
- controller.enqueue(encoder.encode(prefix + payload + "\n"));
+ if (lastEventLine) {
+ controller.enqueue(encoder.encode(lastEventLine + "\n"));
+ }
+ controller.enqueue(encoder.encode(prefix + payload + "\n\n"));
}
flushed = true;
}
@@ -172,11 +187,15 @@ export function createSseTextTransform(
}
} else {
// Starts with data: but not JSON, process as raw text
+ lastEventLine = currentEventLine;
const processed = processor(segment, "content");
controller.enqueue(encoder.encode(prefix + processed + "\n"));
}
} else {
// Non-data line, pass through (e.g. event: content_block_delta)
+ if (line.startsWith("event:")) {
+ currentEventLine = line;
+ }
controller.enqueue(encoder.encode(line + "\n"));
}
};
@@ -221,7 +240,10 @@ export function createSseTextTransform(
if (flushedValue) {
const prefix = lastPrefix || "data: ";
const payload = typeof flushedValue === "string" ? flushedValue : JSON.stringify(flushedValue);
- controller.enqueue(encoder.encode(prefix + payload + "\n"));
+ if (lastEventLine) {
+ controller.enqueue(encoder.encode(lastEventLine + "\n"));
+ }
+ controller.enqueue(encoder.encode(prefix + payload + "\n\n"));
}
}
} catch (err) {
diff --git a/tests/unit/piiReproduction.test.ts b/tests/unit/piiReproduction.test.ts
index 34e867649c..a1c984b911 100644
--- a/tests/unit/piiReproduction.test.ts
+++ b/tests/unit/piiReproduction.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { resetDbInstance } from "../../src/lib/db/core";
// Isolate DB state
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-test-repro-"));
@@ -35,6 +36,7 @@ test("PII Reproduction Tests", async (t) => {
// Write 50 alphanumeric characters starting with "sk-"
const piiText = "sk-123456789012345678901234567890123456789012345678"; // 51 chars
+
await writer.write(encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: piiText } }] })}\n`));
// Wait a bit — if the buffer is withheld (W=10, PII window), nothing should be emitted yet
@@ -62,9 +64,18 @@ test("PII Reproduction Tests", async (t) => {
assert.strictEqual(resultWordJoiner.text, "[API_KEY_REDACTED]", "API Key with Word Joiner is now correctly redacted");
assert.strictEqual(resultSoftHyphen.text, "[API_KEY_REDACTED]", "API Key with Soft Hyphen is now correctly redacted");
- // 2. IPv6 lookbehind/lookahead issues — sanitizer no longer falsely redacts abc::1
- const resultIpv6Lookbehind = sanitizePII("abc::1");
- assert.strictEqual(resultIpv6Lookbehind.text, "abc::1", "abc::1 should not be redacted");
+ // 2. IPv6 lookbehind/lookahead issues
+ // xyz::1 (preceded by non-hex alphabetic characters) should NOT be redacted
+ const resultIpv6Lookbehind = sanitizePII("xyz::1");
+ assert.strictEqual(resultIpv6Lookbehind.text, "xyz::1", "xyz::1 should not be redacted");
+
+ // abc::1 (preceded by valid hex characters) is a valid compressed IPv6 address and should be redacted
+ const resultIpv6ValidCompressed = sanitizePII("abc::1");
+ assert.strictEqual(resultIpv6ValidCompressed.text, "[IP_REDACTED]", "abc::1 should be redacted as a valid compressed IP");
+
+ // Invalid IPv6 followed by letters should NOT be redacted
+ const resultIpv6Lookahead = sanitizePII("2001:db8:3333:4444:5555:6666:7777:8888abcd");
+ assert.strictEqual(resultIpv6Lookahead.text, "2001:db8:3333:4444:5555:6666:7777:8888abcd", "Invalid IPv6 with trailing characters should not be redacted");
// Valid IPv6 is correctly redacted
const resultIpv6Valid = sanitizePII("2001:db8:3333:4444:5555:6666:7777:8888");
@@ -123,3 +134,8 @@ test("PII Reproduction Tests", async (t) => {
assert.ok(outputB.includes('"H"') && outputB.includes("ello world"), "Scenario B: buffered content must not be lost — expect window-split output containing both parts");
});
});
+
+test.after(() => {
+ resetDbInstance();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
diff --git a/tests/unit/piiSanitizerIpv6.test.ts b/tests/unit/piiSanitizerIpv6.test.ts
new file mode 100644
index 0000000000..03fdb4c353
--- /dev/null
+++ b/tests/unit/piiSanitizerIpv6.test.ts
@@ -0,0 +1,202 @@
+/**
+ * Additional tests for piiSanitizer.ts changes introduced in this PR:
+ *
+ * 1. getMode() — String(value) coercion so that the string "false" returns "off"
+ * 2. IPv6 regex — expanded to handle compressed forms (::, ::1, fe80::1, etc.)
+ * and fixed lookbehind/lookahead boundary assertions.
+ */
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { resetDbInstance } from "../../src/lib/db/core";
+
+// Isolate DB state
+const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-test-pii-ipv6-"));
+process.env.DATA_DIR = tmpDir;
+
+// Enable PII sanitization for all tests in this file
+process.env.PII_RESPONSE_SANITIZATION = "true";
+process.env.PII_RESPONSE_SANITIZATION_MODE = "redact";
+
+import { sanitizePII } from "../../src/lib/piiSanitizer";
+
+// ── getMode() via PII_RESPONSE_SANITIZATION_MODE env var ──────────────────────
+
+test('getMode: string "false" maps to mode "off" (sanitization skipped)', () => {
+ const originalMode = process.env.PII_RESPONSE_SANITIZATION_MODE;
+ process.env.PII_RESPONSE_SANITIZATION_MODE = "false";
+ try {
+ // In "off" mode sanitizePII should return the raw text unchanged even when
+ // PII_RESPONSE_SANITIZATION is enabled.
+ const ip = "2001:db8:3333:4444:5555:6666:7777:8888";
+ const result = sanitizePII(ip);
+ // "off" mode means no redaction at all — text passes through as-is.
+ assert.strictEqual(result.text, ip, 'mode "off" should not redact anything');
+ assert.strictEqual(result.redacted, false, 'mode "off" should report redacted=false');
+ } finally {
+ process.env.PII_RESPONSE_SANITIZATION_MODE = originalMode;
+ }
+});
+
+test("getMode: invalid value falls back to redact (PII is still redacted)", () => {
+ const originalMode = process.env.PII_RESPONSE_SANITIZATION_MODE;
+ process.env.PII_RESPONSE_SANITIZATION_MODE = "not_a_valid_mode";
+ try {
+ const ip = "2001:db8:3333:4444:5555:6666:7777:8888";
+ const result = sanitizePII(ip);
+ // Invalid mode falls back to "redact" — IP should be redacted.
+ assert.ok(result.text.includes("[IP_REDACTED]"), "invalid mode falls back to redact");
+ } finally {
+ process.env.PII_RESPONSE_SANITIZATION_MODE = originalMode;
+ }
+});
+
+test("getMode: empty string falls back to redact", () => {
+ const originalMode = process.env.PII_RESPONSE_SANITIZATION_MODE;
+ process.env.PII_RESPONSE_SANITIZATION_MODE = "";
+ try {
+ const ip = "2001:db8:3333:4444:5555:6666:7777:8888";
+ const result = sanitizePII(ip);
+ assert.ok(result.text.includes("[IP_REDACTED]"), "empty mode string falls back to redact");
+ } finally {
+ process.env.PII_RESPONSE_SANITIZATION_MODE = originalMode;
+ }
+});
+
+// ── IPv6 regex — compressed-form detection ────────────────────────────────────
+
+test("IPv6 :: (all-zeros) alone is redacted", () => {
+ const result = sanitizePII("::");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "bare :: should be redacted as IPv6 all-zeros");
+});
+
+test("IPv6 ::1 (loopback) standalone is redacted", () => {
+ const result = sanitizePII("::1");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "standalone ::1 should be redacted");
+});
+
+test("IPv6 ::1 embedded in sentence is redacted", () => {
+ const result = sanitizePII("connecting to ::1 on port 8080");
+ assert.ok(!result.text.includes("::1"), "::1 in sentence should be redacted");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "redaction marker should appear");
+});
+
+test("IPv6 fe80::1 (link-local compressed) is redacted", () => {
+ const result = sanitizePII("fe80::1");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "fe80::1 should be redacted");
+ assert.ok(!result.text.includes("fe80::1"), "raw fe80::1 should not remain");
+});
+
+test("IPv6 2001:db8:: (trailing double-colon) is redacted", () => {
+ const result = sanitizePII("2001:db8::");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "trailing :: form should be redacted");
+});
+
+test("IPv6 ::ffff:0:0 (IPv4-mapped compressed prefix) is redacted", () => {
+ const result = sanitizePII("::ffff:0:0");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "::ffff:0:0 should be redacted");
+});
+
+test("IPv6 full 8-segment address is redacted", () => {
+ const result = sanitizePII("1:2:3:4:5:6:7:8");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "full 8-segment IPv6 should be redacted");
+ assert.ok(!result.text.includes("1:2:3:4:5:6:7:8"), "raw 8-segment should not remain");
+});
+
+// ── IPv6 regex — boundary / false-positive guards ─────────────────────────────
+
+test("IPv6 9-segment address (invalid) is NOT redacted", () => {
+ // 9 colon-separated groups can never be a valid IPv6 address.
+ const invalid = "1:2:3:4:5:6:7:8:9";
+ const result = sanitizePII(invalid);
+ assert.strictEqual(result.text, invalid, "9-segment sequence should not be redacted");
+});
+
+test("IPv6 address preceded by a colon is NOT redacted (colon in lookbehind)", () => {
+ // The new lookbehind `(?<=^|[^A-Za-z0-9:])` must block matches where the
+ // preceding character is a colon (part of a longer sequence).
+ const text = "x:1:2:3:4:5:6:7:8";
+ const result = sanitizePII(text);
+ // The full sequence has a leading "x:" prefix — the 8-segment sub-slice should
+ // NOT be extracted as a standalone IPv6 address.
+ assert.strictEqual(result.text, text, "colon-prefixed sequence should not be redacted");
+});
+
+test("IPv6 followed by colon-hex suffix is NOT redacted (lookahead guard)", () => {
+ // The lookahead `(?!:[0-9a-fA-F:])` prevents a valid 8-segment address from
+ // being carved out of a longer colon-separated sequence.
+ const text = "1:2:3:4:5:6:7:8:extra";
+ const result = sanitizePII(text);
+ assert.strictEqual(result.text, text, "8-segment prefix of a longer colon sequence should not be redacted");
+});
+
+test("IPv6 xyz::1 (non-hex prefix) is NOT redacted", () => {
+ // x, y, z are outside [0-9a-fA-F] so the lookbehind must prevent a match.
+ const result = sanitizePII("xyz::1");
+ assert.strictEqual(result.text, "xyz::1", "xyz::1 should not be redacted (non-hex prefix)");
+});
+
+test("IPv6 abc::1 (valid hex prefix) IS redacted", () => {
+ // a, b, c are valid hex digits, so abc::1 is a valid compressed IPv6 address.
+ const result = sanitizePII("abc::1");
+ assert.ok(result.text.includes("[IP_REDACTED]"), "abc::1 should be redacted as valid compressed IPv6");
+});
+
+test("IPv6 full 8-segment with trailing alphanumeric is NOT redacted", () => {
+ // Lookahead must reject the match when the address is immediately followed by
+ // a letter/digit (8888abcd).
+ const text = "2001:db8:3333:4444:5555:6666:7777:8888abcd";
+ const result = sanitizePII(text);
+ assert.strictEqual(result.text, text, "8-segment address with trailing alnum should not be redacted");
+});
+
+test("multiple IPv6 addresses in the same string are all redacted", () => {
+ const text = "hosts: ::1 and 2001:db8::cafe";
+ const result = sanitizePII(text);
+ assert.ok(!result.text.includes("::1"), "first IPv6 should be redacted");
+ assert.ok(!result.text.includes("2001:db8::cafe"), "second IPv6 should be redacted");
+ const markerCount = (result.text.match(/\[IP_REDACTED\]/g) || []).length;
+ assert.ok(markerCount >= 2, "two redaction markers should be present");
+});
+
+// ── Regression: IPv6 redaction inside JSON SSE stream ────────────────────────
+
+test("IPv6 address inside SSE JSON content is redacted end-to-end", async () => {
+ // This verifies the full pipeline: SSE transform → PII sanitizer → IPv6 regex.
+ process.env.PII_TEST_BYPASS_MIN_WINDOW = "true";
+ const { createPiiSseTransform } = await import("../../src/lib/streamingPiiTransform");
+
+ const transform = createPiiSseTransform();
+ const writer = transform.writable.getWriter();
+ const reader = transform.readable.getReader();
+
+ const encoder = new TextEncoder();
+ const writePromise = (async () => {
+ await writer.write(encoder.encode(
+ `data: {"choices":[{"delta":{"content":"server is at 2001:db8:3333:4444:5555:6666:7777:8888"}}]}\n\n`
+ ));
+ await writer.write(encoder.encode(`data: [DONE]\n\n`));
+ await writer.close();
+ })();
+
+ const chunks: string[] = [];
+ let res = await reader.read();
+ while (!res.done) {
+ chunks.push(new TextDecoder().decode(res.value));
+ res = await reader.read();
+ }
+ await writePromise;
+
+ const output = chunks.join("");
+ assert.ok(!output.includes("2001:db8:3333:4444:5555:6666:7777:8888"),
+ "full IPv6 address in SSE stream should be redacted");
+ assert.ok(output.includes("[IP_REDACTED]"),
+ "redaction marker should appear in SSE stream output");
+});
+
+test.after(() => {
+ resetDbInstance();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
\ No newline at end of file
diff --git a/tests/unit/streamingPiiTransform.test.ts b/tests/unit/streamingPiiTransform.test.ts
index b08d86958e..a8484f2dd7 100644
--- a/tests/unit/streamingPiiTransform.test.ts
+++ b/tests/unit/streamingPiiTransform.test.ts
@@ -183,6 +183,183 @@ test("PII split across sliding window boundary is still redacted", async () => {
"email spanning window boundary should be redacted");
});
+test("preserve event names when flushing buffered SSE text", async () => {
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const eventLine = "event: response.output_text.delta\n";
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [eventLine + inputLine + doneLine]);
+
+ const occurrences = (output.match(/event: response\.output_text\.delta/g) || []).length;
+ assert.strictEqual(occurrences, 2, "flushed chunk should re-emit the custom event line");
+});
+
+test("do not leak custom event name to subsequent default message events on flush", async () => {
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const eventLine = "event: response.output_text.delta\n";
+ const inputLine1 = `data: {"choices":[{"delta":{"content":"abcdefghij"}}]}\n\n`;
+ const inputLine2 = `data: {"choices":[{"delta":{"content":"klmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [eventLine + inputLine1 + inputLine2 + doneLine]);
+
+ const occurrences = (output.match(/event: response.output_text.delta/g) || []).length;
+ assert.strictEqual(occurrences, 1, "custom event name should only appear once and not leak to the flushed chunk of the default message");
+});
+
+test("insert an SSE event separator before flushed chunks", async () => {
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [inputLine + doneLine]);
+
+ // Output must contain the payload and [DONE] separated by double newlines to form separate SSE events
+ assert.ok(output.includes("\n\ndata: [DONE]"), "should separate flushed chunk and [DONE] event");
+});
+
+test("reset event line on empty line message boundary", async () => {
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const eventLine = "event: response.output_text.delta\n";
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+ const defaultLine = `data: {"choices":[{"delta":{"content":"uvwxyz"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [eventLine + inputLine, defaultLine + doneLine]);
+
+ // The defaultLine is preceded by a blank line (\n\n), so it is a separate event.
+ // The event name "response.output_text.delta" must NOT leak into the second event.
+ const parts = output.split("\n\n");
+
+ // parts[0] should have the custom event name
+ assert.ok(parts[0].includes("event: response.output_text.delta"), "first block should have custom event name");
+
+ // parts[1] should NOT have the custom event name
+ assert.ok(!parts[1].includes("event: response.output_text.delta"), "second block should reset event name and not leak it");
+});
+
+test("sanitize compressed IPv6 addresses", async () => {
+ const transform = createPiiSseTransform();
+
+ const inputLoopback = `data: {"choices":[{"delta":{"content":"server address is ::1"}}]}\n\n`;
+ const inputCompressed = `data: {"choices":[{"delta":{"content":"server address is 2001:db8::1"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const outputLoopback = await testTransform(transform, [inputLoopback + doneLine]);
+ assert.ok(!outputLoopback.includes("::1"), "compressed loopback IPv6 should be redacted");
+ assert.ok(outputLoopback.includes("[IP_REDACTED]"), "redaction marker should be present for loopback IPv6");
+
+ const transform2 = createPiiSseTransform();
+ const outputCompressed = await testTransform(transform2, [inputCompressed + doneLine]);
+ assert.ok(!outputCompressed.includes("2001:db8::1"), "compressed IPv6 should be redacted");
+ assert.ok(outputCompressed.includes("[IP_REDACTED]"), "redaction marker should be present for compressed IPv6");
+});
+
+test("no event: prefix in flushed chunk when no event line was seen", async () => {
+ // If no "event:" line preceded the data lines, lastEventLine should remain
+ // empty and the flushed payload must NOT have any "event:" prepended.
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [inputLine + doneLine]);
+
+ // The flushed chunk (last 10 chars "klmnopqrst") must NOT be preceded by any "event:" line.
+ assert.ok(!output.includes("event:"), "no event: prefix should appear when no event line was seen");
+});
+
+test("event name preserved when stream closes without [DONE] sentinel", async () => {
+ // The stream flush path (TransformStream flush()) must also prepend lastEventLine.
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ const eventLine = "event: response.output_text.delta\n";
+ // 20-char content — window=10 means 10 chars are buffered and flushed on close.
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+
+ // No [DONE] — rely on the TransformStream flush() callback.
+ const output = await testTransform(transform, [eventLine + inputLine]);
+
+ assert.ok(
+ output.includes("event: response.output_text.delta"),
+ "event name should be preserved even when stream closes without [DONE]"
+ );
+});
+
+test("event: line without trailing space is tracked as currentEventLine", async () => {
+ // The code checks `line.startsWith("event:")` — this matches both
+ // "event: foo" and "event:foo". Both forms should be captured.
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ // Use the no-space variant: "event:custom.event"
+ const eventLine = "event:custom.event\n";
+ const inputLine = `data: {"choices":[{"delta":{"content":"abcdefghijklmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [eventLine + inputLine + doneLine]);
+
+ assert.ok(output.includes("event:custom.event"), "no-space event: form should be tracked and prepended on flush");
+});
+
+test("lastEventLine is not updated when processing a stop-signal chunk", async () => {
+ // The code guards: `if (!isStopSignal && !isSnapshot) { lastEventLine = currentEventLine; }`
+ // A stop-signal chunk (finish_reason present) must not overwrite lastEventLine with an
+ // event name that belongs only to the stop chunk.
+ const transform = (createPiiSseTransform as any)({ windowSize: 10 });
+
+ // First: a regular content chunk preceded by a named event.
+ const contentEventLine = "event: response.output_text.delta\n";
+ const contentData = `data: {"choices":[{"delta":{"content":"abcdefghijklmno"}}]}\n\n`;
+
+ // Second: a stop signal preceded by a DIFFERENT event name.
+ // lastEventLine should remain "response.output_text.delta" (from the content chunk),
+ // not "response.done" (from the stop signal).
+ const stopEventLine = "event: response.done\n";
+ const stopData = `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [
+ contentEventLine + contentData,
+ stopEventLine + stopData + doneLine,
+ ]);
+
+ // The flushed chunk (the buffered tail of "abcdefghijklmno") should be preceded by
+ // "response.output_text.delta", not "response.done".
+ assert.ok(
+ output.includes("event: response.output_text.delta"),
+ "flushed chunk should carry the content event name, not the stop-signal event name"
+ );
+ // "response.done" may appear in the pass-through of the stop event line itself,
+ // but should NOT be the event name attached to the flushed data payload.
+ const flushedSection = output.slice(output.lastIndexOf("event: response.output_text.delta"));
+ assert.ok(
+ !flushedSection.startsWith("event: response.done"),
+ "flushed payload must not be tagged with the stop-signal event name"
+ );
+});
+
+test("two consecutive events with different names each get their own event name on flush", async () => {
+ // Sequence: event-A → content-A (fills window) → event-B → content-B (fills window) → [DONE]
+ // The flushed tail of content-A should carry event-A, and the flushed tail of content-B event-B.
+ const transform = (createPiiSseTransform as any)({ windowSize: 5 });
+
+ const eventA = "event: event.type.alpha\n";
+ const dataA = `data: {"choices":[{"delta":{"content":"abcdefghij"}}]}\n\n`;
+
+ const eventB = "event: event.type.beta\n";
+ const dataB = `data: {"choices":[{"delta":{"content":"klmnopqrst"}}]}\n\n`;
+ const doneLine = `data: [DONE]\n\n`;
+
+ const output = await testTransform(transform, [eventA + dataA + eventB + dataB + doneLine]);
+
+ assert.ok(output.includes("event: event.type.alpha"), "event-A name should appear in output");
+ assert.ok(output.includes("event: event.type.beta"), "event-B name should appear in output");
+});
test.after(async () => {
if (originalEnv !== undefined) {
process.env.PII_RESPONSE_SANITIZATION = originalEnv;