'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var errors = require('@backstage/errors');
var pluginScaffolderNode = require('@backstage/plugin-scaffolder-node');
var fetch = require('node-fetch');
var yaml = require('yaml');
var integration = require('@backstage/integration');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
var yaml__default = /*#__PURE__*/_interopDefaultLegacy(yaml);

const examples$1 = [
  {
    description: "Initializes a git repository of contents in workspace and publish it to Bitbucket with default configuration.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project"
          }
        }
      ]
    })
  },
  {
    description: "Add a description.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository"
          }
        }
      ]
    })
  },
  {
    description: "Change visibility of the repository.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public"
          }
        }
      ]
    })
  },
  {
    description: "Set the default branch.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main"
          }
        }
      ]
    })
  },
  {
    description: "Specify a source path within the workspace.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main",
            sourcePath: "./repoRoot"
          }
        }
      ]
    })
  },
  {
    description: "Enable LFS for the repository.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "hosted.bitbucket.com?project=project&repo=repo",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main",
            sourcePath: "./repoRoot",
            enableLFS: true
          }
        }
      ]
    })
  },
  {
    description: "Provide an authentication token for Bitbucket.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main",
            token: "your-auth-token"
          }
        }
      ]
    })
  },
  {
    description: "Set a custom commit message.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main",
            token: "your-auth-token",
            gitCommitMessage: "Initial commit with custom message"
          }
        }
      ]
    })
  },
  {
    description: "Set a custom author name and email for the commit.",
    example: yaml__default["default"].stringify({
      steps: [
        {
          id: "publish",
          action: "publish:bitbucket",
          name: "Publish to Bitbucket",
          input: {
            repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
            description: "Initialize a git repository",
            repoVisibility: "public",
            defaultBranch: "main",
            token: "your-auth-token",
            gitCommitMessage: "Initial commit with custom message",
            gitAuthorName: "Your Name",
            gitAuthorEmail: "your.email@example.com"
          }
        }
      ]
    })
  }
];

const createBitbucketCloudRepository = async (opts) => {
  const {
    workspace,
    project,
    repo,
    description,
    repoVisibility,
    mainBranch,
    authorization,
    apiBaseUrl
  } = opts;
  const options = {
    method: "POST",
    body: JSON.stringify({
      scm: "git",
      description,
      is_private: repoVisibility === "private",
      project: { key: project }
    }),
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  let response;
  try {
    response = await fetch__default["default"](
      `${apiBaseUrl}/repositories/${workspace}/${repo}`,
      options
    );
  } catch (e) {
    throw new Error(`Unable to create repository, ${e}`);
  }
  if (response.status !== 200) {
    throw new Error(
      `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  let remoteUrl = "";
  for (const link of r.links.clone) {
    if (link.name === "https") {
      remoteUrl = link.href;
    }
  }
  const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;
  return { remoteUrl, repoContentsUrl };
};
const createBitbucketServerRepository = async (opts) => {
  const {
    project,
    repo,
    description,
    authorization,
    repoVisibility,
    apiBaseUrl
  } = opts;
  let response;
  const options = {
    method: "POST",
    body: JSON.stringify({
      name: repo,
      description,
      public: repoVisibility === "public"
    }),
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  try {
    response = await fetch__default["default"](`${apiBaseUrl}/projects/${project}/repos`, options);
  } catch (e) {
    throw new Error(`Unable to create repository, ${e}`);
  }
  if (response.status !== 201) {
    throw new Error(
      `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  let remoteUrl = "";
  for (const link of r.links.clone) {
    if (link.name === "http") {
      remoteUrl = link.href;
    }
  }
  const repoContentsUrl = `${r.links.self[0].href}`;
  return { remoteUrl, repoContentsUrl };
};
const getAuthorizationHeader$1 = (config) => {
  if (config.username && config.appPassword) {
    const buffer = Buffer.from(
      `${config.username}:${config.appPassword}`,
      "utf8"
    );
    return `Basic ${buffer.toString("base64")}`;
  }
  if (config.token) {
    return `Bearer ${config.token}`;
  }
  throw new Error(
    `Authorization has not been provided for Bitbucket. Please add either username + appPassword or token to the Integrations config`
  );
};
const performEnableLFS$1 = async (opts) => {
  const { authorization, host, project, repo } = opts;
  const options = {
    method: "PUT",
    headers: {
      Authorization: authorization
    }
  };
  const { ok, status, statusText } = await fetch__default["default"](
    `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
    options
  );
  if (!ok)
    throw new Error(
      `Failed to enable LFS in the repository, ${status}: ${statusText}`
    );
};
function createPublishBitbucketAction(options) {
  const { integrations, config } = options;
  return pluginScaffolderNode.createTemplateAction({
    id: "publish:bitbucket",
    description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket.",
    examples: examples$1,
    schema: {
      input: {
        type: "object",
        required: ["repoUrl"],
        properties: {
          repoUrl: {
            title: "Repository Location",
            type: "string"
          },
          description: {
            title: "Repository Description",
            type: "string"
          },
          repoVisibility: {
            title: "Repository Visibility",
            type: "string",
            enum: ["private", "public"]
          },
          defaultBranch: {
            title: "Default Branch",
            type: "string",
            description: `Sets the default branch on the repository. The default value is 'master'`
          },
          sourcePath: {
            title: "Source Path",
            description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
            type: "string"
          },
          enableLFS: {
            title: "Enable LFS?",
            description: "Enable LFS for the repository. Only available for hosted Bitbucket.",
            type: "boolean"
          },
          token: {
            title: "Authentication Token",
            type: "string",
            description: "The token to use for authorization to BitBucket"
          },
          gitCommitMessage: {
            title: "Git Commit Message",
            type: "string",
            description: `Sets the commit message on the repository. The default value is 'initial commit'`
          },
          gitAuthorName: {
            title: "Default Author Name",
            type: "string",
            description: `Sets the default author name for the commit. The default value is 'Scaffolder'`
          },
          gitAuthorEmail: {
            title: "Default Author Email",
            type: "string",
            description: `Sets the default author email for the commit.`
          }
        }
      },
      output: {
        type: "object",
        properties: {
          remoteUrl: {
            title: "A URL to the repository with the provider",
            type: "string"
          },
          repoContentsUrl: {
            title: "A URL to the root of the repository",
            type: "string"
          },
          commitHash: {
            title: "The git commit hash of the initial commit",
            type: "string"
          }
        }
      }
    },
    async handler(ctx) {
      var _a;
      ctx.logger.warn(
        `[Deprecated] Please migrate the use of action "publish:bitbucket" to "publish:bitbucketCloud" or "publish:bitbucketServer".`
      );
      const {
        repoUrl,
        description,
        defaultBranch = "master",
        repoVisibility = "private",
        enableLFS = false,
        gitCommitMessage = "initial commit",
        gitAuthorName,
        gitAuthorEmail
      } = ctx.input;
      const { workspace, project, repo, host } = pluginScaffolderNode.parseRepoUrl(
        repoUrl,
        integrations
      );
      if (host === "bitbucket.org") {
        if (!workspace) {
          throw new errors.InputError(
            `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
          );
        }
      }
      if (!project) {
        throw new errors.InputError(
          `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
        );
      }
      const integrationConfig = integrations.bitbucket.byHost(host);
      if (!integrationConfig) {
        throw new errors.InputError(
          `No matching integration configuration for host ${host}, please check your integrations config`
        );
      }
      const authorization = getAuthorizationHeader$1(
        ctx.input.token ? {
          host: integrationConfig.config.host,
          apiBaseUrl: integrationConfig.config.apiBaseUrl,
          token: ctx.input.token
        } : integrationConfig.config
      );
      const apiBaseUrl = integrationConfig.config.apiBaseUrl;
      const createMethod = host === "bitbucket.org" ? createBitbucketCloudRepository : createBitbucketServerRepository;
      const { remoteUrl, repoContentsUrl } = await createMethod({
        authorization,
        workspace: workspace || "",
        project,
        repo,
        repoVisibility,
        mainBranch: defaultBranch,
        description,
        apiBaseUrl
      });
      const gitAuthorInfo = {
        name: gitAuthorName ? gitAuthorName : config.getOptionalString("scaffolder.defaultAuthor.name"),
        email: gitAuthorEmail ? gitAuthorEmail : config.getOptionalString("scaffolder.defaultAuthor.email")
      };
      let auth;
      if (ctx.input.token) {
        auth = {
          username: "x-token-auth",
          password: ctx.input.token
        };
      } else {
        auth = {
          username: integrationConfig.config.username ? integrationConfig.config.username : "x-token-auth",
          password: integrationConfig.config.appPassword ? integrationConfig.config.appPassword : (_a = integrationConfig.config.token) != null ? _a : ""
        };
      }
      const commitResult = await pluginScaffolderNode.initRepoAndPush({
        dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
        remoteUrl,
        auth,
        defaultBranch,
        logger: ctx.logger,
        commitMessage: gitCommitMessage ? gitCommitMessage : config.getOptionalString("scaffolder.defaultCommitMessage"),
        gitAuthorInfo
      });
      if (enableLFS && host !== "bitbucket.org") {
        await performEnableLFS$1({ authorization, host, project, repo });
      }
      ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
      ctx.output("remoteUrl", remoteUrl);
      ctx.output("repoContentsUrl", repoContentsUrl);
    }
  });
}

const getAuthorizationHeader = (config) => {
  if (config.username && config.appPassword) {
    const buffer = Buffer.from(
      `${config.username}:${config.appPassword}`,
      "utf8"
    );
    return `Basic ${buffer.toString("base64")}`;
  }
  if (config.token) {
    return `Bearer ${config.token}`;
  }
  throw new Error(
    `Authorization has not been provided for Bitbucket Cloud. Please add either username + appPassword to the Integrations config or a user login auth token`
  );
};

const createRepository$1 = async (opts) => {
  const {
    workspace,
    project,
    repo,
    description,
    repoVisibility,
    mainBranch,
    authorization,
    apiBaseUrl
  } = opts;
  const options = {
    method: "POST",
    body: JSON.stringify({
      scm: "git",
      description,
      is_private: repoVisibility === "private",
      project: { key: project }
    }),
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  let response;
  try {
    response = await fetch__default["default"](
      `${apiBaseUrl}/repositories/${workspace}/${repo}`,
      options
    );
  } catch (e) {
    throw new Error(`Unable to create repository, ${e}`);
  }
  if (response.status !== 200) {
    throw new Error(
      `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  let remoteUrl = "";
  for (const link of r.links.clone) {
    if (link.name === "https") {
      remoteUrl = link.href;
    }
  }
  const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;
  return { remoteUrl, repoContentsUrl };
};
function createPublishBitbucketCloudAction(options) {
  const { integrations, config } = options;
  return pluginScaffolderNode.createTemplateAction({
    id: "publish:bitbucketCloud",
    description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Cloud.",
    schema: {
      input: {
        type: "object",
        required: ["repoUrl"],
        properties: {
          repoUrl: {
            title: "Repository Location",
            type: "string"
          },
          description: {
            title: "Repository Description",
            type: "string"
          },
          repoVisibility: {
            title: "Repository Visibility",
            type: "string",
            enum: ["private", "public"]
          },
          defaultBranch: {
            title: "Default Branch",
            type: "string",
            description: `Sets the default branch on the repository. The default value is 'master'`
          },
          sourcePath: {
            title: "Source Path",
            description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
            type: "string"
          },
          token: {
            title: "Authentication Token",
            type: "string",
            description: "The token to use for authorization to BitBucket Cloud"
          }
        }
      },
      output: {
        type: "object",
        properties: {
          remoteUrl: {
            title: "A URL to the repository with the provider",
            type: "string"
          },
          repoContentsUrl: {
            title: "A URL to the root of the repository",
            type: "string"
          },
          commitHash: {
            title: "The git commit hash of the initial commit",
            type: "string"
          }
        }
      }
    },
    async handler(ctx) {
      const {
        repoUrl,
        description,
        defaultBranch = "master",
        repoVisibility = "private"
      } = ctx.input;
      const { workspace, project, repo, host } = pluginScaffolderNode.parseRepoUrl(
        repoUrl,
        integrations
      );
      if (!workspace) {
        throw new errors.InputError(
          `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
        );
      }
      if (!project) {
        throw new errors.InputError(
          `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
        );
      }
      const integrationConfig = integrations.bitbucketCloud.byHost(host);
      if (!integrationConfig) {
        throw new errors.InputError(
          `No matching integration configuration for host ${host}, please check your integrations config`
        );
      }
      const authorization = getAuthorizationHeader(
        ctx.input.token ? { token: ctx.input.token } : integrationConfig.config
      );
      const apiBaseUrl = integrationConfig.config.apiBaseUrl;
      const { remoteUrl, repoContentsUrl } = await createRepository$1({
        authorization,
        workspace: workspace || "",
        project,
        repo,
        repoVisibility,
        mainBranch: defaultBranch,
        description,
        apiBaseUrl
      });
      const gitAuthorInfo = {
        name: config.getOptionalString("scaffolder.defaultAuthor.name"),
        email: config.getOptionalString("scaffolder.defaultAuthor.email")
      };
      let auth;
      if (ctx.input.token) {
        auth = {
          username: "x-token-auth",
          password: ctx.input.token
        };
      } else {
        if (!integrationConfig.config.username || !integrationConfig.config.appPassword) {
          throw new Error(
            "Credentials for Bitbucket Cloud integration required for this action."
          );
        }
        auth = {
          username: integrationConfig.config.username,
          password: integrationConfig.config.appPassword
        };
      }
      const commitResult = await pluginScaffolderNode.initRepoAndPush({
        dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
        remoteUrl,
        auth,
        defaultBranch,
        logger: ctx.logger,
        commitMessage: config.getOptionalString(
          "scaffolder.defaultCommitMessage"
        ),
        gitAuthorInfo
      });
      ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
      ctx.output("remoteUrl", remoteUrl);
      ctx.output("repoContentsUrl", repoContentsUrl);
    }
  });
}

const createRepository = async (opts) => {
  const {
    project,
    repo,
    description,
    authorization,
    repoVisibility,
    defaultBranch,
    apiBaseUrl
  } = opts;
  let response;
  const options = {
    method: "POST",
    body: JSON.stringify({
      name: repo,
      description,
      defaultBranch,
      public: repoVisibility === "public"
    }),
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  try {
    response = await fetch__default["default"](`${apiBaseUrl}/projects/${project}/repos`, options);
  } catch (e) {
    throw new Error(`Unable to create repository, ${e}`);
  }
  if (response.status !== 201) {
    throw new Error(
      `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  let remoteUrl = "";
  for (const link of r.links.clone) {
    if (link.name === "http") {
      remoteUrl = link.href;
    }
  }
  const repoContentsUrl = `${r.links.self[0].href}`;
  return { remoteUrl, repoContentsUrl };
};
const performEnableLFS = async (opts) => {
  const { authorization, host, project, repo } = opts;
  const options = {
    method: "PUT",
    headers: {
      Authorization: authorization
    }
  };
  const { ok, status, statusText } = await fetch__default["default"](
    `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
    options
  );
  if (!ok)
    throw new Error(
      `Failed to enable LFS in the repository, ${status}: ${statusText}`
    );
};
function createPublishBitbucketServerAction(options) {
  const { integrations, config } = options;
  return pluginScaffolderNode.createTemplateAction({
    id: "publish:bitbucketServer",
    description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Server.",
    schema: {
      input: {
        type: "object",
        required: ["repoUrl"],
        properties: {
          repoUrl: {
            title: "Repository Location",
            type: "string"
          },
          description: {
            title: "Repository Description",
            type: "string"
          },
          repoVisibility: {
            title: "Repository Visibility",
            type: "string",
            enum: ["private", "public"]
          },
          defaultBranch: {
            title: "Default Branch",
            type: "string",
            description: `Sets the default branch on the repository. The default value is 'master'`
          },
          sourcePath: {
            title: "Source Path",
            description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
            type: "string"
          },
          enableLFS: {
            title: "Enable LFS?",
            description: "Enable LFS for the repository.",
            type: "boolean"
          },
          token: {
            title: "Authentication Token",
            type: "string",
            description: "The token to use for authorization to BitBucket Server"
          },
          gitCommitMessage: {
            title: "Git Commit Message",
            type: "string",
            description: `Sets the commit message on the repository. The default value is 'initial commit'`
          },
          gitAuthorName: {
            title: "Author Name",
            type: "string",
            description: `Sets the author name for the commit. The default value is 'Scaffolder'`
          },
          gitAuthorEmail: {
            title: "Author Email",
            type: "string",
            description: `Sets the author email for the commit.`
          }
        }
      },
      output: {
        type: "object",
        properties: {
          remoteUrl: {
            title: "A URL to the repository with the provider",
            type: "string"
          },
          repoContentsUrl: {
            title: "A URL to the root of the repository",
            type: "string"
          },
          commitHash: {
            title: "The git commit hash of the initial commit",
            type: "string"
          }
        }
      }
    },
    async handler(ctx) {
      var _a;
      const {
        repoUrl,
        description,
        defaultBranch = "master",
        repoVisibility = "private",
        enableLFS = false,
        gitCommitMessage = "initial commit",
        gitAuthorName,
        gitAuthorEmail
      } = ctx.input;
      const { project, repo, host } = pluginScaffolderNode.parseRepoUrl(repoUrl, integrations);
      if (!project) {
        throw new errors.InputError(
          `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
        );
      }
      const integrationConfig = integrations.bitbucketServer.byHost(host);
      if (!integrationConfig) {
        throw new errors.InputError(
          `No matching integration configuration for host ${host}, please check your integrations config`
        );
      }
      const token = (_a = ctx.input.token) != null ? _a : integrationConfig.config.token;
      const authConfig = {
        ...integrationConfig.config,
        ...{ token }
      };
      const reqOpts = integration.getBitbucketServerRequestOptions(authConfig);
      const authorization = reqOpts.headers.Authorization;
      if (!authorization) {
        throw new Error(
          `Authorization has not been provided for ${integrationConfig.config.host}. Please add either (a) a user login auth token, or (b) a token or (c) username + password to the integration config.`
        );
      }
      const apiBaseUrl = integrationConfig.config.apiBaseUrl;
      const { remoteUrl, repoContentsUrl } = await createRepository({
        authorization,
        project,
        repo,
        repoVisibility,
        defaultBranch,
        description,
        apiBaseUrl
      });
      const gitAuthorInfo = {
        name: gitAuthorName ? gitAuthorName : config.getOptionalString("scaffolder.defaultAuthor.name"),
        email: gitAuthorEmail ? gitAuthorEmail : config.getOptionalString("scaffolder.defaultAuthor.email")
      };
      const auth = authConfig.token ? {
        token
      } : {
        username: authConfig.username,
        password: authConfig.password
      };
      const commitResult = await pluginScaffolderNode.initRepoAndPush({
        dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
        remoteUrl,
        auth,
        defaultBranch,
        logger: ctx.logger,
        commitMessage: gitCommitMessage ? gitCommitMessage : config.getOptionalString("scaffolder.defaultCommitMessage"),
        gitAuthorInfo
      });
      if (enableLFS) {
        await performEnableLFS({ authorization, host, project, repo });
      }
      ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
      ctx.output("remoteUrl", remoteUrl);
      ctx.output("repoContentsUrl", repoContentsUrl);
    }
  });
}

const createPullRequest = async (opts) => {
  const {
    project,
    repo,
    title,
    description,
    toRef,
    fromRef,
    authorization,
    apiBaseUrl
  } = opts;
  let response;
  const data = {
    method: "POST",
    body: JSON.stringify({
      title,
      description,
      state: "OPEN",
      open: true,
      closed: false,
      locked: true,
      toRef,
      fromRef
    }),
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  try {
    response = await fetch__default["default"](
      `${apiBaseUrl}/projects/${encodeURIComponent(
        project
      )}/repos/${encodeURIComponent(repo)}/pull-requests`,
      data
    );
  } catch (e) {
    throw new Error(`Unable to create pull-reqeusts, ${e}`);
  }
  if (response.status !== 201) {
    throw new Error(
      `Unable to create pull requests, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  return `${r.links.self[0].href}`;
};
const findBranches = async (opts) => {
  const { project, repo, branchName, authorization, apiBaseUrl } = opts;
  let response;
  const options = {
    method: "GET",
    headers: {
      Authorization: authorization,
      "Content-Type": "application/json"
    }
  };
  try {
    response = await fetch__default["default"](
      `${apiBaseUrl}/projects/${encodeURIComponent(
        project
      )}/repos/${encodeURIComponent(
        repo
      )}/branches?boostMatches=true&filterText=${encodeURIComponent(
        branchName
      )}`,
      options
    );
  } catch (e) {
    throw new Error(`Unable to get branches, ${e}`);
  }
  if (response.status !== 200) {
    throw new Error(
      `Unable to get branches, ${response.status} ${response.statusText}, ${await response.text()}`
    );
  }
  const r = await response.json();
  for (const object of r.values) {
    if (object.displayId === branchName) {
      return object;
    }
  }
  return void 0;
};
function createPublishBitbucketServerPullRequestAction(options) {
  const { integrations } = options;
  return pluginScaffolderNode.createTemplateAction({
    id: "publish:bitbucketServer:pull-request",
    schema: {
      input: {
        type: "object",
        required: ["repoUrl", "title", "sourceBranch"],
        properties: {
          repoUrl: {
            title: "Repository Location",
            type: "string"
          },
          title: {
            title: "Pull Request title",
            type: "string",
            description: "The title for the pull request"
          },
          description: {
            title: "Pull Request Description",
            type: "string",
            description: "The description of the pull request"
          },
          targetBranch: {
            title: "Target Branch",
            type: "string",
            description: `Branch of repository to apply changes to. The default value is 'master'`
          },
          sourceBranch: {
            title: "Source Branch",
            type: "string",
            description: "Branch of repository to copy changes from"
          },
          token: {
            title: "Authorization Token",
            type: "string",
            description: "The token to use for authorization to BitBucket Server"
          }
        }
      },
      output: {
        type: "object",
        properties: {
          pullRequestUrl: {
            title: "A URL to the pull request with the provider",
            type: "string"
          }
        }
      }
    },
    async handler(ctx) {
      var _a;
      const {
        repoUrl,
        title,
        description,
        targetBranch = "master",
        sourceBranch
      } = ctx.input;
      const { project, repo, host } = pluginScaffolderNode.parseRepoUrl(repoUrl, integrations);
      if (!project) {
        throw new errors.InputError(
          `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
        );
      }
      const integrationConfig = integrations.bitbucketServer.byHost(host);
      if (!integrationConfig) {
        throw new errors.InputError(
          `No matching integration configuration for host ${host}, please check your integrations config`
        );
      }
      const token = (_a = ctx.input.token) != null ? _a : integrationConfig.config.token;
      const authConfig = {
        ...integrationConfig.config,
        ...{ token }
      };
      const reqOpts = integration.getBitbucketServerRequestOptions(authConfig);
      const authorization = reqOpts.headers.Authorization;
      if (!authorization) {
        throw new Error(
          `Authorization has not been provided for ${integrationConfig.config.host}. Please add either (a) a user login auth token, or (b) a token input from the template or (c) username + password to the integration config.`
        );
      }
      const apiBaseUrl = integrationConfig.config.apiBaseUrl;
      const toRef = await findBranches({
        project,
        repo,
        branchName: targetBranch,
        authorization,
        apiBaseUrl
      });
      const fromRef = await findBranches({
        project,
        repo,
        branchName: sourceBranch,
        authorization,
        apiBaseUrl
      });
      const pullRequestUrl = await createPullRequest({
        project,
        repo,
        title,
        description,
        toRef,
        fromRef,
        authorization,
        apiBaseUrl
      });
      ctx.output("pullRequestUrl", pullRequestUrl);
    }
  });
}

const examples = [
  {
    description: "Trigger a pipeline for a branch",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                ref_type: "branch",
                type: "pipeline_ref_target",
                ref_name: "master"
              }
            }
          }
        }
      ]
    })
  },
  {
    description: "Trigger a pipeline for a commit on a branch",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                commit: {
                  type: "commit",
                  hash: "ce5b7431602f7cbba007062eeb55225c6e18e956"
                },
                ref_type: "branch",
                type: "pipeline_ref_target",
                ref_name: "master"
              }
            }
          }
        }
      ]
    })
  },
  {
    description: "Trigger a specific pipeline definition for a commit",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                commit: {
                  type: "commit",
                  hash: "a3c4e02c9a3755eccdc3764e6ea13facdf30f923"
                },
                selector: {
                  type: "custom",
                  pattern: "Deploy to production"
                },
                type: "pipeline_commit_target"
              }
            }
          }
        }
      ]
    })
  },
  {
    description: "Trigger a specific pipeline definition for a commit on a branch or tag",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                commit: {
                  type: "commit",
                  hash: "a3c4e02c9a3755eccdc3764e6ea13facdf30f923"
                },
                selector: {
                  type: "custom",
                  pattern: "Deploy to production"
                },
                type: "pipeline_ref_target",
                ref_name: "master",
                ref_type: "branch"
              }
            }
          }
        }
      ]
    })
  },
  {
    description: "Trigger a custom pipeline with variables",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                type: "pipeline_ref_target",
                ref_name: "master",
                ref_type: "branch",
                selector: {
                  type: "custom",
                  pattern: "Deploy to production"
                }
              },
              variables: [
                { key: "var1key", value: "var1value", secured: true },
                {
                  key: "var2key",
                  value: "var2value"
                }
              ]
            }
          }
        }
      ]
    })
  },
  {
    description: "Trigger a pull request pipeline",
    example: yaml__default["default"].stringify({
      steps: [
        {
          action: "bitbucket:pipelines:run",
          id: "run-bitbucket-pipeline",
          name: "Run an example bitbucket pipeline",
          input: {
            workspace: "test-workspace",
            repo_slug: "test-repo-slug",
            body: {
              target: {
                type: "pipeline_pullrequest_target",
                source: "pull-request-branch",
                destination: "master",
                destination_commit: {
                  hash: "9f848b7"
                },
                commit: {
                  hash: "1a372fc"
                },
                pull_request: {
                  id: "3"
                },
                selector: {
                  type: "pull-requests",
                  pattern: "**"
                }
              }
            }
          }
        }
      ]
    })
  }
];

const workspace = {
  title: "Workspace",
  description: `The workspace name`,
  type: "string"
};
const repo_slug = {
  title: "Repository name",
  description: "The repository name",
  type: "string"
};
const ref_type = {
  title: "ref_type",
  type: "string"
};
const type = {
  title: "type",
  type: "string"
};
const ref_name = {
  title: "ref_name",
  type: "string"
};
const source = {
  title: "source",
  type: "string"
};
const destination = {
  title: "destination",
  type: "string"
};
const hash = {
  title: "hash",
  type: "string"
};
const pattern = {
  title: "pattern",
  type: "string"
};
const id$1 = {
  title: "id",
  type: "string"
};
const key = {
  title: "key",
  type: "string"
};
const value = {
  title: "value",
  type: "string"
};
const secured = {
  title: "secured",
  type: "boolean"
};
const token = {
  title: "Authentication Token",
  type: "string",
  description: "The token to use for authorization to BitBucket Cloud"
};
const destination_commit = {
  title: "destination_commit",
  type: "object",
  properties: {
    hash
  }
};
const commit = {
  title: "commit",
  type: "object",
  properties: {
    type,
    hash
  }
};
const selector = {
  title: "selector",
  type: "object",
  properties: {
    type,
    pattern
  }
};
const pull_request = {
  title: "pull_request",
  type: "object",
  properties: {
    id: id$1
  }
};
const pipelinesRunBody = {
  title: "Request Body",
  description: "Request body properties: see Bitbucket Cloud Rest API documentation for more details",
  type: "object",
  properties: {
    target: {
      title: "target",
      type: "object",
      properties: {
        ref_type,
        type,
        ref_name,
        source,
        destination,
        destination_commit,
        commit,
        selector,
        pull_request
      }
    },
    variables: {
      title: "variables",
      type: "array",
      items: {
        type: "object",
        properties: {
          key,
          value,
          secured
        }
      }
    }
  }
};

const id = "bitbucket:pipelines:run";
const createBitbucketPipelinesRunAction = (options) => {
  const { integrations } = options;
  return pluginScaffolderNode.createTemplateAction({
    id,
    description: "Run a bitbucket cloud pipeline",
    examples,
    schema: {
      input: {
        type: "object",
        required: ["workspace", "repo_slug"],
        properties: {
          workspace: workspace,
          repo_slug: repo_slug,
          body: pipelinesRunBody,
          token: token
        }
      },
      output: {
        type: "object",
        properties: {
          buildNumber: {
            title: "Build number",
            type: "number"
          },
          repoUrl: {
            title: "A URL to the pipeline repositry",
            type: "string"
          },
          repoContentsUrl: {
            title: "A URL to the pipeline",
            type: "string"
          }
        }
      }
    },
    supportsDryRun: false,
    async handler(ctx) {
      var _a;
      const { workspace, repo_slug, body, token } = ctx.input;
      const host = "bitbucket.org";
      const integrationConfig = integrations.bitbucketCloud.byHost(host);
      const authorization = getAuthorizationHeader(
        token ? { token } : integrationConfig.config
      );
      let response;
      try {
        response = await fetch__default["default"](
          `https://api.bitbucket.org/2.0/repositories/${workspace}/${repo_slug}/pipelines`,
          {
            method: "POST",
            headers: {
              Authorization: authorization,
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: (_a = JSON.stringify(body)) != null ? _a : {}
          }
        );
      } catch (e) {
        throw new Error(`Unable to run pipeline, ${e}`);
      }
      if (response.status !== 201) {
        throw new Error(
          `Unable to run pipeline, ${response.status} ${response.statusText}, ${await response.text()}`
        );
      }
      const responseObject = await response.json();
      ctx.output("buildNumber", responseObject.build_number);
      ctx.output("repoUrl", responseObject.repository.links.html.href);
      ctx.output(
        "pipelinesUrl",
        `${responseObject.repository.links.html.href}/pipelines`
      );
    }
  });
};

exports.createBitbucketPipelinesRunAction = createBitbucketPipelinesRunAction;
exports.createPublishBitbucketAction = createPublishBitbucketAction;
exports.createPublishBitbucketCloudAction = createPublishBitbucketCloudAction;
exports.createPublishBitbucketServerAction = createPublishBitbucketServerAction;
exports.createPublishBitbucketServerPullRequestAction = createPublishBitbucketServerPullRequestAction;
//# sourceMappingURL=index.cjs.js.map
