@gitkraken/core-gitlens 0.55.0 → 0.56.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 (58) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/git/cache.js +3 -0
  3. package/dist/git/cache.js.map +1 -1
  4. package/dist/git-cli/providers/config.js +2 -2
  5. package/dist/git-cli/providers/pausedOperations.d.ts +2 -0
  6. package/dist/git-cli/providers/pausedOperations.js +106 -42
  7. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  8. package/dist/git-cli/providers/staging.js +1 -1
  9. package/dist/ipc/discovery.js +1 -1
  10. package/dist/plus/agents/providers/claudeCodeTranscript.js +6 -6
  11. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -1
  12. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -1
  13. package/dist/plus/integrations/index.d.ts +2 -1
  14. package/dist/plus/integrations/index.js.map +1 -1
  15. package/dist/plus/integrations/integrationService.d.ts +9 -0
  16. package/dist/plus/integrations/integrationService.js +75 -3
  17. package/dist/plus/integrations/integrationService.js.map +1 -1
  18. package/dist/plus/integrations/manager.d.ts +10 -0
  19. package/dist/plus/integrations/models/bitbucketPullRequestWrites.d.ts +217 -0
  20. package/dist/plus/integrations/models/bitbucketPullRequestWrites.js +0 -0
  21. package/dist/plus/integrations/models/integration.d.ts +2 -1
  22. package/dist/plus/integrations/models/integration.js +6 -0
  23. package/dist/plus/integrations/models/integration.js.map +1 -1
  24. package/dist/plus/integrations/providers/azure/azure.js +1 -1
  25. package/dist/plus/integrations/providers/azure/writeIdentity.d.ts +0 -3
  26. package/dist/plus/integrations/providers/azure/writeIdentity.js +4 -12
  27. package/dist/plus/integrations/providers/azure/writeIdentity.js.map +1 -1
  28. package/dist/plus/integrations/providers/azureDevOps.d.ts +0 -2
  29. package/dist/plus/integrations/providers/azureDevOps.js +1 -7
  30. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  31. package/dist/plus/integrations/providers/azurePullRequestWrites.js +24 -26
  32. package/dist/plus/integrations/providers/azurePullRequestWrites.js.map +1 -1
  33. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js +4 -3
  34. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js.map +1 -1
  35. package/dist/plus/integrations/providers/azureWorkItemWrites.js +22 -21
  36. package/dist/plus/integrations/providers/azureWorkItemWrites.js.map +1 -1
  37. package/dist/plus/integrations/providers/bitbucket.d.ts +4 -0
  38. package/dist/plus/integrations/providers/bitbucket.js +8 -0
  39. package/dist/plus/integrations/providers/bitbucket.js.map +1 -1
  40. package/dist/plus/integrations/providers/bitbucketPullRequestWriteErrors.d.ts +13 -0
  41. package/dist/plus/integrations/providers/bitbucketPullRequestWriteErrors.js +88 -0
  42. package/dist/plus/integrations/providers/bitbucketPullRequestWriteErrors.js.map +1 -0
  43. package/dist/plus/integrations/providers/bitbucketPullRequestWriteLedger.d.ts +14 -0
  44. package/dist/plus/integrations/providers/bitbucketPullRequestWriteLedger.js +36 -0
  45. package/dist/plus/integrations/providers/bitbucketPullRequestWriteLedger.js.map +1 -0
  46. package/dist/plus/integrations/providers/bitbucketPullRequestWrites.d.ts +47 -0
  47. package/dist/plus/integrations/providers/bitbucketPullRequestWrites.js +795 -0
  48. package/dist/plus/integrations/providers/bitbucketPullRequestWrites.js.map +1 -0
  49. package/dist/plus/integrations/providers/github.js +1 -1
  50. package/dist/plus/integrations/providers/providersApi.d.ts +4 -0
  51. package/dist/plus/integrations/providers/providersApi.js +5 -0
  52. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  53. package/dist/plus/integrations/providers/utils/writeInputs.d.ts +7 -0
  54. package/dist/plus/integrations/providers/utils/writeInputs.js +17 -0
  55. package/dist/plus/integrations/providers/utils/writeInputs.js.map +1 -0
  56. package/dist/utils/env/node/exec.js +2 -2
  57. package/docs/integrations.md +155 -0
  58. package/package.json +1 -1
@@ -0,0 +1,795 @@
1
+ import { uuid } from "../../../utils/crypto.js";
2
+ import { getResponseHeader } from "../errors.js";
3
+ import { isCommitSha, isPositiveInt32, isWriteIdentifier, sameIdentifier } from "./utils/writeInputs.js";
4
+ import { BitbucketPullRequestWriteError, getBitbucketMergeRefusal, toBitbucketPullRequestWriteFailure } from "./bitbucketPullRequestWriteErrors.js";
5
+ //#region ../plus/integrations/src/providers/bitbucketPullRequestWrites.ts
6
+ const apiUrl = "https://api.bitbucket.org/2.0";
7
+ const webUrl = "https://bitbucket.org";
8
+ const mergeStrategies = [
9
+ "merge_commit",
10
+ "squash",
11
+ "fast_forward",
12
+ "squash_fast_forward",
13
+ "rebase_fast_forward",
14
+ "rebase_merge"
15
+ ];
16
+ const queueStrategies = [
17
+ "merge_commit",
18
+ "squash",
19
+ "rebase_merge"
20
+ ];
21
+ const uuidPattern = /^\{[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}\}$/i;
22
+ const slugPattern = /^[\w.-]+$/;
23
+ const mergeTaskIdPattern = /^(?!\.{1,2}$)[\w.:-]{1,256}$/;
24
+ function isBitbucketUuid(value) {
25
+ return typeof value === "string" && uuidPattern.test(value);
26
+ }
27
+ function isSlugOrUuid(value) {
28
+ return isBitbucketUuid(value) || typeof value === "string" && slugPattern.test(value) && !/^\.\.?$/.test(value);
29
+ }
30
+ function isBranchName(name) {
31
+ return typeof name === "string" && name.length > 0 && !name.startsWith("refs/") && !name.startsWith("-") && ![...name].some((character) => character <= " " || "~^:?*[\\\"".includes(character)) && !name.includes("..") && !name.includes("@{") && name !== "@" && !name.endsWith(".") && name.split("/").every((part) => part.length > 0 && !part.startsWith(".") && !part.endsWith(".lock"));
32
+ }
33
+ function isTitle(title) {
34
+ return typeof title === "string" && title.trim().length > 0;
35
+ }
36
+ function seg(value) {
37
+ return encodeURIComponent(value);
38
+ }
39
+ function isAttemptPullRequest(pullRequest, sourceBranch, targetBranch) {
40
+ return !pullRequest.isCrossRepository && pullRequest.sourceBranch === sourceBranch && (targetBranch === void 0 || pullRequest.targetBranch === targetBranch);
41
+ }
42
+ function getCreateKey(repositoryId, sourceBranch) {
43
+ return `create\n${repositoryId.toLowerCase()}\n${sourceBranch}`;
44
+ }
45
+ function getMergeKey(repositoryId, number) {
46
+ return `merge\n${repositoryId.toLowerCase()}\n${number}`;
47
+ }
48
+ function isBitbucketMergeTaskId(value) {
49
+ return typeof value === "string" && mergeTaskIdPattern.test(value);
50
+ }
51
+ function isBitbucketPullRequestMergeStatusRead(options) {
52
+ return (options.providerId === void 0 || options.providerId === "bitbucket") && isWriteIdentifier(options.connectionId) && isBitbucketUuid(options.workspaceId) && isBitbucketUuid(options.repositoryId) && isBitbucketUuid(options.expectedAccountId) && isPositiveInt32(options.number) && isBitbucketMergeTaskId(options.mergeTaskId) && isBranchName(options.expectedSourceBranch) && isBranchName(options.expectedTargetBranch) && options.expectedSourceBranch !== options.expectedTargetBranch && isCommitSha(options.expectedSourceSha);
53
+ }
54
+ function isBitbucketPullRequestScope(options) {
55
+ return (options.providerId === void 0 || options.providerId === "bitbucket") && isWriteIdentifier(options.connectionId) && isSlugOrUuid(options.workspace) && isSlugOrUuid(options.repository) && (options.expectedAccountId === void 0 || isBitbucketUuid(options.expectedAccountId));
56
+ }
57
+ function isBitbucketPullRequestWrite(options) {
58
+ if (options.providerId !== void 0 && options.providerId !== "bitbucket" || !isWriteIdentifier(options.connectionId) || !isBitbucketUuid(options.workspaceId) || !isBitbucketUuid(options.repositoryId) || !isBitbucketUuid(options.expectedAccountId)) return false;
59
+ if (options.action === "create") return isBranchName(options.sourceBranch) && isBranchName(options.targetBranch) && options.sourceBranch !== options.targetBranch && isTitle(options.title) && (options.description === void 0 || typeof options.description === "string");
60
+ if (!isPositiveInt32(options.number)) return false;
61
+ switch (options.action) {
62
+ 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");
63
+ case "decline": return true;
64
+ case "merge": return mergeStrategies.includes(options.strategy) && isBranchName(options.expectedSourceBranch) && isBranchName(options.expectedTargetBranch) && options.expectedSourceBranch !== options.expectedTargetBranch && isCommitSha(options.expectedSourceSha) && isCommitSha(options.expectedTargetSha);
65
+ default: return false;
66
+ }
67
+ }
68
+ function isBitbucketPullRequestWriteRelease(options) {
69
+ return (options.providerId === void 0 || options.providerId === "bitbucket") && isWriteIdentifier(options.connectionId) && isBitbucketUuid(options.workspaceId) && isBitbucketUuid(options.repositoryId) && isBitbucketUuid(options.expectedAccountId) && isWriteIdentifier(options.attemptId) && (options.action === "create" ? isBranchName(options.sourceBranch) : options.action === "merge" && isPositiveInt32(options.number) && (options.mergeTaskId === void 0 || isBitbucketMergeTaskId(options.mergeTaskId)));
70
+ }
71
+ function toStrategies(value) {
72
+ return Array.isArray(value) ? mergeStrategies.filter((strategy) => value.includes(strategy)) : [];
73
+ }
74
+ function getBlockingCheckFailure(checks) {
75
+ const blocking = new Set(checks.filter((check) => check.blocking === true).map((check) => check.type));
76
+ if (blocking.size === 0) return void 0;
77
+ if (blocking.has("pullrequest_state_check")) return "conflict";
78
+ if (blocking.has("current_user_permission_check")) return "forbidden";
79
+ if (blocking.has("git_mergeability_check")) return "conflict";
80
+ return "policy-blocked";
81
+ }
82
+ function getMergeStateFailure(pullRequest) {
83
+ if (pullRequest.state !== "open" || pullRequest.queued) return "conflict";
84
+ if (pullRequest.isCrossRepository) return "unsupported";
85
+ if (pullRequest.draft) return "policy-blocked";
86
+ }
87
+ function getMergeRefFailure(options, read) {
88
+ const { pullRequest, sourceHash } = read;
89
+ if (pullRequest.sourceBranch !== options.expectedSourceBranch) return "source-changed";
90
+ if (pullRequest.targetBranch !== options.expectedTargetBranch) return "target-changed";
91
+ if (sourceHash == null || !options.expectedSourceSha.toLowerCase().startsWith(sourceHash)) return "source-changed";
92
+ }
93
+ var BitbucketPullRequestWriter = class BitbucketPullRequestWriter {
94
+ request;
95
+ headers;
96
+ accountId;
97
+ repository;
98
+ defaultBranch;
99
+ isSessionCurrent;
100
+ ledger;
101
+ static async connect(request, accessToken, options, isSessionCurrent, ledger) {
102
+ const headers = { Authorization: `Bearer ${accessToken}` };
103
+ const { body: user } = await request({
104
+ url: `${apiUrl}/user`,
105
+ headers,
106
+ redirect: "error"
107
+ });
108
+ const accountId = user?.uuid;
109
+ if (!isBitbucketUuid(accountId) || options.expectedAccountId !== void 0 && !sameIdentifier(accountId, options.expectedAccountId)) throw new BitbucketPullRequestWriteError("no-connection");
110
+ const { body: repo } = await request({
111
+ url: `${apiUrl}/repositories/${seg(options.workspace)}/${seg(options.repository)}`,
112
+ headers,
113
+ redirect: "error"
114
+ });
115
+ const workspace = repo?.workspace;
116
+ if (!isBitbucketUuid(repo?.uuid) || !isBitbucketUuid(workspace?.uuid) || !isSlugOrUuid(repo.slug) || !isSlugOrUuid(workspace.slug) || typeof repo.full_name !== "string" || !sameIdentifier(isBitbucketUuid(options.workspace) ? workspace.uuid : workspace.slug, options.workspace) || !sameIdentifier(isBitbucketUuid(options.repository) ? repo.uuid : repo.slug, options.repository)) throw new BitbucketPullRequestWriteError("not-found");
117
+ const mainBranch = repo.mainbranch?.name;
118
+ return new BitbucketPullRequestWriter(request, headers, accountId, {
119
+ workspaceId: workspace.uuid,
120
+ workspaceSlug: workspace.slug,
121
+ repositoryId: repo.uuid,
122
+ repositorySlug: repo.slug,
123
+ fullName: repo.full_name
124
+ }, isBranchName(mainBranch) ? mainBranch : void 0, isSessionCurrent, ledger);
125
+ }
126
+ repoUrl;
127
+ constructor(request, headers, accountId, repository, defaultBranch, isSessionCurrent, ledger) {
128
+ this.request = request;
129
+ this.headers = headers;
130
+ this.accountId = accountId;
131
+ this.repository = repository;
132
+ this.defaultBranch = defaultBranch;
133
+ this.isSessionCurrent = isSessionCurrent;
134
+ this.ledger = ledger;
135
+ this.repoUrl = `${apiUrl}/repositories/${seg(repository.workspaceId)}/${seg(repository.repositoryId)}`;
136
+ }
137
+ getCreateCapability() {
138
+ return {
139
+ ok: true,
140
+ accountId: this.accountId,
141
+ repository: this.repository,
142
+ ...this.defaultBranch !== void 0 && { defaultBranch: this.defaultBranch }
143
+ };
144
+ }
145
+ async resolveTarget(number) {
146
+ if (!isPositiveInt32(number)) return {
147
+ ok: false,
148
+ reason: "invalid-input"
149
+ };
150
+ const read = await this.readPullRequest(number);
151
+ const open = read.pullRequest.state === "open";
152
+ const key = getMergeKey(this.repository.repositoryId, number);
153
+ if (!open) this.ledger.settle(key);
154
+ const target = await this.getMergeTarget(read);
155
+ const { pullRequest } = target;
156
+ const unsettled = open ? this.ledger.get(key) : void 0;
157
+ let merge = target.merge;
158
+ if (unsettled != null) merge = merge.kind === "available" ? {
159
+ kind: "unavailable",
160
+ reason: "outcome-unknown",
161
+ unsettled
162
+ } : {
163
+ ...merge,
164
+ unsettled
165
+ };
166
+ return {
167
+ ok: true,
168
+ accountId: this.accountId,
169
+ pullRequest,
170
+ capabilities: {
171
+ edit: open,
172
+ decline: open,
173
+ reopen: false,
174
+ merge
175
+ }
176
+ };
177
+ }
178
+ async write(options) {
179
+ if (options.action === "create") {
180
+ const key = getCreateKey(this.repository.repositoryId, options.sourceBranch);
181
+ return this.ledger.run(key, () => this.create(options, key));
182
+ }
183
+ if (options.action === "merge") {
184
+ const key = getMergeKey(this.repository.repositoryId, options.number);
185
+ return this.ledger.run(key, () => this.merge(options, key));
186
+ }
187
+ const current = await this.readPullRequest(options.number);
188
+ switch (options.action) {
189
+ case "edit":
190
+ if (current.pullRequest.state !== "open") return {
191
+ ok: false,
192
+ reason: "conflict"
193
+ };
194
+ return this.send(options, "PUT", this.pullRequestUrl(options.number), {
195
+ title: options.title,
196
+ description: options.description
197
+ });
198
+ case "decline":
199
+ if (current.pullRequest.state !== "open") return {
200
+ ok: false,
201
+ reason: "conflict"
202
+ };
203
+ return this.send(options, "POST", `${this.pullRequestUrl(options.number)}/decline`);
204
+ }
205
+ }
206
+ async create(options, key) {
207
+ const [source, target] = await Promise.all([this.readBranch(options.sourceBranch), this.readBranch(options.targetBranch)]);
208
+ if (source == null || target == null) return {
209
+ ok: false,
210
+ reason: "not-found"
211
+ };
212
+ const preflight = await this.readCreateEvidence(key, options.sourceBranch);
213
+ if (preflight.open.length) return {
214
+ ok: false,
215
+ reason: "conflict"
216
+ };
217
+ if (preflight.unsettled != null) return {
218
+ ok: false,
219
+ reason: "outcome-unknown",
220
+ unsettled: preflight.unsettled
221
+ };
222
+ const { serverTime } = preflight;
223
+ const dispatchedAt = Date.now();
224
+ let pullRequestNumber;
225
+ const result = await this.send(options, "POST", `${this.repoUrl}/pullrequests`, {
226
+ title: options.title,
227
+ description: options.description,
228
+ source: { branch: { name: options.sourceBranch } },
229
+ destination: { branch: { name: options.targetBranch } }
230
+ }, {
231
+ createdNotBefore: serverTime,
232
+ onReceipt: (pullRequest) => {
233
+ if (!pullRequest.isCrossRepository && pullRequest.sourceBranch === options.sourceBranch) pullRequestNumber = pullRequest.number;
234
+ }
235
+ });
236
+ return this.recordUnsettled(key, result, {
237
+ attemptId: uuid(),
238
+ accountId: this.accountId,
239
+ dispatchedAt,
240
+ action: "create",
241
+ sourceBranch: options.sourceBranch,
242
+ targetBranch: options.targetBranch,
243
+ ...pullRequestNumber !== void 0 && { pullRequestNumber }
244
+ });
245
+ }
246
+ async readCreateEvidence(key, branch) {
247
+ const entry = this.ledger.get(key);
248
+ const receipt = entry?.action === "create" ? entry.pullRequestNumber : void 0;
249
+ const open = [];
250
+ const serverTime = await this.scanPullRequests(this.getOpenPullRequestsFromQuery(branch), (pr) => {
251
+ if (!sameIdentifier(pr?.source?.repository?.uuid, this.repository.repositoryId)) return false;
252
+ open.push(isPositiveInt32(pr.id) ? pr.id : NaN);
253
+ return receipt !== void 0 ? pr.id === receipt : open.length > 1;
254
+ });
255
+ const landed = receipt !== void 0 && open.includes(receipt) ? receipt : void 0;
256
+ const closed = !open.length && receipt !== void 0 ? await this.readClosed(receipt) : void 0;
257
+ if (entry == null || landed !== void 0 || closed != null) {
258
+ this.ledger.settle(key);
259
+ return {
260
+ open,
261
+ serverTime,
262
+ landed,
263
+ closed
264
+ };
265
+ }
266
+ return {
267
+ open,
268
+ serverTime,
269
+ unsettled: entry
270
+ };
271
+ }
272
+ refuseRelease(reason, held) {
273
+ return sameIdentifier(held.accountId, this.accountId) ? {
274
+ ok: false,
275
+ reason,
276
+ unsettled: held
277
+ } : {
278
+ ok: false,
279
+ reason
280
+ };
281
+ }
282
+ async readShownPullRequest(number, sourceBranch, targetBranch) {
283
+ if (number === void 0) return void 0;
284
+ const pullRequest = await this.readPullRequest(number).then((read) => read.pullRequest, () => void 0);
285
+ return pullRequest?.state === "open" && isAttemptPullRequest(pullRequest, sourceBranch, targetBranch) ? pullRequest : void 0;
286
+ }
287
+ async readClosed(number) {
288
+ const pullRequest = await this.readPullRequest(number).then((read) => read.pullRequest, (ex) => {
289
+ if (toBitbucketPullRequestWriteFailure(ex).reason === "not-found") return void 0;
290
+ throw ex;
291
+ });
292
+ return pullRequest != null && pullRequest.state !== "open" ? pullRequest : void 0;
293
+ }
294
+ recordUnsettled(key, result, write) {
295
+ if (result.ok ? result.status !== "pending" : result.reason !== "outcome-unknown") return result;
296
+ this.ledger.record(key, write);
297
+ const unsettled = this.ledger.get(key);
298
+ return result.ok ? {
299
+ ...result,
300
+ status: "pending",
301
+ unsettled
302
+ } : {
303
+ ...result,
304
+ unsettled
305
+ };
306
+ }
307
+ async merge(options, key) {
308
+ const current = await this.readPullRequest(options.number);
309
+ const held = this.ledger.get(key);
310
+ if (held != null) {
311
+ if (current.pullRequest.state === "open") return {
312
+ ok: false,
313
+ reason: "outcome-unknown",
314
+ unsettled: held
315
+ };
316
+ this.ledger.settle(key);
317
+ }
318
+ const failure = getMergeStateFailure(current.pullRequest) ?? getMergeRefFailure(options, current);
319
+ if (failure != null) return {
320
+ ok: false,
321
+ reason: failure
322
+ };
323
+ const checks = await this.readMergeabilityChecks(options.number);
324
+ const [latest, source, target] = await Promise.all([
325
+ this.readPullRequest(options.number),
326
+ this.readBranch(options.expectedSourceBranch),
327
+ this.readBranch(options.expectedTargetBranch)
328
+ ]);
329
+ const latestFailure = getMergeStateFailure(latest.pullRequest) ?? getMergeRefFailure(options, latest);
330
+ if (latestFailure != null) return {
331
+ ok: false,
332
+ reason: latestFailure
333
+ };
334
+ if (!sameIdentifier(source?.sha, options.expectedSourceSha)) return {
335
+ ok: false,
336
+ reason: "source-changed"
337
+ };
338
+ if (target == null || !sameIdentifier(target.sha, options.expectedTargetSha)) return {
339
+ ok: false,
340
+ reason: "target-changed"
341
+ };
342
+ if (!getAllowedStrategies(target, checks).includes(options.strategy)) return {
343
+ ok: false,
344
+ reason: "policy-blocked"
345
+ };
346
+ const blocked = getBlockingCheckFailure(checks);
347
+ if (blocked != null) return {
348
+ ok: false,
349
+ reason: blocked
350
+ };
351
+ const dispatchedAt = Date.now();
352
+ const result = await this.send(options, "POST", `${this.pullRequestUrl(options.number)}/merge?async=false`, {
353
+ type: "pullrequest",
354
+ merge_strategy: options.strategy
355
+ }, { pending: latest.pullRequest });
356
+ const mergeTaskId = result.ok && result.status === "pending" ? result.mergeTaskId : void 0;
357
+ return this.recordUnsettled(key, result, {
358
+ attemptId: uuid(),
359
+ accountId: this.accountId,
360
+ dispatchedAt,
361
+ action: "merge",
362
+ number: options.number,
363
+ ...mergeTaskId !== void 0 && { mergeTaskId }
364
+ });
365
+ }
366
+ release(options) {
367
+ if (options.action === "create") {
368
+ const key = getCreateKey(this.repository.repositoryId, options.sourceBranch);
369
+ return this.ledger.run(key, async () => {
370
+ const held = this.ledger.get(key);
371
+ if (held != null && held.attemptId !== options.attemptId) return this.refuseRelease("conflict", held);
372
+ const matches = held != null;
373
+ const target = held?.action === "create" ? held.targetBranch : void 0;
374
+ const evidence = await this.readCreateEvidence(key, options.sourceBranch);
375
+ const only = evidence.open.length === 1 && isPositiveInt32(evidence.open[0]) ? evidence.open[0] : void 0;
376
+ const shown = evidence.landed ?? only;
377
+ if (evidence.open.length && evidence.landed === void 0) return {
378
+ ok: false,
379
+ reason: "conflict",
380
+ pullRequest: await this.readShownPullRequest(shown, options.sourceBranch, target)
381
+ };
382
+ const released = matches && evidence.unsettled == null || this.ledger.release(key, options.attemptId);
383
+ if (evidence.landed !== void 0) return {
384
+ ok: true,
385
+ released,
386
+ observed: "pull-request-open",
387
+ pullRequest: await this.readShownPullRequest(shown, options.sourceBranch, target)
388
+ };
389
+ if (evidence.closed != null && matches) return {
390
+ ok: true,
391
+ released,
392
+ observed: "pull-request-closed",
393
+ pullRequest: isAttemptPullRequest(evidence.closed, options.sourceBranch, target) ? evidence.closed : void 0
394
+ };
395
+ return {
396
+ ok: true,
397
+ released,
398
+ observed: "no-open-pull-request"
399
+ };
400
+ });
401
+ }
402
+ const key = getMergeKey(this.repository.repositoryId, options.number);
403
+ return this.ledger.run(key, async () => {
404
+ const held = this.ledger.get(key);
405
+ const heldTaskId = held?.action === "merge" ? held.mergeTaskId : void 0;
406
+ if (held != null && heldTaskId != null && options.mergeTaskId != null && options.mergeTaskId !== heldTaskId) return this.refuseRelease("invalid-input", held);
407
+ if (held != null && held.attemptId !== options.attemptId) return this.refuseRelease("conflict", held);
408
+ const matches = held != null;
409
+ const { pullRequest } = await this.readPullRequest(options.number);
410
+ if (pullRequest.state !== "open") {
411
+ this.ledger.settle(key);
412
+ return {
413
+ ok: true,
414
+ released: matches,
415
+ observed: "pull-request-closed",
416
+ pullRequest
417
+ };
418
+ }
419
+ if (pullRequest.queued) return {
420
+ ok: false,
421
+ reason: "conflict"
422
+ };
423
+ const mergeTaskId = heldTaskId ?? options.mergeTaskId;
424
+ if (mergeTaskId != null) {
425
+ const task = await this.readMergeTaskForRelease(options.number, mergeTaskId);
426
+ if (task !== "expired") return {
427
+ ok: false,
428
+ reason: task
429
+ };
430
+ }
431
+ return {
432
+ ok: true,
433
+ released: this.ledger.release(key, options.attemptId),
434
+ observed: "pull-request-open",
435
+ pullRequest
436
+ };
437
+ });
438
+ }
439
+ async readMergeTaskForRelease(number, mergeTaskId) {
440
+ const key = getMergeKey(this.repository.repositoryId, number);
441
+ let task;
442
+ try {
443
+ ({body: task} = await this.request({
444
+ url: `${this.pullRequestUrl(number)}/merge/task-status/${seg(mergeTaskId)}`,
445
+ headers: this.headers,
446
+ redirect: "error"
447
+ }));
448
+ } catch (ex) {
449
+ const refusal = getBitbucketMergeRefusal(ex);
450
+ if (refusal == null) throw ex;
451
+ if (refusal === "invalid-input") throw new BitbucketPullRequestWriteError(refusal);
452
+ if (refusal !== "conflict" && refusal !== "policy-blocked") return "outcome-unknown";
453
+ this.ledger.settleMergeTask(key, mergeTaskId);
454
+ return "conflict";
455
+ }
456
+ if (task == null || typeof task !== "object") return "outcome-unknown";
457
+ if (task.task_status === "SUCCESS") {
458
+ this.ledger.settleMergeTask(key, mergeTaskId);
459
+ return "conflict";
460
+ }
461
+ if (task.task_status !== "PENDING") return "outcome-unknown";
462
+ if (task.queued_pullrequest == null) return "expired";
463
+ return this.isQueuedPullRequest(task.queued_pullrequest, number) ? "conflict" : "outcome-unknown";
464
+ }
465
+ async readMergeStatus(options) {
466
+ const key = getMergeKey(this.repository.repositoryId, options.number);
467
+ let task;
468
+ let refusal;
469
+ try {
470
+ ({body: task} = await this.request({
471
+ url: `${this.pullRequestUrl(options.number)}/merge/task-status/${seg(options.mergeTaskId)}`,
472
+ headers: this.headers,
473
+ redirect: "error"
474
+ }));
475
+ } catch (ex) {
476
+ refusal = getBitbucketMergeRefusal(ex);
477
+ if (refusal == null) throw ex;
478
+ }
479
+ if (refusal === "invalid-input") return {
480
+ ok: false,
481
+ reason: refusal
482
+ };
483
+ if (refusal === "conflict" || refusal === "policy-blocked") {
484
+ this.ledger.settleMergeTask(key, options.mergeTaskId);
485
+ const snapshot = await this.readPullRequest(options.number).catch(() => void 0);
486
+ if (snapshot != null && snapshot.pullRequest.state !== "open") this.ledger.settle(key);
487
+ return {
488
+ ok: true,
489
+ status: "failed",
490
+ reason: refusal,
491
+ ...snapshot != null && { pullRequest: snapshot.pullRequest }
492
+ };
493
+ }
494
+ if (refusal != null) return {
495
+ ok: false,
496
+ reason: refusal
497
+ };
498
+ if (task?.task_status === "SUCCESS") {
499
+ const merged = this.getApprovedMergeResult(task.merge_result, options);
500
+ if (merged != null) {
501
+ this.ledger.settleMergeTask(key, options.mergeTaskId);
502
+ return {
503
+ ok: true,
504
+ status: "merged",
505
+ pullRequest: merged
506
+ };
507
+ }
508
+ }
509
+ const { pullRequest } = await this.readPullRequest(options.number);
510
+ if (pullRequest.state !== "open") this.ledger.settle(key);
511
+ return task?.task_status === "PENDING" && this.isQueuedPullRequest(task.queued_pullrequest, options.number) ? {
512
+ ok: true,
513
+ status: "pending",
514
+ pullRequest
515
+ } : {
516
+ ok: false,
517
+ reason: "outcome-unknown"
518
+ };
519
+ }
520
+ getApprovedMergeResult(raw, options) {
521
+ if (raw == null) return void 0;
522
+ let read;
523
+ try {
524
+ read = this.toPullRequestRead(raw, options.number);
525
+ } catch {
526
+ return;
527
+ }
528
+ const { pullRequest } = read;
529
+ return pullRequest.state === "merged" && pullRequest.sourceBranch === options.expectedSourceBranch && pullRequest.targetBranch === options.expectedTargetBranch && isApprovedSource(options.expectedSourceSha, read) ? pullRequest : void 0;
530
+ }
531
+ isQueuedPullRequest(queued, number) {
532
+ const pullRequest = queued?.pullrequest;
533
+ const repositoryId = pullRequest?.destination?.repository?.uuid;
534
+ return queued?.type === "queued_pullrequest" && pullRequest?.id === number && (repositoryId == null || sameIdentifier(repositoryId, this.repository.repositoryId));
535
+ }
536
+ async getMergeTarget(read) {
537
+ const { pullRequest } = read;
538
+ const stateFailure = getMergeStateFailure(pullRequest);
539
+ if (stateFailure != null) return {
540
+ merge: {
541
+ kind: "unavailable",
542
+ reason: stateFailure
543
+ },
544
+ pullRequest
545
+ };
546
+ try {
547
+ const [source, target] = await Promise.all([this.readBranch(pullRequest.sourceBranch), this.readBranch(pullRequest.targetBranch)]);
548
+ const snapshot = {
549
+ ...pullRequest,
550
+ ...source != null && { sourceSha: source.sha },
551
+ ...target != null && { targetSha: target.sha }
552
+ };
553
+ if (source == null || read.sourceHash == null || !source.sha.toLowerCase().startsWith(read.sourceHash)) return {
554
+ merge: {
555
+ kind: "unavailable",
556
+ reason: "source-changed"
557
+ },
558
+ pullRequest: snapshot
559
+ };
560
+ if (target == null) return {
561
+ merge: {
562
+ kind: "unavailable",
563
+ reason: "target-changed"
564
+ },
565
+ pullRequest: snapshot
566
+ };
567
+ const checks = await this.readMergeabilityChecks(pullRequest.number);
568
+ const strategies = getAllowedStrategies(target, checks);
569
+ const blocked = strategies.length ? getBlockingCheckFailure(checks) : "policy-blocked";
570
+ if (blocked != null) return {
571
+ merge: {
572
+ kind: "unavailable",
573
+ reason: blocked
574
+ },
575
+ pullRequest: snapshot
576
+ };
577
+ const defaultStrategy = strategies.find((strategy) => strategy === target.defaultStrategy);
578
+ return {
579
+ merge: {
580
+ kind: "available",
581
+ strategies,
582
+ ...defaultStrategy !== void 0 && { defaultStrategy }
583
+ },
584
+ pullRequest: snapshot
585
+ };
586
+ } catch (ex) {
587
+ return {
588
+ merge: {
589
+ kind: "unavailable",
590
+ reason: toBitbucketPullRequestWriteFailure(ex).reason
591
+ },
592
+ pullRequest
593
+ };
594
+ }
595
+ }
596
+ pullRequestUrl(number) {
597
+ return `${this.repoUrl}/pullrequests/${number}`;
598
+ }
599
+ async readPullRequest(number) {
600
+ const { body: raw } = await this.request({
601
+ url: this.pullRequestUrl(number),
602
+ headers: this.headers,
603
+ redirect: "error"
604
+ });
605
+ return this.toPullRequestRead(raw, number);
606
+ }
607
+ toPullRequestRead(raw, number) {
608
+ if (!sameIdentifier(raw?.destination?.repository?.uuid, this.repository.repositoryId)) throw new BitbucketPullRequestWriteError("not-found");
609
+ const { id, title, description, source, destination } = raw;
610
+ const state = typeof raw.state === "string" ? raw.state.toLowerCase() : void 0;
611
+ const sourceBranch = source?.branch?.name;
612
+ const targetBranch = destination?.branch?.name;
613
+ const sourceHash = source?.commit?.hash;
614
+ if (!isPositiveInt32(id) || number !== void 0 && id !== number || typeof title !== "string" || description != null && typeof description !== "string" || state !== "open" && state !== "merged" && state !== "declined" && state !== "superseded" || typeof sourceBranch !== "string" || sourceBranch.length === 0 || typeof targetBranch !== "string" || targetBranch.length === 0) throw new BitbucketPullRequestWriteError("unknown");
615
+ const sourceRepository = source?.repository?.uuid;
616
+ return {
617
+ sourceHash: typeof sourceHash === "string" && /^[\da-f]{7,40}$/i.test(sourceHash) ? sourceHash.toLowerCase() : void 0,
618
+ pullRequest: {
619
+ repository: this.repository,
620
+ number: id,
621
+ url: `${webUrl}/${seg(this.repository.workspaceSlug)}/${seg(this.repository.repositorySlug)}/pull-requests/${id}`,
622
+ title,
623
+ description: description ?? "",
624
+ state,
625
+ draft: raw.draft === true,
626
+ queued: raw.queued === true,
627
+ isCrossRepository: !sameIdentifier(sourceRepository, this.repository.repositoryId),
628
+ sourceBranch,
629
+ targetBranch
630
+ }
631
+ };
632
+ }
633
+ async readBranch(name) {
634
+ let branch;
635
+ try {
636
+ ({body: branch} = await this.request({
637
+ url: `${this.repoUrl}/refs/branches/${seg(name)}`,
638
+ headers: this.headers,
639
+ redirect: "error"
640
+ }));
641
+ } catch (ex) {
642
+ if (toBitbucketPullRequestWriteFailure(ex).reason === "not-found") return void 0;
643
+ throw ex;
644
+ }
645
+ const sha = branch?.target?.hash;
646
+ if (branch?.name !== name || !isCommitSha(sha)) throw new BitbucketPullRequestWriteError("unknown");
647
+ return {
648
+ sha,
649
+ strategies: toStrategies(branch.merge_strategies),
650
+ defaultStrategy: typeof branch.default_merge_strategy === "string" ? branch.default_merge_strategy : void 0
651
+ };
652
+ }
653
+ async readMergeabilityChecks(number) {
654
+ const { body } = await this.request({
655
+ url: `${this.pullRequestUrl(number)}/mergeability/checks`,
656
+ headers: this.headers,
657
+ redirect: "error"
658
+ });
659
+ const values = body?.values;
660
+ if (!Array.isArray(values) || values.some((check) => check == null || typeof check !== "object")) throw new BitbucketPullRequestWriteError("unknown");
661
+ return values;
662
+ }
663
+ getOpenPullRequestsFromQuery(branch) {
664
+ return new URLSearchParams({
665
+ q: `source.branch.name="${branch}"`,
666
+ state: "OPEN",
667
+ fields: "next,values.id,values.source.repository.uuid",
668
+ pagelen: "50"
669
+ });
670
+ }
671
+ async scanPullRequests(query, visit) {
672
+ let url = `${this.repoUrl}/pullrequests?${query.toString()}`;
673
+ const seen = /* @__PURE__ */ new Set();
674
+ let serverTime;
675
+ while (true) {
676
+ seen.add(url);
677
+ const response = await this.request({
678
+ url,
679
+ headers: this.headers,
680
+ redirect: "error"
681
+ });
682
+ serverTime ??= getServerTime(response.headers);
683
+ const { values, next } = response.body ?? {};
684
+ if (!Array.isArray(values)) throw new BitbucketPullRequestWriteError("unknown");
685
+ if (values.some((pr) => visit(pr))) return serverTime;
686
+ if (next == null) return serverTime;
687
+ if (typeof next !== "string" || !next.startsWith(`${apiUrl}/`) || seen.has(next)) throw new BitbucketPullRequestWriteError("unknown");
688
+ url = next;
689
+ }
690
+ }
691
+ getMergeTaskId(number, headers) {
692
+ const location = getResponseHeader(headers, "location");
693
+ if (typeof location !== "string" || !URL.canParse(location, apiUrl)) return void 0;
694
+ const url = new URL(location, apiUrl);
695
+ const match = /^\/2\.0\/repositories\/([^/]+)\/([^/]+)\/pullrequests\/(\d+)\/merge\/task-status\/([^/]+)$/.exec(url.pathname);
696
+ if (url.origin !== new URL(apiUrl).origin || url.search !== "" || match == null) return void 0;
697
+ const [, workspace, repository, id, taskId] = match.map((part) => safeDecode(part));
698
+ const { workspaceId, workspaceSlug, repositoryId, repositorySlug } = this.repository;
699
+ return Number(id) === number && (sameIdentifier(workspace, workspaceId) || sameIdentifier(workspace, workspaceSlug)) && (sameIdentifier(repository, repositoryId) || sameIdentifier(repository, repositorySlug)) && isBitbucketMergeTaskId(taskId) ? taskId : void 0;
700
+ }
701
+ async send(options, method, url, body, context) {
702
+ const pending = context?.pending;
703
+ if (!await this.isSessionCurrent()) return {
704
+ ok: false,
705
+ reason: "no-connection"
706
+ };
707
+ let response;
708
+ try {
709
+ response = await this.request({
710
+ url,
711
+ method,
712
+ headers: body == null ? this.headers : {
713
+ ...this.headers,
714
+ "Content-Type": "application/json"
715
+ },
716
+ body: body == null ? void 0 : JSON.stringify(body),
717
+ redirect: "error"
718
+ });
719
+ } catch (ex) {
720
+ return toBitbucketPullRequestWriteFailure(ex, { action: options.action });
721
+ }
722
+ if (options.action === "merge" && response.status === 202 && pending != null) {
723
+ const mergeTaskId = this.getMergeTaskId(options.number, response.headers);
724
+ return {
725
+ ok: true,
726
+ status: "pending",
727
+ pullRequest: pending,
728
+ ...mergeTaskId !== void 0 && { mergeTaskId }
729
+ };
730
+ }
731
+ let read;
732
+ try {
733
+ read = this.toPullRequestRead(response.body, options.action === "create" ? void 0 : options.number);
734
+ } catch {
735
+ return {
736
+ ok: false,
737
+ reason: "outcome-unknown"
738
+ };
739
+ }
740
+ context?.onReceipt?.(read.pullRequest);
741
+ const status = getReceiptStatus(options, response, read, this.accountId, context?.createdNotBefore);
742
+ return status === void 0 ? {
743
+ ok: false,
744
+ reason: "outcome-unknown"
745
+ } : {
746
+ ok: true,
747
+ status,
748
+ pullRequest: read.pullRequest
749
+ };
750
+ }
751
+ };
752
+ function getAllowedStrategies(target, checks) {
753
+ return checks.some((check) => check.type === "merge_queue_check" && check.required === true) ? target.strategies.filter((strategy) => queueStrategies.includes(strategy)) : target.strategies;
754
+ }
755
+ function safeDecode(value) {
756
+ try {
757
+ return decodeURIComponent(value);
758
+ } catch {
759
+ return;
760
+ }
761
+ }
762
+ function isApprovedSource(expectedSourceSha, read) {
763
+ return read.sourceHash != null && expectedSourceSha.toLowerCase().startsWith(read.sourceHash);
764
+ }
765
+ function sameText(actual, expected) {
766
+ return actual.replaceAll("\r\n", "\n").trim() === expected.replaceAll("\r\n", "\n").trim();
767
+ }
768
+ function getServerTime(headers) {
769
+ const date = getResponseHeader(headers, "date");
770
+ if (typeof date !== "string") return void 0;
771
+ const time = Date.parse(date);
772
+ return Number.isNaN(time) ? void 0 : Math.floor(time / 1e3) * 1e3;
773
+ }
774
+ function isCreatedSince(raw, accountId, notBefore) {
775
+ if (notBefore == null || !sameIdentifier(raw.author?.uuid, accountId)) return false;
776
+ if (typeof raw.created_on !== "string") return false;
777
+ const createdOn = Date.parse(raw.created_on);
778
+ return !Number.isNaN(createdOn) && createdOn >= notBefore;
779
+ }
780
+ function getReceiptStatus(options, response, read, accountId, createdNotBefore) {
781
+ const { pullRequest } = read;
782
+ switch (options.action) {
783
+ case "create": return response.status === 201 && isCreatedSince(response.body, accountId, createdNotBefore) && pullRequest.state === "open" && !pullRequest.isCrossRepository && pullRequest.sourceBranch === options.sourceBranch && pullRequest.targetBranch === options.targetBranch && sameText(pullRequest.title, options.title) && (options.description === void 0 || sameText(pullRequest.description, options.description)) ? "created" : void 0;
784
+ case "edit": return pullRequest.state === "open" && (options.title === void 0 || sameText(pullRequest.title, options.title)) && (options.description === void 0 || sameText(pullRequest.description, options.description)) ? "updated" : void 0;
785
+ case "decline": return pullRequest.state === "declined" ? "declined" : void 0;
786
+ case "merge":
787
+ if (pullRequest.sourceBranch !== options.expectedSourceBranch || pullRequest.targetBranch !== options.expectedTargetBranch) return;
788
+ if (pullRequest.state === "merged") return isApprovedSource(options.expectedSourceSha, read) ? "merged" : void 0;
789
+ return pullRequest.state === "open" && pullRequest.queued ? "pending" : void 0;
790
+ }
791
+ }
792
+ //#endregion
793
+ export { BitbucketPullRequestWriter, isBitbucketPullRequestMergeStatusRead, isBitbucketPullRequestScope, isBitbucketPullRequestWrite, isBitbucketPullRequestWriteRelease };
794
+
795
+ //# sourceMappingURL=bitbucketPullRequestWrites.js.map