// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'node:path';
import { Sort, Import, Path } from '@rushstack/node-core-library';
import { BaseWorkspaceFile } from '../base/BaseWorkspaceFile';
import { PNPM_SHRINKWRAP_YAML_FORMAT } from './PnpmYamlCommon';
const yamlModule = Import.lazy('js-yaml', require);
const globEscape = require('glob-escape'); // No @types/glob-escape package exists
export class PnpmWorkspaceFile extends BaseWorkspaceFile {
    /**
     * The PNPM workspace file is used to specify the location of workspaces relative to the root
     * of your PNPM install.
     */
    constructor(workspaceYamlFilename) {
        super();
        this.workspaceFilename = workspaceYamlFilename;
        // Ignore any existing file since this file is generated and we need to handle deleting packages
        // If we need to support manual customization, that should be an additional parameter for "base file"
        this._workspacePackages = new Set();
        this._catalogs = undefined;
    }
    /**
     * Sets the catalog definitions for the workspace.
     * @param catalogs - A map of catalog name to package versions
     */
    setCatalogs(catalogs) {
        this._catalogs = catalogs;
    }
    /** @override */
    addPackage(packagePath) {
        // Ensure the path is relative to the pnpm-workspace.yaml file
        if (path.isAbsolute(packagePath)) {
            packagePath = path.relative(path.dirname(this.workspaceFilename), packagePath);
        }
        // Glob can't handle Windows paths
        const globPath = Path.convertToSlashes(packagePath);
        this._workspacePackages.add(globEscape(globPath));
    }
    /** @override */
    serialize() {
        // Ensure stable sort order when serializing
        Sort.sortSet(this._workspacePackages);
        const workspaceYaml = {
            packages: Array.from(this._workspacePackages)
        };
        if (this._catalogs && Object.keys(this._catalogs).length > 0) {
            workspaceYaml.catalogs = this._catalogs;
        }
        return yamlModule.dump(workspaceYaml, PNPM_SHRINKWRAP_YAML_FORMAT);
    }
}
//# sourceMappingURL=PnpmWorkspaceFile.js.map