// SPDX-License-Identifier: Apache-2.0
import { LayeredConfigSource } from './layered-config-source.js';
import { EnvironmentStorageBackend } from '../../backend/impl/environment-storage-backend.js';
import { ConfigurationError } from '../api/configuration-error.js';
import { Forest } from '../../key/lexer/forest.js';
/**
 * A {@link ConfigSource} that reads configuration data from the environment.
 *
 * <p>
 * Strings are read verbatim from the environment variables.
 * Numbers and booleans are converted from strings using the JSON parser.
 * Objects, arrays of objects, and arrays of primitives are assumed to be stored as serialized JSON strings.
 */
export class EnvironmentConfigSource extends LayeredConfigSource {
    /**
     * The data read from the environment.
     * @private
     */
    data;
    constructor(mapper, prefix) {
        super(new EnvironmentStorageBackend(prefix), mapper, prefix);
        this.data = new Map();
    }
    get name() {
        return 'EnvironmentConfigSource';
    }
    get ordinal() {
        return 100;
    }
    async refresh() {
        await this.load();
    }
    async load() {
        this.data.clear();
        this.forest = undefined;
        const variables = await this.backend.list();
        for (const k of variables) {
            try {
                const va = await this.backend.readBytes(k);
                this.data.set(k, va.toString('utf8'));
            }
            catch (error) {
                throw new ConfigurationError(`Failed to read environment variable: ${k}`, error);
            }
        }
        this.forest = Forest.from(this.data);
    }
}
//# sourceMappingURL=environment-config-source.js.map