import '../../../../../../@bufbuild_protobuf@1.10.1/node_modules/@bufbuild/protobuf/dist/esm/index.js';
import { ConnectError } from './connect-error.js';
import { Code } from './code.js';
import { protoBase64 } from '../../../../../../@bufbuild_protobuf@1.10.1/node_modules/@bufbuild/protobuf/dist/esm/proto-base64.js';

// Copyright 2021-2024 The Connect Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
 * Encode a single binary header value according to the Connect
 * and gRPC specifications.
 *
 * This function accepts raw binary data from a buffer, a string
 * with UTF-8 text, or a protobuf message. It encodes the input
 * with unpadded base64 and returns a string that can be used for
 * a header whose name ends with `-bin`.
 */
function encodeBinaryHeader(value) {
    let bytes;
    if (typeof value == "object" && "getType" in value) {
        bytes = value.toBinary();
    }
    else if (typeof value == "string") {
        bytes = new TextEncoder().encode(value);
    }
    else {
        bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
    }
    return protoBase64.enc(bytes).replace(/=+$/, "");
}
function decodeBinaryHeader(value, type, options) {
    try {
        const bytes = protoBase64.dec(value);
        if (type) {
            return type.fromBinary(bytes, options);
        }
        return bytes;
    }
    catch (e) {
        throw ConnectError.from(e, Code.DataLoss);
    }
}
/**
 * Merge two or more Headers objects by appending all fields from
 * all inputs to a new Headers object.
 */
function appendHeaders(...headers) {
    const h = new Headers();
    for (const e of headers) {
        e.forEach((value, key) => {
            h.append(key, value);
        });
    }
    return h;
}

export { appendHeaders, decodeBinaryHeader, encodeBinaryHeader };
