// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { stringify } from "./stringify.ts";
/**
 * Convert each chunk to a CSV record.
 *
 * @example
 * ```ts
 * import { CsvStringifyStream } from "https://deno.land/std@$STD_VERSION/csv/csv_stringify_stream.ts";
 *
 * const file = await Deno.open("data.csv", { create: true, write: true });
 * const readable = ReadableStream.from([
 *   { id: 1, name: "one" },
 *   { id: 2, name: "two" },
 *   { id: 3, name: "three" },
 * ]);
 *
 * await readable
 *   .pipeThrough(new CsvStringifyStream({ columns: ["id", "name"] }))
 *   .pipeThrough(new TextEncoderStream())
 *   .pipeTo(file.writable);
 * ````
 */ export class CsvStringifyStream extends TransformStream {
  /** Construct a new instance. */ constructor(options){
    const { separator, columns = [] } = options ?? {};
    super({
      start (controller) {
        if (columns && columns.length > 0) {
          try {
            controller.enqueue(stringify([
              columns
            ], {
              separator,
              headers: false
            }));
          } catch (error) {
            controller.error(error);
          }
        }
      },
      transform (chunk, controller) {
        try {
          controller.enqueue(stringify([
            chunk
          ], {
            separator,
            headers: false,
            columns
          }));
        } catch (error) {
          controller.error(error);
        }
      }
    });
  }
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImh0dHBzOi8vZGVuby5sYW5kL3N0ZEAwLjIxNy4wL2Nzdi9jc3Zfc3RyaW5naWZ5X3N0cmVhbS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvLyBDb3B5cmlnaHQgMjAxOC0yMDI0IHRoZSBEZW5vIGF1dGhvcnMuIEFsbCByaWdodHMgcmVzZXJ2ZWQuIE1JVCBsaWNlbnNlLlxuaW1wb3J0IHsgc3RyaW5naWZ5IH0gZnJvbSBcIi4vc3RyaW5naWZ5LnRzXCI7XG5cbi8qKiBPcHRpb25zIGZvciB7QGxpbmtjb2RlIENzdlN0cmluZ2lmeVN0cmVhbX0uICovXG5leHBvcnQgaW50ZXJmYWNlIENzdlN0cmluZ2lmeVN0cmVhbU9wdGlvbnMge1xu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