@gitkraken/core-gitlens 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/git-cli/providers/config.js +2 -2
  3. package/dist/git-cli/providers/pausedOperations.js +2 -2
  4. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  5. package/dist/git-cli/providers/staging.js +1 -1
  6. package/dist/ipc/discovery.js +1 -1
  7. package/dist/plus/agents/providers/claudeCodeTranscript.js +6 -6
  8. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -1
  9. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -1
  10. package/dist/plus/integrations/authentication/configuredIntegrationService.d.ts +4 -0
  11. package/dist/plus/integrations/authentication/configuredIntegrationService.js +8 -2
  12. package/dist/plus/integrations/authentication/configuredIntegrationService.js.map +1 -1
  13. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +1 -1
  14. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +2 -2
  15. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  16. package/dist/plus/integrations/authentication/observedAuthenticationProvider.d.ts +2 -1
  17. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js +16 -12
  18. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js.map +1 -1
  19. package/dist/plus/integrations/index.d.ts +2 -1
  20. package/dist/plus/integrations/index.js.map +1 -1
  21. package/dist/plus/integrations/integrationService.d.ts +5 -0
  22. package/dist/plus/integrations/integrationService.js +54 -0
  23. package/dist/plus/integrations/integrationService.js.map +1 -1
  24. package/dist/plus/integrations/manager.d.ts +8 -0
  25. package/dist/plus/integrations/models/bitbucketServerPullRequestWrites.d.ts +142 -0
  26. package/dist/plus/integrations/models/bitbucketServerPullRequestWrites.js +0 -0
  27. package/dist/plus/integrations/models/integration.d.ts +6 -3
  28. package/dist/plus/integrations/models/integration.js +11 -10
  29. package/dist/plus/integrations/models/integration.js.map +1 -1
  30. package/dist/plus/integrations/providers/azure/azure.js +1 -1
  31. package/dist/plus/integrations/providers/bitbucket-server.d.ts +4 -1
  32. package/dist/plus/integrations/providers/bitbucket-server.js +23 -0
  33. package/dist/plus/integrations/providers/bitbucket-server.js.map +1 -1
  34. package/dist/plus/integrations/providers/bitbucketPullRequestWrites.js +2 -2
  35. package/dist/plus/integrations/providers/bitbucketPullRequestWrites.js.map +1 -1
  36. package/dist/plus/integrations/providers/bitbucketServerPullRequestWriteErrors.d.ts +22 -0
  37. package/dist/plus/integrations/providers/bitbucketServerPullRequestWriteErrors.js +94 -0
  38. package/dist/plus/integrations/providers/bitbucketServerPullRequestWriteErrors.js.map +1 -0
  39. package/dist/plus/integrations/providers/bitbucketServerPullRequestWrites.d.ts +51 -0
  40. package/dist/plus/integrations/providers/bitbucketServerPullRequestWrites.js +593 -0
  41. package/dist/plus/integrations/providers/bitbucketServerPullRequestWrites.js.map +1 -0
  42. package/dist/plus/integrations/providers/github.js +1 -1
  43. package/dist/plus/integrations/providers/providerApiClient.js +4 -3
  44. package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
  45. package/dist/plus/integrations/providers/providersApi.d.ts +10 -0
  46. package/dist/plus/integrations/providers/providersApi.js +45 -1
  47. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  48. package/dist/plus/integrations/providers/utils/writeInputs.d.ts +1 -0
  49. package/dist/plus/integrations/providers/utils/writeInputs.js +4 -1
  50. package/dist/plus/integrations/providers/utils/writeInputs.js.map +1 -1
  51. package/dist/utils/env/node/exec.js +2 -2
  52. package/docs/integrations.md +81 -0
  53. package/package.json +1 -1
@@ -0,0 +1,593 @@
1
+ import { getAuthenticatedUser, getResponseHeader } from "../errors.js";
2
+ import { isCommitSha, isGitBranchName, isPositiveInt32, isWriteIdentifier, sameIdentifier } from "./utils/writeInputs.js";
3
+ import { BitbucketServerPullRequestWriteError, getBitbucketServerErrorDetail, toBitbucketServerPullRequestWriteFailure, toVetoes } from "./bitbucketServerPullRequestWriteErrors.js";
4
+ //#region ../plus/integrations/src/providers/bitbucketServerPullRequestWrites.ts
5
+ const deleteSince = [5, 1];
6
+ const draftSince = [8, 18];
7
+ const projectKeyPattern = /^~?[\w.@+-]+$/;
8
+ const slugPattern = /^[\w.-]+$/;
9
+ const accountIdPattern = /^\d{1,19}$/;
10
+ const strategyIdPattern = /^[\w-]{1,64}$/;
11
+ function isProjectKey(value) {
12
+ return typeof value === "string" && projectKeyPattern.test(value) && !/^~?\.{1,2}$/.test(value);
13
+ }
14
+ function isRepositorySlug(value) {
15
+ return typeof value === "string" && slugPattern.test(value) && !/^\.\.?$/.test(value);
16
+ }
17
+ function isVersionNumber(value) {
18
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2147483647;
19
+ }
20
+ function isTitle(title) {
21
+ return typeof title === "string" && title.trim().length > 0;
22
+ }
23
+ function isBaseUrl(value) {
24
+ if (typeof value !== "string" || !isWriteIdentifier(value)) return false;
25
+ const url = URL.parse(/^[a-z][a-z\d+\-.]*:\/\//i.test(value) ? value : `https://${value}`);
26
+ return (url?.protocol === "https:" || url?.protocol === "http:") && !url.username && !url.password && !url.search && !url.hash;
27
+ }
28
+ function seg(value) {
29
+ return encodeURIComponent(value);
30
+ }
31
+ function toBranchRef(branch) {
32
+ return `refs/heads/${branch}`;
33
+ }
34
+ function parseVersion(value) {
35
+ const match = typeof value === "string" ? /^(\d+)\.(\d+)/.exec(value) : null;
36
+ return match == null ? void 0 : [Number(match[1]), Number(match[2])];
37
+ }
38
+ function isAtLeast(version, since) {
39
+ return version[0] > since[0] || version[0] === since[0] && version[1] >= since[1];
40
+ }
41
+ function sameText(actual, expected) {
42
+ return actual.replaceAll("\r\n", "\n").trim() === expected.replaceAll("\r\n", "\n").trim();
43
+ }
44
+ function isBitbucketServerPullRequestScope(options) {
45
+ return options.providerId === "bitbucket-server" && isWriteIdentifier(options.connectionId) && (options.domain === void 0 || isWriteIdentifier(options.domain)) && isBaseUrl(options.baseUrl) && isProjectKey(options.projectKey) && isRepositorySlug(options.repositorySlug) && (options.expectedAccountId === void 0 || typeof options.expectedAccountId === "string" && accountIdPattern.test(options.expectedAccountId));
46
+ }
47
+ function isBitbucketServerPullRequestWrite(options) {
48
+ if (!isBitbucketServerPullRequestScope(options) || typeof options.expectedAccountId !== "string" || !isPositiveInt32(options.repositoryId)) return false;
49
+ if (options.action === "create") return isGitBranchName(options.sourceBranch) && isGitBranchName(options.targetBranch) && options.sourceBranch !== options.targetBranch && isTitle(options.title) && (options.description === void 0 || typeof options.description === "string") && (options.draft === void 0 || typeof options.draft === "boolean");
50
+ if (!isPositiveInt32(options.number) || !isVersionNumber(options.expectedVersion)) return false;
51
+ switch (options.action) {
52
+ case "edit": return (options.title !== void 0 || options.description !== void 0) && (options.title === void 0 || isTitle(options.title)) && (options.description === void 0 || typeof options.description === "string");
53
+ case "decline":
54
+ case "reopen":
55
+ case "delete": return true;
56
+ case "merge": return (options.strategy === void 0 || typeof options.strategy === "string" && strategyIdPattern.test(options.strategy)) && isGitBranchName(options.expectedSourceBranch) && isGitBranchName(options.expectedTargetBranch) && isCommitSha(options.expectedSourceSha) && isCommitSha(options.expectedTargetSha);
57
+ default: return false;
58
+ }
59
+ }
60
+ var BitbucketServerPullRequestWriter = class BitbucketServerPullRequestWriter {
61
+ transport;
62
+ apiUrl;
63
+ headers;
64
+ accountId;
65
+ version;
66
+ repository;
67
+ static async connect(transport, options) {
68
+ const apiUrl = `${transport.installationUrl}/rest/api/1.0`;
69
+ const headers = { Authorization: `Bearer ${transport.accessToken}` };
70
+ const [{ body: properties }, repoResponse] = await Promise.all([transport.request({
71
+ url: `${apiUrl}/application-properties`,
72
+ headers
73
+ }), transport.request({
74
+ url: `${apiUrl}/projects/${seg(options.projectKey)}/repos/${seg(options.repositorySlug)}`,
75
+ headers
76
+ })]);
77
+ const serverVersion = typeof properties?.version === "string" ? properties.version : void 0;
78
+ const version = parseVersion(serverVersion);
79
+ if (serverVersion == null || version == null) throw new BitbucketServerPullRequestWriteError("unknown");
80
+ const username = getAuthenticatedUser(repoResponse.headers);
81
+ const accountId = getResponseHeader(repoResponse.headers, "x-auserid") ?? (username != null && username !== "anonymous" ? await transport.getAccountId(decodeURIComponent(username)) : void 0);
82
+ if (typeof accountId !== "string" || !accountIdPattern.test(accountId) || options.expectedAccountId !== void 0 && accountId !== options.expectedAccountId) throw new BitbucketServerPullRequestWriteError("no-connection");
83
+ const repo = repoResponse.body;
84
+ const project = repo?.project;
85
+ if (!isPositiveInt32(repo?.id) || !isRepositorySlug(repo.slug) || typeof repo.name !== "string" || !isPositiveInt32(project?.id) || !isProjectKey(project.key) || !sameIdentifier(project.key, options.projectKey) || !sameIdentifier(repo.slug, options.repositorySlug)) throw new BitbucketServerPullRequestWriteError("not-found");
86
+ return new BitbucketServerPullRequestWriter(transport, apiUrl, headers, accountId, version, {
87
+ providerId: options.providerId,
88
+ connectionId: transport.connectionId,
89
+ baseUrl: transport.installationUrl,
90
+ serverVersion,
91
+ projectId: project.id,
92
+ projectKey: project.key,
93
+ repositoryId: repo.id,
94
+ repositorySlug: repo.slug,
95
+ repositoryName: repo.name
96
+ });
97
+ }
98
+ repoUrl;
99
+ constructor(transport, apiUrl, headers, accountId, version, repository) {
100
+ this.transport = transport;
101
+ this.apiUrl = apiUrl;
102
+ this.headers = headers;
103
+ this.accountId = accountId;
104
+ this.version = version;
105
+ this.repository = repository;
106
+ this.repoUrl = `${apiUrl}/projects/${seg(repository.projectKey)}/repos/${seg(repository.repositorySlug)}`;
107
+ }
108
+ isConnectionCurrent() {
109
+ return this.transport.isConnectionCurrent();
110
+ }
111
+ async getCreateCapability() {
112
+ const defaultBranch = await this.readDefaultBranch();
113
+ return {
114
+ ok: true,
115
+ accountId: this.accountId,
116
+ repository: this.repository,
117
+ ...defaultBranch !== void 0 && { defaultBranch },
118
+ draft: isAtLeast(this.version, draftSince)
119
+ };
120
+ }
121
+ async resolveTarget(number) {
122
+ if (!isPositiveInt32(number)) return {
123
+ ok: false,
124
+ reason: "invalid-input"
125
+ };
126
+ const read = await this.readPullRequest(number);
127
+ const { pullRequest } = read;
128
+ const open = pullRequest.state === "open";
129
+ return {
130
+ ok: true,
131
+ accountId: this.accountId,
132
+ pullRequest,
133
+ capabilities: {
134
+ edit: open && toReviewers(read.reviewers) != null,
135
+ decline: open,
136
+ reopen: pullRequest.state === "declined",
137
+ delete: this.getDeleteCapability(pullRequest),
138
+ merge: await this.getMergeCapability(read)
139
+ }
140
+ };
141
+ }
142
+ write(options) {
143
+ if (options.repositoryId !== this.repository.repositoryId) return Promise.resolve({
144
+ ok: false,
145
+ reason: "not-found"
146
+ });
147
+ if (options.action === "create") return this.create(options);
148
+ return this.writeExisting(options);
149
+ }
150
+ async create(options) {
151
+ if (options.draft === true && !isAtLeast(this.version, draftSince)) return {
152
+ ok: false,
153
+ reason: "unsupported"
154
+ };
155
+ const [source, target] = await Promise.all([this.readBranchTip(this.repoUrl, options.sourceBranch), this.readBranchTip(this.repoUrl, options.targetBranch)]);
156
+ if (source == null || target == null) return {
157
+ ok: false,
158
+ reason: "not-found"
159
+ };
160
+ const ref = (branch) => ({
161
+ id: toBranchRef(branch),
162
+ repository: {
163
+ slug: this.repository.repositorySlug,
164
+ project: { key: this.repository.projectKey }
165
+ }
166
+ });
167
+ const sent = await this.send(options, "POST", `${this.repoUrl}/pull-requests`, {
168
+ title: options.title,
169
+ ...options.description !== void 0 && { description: options.description },
170
+ ...options.draft === true && { draft: true },
171
+ fromRef: ref(options.sourceBranch),
172
+ toRef: ref(options.targetBranch)
173
+ });
174
+ if (!sent.ok) {
175
+ const { existing, ...failure } = sent;
176
+ return failure.reason === "conflict" ? {
177
+ ...failure,
178
+ ...await this.findOpenPullRequest(options, existing)
179
+ } : failure;
180
+ }
181
+ const read = this.toReadOrUndefined(sent.body);
182
+ if (read == null) return {
183
+ ok: false,
184
+ reason: "outcome-unknown"
185
+ };
186
+ const { pullRequest } = read;
187
+ return sent.status === 201 && pullRequest.state === "open" && pullRequest.draft === (options.draft === true) && pullRequest.authorId === this.accountId && !pullRequest.isCrossRepository && pullRequest.sourceBranch === options.sourceBranch && pullRequest.targetBranch === options.targetBranch && sameText(pullRequest.title, options.title) && (options.description === void 0 || sameText(pullRequest.description, options.description)) ? {
188
+ ok: true,
189
+ status: "created",
190
+ pullRequest
191
+ } : {
192
+ ok: false,
193
+ reason: "outcome-unknown"
194
+ };
195
+ }
196
+ async findOpenPullRequest(options, reported) {
197
+ const matches = (read) => read?.pullRequest.state === "open" && !read.pullRequest.isCrossRepository && read.pullRequest.sourceBranch === options.sourceBranch && read.pullRequest.targetBranch === options.targetBranch;
198
+ const existing = this.toReadOrUndefined(reported);
199
+ if (matches(existing)) return { pullRequest: existing.pullRequest };
200
+ try {
201
+ const query = new URLSearchParams({
202
+ state: "OPEN",
203
+ direction: "OUTGOING",
204
+ at: toBranchRef(options.sourceBranch),
205
+ limit: "100"
206
+ });
207
+ const found = await this.findOnPages(`${this.repoUrl}/pull-requests`, query, (raw) => {
208
+ const read = this.toReadOrUndefined(raw);
209
+ return matches(read) ? read.pullRequest : void 0;
210
+ });
211
+ return found != null ? { pullRequest: found } : {};
212
+ } catch {
213
+ return {};
214
+ }
215
+ }
216
+ async writeExisting(options) {
217
+ const read = await this.readPullRequest(options.number);
218
+ const { pullRequest } = read;
219
+ if (pullRequest.version !== options.expectedVersion) return {
220
+ ok: false,
221
+ reason: "stale-version"
222
+ };
223
+ const url = this.pullRequestUrl(options.number);
224
+ const versioned = `?version=${options.expectedVersion}`;
225
+ switch (options.action) {
226
+ case "edit":
227
+ if (pullRequest.state !== "open") return {
228
+ ok: false,
229
+ reason: "conflict"
230
+ };
231
+ return this.edit(options, read);
232
+ case "decline":
233
+ if (pullRequest.state !== "open") return {
234
+ ok: false,
235
+ reason: "conflict"
236
+ };
237
+ return this.sendForReceipt(options, "POST", `${url}/decline${versioned}`, {}, (read) => read.pullRequest.state === "declined" ? "declined" : void 0);
238
+ case "reopen":
239
+ if (pullRequest.state !== "declined") return {
240
+ ok: false,
241
+ reason: "conflict"
242
+ };
243
+ return this.sendForReceipt(options, "POST", `${url}/reopen${versioned}`, {}, (read) => read.pullRequest.state === "open" ? "reopened" : void 0);
244
+ case "delete": {
245
+ const capability = this.getDeleteCapability(pullRequest);
246
+ if (capability.kind === "unavailable") return {
247
+ ok: false,
248
+ reason: capability.reason
249
+ };
250
+ const sent = await this.send(options, "DELETE", url, { version: options.expectedVersion });
251
+ if (!sent.ok) return sent;
252
+ return sent.status === 204 ? {
253
+ ok: true,
254
+ status: "deleted",
255
+ number: options.number
256
+ } : {
257
+ ok: false,
258
+ reason: "outcome-unknown"
259
+ };
260
+ }
261
+ case "merge": return this.merge(options, read);
262
+ }
263
+ }
264
+ async edit(options, read) {
265
+ const reviewers = toReviewers(read.reviewers);
266
+ if (reviewers == null) return {
267
+ ok: false,
268
+ reason: "unknown"
269
+ };
270
+ const { pullRequest } = read;
271
+ const title = options.title ?? pullRequest.title;
272
+ const description = options.description ?? pullRequest.description;
273
+ return this.sendForReceipt(options, "PUT", this.pullRequestUrl(options.number), {
274
+ version: options.expectedVersion,
275
+ title,
276
+ description,
277
+ reviewers
278
+ }, (receipt) => receipt.pullRequest.state === "open" && sameText(receipt.pullRequest.title, title) && sameText(receipt.pullRequest.description, description) ? "updated" : void 0);
279
+ }
280
+ async merge(options, read) {
281
+ const { pullRequest } = read;
282
+ const stateFailure = getMergeStateFailure(pullRequest);
283
+ if (stateFailure != null) return {
284
+ ok: false,
285
+ reason: stateFailure
286
+ };
287
+ if (pullRequest.sourceBranch !== options.expectedSourceBranch) return {
288
+ ok: false,
289
+ reason: "source-changed"
290
+ };
291
+ if (pullRequest.targetBranch !== options.expectedTargetBranch) return {
292
+ ok: false,
293
+ reason: "target-changed"
294
+ };
295
+ if (!sameIdentifier(pullRequest.sourceSha, options.expectedSourceSha)) return {
296
+ ok: false,
297
+ reason: "source-changed"
298
+ };
299
+ if (!sameIdentifier(pullRequest.targetSha, options.expectedTargetSha)) return {
300
+ ok: false,
301
+ reason: "target-changed"
302
+ };
303
+ const sourceRepoUrl = read.sourceRepository == null ? void 0 : `${this.apiUrl}/projects/${seg(read.sourceRepository.projectKey)}/repos/${seg(read.sourceRepository.slug)}`;
304
+ if (sourceRepoUrl == null) return {
305
+ ok: false,
306
+ reason: "source-changed"
307
+ };
308
+ const policy = await this.readMergePolicy(options.number);
309
+ if ("ok" in policy) return policy;
310
+ if (options.strategy !== void 0 && !policy.strategies.includes(options.strategy)) return {
311
+ ok: false,
312
+ reason: "policy-blocked"
313
+ };
314
+ const [source, target] = await Promise.all([this.readBranchTip(sourceRepoUrl, pullRequest.sourceBranch), this.readBranchTip(this.repoUrl, pullRequest.targetBranch)]);
315
+ if (!sameIdentifier(source, options.expectedSourceSha)) return {
316
+ ok: false,
317
+ reason: "source-changed"
318
+ };
319
+ if (!sameIdentifier(target, options.expectedTargetSha)) return {
320
+ ok: false,
321
+ reason: "target-changed"
322
+ };
323
+ return this.sendForReceipt(options, "POST", `${this.pullRequestUrl(options.number)}/merge?version=${options.expectedVersion}`, options.strategy !== void 0 ? { strategyId: options.strategy } : {}, (receipt) => receipt.pullRequest.state === "merged" && receipt.pullRequest.sourceBranch === options.expectedSourceBranch && receipt.pullRequest.targetBranch === options.expectedTargetBranch && sameIdentifier(receipt.pullRequest.sourceSha, options.expectedSourceSha) && sameIdentifier(receipt.pullRequest.targetSha, options.expectedTargetSha) ? "merged" : void 0);
324
+ }
325
+ getDeleteCapability(pullRequest) {
326
+ if (!isAtLeast(this.version, deleteSince)) return {
327
+ kind: "unavailable",
328
+ reason: "unsupported"
329
+ };
330
+ if (pullRequest.state === "merged") return {
331
+ kind: "unavailable",
332
+ reason: "conflict"
333
+ };
334
+ return { kind: "available" };
335
+ }
336
+ async getMergeCapability(read) {
337
+ const stateFailure = getMergeStateFailure(read.pullRequest);
338
+ if (stateFailure != null) return {
339
+ kind: "unavailable",
340
+ reason: stateFailure
341
+ };
342
+ try {
343
+ const policy = await this.readMergePolicy(read.pullRequest.number);
344
+ if ("ok" in policy) return {
345
+ kind: "unavailable",
346
+ reason: policy.reason,
347
+ ...policy.vetoes?.length && { vetoes: policy.vetoes }
348
+ };
349
+ return {
350
+ kind: "available",
351
+ ...policy
352
+ };
353
+ } catch (ex) {
354
+ const { reason } = toBitbucketServerPullRequestWriteFailure(ex);
355
+ if (reason === "no-connection") throw ex;
356
+ return {
357
+ kind: "unavailable",
358
+ reason
359
+ };
360
+ }
361
+ }
362
+ async readMergePolicy(number) {
363
+ const [mergeability, strategies] = await Promise.all([this.readMergeability(number), this.readMergeStrategies()]);
364
+ return getMergeabilityFailure(mergeability) ?? strategies;
365
+ }
366
+ pullRequestUrl(number) {
367
+ return `${this.repoUrl}/pull-requests/${number}`;
368
+ }
369
+ async readPullRequest(number) {
370
+ const { body } = await this.transport.request({
371
+ url: this.pullRequestUrl(number),
372
+ headers: this.headers
373
+ });
374
+ const read = this.toPullRequestRead(body, number);
375
+ if (body.toRef?.repository?.id === void 0) {
376
+ const { body: repository } = await this.transport.request({
377
+ url: this.repoUrl,
378
+ headers: this.headers
379
+ });
380
+ if (repository?.id !== this.repository.repositoryId) throw new BitbucketServerPullRequestWriteError("not-found");
381
+ }
382
+ return read;
383
+ }
384
+ toReadOrUndefined(raw, number) {
385
+ try {
386
+ return this.toPullRequestRead(raw, number);
387
+ } catch {
388
+ return;
389
+ }
390
+ }
391
+ toPullRequestRead(raw, number) {
392
+ if (raw == null || !this.isSelectedRepository(raw.toRef?.repository)) throw new BitbucketServerPullRequestWriteError("not-found");
393
+ const { id, version, title, description, fromRef, toRef } = raw;
394
+ const state = typeof raw.state === "string" ? raw.state.toLowerCase() : void 0;
395
+ const sourceBranch = getBranchName(fromRef?.id);
396
+ const targetBranch = getBranchName(toRef?.id);
397
+ if (!isPositiveInt32(id) || number !== void 0 && id !== number || !isVersionNumber(version) || typeof title !== "string" || description != null && typeof description !== "string" || state !== "open" && state !== "declined" && state !== "merged" || sourceBranch == null || targetBranch == null) throw new BitbucketServerPullRequestWriteError("unknown");
398
+ const sourceRepo = fromRef?.repository;
399
+ const sourceProjectKey = sourceRepo?.project?.key;
400
+ const authorId = raw.author?.user?.id;
401
+ const { projectKey, repositorySlug, baseUrl } = this.repository;
402
+ return {
403
+ pullRequest: {
404
+ repository: this.repository,
405
+ number: id,
406
+ version,
407
+ url: `${baseUrl}/projects/${seg(projectKey)}/repos/${seg(repositorySlug)}/pull-requests/${id}`,
408
+ title,
409
+ description: description ?? "",
410
+ state,
411
+ draft: raw.draft === true,
412
+ isCrossRepository: !this.isSelectedRepository(sourceRepo),
413
+ ...typeof authorId === "number" && { authorId: String(authorId) },
414
+ sourceBranch,
415
+ targetBranch,
416
+ ...isCommitSha(fromRef?.latestCommit) && { sourceSha: fromRef.latestCommit.toLowerCase() },
417
+ ...isCommitSha(toRef?.latestCommit) && { targetSha: toRef.latestCommit.toLowerCase() }
418
+ },
419
+ reviewers: raw.reviewers,
420
+ sourceRepository: isProjectKey(sourceProjectKey) && isRepositorySlug(sourceRepo?.slug) ? {
421
+ projectKey: sourceProjectKey,
422
+ slug: sourceRepo.slug
423
+ } : void 0
424
+ };
425
+ }
426
+ isSelectedRepository(repo) {
427
+ if (repo?.id !== void 0) return repo.id === this.repository.repositoryId;
428
+ return sameIdentifier(repo?.project?.key, this.repository.projectKey) && sameIdentifier(repo?.slug, this.repository.repositorySlug);
429
+ }
430
+ async readBranchTip(repoUrl, branch) {
431
+ const query = new URLSearchParams({
432
+ filterText: branch,
433
+ boostMatches: "true",
434
+ details: "false",
435
+ limit: "25"
436
+ });
437
+ const ref = toBranchRef(branch);
438
+ return this.findOnPages(`${repoUrl}/branches`, query, (value) => {
439
+ const entry = value;
440
+ if (entry?.id !== ref) return void 0;
441
+ if (!isCommitSha(entry.latestCommit)) throw new BitbucketServerPullRequestWriteError("unknown");
442
+ return entry.latestCommit.toLowerCase();
443
+ });
444
+ }
445
+ async findOnPages(url, query, match) {
446
+ let start = 0;
447
+ while (true) {
448
+ query.set("start", String(start));
449
+ const { body } = await this.transport.request({
450
+ url: `${url}?${query.toString()}`,
451
+ headers: this.headers
452
+ });
453
+ if (!Array.isArray(body?.values)) throw new BitbucketServerPullRequestWriteError("unknown");
454
+ for (const value of body.values) {
455
+ const result = match(value);
456
+ if (result !== void 0) return result;
457
+ }
458
+ if (body.isLastPage === true) return void 0;
459
+ const next = body.nextPageStart;
460
+ if (typeof next !== "number" || !Number.isSafeInteger(next) || next <= start) throw new BitbucketServerPullRequestWriteError("unknown");
461
+ start = next;
462
+ }
463
+ }
464
+ async readDefaultBranch() {
465
+ for (const path of ["default-branch", "branches/default"]) try {
466
+ const { body } = await this.transport.request({
467
+ url: `${this.repoUrl}/${path}`,
468
+ headers: this.headers
469
+ });
470
+ return getBranchName(body?.id);
471
+ } catch (ex) {
472
+ const { reason } = toBitbucketServerPullRequestWriteFailure(ex);
473
+ if (reason === "no-connection") throw ex;
474
+ if (reason !== "not-found") return void 0;
475
+ }
476
+ }
477
+ async readMergeability(number) {
478
+ const { body } = await this.transport.request({
479
+ url: `${this.pullRequestUrl(number)}/merge`,
480
+ headers: this.headers
481
+ });
482
+ if (body == null || typeof body !== "object") throw new BitbucketServerPullRequestWriteError("unknown");
483
+ return body;
484
+ }
485
+ async readMergeStrategies() {
486
+ let settings;
487
+ try {
488
+ ({body: settings} = await this.transport.request({
489
+ url: `${this.repoUrl}/settings/pull-requests`,
490
+ headers: this.headers
491
+ }));
492
+ } catch (ex) {
493
+ const { reason } = toBitbucketServerPullRequestWriteFailure(ex);
494
+ if (reason === "forbidden" || reason === "not-found") return { strategies: [] };
495
+ throw ex;
496
+ }
497
+ const config = settings?.mergeConfig;
498
+ const strategies = Array.isArray(config?.strategies) ? config.strategies.flatMap((strategy) => strategy?.enabled === true && typeof strategy.id === "string" && strategyIdPattern.test(strategy.id) ? [strategy.id] : []) : [];
499
+ const defaultStrategy = (config?.defaultStrategy)?.id;
500
+ return {
501
+ strategies,
502
+ ...typeof defaultStrategy === "string" && strategies.includes(defaultStrategy) && { defaultStrategy }
503
+ };
504
+ }
505
+ async sendForReceipt(options, method, url, body, getStatus) {
506
+ const sent = await this.send(options, method, url, body);
507
+ if (!sent.ok) return sent;
508
+ const receipt = this.toReadOrUndefined(sent.body, options.number);
509
+ if (receipt == null || receipt.pullRequest.version <= options.expectedVersion) return {
510
+ ok: false,
511
+ reason: "outcome-unknown"
512
+ };
513
+ const status = getStatus(receipt);
514
+ return status === void 0 ? {
515
+ ok: false,
516
+ reason: "outcome-unknown"
517
+ } : {
518
+ ok: true,
519
+ status,
520
+ pullRequest: receipt.pullRequest
521
+ };
522
+ }
523
+ async send(options, method, url, body) {
524
+ if (!await this.transport.isSessionCurrent()) return {
525
+ ok: false,
526
+ reason: "no-connection"
527
+ };
528
+ try {
529
+ const response = await this.transport.request({
530
+ url,
531
+ method,
532
+ headers: {
533
+ ...this.headers,
534
+ "Content-Type": "application/json"
535
+ },
536
+ body: JSON.stringify(body)
537
+ });
538
+ return {
539
+ ok: true,
540
+ status: response.status,
541
+ body: response.body
542
+ };
543
+ } catch (ex) {
544
+ const failure = toBitbucketServerPullRequestWriteFailure(ex, options.action);
545
+ const detail = getBitbucketServerErrorDetail(ex);
546
+ return {
547
+ ...failure,
548
+ ...failure.reason === "policy-blocked" && detail.vetoes.length && { vetoes: detail.vetoes },
549
+ ...options.action === "create" && failure.reason === "conflict" && detail.existingPullRequest != null && { existing: detail.existingPullRequest }
550
+ };
551
+ }
552
+ }
553
+ };
554
+ function getBranchName(refId) {
555
+ if (typeof refId !== "string" || !refId.startsWith("refs/heads/")) return void 0;
556
+ const name = refId.slice(11);
557
+ return isGitBranchName(name) ? name : void 0;
558
+ }
559
+ function toReviewers(value) {
560
+ if (!Array.isArray(value)) return void 0;
561
+ const reviewers = [];
562
+ for (const reviewer of value) {
563
+ const name = reviewer?.user?.name;
564
+ if (!isWriteIdentifier(name)) return void 0;
565
+ reviewers.push({ user: { name } });
566
+ }
567
+ return reviewers;
568
+ }
569
+ function getMergeStateFailure(pullRequest) {
570
+ if (pullRequest.state !== "open") return "conflict";
571
+ if (pullRequest.draft) return "policy-blocked";
572
+ if (pullRequest.sourceSha == null || pullRequest.targetSha == null) return "unsupported";
573
+ }
574
+ function getMergeabilityFailure(mergeability) {
575
+ if (mergeability.conflicted === true || mergeability.outcome === "CONFLICTED") return {
576
+ ok: false,
577
+ reason: "conflict"
578
+ };
579
+ const vetoes = toVetoes(mergeability.vetoes);
580
+ if (Array.isArray(mergeability.vetoes) && mergeability.vetoes.length > 0 || mergeability.canMerge === false) return {
581
+ ok: false,
582
+ reason: "policy-blocked",
583
+ ...vetoes.length && { vetoes }
584
+ };
585
+ return mergeability.canMerge === true ? void 0 : {
586
+ ok: false,
587
+ reason: "unknown"
588
+ };
589
+ }
590
+ //#endregion
591
+ export { BitbucketServerPullRequestWriter, isBitbucketServerPullRequestScope, isBitbucketServerPullRequestWrite };
592
+
593
+ //# sourceMappingURL=bitbucketServerPullRequestWrites.js.map