/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { InternalError } from "#general";
import { BdxMessageType, BdxStatusCode } from "#types";
import { BdxError } from "../BdxError.js";
import { Flow } from "./Flow.js";
class InboundFlow extends Flow {
  #closeStreams;
  #writeController;
  #writePromise;
  /**
   * Returns initialized streams for the transfer and initializes the #closeStream class function
   */
  async initTransfer() {
    let writeController;
    const stream = new ReadableStream({
      start: (controller) => {
        writeController = controller;
      }
    });
    const { fileDesignator } = this.transferParameters;
    const writePromise = fileDesignator.writeFromStream(stream);
    this.#closeStreams = async (error) => {
      if (writeController !== void 0) {
        if (error !== void 0) {
          writeController.error(error);
          try {
            await writePromise;
          } catch {
          }
        }
      }
      if (!stream.locked) {
        await stream.cancel();
      }
    };
    this.#writeController = writeController;
    this.#writePromise = writePromise;
  }
  get stream() {
    if (!this.#writeController || !this.#writePromise) {
      throw new InternalError("Transfer not initialized. Call initTransfer() before starting the transfer.");
    }
    return { writeController: this.#writeController, writePromise: this.#writePromise };
  }
  async finalizeTransfer() {
    const { writePromise } = this.stream;
    const blockCounter = this.finalBlockCounter;
    await writePromise;
    await this.messenger.sendBlockAckEof({ blockCounter });
  }
  writeDataChunk(writeController, data, messageType) {
    writeController.enqueue(data);
    if (this.bytesLeft !== void 0) {
      this.bytesLeft -= data.byteLength;
    }
    let done = false;
    if (messageType === BdxMessageType.BlockEof) {
      if (this.bytesLeft !== void 0 && this.bytesLeft !== 0) {
        throw new BdxError(
          `Received BlockEof with ${this.bytesLeft}bytes left, but no more data available`,
          this.bytesLeft > 0 ? BdxStatusCode.LengthTooShort : BdxStatusCode.LengthTooLarge
        );
      }
      done = true;
      writeController.close();
    }
    return done;
  }
  async close(error) {
    await super.close(error);
    await this.#closeStreams?.(error);
  }
}
export {
  InboundFlow
};
//# sourceMappingURL=InboundFlow.js.map
