{"version":3,"file":"output-capture.d.ts","sourceRoot":"","sources":["../../../src/harness/utils/output-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,KAAK,EAAE,yBAAyB,EAAuB,iBAAiB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAItH,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAC/C,eAAO,MAAM,8BAA8B,QAAa,CAAC;AAMzD,UAAU,qBAAqB;IAC9B,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;IACjE,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;CAC9B;AAED;;;;;;;GAOG;AACH,qBAAa,aAAa;;IAkBzB,YAAY,OAAO,EAAE,yBAAyB,GAAG,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,qBAAqB,EAqB5G;IAED,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAQrC;IAED,MAAM,IAAI,IAAI,CAGb;IAED,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAK/B;IAED,QAAQ,IAAI,eAAe,CAoB1B;IAED,KAAK,IAAI,IAAI,CAGZ;IAED,OAAO,IAAI,IAAI,CAGd;CA4BD;AAED,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,eAAe,GAAG,SAAS,EACpC,MAAM,EAAE,iBAAiB,GACvB,eAAe,CAWjB;AA+CD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAExD","sourcesContent":["import type { Context } from \"../context.ts\";\nimport type { ShellOutputCaptureOptions, ShellOutputMetadata, ShellOutputUpdate, ShellOutputView } from \"../types.ts\";\nimport { AdaptivePublisher } from \"./adaptive-publisher.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateHead, truncateTail, utf8ByteLength } from \"./truncate.ts\";\n\nexport const OUTPUT_MIN_EMIT_INTERVAL_MS = 100;\nexport const OUTPUT_TARGET_BYTES_PER_SECOND = 100 * 1024;\n\nconst INVALID_SHELL_OUTPUT = /[\\x00-\\x08\\x0b-\\x1f\\ufff9-\\ufffb]/g;\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\ninterface OutputCaptureHandlers {\n\tonUpdate?: (update: ShellOutputUpdate, context: Context) => void;\n\tonError(error: unknown): void;\n}\n\n/**\n * Maintains and publishes one bounded shell-output view.\n *\n * Writes received while publication is rate-limited collapse into the latest\n * view. Small changes remain responsive; complete window turnovers purchase a\n * proportionally longer delay. The first update after idle and an explicit\n * final flush are immediate.\n */\nexport class OutputCapture {\n\treadonly #maxBytes: number;\n\treadonly #maxLines: number;\n\treadonly #retain: \"head\" | \"tail\";\n\treadonly #context: Context;\n\treadonly #onUpdate: OutputCaptureHandlers[\"onUpdate\"];\n\n\treadonly #decoder = new TextDecoder();\n\t#buffer = \"\";\n\t#bufferBytes = 0;\n\t#totalBytes = 0;\n\t#newlines = 0;\n\t#endsWithNewline = true;\n\t#currentLineBytes = 0;\n\t#spillPath: string | undefined;\n\t#disposed = false;\n\treadonly #publisher: AdaptivePublisher<ShellOutputView, ShellOutputUpdate>;\n\n\tconstructor(options: ShellOutputCaptureOptions | undefined, context: Context, handlers: OutputCaptureHandlers) {\n\t\tthis.#maxBytes = options?.limits.maxBytes ?? DEFAULT_MAX_BYTES;\n\t\tthis.#maxLines = options?.limits.maxLines ?? DEFAULT_MAX_LINES;\n\t\tthis.#retain = options?.limits.retain ?? \"tail\";\n\t\tthis.#context = context;\n\t\tthis.#onUpdate = handlers.onUpdate;\n\t\tif (!Number.isFinite(this.#maxBytes) || this.#maxBytes <= 0) {\n\t\t\tthrow new TypeError(\"Output maxBytes must be a positive finite number\");\n\t\t}\n\t\tif (!Number.isInteger(this.#maxLines) || this.#maxLines <= 0) {\n\t\t\tthrow new TypeError(\"Output maxLines must be a positive integer\");\n\t\t}\n\t\tthis.#publisher = new AdaptivePublisher({\n\t\t\tsnapshot: () => this.snapshot(),\n\t\t\tupdate: updateFrom,\n\t\t\tmeasure: (update) => utf8ByteLength(JSON.stringify(update)),\n\t\t\tpublish: (update) => this.#onUpdate?.(update, this.#context),\n\t\t\tonError: handlers.onError,\n\t\t\tminIntervalMs: OUTPUT_MIN_EMIT_INTERVAL_MS,\n\t\t\ttargetBytesPerSecond: OUTPUT_TARGET_BYTES_PER_SECOND,\n\t\t});\n\t}\n\n\tget truncated(): boolean {\n\t\treturn this.#totalBytes > this.#maxBytes || this.#totalLines() > this.#maxLines;\n\t}\n\n\tpush(chunk: string | Uint8Array): void {\n\t\tif (this.#disposed) return;\n\t\tif (typeof chunk === \"string\") {\n\t\t\tthis.#appendText(this.#decoder.decode());\n\t\t\tthis.#appendText(chunk);\n\t\t\treturn;\n\t\t}\n\t\tthis.#appendText(this.#decoder.decode(chunk, { stream: true }));\n\t}\n\n\tfinish(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#appendText(this.#decoder.decode());\n\t}\n\n\tsetSpillPath(path: string): void {\n\t\tif (this.#disposed || this.#spillPath === path) return;\n\t\tthis.#spillPath = path;\n\t\tthis.#publisher.markDirty();\n\t\tthis.flush();\n\t}\n\n\tsnapshot(): ShellOutputView {\n\t\tconst retained =\n\t\t\tthis.#retain === \"head\"\n\t\t\t\t? truncateHead(this.#buffer, { maxBytes: this.#maxBytes, maxLines: this.#maxLines })\n\t\t\t\t: truncateTail(this.#buffer, { maxBytes: this.#maxBytes, maxLines: this.#maxLines });\n\t\tconst totalLines = this.#totalLines();\n\t\tconst truncated = this.truncated;\n\t\tconst { content, ...truncation } = retained;\n\t\treturn {\n\t\t\ttext: sanitizeShellOutput(content),\n\t\t\ttruncation: {\n\t\t\t\t...truncation,\n\t\t\t\ttruncated,\n\t\t\t\ttruncatedBy: truncated ? (totalLines > this.#maxLines ? \"lines\" : \"bytes\") : null,\n\t\t\t\ttotalBytes: this.#totalBytes,\n\t\t\t\ttotalLines,\n\t\t\t},\n\t\t\t...(this.#spillPath === undefined ? {} : { spillPath: this.#spillPath }),\n\t\t\t...(retained.lastLinePartial ? { lastLineBytes: this.#currentLineBytes } : {}),\n\t\t};\n\t}\n\n\tflush(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#publisher.flush(true);\n\t}\n\n\tdispose(): void {\n\t\tthis.#publisher.dispose();\n\t\tthis.#disposed = true;\n\t}\n\n\t#appendText(text: string): void {\n\t\tif (text === \"\") return;\n\t\tconst textBytes = utf8ByteLength(text);\n\t\tthis.#totalBytes += textBytes;\n\t\tthis.#newlines += countNewlines(text);\n\t\tthis.#endsWithNewline = text.endsWith(\"\\n\");\n\t\tconst lastNewline = text.lastIndexOf(\"\\n\");\n\t\tthis.#currentLineBytes =\n\t\t\tlastNewline === -1 ? this.#currentLineBytes + textBytes : utf8ByteLength(text.slice(lastNewline + 1));\n\t\tthis.#buffer += text;\n\t\tthis.#bufferBytes += textBytes;\n\n\t\tconst guard = this.#maxBytes * 2;\n\t\tif (this.#bufferBytes > guard * 2) {\n\t\t\tthis.#buffer =\n\t\t\t\tthis.#retain === \"tail\"\n\t\t\t\t\t? trimToLastUtf8Bytes(this.#buffer, guard)\n\t\t\t\t\t: trimToFirstUtf8Bytes(this.#buffer, guard);\n\t\t\tthis.#bufferBytes = utf8ByteLength(this.#buffer);\n\t\t}\n\t\tthis.#publisher.markDirty();\n\t}\n\n\t#totalLines(): number {\n\t\treturn this.#newlines + (this.#endsWithNewline || this.#totalBytes === 0 ? 0 : 1);\n\t}\n}\n\nexport function applyShellOutputUpdate(\n\tcurrent: ShellOutputView | undefined,\n\tupdate: ShellOutputUpdate,\n): ShellOutputView {\n\tswitch (update.kind) {\n\t\tcase \"replace\":\n\t\t\treturn update.output;\n\t\tcase \"append\":\n\t\t\treturn { text: `${current?.text ?? \"\"}${update.text}`, ...update.metadata };\n\t\tcase \"slide\":\n\t\t\treturn { text: `${current?.text.slice(update.drop) ?? \"\"}${update.text}`, ...update.metadata };\n\t\tcase \"metadata\":\n\t\t\treturn { text: current?.text ?? \"\", ...update.metadata };\n\t}\n}\n\nfunction updateFrom(previous: ShellOutputView | undefined, current: ShellOutputView): ShellOutputUpdate {\n\tif (previous === undefined) return { kind: \"replace\", output: current };\n\tconst metadata: ShellOutputMetadata = {\n\t\ttruncation: current.truncation,\n\t\t...(current.spillPath === undefined ? {} : { spillPath: current.spillPath }),\n\t\t...(current.lastLineBytes === undefined ? {} : { lastLineBytes: current.lastLineBytes }),\n\t};\n\tif (current.text === previous.text) return { kind: \"metadata\", metadata };\n\tif (current.text.length > previous.text.length && current.text.slice(0, previous.text.length) === previous.text) {\n\t\treturn { kind: \"append\", text: current.text.slice(previous.text.length), metadata };\n\t}\n\tconst shared = suffixPrefixOverlap(\n\t\tprevious.text,\n\t\tcurrent.text,\n\t\tMath.min(previous.text.length, current.text.length, current.truncation.maxBytes * 2),\n\t);\n\tif (shared > 0) {\n\t\treturn {\n\t\t\tkind: \"slide\",\n\t\t\tdrop: previous.text.length - shared,\n\t\t\ttext: current.text.slice(shared),\n\t\t\tmetadata,\n\t\t};\n\t}\n\treturn { kind: \"replace\", output: current };\n}\n\nfunction suffixPrefixOverlap(before: string, after: string, scan: number): number {\n\tif (before.length === 0 || after.length === 0 || scan === 0) return 0;\n\tconst tail = before.length > scan ? before.slice(before.length - scan) : before;\n\tfor (const probeLength of [Math.min(64, after.length), 1]) {\n\t\tconst probe = after.slice(0, probeLength);\n\t\tlet candidates = 0;\n\t\tfor (let index = tail.indexOf(probe); index !== -1; index = tail.indexOf(probe, index + 1)) {\n\t\t\tif (++candidates > 8) break;\n\t\t\tconst overlapLength = tail.length - index;\n\t\t\tif (overlapLength <= after.length && tail.slice(index) === after.slice(0, overlapLength)) {\n\t\t\t\treturn overlapLength;\n\t\t\t}\n\t\t}\n\t\tif (probeLength === 1) break;\n\t}\n\treturn 0;\n}\n\nexport function sanitizeShellOutput(text: string): string {\n\treturn text.replace(INVALID_SHELL_OUTPUT, \"\");\n}\n\nfunction countNewlines(text: string): number {\n\tlet count = 0;\n\tfor (let index = text.indexOf(\"\\n\"); index !== -1; index = text.indexOf(\"\\n\", index + 1)) count++;\n\treturn count;\n}\n\nfunction trimToLastUtf8Bytes(text: string, maxBytes: number): string {\n\tconst bytes = textEncoder.encode(text);\n\tif (bytes.length <= maxBytes) return text;\n\tlet start = bytes.length - maxBytes;\n\twhile (start < bytes.length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start++;\n\treturn textDecoder.decode(bytes.subarray(start));\n}\n\nfunction trimToFirstUtf8Bytes(text: string, maxBytes: number): string {\n\tconst bytes = textEncoder.encode(text);\n\tif (bytes.length <= maxBytes) return text;\n\tlet end = maxBytes;\n\twhile (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end--;\n\treturn textDecoder.decode(bytes.subarray(0, end));\n}\n"]}