@gitkraken/core-gitlens 0.43.0 → 0.45.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 (92) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/dist/git/errors.d.ts +1 -0
  3. package/dist/git/errors.js +7 -1
  4. package/dist/git/errors.js.map +1 -1
  5. package/dist/plus/git-github/api/aliasedQuery.d.ts +3 -2
  6. package/dist/plus/git-github/api/aliasedQuery.js +7 -3
  7. package/dist/plus/git-github/api/aliasedQuery.js.map +1 -1
  8. package/dist/plus/git-github/api/github.d.ts +12 -0
  9. package/dist/plus/git-github/api/github.js +188 -41
  10. package/dist/plus/git-github/api/github.js.map +1 -1
  11. package/dist/plus/git-github/api/issueWrites.d.ts +7 -2
  12. package/dist/plus/git-github/api/issueWrites.js +9 -4
  13. package/dist/plus/git-github/api/issueWrites.js.map +1 -1
  14. package/dist/plus/git-github/api/pullRequestWrites.d.ts +95 -0
  15. package/dist/plus/git-github/api/pullRequestWrites.js +469 -0
  16. package/dist/plus/git-github/api/pullRequestWrites.js.map +1 -0
  17. package/dist/plus/integrations/authentication/configuredIntegrationService.d.ts +10 -9
  18. package/dist/plus/integrations/authentication/configuredIntegrationService.js +18 -12
  19. package/dist/plus/integrations/authentication/configuredIntegrationService.js.map +1 -1
  20. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.d.ts +9 -4
  21. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.js +26 -9
  22. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.js.map +1 -1
  23. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +1 -0
  24. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +3 -0
  25. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  26. package/dist/plus/integrations/authentication/observedAuthenticationProvider.d.ts +1 -0
  27. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js +14 -4
  28. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js.map +1 -1
  29. package/dist/plus/integrations/authentication/rejectedTokenTracker.d.ts +2 -2
  30. package/dist/plus/integrations/authentication/rejectedTokenTracker.js +19 -5
  31. package/dist/plus/integrations/authentication/rejectedTokenTracker.js.map +1 -1
  32. package/dist/plus/integrations/collectionMetadata.js +2 -1
  33. package/dist/plus/integrations/collectionMetadata.js.map +1 -1
  34. package/dist/plus/integrations/context.d.ts +3 -3
  35. package/dist/plus/integrations/errors.d.ts +4 -0
  36. package/dist/plus/integrations/errors.js +8 -1
  37. package/dist/plus/integrations/errors.js.map +1 -1
  38. package/dist/plus/integrations/index.d.ts +4 -2
  39. package/dist/plus/integrations/index.js.map +1 -1
  40. package/dist/plus/integrations/integrationService.d.ts +22 -1
  41. package/dist/plus/integrations/integrationService.js +51 -2
  42. package/dist/plus/integrations/integrationService.js.map +1 -1
  43. package/dist/plus/integrations/lite.js +11 -1
  44. package/dist/plus/integrations/lite.js.map +1 -1
  45. package/dist/plus/integrations/manager.d.ts +96 -4
  46. package/dist/plus/integrations/models/gitHostIntegration.d.ts +21 -2
  47. package/dist/plus/integrations/models/gitHostIntegration.js +182 -14
  48. package/dist/plus/integrations/models/gitHostIntegration.js.map +1 -1
  49. package/dist/plus/integrations/models/integration.d.ts +10 -2
  50. package/dist/plus/integrations/models/integration.js +53 -8
  51. package/dist/plus/integrations/models/integration.js.map +1 -1
  52. package/dist/plus/integrations/providers/apiClients.d.ts +1 -0
  53. package/dist/plus/integrations/providers/apiClients.js +3 -0
  54. package/dist/plus/integrations/providers/apiClients.js.map +1 -1
  55. package/dist/plus/integrations/providers/azure/azure.d.ts +3 -0
  56. package/dist/plus/integrations/providers/azure/azure.js +109 -18
  57. package/dist/plus/integrations/providers/azure/azure.js.map +1 -1
  58. package/dist/plus/integrations/providers/azureDevOps.d.ts +12 -0
  59. package/dist/plus/integrations/providers/azureDevOps.js +22 -0
  60. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  61. package/dist/plus/integrations/providers/bitbucket/bitbucket.d.ts +21 -2
  62. package/dist/plus/integrations/providers/bitbucket/bitbucket.js +59 -19
  63. package/dist/plus/integrations/providers/bitbucket/bitbucket.js.map +1 -1
  64. package/dist/plus/integrations/providers/bitbucket-server.d.ts +2 -0
  65. package/dist/plus/integrations/providers/bitbucket-server.js +11 -3
  66. package/dist/plus/integrations/providers/bitbucket-server.js.map +1 -1
  67. package/dist/plus/integrations/providers/bitbucket.d.ts +14 -0
  68. package/dist/plus/integrations/providers/bitbucket.js +30 -2
  69. package/dist/plus/integrations/providers/bitbucket.js.map +1 -1
  70. package/dist/plus/integrations/providers/github.d.ts +12 -0
  71. package/dist/plus/integrations/providers/github.js +66 -2
  72. package/dist/plus/integrations/providers/github.js.map +1 -1
  73. package/dist/plus/integrations/providers/gitlab/gitlab.d.ts +19 -1
  74. package/dist/plus/integrations/providers/gitlab/gitlab.js +116 -17
  75. package/dist/plus/integrations/providers/gitlab/gitlab.js.map +1 -1
  76. package/dist/plus/integrations/providers/gitlab.d.ts +15 -2
  77. package/dist/plus/integrations/providers/gitlab.js +34 -4
  78. package/dist/plus/integrations/providers/gitlab.js.map +1 -1
  79. package/dist/plus/integrations/providers/providerErrors.d.ts +8 -0
  80. package/dist/plus/integrations/providers/providerErrors.js +15 -2
  81. package/dist/plus/integrations/providers/providerErrors.js.map +1 -1
  82. package/dist/plus/integrations/reads/pullRequestsForCommits.d.ts +45 -0
  83. package/dist/plus/integrations/reads/pullRequestsForCommits.js +97 -0
  84. package/dist/plus/integrations/reads/pullRequestsForCommits.js.map +1 -0
  85. package/dist/plus/integrations/utils/domain.utils.d.ts +1 -0
  86. package/dist/plus/integrations/utils/domain.utils.js +5 -1
  87. package/dist/plus/integrations/utils/domain.utils.js.map +1 -1
  88. package/dist/plus/integrations/utils/failureBackoff.d.ts +13 -0
  89. package/dist/plus/integrations/utils/failureBackoff.js +47 -0
  90. package/dist/plus/integrations/utils/failureBackoff.js.map +1 -0
  91. package/docs/integrations.md +126 -6
  92. package/package.json +1 -1
@@ -0,0 +1,469 @@
1
+ import { AuthenticationError, RequestNotFoundError } from "../../../git/errors.js";
2
+ import { issueWriteFailure } from "./issueWrites.js";
3
+ import { GraphqlResponseError } from "@octokit/graphql";
4
+ //#region ../plus/git-github/src/api/pullRequestWrites.ts
5
+ const repositoryIdentity = "id owner { login } name";
6
+ const repositoryFields = `${repositoryIdentity} isArchived isDisabled isLocked viewerPermission`;
7
+ const pullRequestFields = `
8
+ id number url title body state closedAt mergedAt updatedAt headRefOid baseRefName
9
+ repository { ${repositoryIdentity} }
10
+ `;
11
+ const mergeMethods = [
12
+ "merge",
13
+ "squash",
14
+ "rebase"
15
+ ];
16
+ function isValidRepository({ owner, repo }) {
17
+ return typeof owner === "string" && /^[a-z\d_-]+$/i.test(owner) && typeof repo === "string" && /^[a-z\d._-]+$/i.test(repo) && repo !== "." && repo !== "..";
18
+ }
19
+ function isValidTarget(input) {
20
+ return isValidRepository(input) && Number.isInteger(input.number) && input.number >= 1 && input.number <= 2147483647 && typeof input.expectedNodeId === "string" && input.expectedNodeId.trim().length > 0;
21
+ }
22
+ function isBranchName(value) {
23
+ return typeof value === "string" && value.length > 0 && value.trim() === value && !value.includes(":") && !value.startsWith("refs/") && !value.startsWith("-");
24
+ }
25
+ function isTitle(value) {
26
+ return typeof value === "string" && value.trim().length > 0;
27
+ }
28
+ function isValidWrite(input) {
29
+ if (input.action === "create") return isValidRepository(input) && isTitle(input.title) && (input.body === void 0 || typeof input.body === "string") && (input.expectedRepositoryId === void 0 || typeof input.expectedRepositoryId === "string" && input.expectedRepositoryId.trim().length > 0) && isBranchName(input.headRef) && isBranchName(input.baseRef) && input.headRef !== input.baseRef;
30
+ if (!isValidTarget(input)) return false;
31
+ switch (input.action) {
32
+ case "edit": return (input.title !== void 0 || input.body !== void 0) && (input.title === void 0 || isTitle(input.title)) && (input.body === void 0 || typeof input.body === "string");
33
+ case "set-state": return input.state === "open" || input.state === "closed";
34
+ case "merge":
35
+ case "enqueue": return (input.action === "enqueue" || mergeMethods.includes(input.mergeMethod)) && isBranchName(input.expectedBaseRef) && typeof input.expectedHeadSha === "string" && /^[a-f\d]{40}$/i.test(input.expectedHeadSha);
36
+ default: return false;
37
+ }
38
+ }
39
+ function pullRequestWriteFailure(ex, phase) {
40
+ if (ex instanceof RequestNotFoundError) return {
41
+ ok: false,
42
+ reason: "not-found"
43
+ };
44
+ if (ex instanceof AuthenticationError) {
45
+ if (ex.reason === 3) return {
46
+ ok: false,
47
+ reason: "forbidden"
48
+ };
49
+ return {
50
+ ok: false,
51
+ reason: "no-connection"
52
+ };
53
+ }
54
+ const failure = issueWriteFailure(ex);
55
+ if (failure.reason === "rate-limit") return failure;
56
+ if (phase === "merge" || phase === "enqueue") {
57
+ const error = ex instanceof GraphqlResponseError ? ex.errors?.[0] : void 0;
58
+ if (error?.type === "UNPROCESSABLE") {
59
+ if (/\b(?:expected head oid|head sha) does not match\b/i.test(error.message)) return {
60
+ ok: false,
61
+ reason: "head-changed"
62
+ };
63
+ return {
64
+ ok: false,
65
+ reason: "blocked"
66
+ };
67
+ }
68
+ }
69
+ return phase != null && failure.reason === "unknown" ? {
70
+ ok: false,
71
+ reason: "outcome-unknown"
72
+ } : failure;
73
+ }
74
+ function hasWritePermission(repository) {
75
+ const { viewerPermission } = repository;
76
+ return viewerPermission == null ? void 0 : viewerPermission === "ADMIN" || viewerPermission === "MAINTAIN" || viewerPermission === "WRITE";
77
+ }
78
+ function isRepositoryWritable(repository) {
79
+ return !repository.isArchived && !repository.isDisabled && !repository.isLocked;
80
+ }
81
+ function sameRepository(a, b) {
82
+ return a.owner.toLowerCase() === b.owner.login.toLowerCase() && a.repo.toLowerCase() === b.name.toLowerCase();
83
+ }
84
+ function toSnapshot(node) {
85
+ const closedAt = node.state === "MERGED" ? node.mergedAt ?? node.closedAt : node.closedAt;
86
+ return {
87
+ owner: node.repository.owner.login,
88
+ repo: node.repository.name,
89
+ number: node.number,
90
+ nodeId: node.id,
91
+ url: node.url,
92
+ title: node.title,
93
+ body: node.body,
94
+ state: node.state === "OPEN" ? "open" : node.state === "CLOSED" ? "closed" : "merged",
95
+ ...node.state !== "OPEN" && typeof closedAt === "string" ? { closedAt } : {},
96
+ ...typeof node.updatedAt === "string" ? { updatedAt: node.updatedAt } : {},
97
+ headSha: node.headRefOid,
98
+ baseRef: node.baseRefName
99
+ };
100
+ }
101
+ async function resolveNode(input, graphql) {
102
+ const { owner, repo, expectedNodeId, number } = input;
103
+ const result = await graphql(`query PullRequestWriteTarget($owner: String!, $repo: String!, $expectedNodeId: ID!) {
104
+ repository(owner: $owner, name: $repo, followRenames: false) {
105
+ ${repositoryFields}
106
+ mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerDefaultMergeMethod
107
+ }
108
+ node(id: $expectedNodeId) {
109
+ __typename
110
+ ... on PullRequest {
111
+ ${pullRequestFields}
112
+ viewerCanUpdate viewerCanClose viewerCanReopen
113
+ isDraft isInMergeQueue isMergeQueueEnabled
114
+ stack { id }
115
+ baseRef { id }
116
+ }
117
+ }
118
+ }`, {
119
+ owner,
120
+ repo,
121
+ expectedNodeId
122
+ });
123
+ const repository = result?.repository;
124
+ const node = result?.node;
125
+ if (repository == null || !sameRepository(input, repository) || node?.__typename !== "PullRequest" || node.number !== number || node.repository.id !== repository.id) return {
126
+ ok: false,
127
+ reason: "not-found"
128
+ };
129
+ return {
130
+ ok: true,
131
+ node,
132
+ repository
133
+ };
134
+ }
135
+ async function readBranchRules(refId, graphql) {
136
+ const rules = [];
137
+ const seen = /* @__PURE__ */ new Set();
138
+ let requiresLinearHistory = false;
139
+ let cursor;
140
+ for (;;) {
141
+ const ref = (await graphql(`
142
+ query PullRequestBranchRules($id: ID!, $cursor: String) {
143
+ node(id: $id) {
144
+ ... on Ref {
145
+ id
146
+ refUpdateRule {
147
+ requiresLinearHistory
148
+ }
149
+ rules(first: 100, after: $cursor) {
150
+ nodes {
151
+ type
152
+ parameters {
153
+ ... on PullRequestParameters {
154
+ allowedMergeMethods
155
+ }
156
+ }
157
+ }
158
+ pageInfo {
159
+ hasNextPage
160
+ endCursor
161
+ }
162
+ }
163
+ }
164
+ }
165
+ }
166
+ `, {
167
+ id: refId,
168
+ cursor
169
+ }))?.node;
170
+ const page = ref?.rules;
171
+ if (ref?.id !== refId || page?.nodes == null) return void 0;
172
+ requiresLinearHistory ||= ref.refUpdateRule?.requiresLinearHistory === true;
173
+ for (const rule of page.nodes) {
174
+ if (rule == null) return void 0;
175
+ rules.push(rule);
176
+ }
177
+ if (!page.pageInfo.hasNextPage) return {
178
+ rules,
179
+ requiresLinearHistory
180
+ };
181
+ const nextCursor = page.pageInfo.endCursor;
182
+ if (nextCursor == null || seen.has(nextCursor)) return void 0;
183
+ seen.add(nextCursor);
184
+ cursor = nextCursor;
185
+ }
186
+ }
187
+ async function getMergeCapability({ node, repository }, graphql) {
188
+ if (!isRepositoryWritable(repository) || node.state !== "OPEN" || node.isDraft || node.isInMergeQueue || node.baseRef == null) return {
189
+ kind: "unavailable",
190
+ reason: "blocked"
191
+ };
192
+ const canWrite = hasWritePermission(repository);
193
+ if (canWrite !== true) return {
194
+ kind: "unavailable",
195
+ reason: canWrite === false ? "forbidden" : "unknown"
196
+ };
197
+ if (node.stack != null) return {
198
+ kind: "unavailable",
199
+ reason: "unsupported"
200
+ };
201
+ if (node.isMergeQueueEnabled) return { kind: "queue" };
202
+ try {
203
+ const branch = await readBranchRules(node.baseRef.id, graphql);
204
+ if (branch == null) return {
205
+ kind: "unavailable",
206
+ reason: "unknown"
207
+ };
208
+ const { rules, requiresLinearHistory } = branch;
209
+ if (rules.some((rule) => rule.type === "MERGE_QUEUE")) return { kind: "queue" };
210
+ const linearHistory = requiresLinearHistory || rules.some((rule) => rule.type === "REQUIRED_LINEAR_HISTORY");
211
+ const methods = mergeMethods.filter((method) => {
212
+ return (method === "merge" ? repository.mergeCommitAllowed && !linearHistory : method === "squash" ? repository.squashMergeAllowed : repository.rebaseMergeAllowed) && rules.every((rule) => {
213
+ const permitted = rule.type === "PULL_REQUEST" ? rule.parameters?.allowedMergeMethods : void 0;
214
+ return permitted == null || permitted.some((allowedMethod) => allowedMethod.toLowerCase() === method);
215
+ });
216
+ });
217
+ if (methods.length === 0) return {
218
+ kind: "unavailable",
219
+ reason: "blocked"
220
+ };
221
+ const preference = repository.viewerDefaultMergeMethod.toLowerCase();
222
+ return {
223
+ kind: "direct",
224
+ methods,
225
+ defaultMethod: methods.find((method) => method === preference)
226
+ };
227
+ } catch (ex) {
228
+ return {
229
+ kind: "unavailable",
230
+ reason: pullRequestWriteFailure(ex).reason
231
+ };
232
+ }
233
+ }
234
+ async function resolveGitHubPullRequestWriteTarget(input, graphql) {
235
+ if (!isValidTarget(input)) return {
236
+ ok: false,
237
+ reason: "invalid-input"
238
+ };
239
+ try {
240
+ const resolved = await resolveNode(input, graphql);
241
+ if (!resolved.ok) return resolved;
242
+ const { node, repository } = resolved;
243
+ const writable = isRepositoryWritable(repository);
244
+ return {
245
+ ok: true,
246
+ pullRequest: toSnapshot(node),
247
+ capabilities: {
248
+ edit: writable && node.viewerCanUpdate,
249
+ close: writable && node.state === "OPEN" && node.viewerCanClose,
250
+ reopen: writable && node.state === "CLOSED" && node.viewerCanReopen,
251
+ merge: await getMergeCapability(resolved, graphql)
252
+ }
253
+ };
254
+ } catch (ex) {
255
+ return pullRequestWriteFailure(ex);
256
+ }
257
+ }
258
+ async function getGitHubPullRequestCreateCapability(input, graphql) {
259
+ if (!isValidRepository(input)) return {
260
+ ok: false,
261
+ reason: "invalid-input"
262
+ };
263
+ try {
264
+ const repository = (await graphql(`query PullRequestCreateCapability($owner: String!, $repo: String!) {
265
+ repository(owner: $owner, name: $repo, followRenames: false) {
266
+ ${repositoryFields}
267
+ }
268
+ }`, {
269
+ owner: input.owner,
270
+ repo: input.repo
271
+ }))?.repository;
272
+ if (repository == null || !sameRepository(input, repository)) return {
273
+ ok: false,
274
+ reason: "not-found"
275
+ };
276
+ return {
277
+ ok: true,
278
+ repositoryId: repository.id,
279
+ canCreate: isRepositoryWritable(repository) && (repository.viewerPermission == null ? void 0 : true)
280
+ };
281
+ } catch (ex) {
282
+ return pullRequestWriteFailure(ex);
283
+ }
284
+ }
285
+ const mutations = {
286
+ created: ["createPullRequest", "CreatePullRequestInput"],
287
+ updated: ["updatePullRequest", "UpdatePullRequestInput"],
288
+ closed: ["closePullRequest", "ClosePullRequestInput"],
289
+ reopened: ["reopenPullRequest", "ReopenPullRequestInput"],
290
+ merged: ["mergePullRequest", "MergePullRequestInput"]
291
+ };
292
+ async function sendMutation(transport, status, repositoryId, values, previous) {
293
+ if (!await transport.isSessionCurrent()) return {
294
+ ok: false,
295
+ reason: "no-connection"
296
+ };
297
+ const [mutation, inputType] = mutations[status];
298
+ let node;
299
+ try {
300
+ node = (await transport.graphql(`mutation WritePullRequest($input: ${inputType}!) {
301
+ change: ${mutation}(input: $input) { pullRequest { ${pullRequestFields} } }
302
+ }`, { input: values }))?.change?.pullRequest;
303
+ } catch (ex) {
304
+ if (ex instanceof GraphqlResponseError) {
305
+ node = ex.data?.change?.pullRequest;
306
+ if (node == null && ex.errors?.some((error) => error.path?.[0] === "change" && error.path.length > 1)) return {
307
+ ok: false,
308
+ reason: "outcome-unknown"
309
+ };
310
+ }
311
+ if (node == null) return pullRequestWriteFailure(ex, status === "merged" ? "merge" : "write");
312
+ }
313
+ const expectedState = status === "created" || status === "reopened" ? "OPEN" : status === "closed" ? "CLOSED" : status === "merged" ? "MERGED" : void 0;
314
+ if (node?.repository?.id !== repositoryId || previous != null && (node.id !== previous.id || node.number !== previous.number) || expectedState != null && node.state !== expectedState || typeof node.repository.owner?.login !== "string" || typeof node.repository.name !== "string" || typeof node.id !== "string" || !Number.isInteger(node.number) || typeof node.url !== "string" || typeof node.title !== "string" || typeof node.body !== "string" || typeof node.headRefOid !== "string" || typeof node.baseRefName !== "string" || node.state !== "OPEN" && node.state !== "CLOSED" && node.state !== "MERGED") return {
315
+ ok: false,
316
+ reason: "outcome-unknown"
317
+ };
318
+ return {
319
+ ok: true,
320
+ status,
321
+ pullRequest: toSnapshot(node)
322
+ };
323
+ }
324
+ async function createPullRequest(input, transport) {
325
+ const repository = (await transport.graphql(`query PullRequestCreateTarget($owner: String!, $repo: String!, $base: String!, $head: String!) {
326
+ repository(owner: $owner, name: $repo, followRenames: false) {
327
+ ${repositoryFields}
328
+ base: ref(qualifiedName: $base) { id }
329
+ head: ref(qualifiedName: $head) { id }
330
+ }
331
+ }`, {
332
+ owner: input.owner,
333
+ repo: input.repo,
334
+ base: `refs/heads/${input.baseRef}`,
335
+ head: `refs/heads/${input.headRef}`
336
+ }))?.repository;
337
+ if (repository == null || !sameRepository(input, repository) || input.expectedRepositoryId != null && input.expectedRepositoryId !== repository.id) return {
338
+ ok: false,
339
+ reason: "not-found"
340
+ };
341
+ if (!isRepositoryWritable(repository)) return {
342
+ ok: false,
343
+ reason: "blocked"
344
+ };
345
+ if (repository.base == null || repository.head == null) return {
346
+ ok: false,
347
+ reason: "invalid-input"
348
+ };
349
+ return sendMutation(transport, "created", repository.id, {
350
+ repositoryId: repository.id,
351
+ baseRefName: input.baseRef,
352
+ headRefName: input.headRef,
353
+ title: input.title,
354
+ body: input.body
355
+ });
356
+ }
357
+ async function mergePullRequest(input, resolved, transport) {
358
+ const { node, repository } = resolved;
359
+ if (node.headRefOid.toLowerCase() !== input.expectedHeadSha.toLowerCase()) return {
360
+ ok: false,
361
+ reason: "head-changed"
362
+ };
363
+ if (node.baseRefName !== input.expectedBaseRef) return {
364
+ ok: false,
365
+ reason: "base-changed"
366
+ };
367
+ const capability = await getMergeCapability(resolved, transport.graphql);
368
+ if (capability.kind === "unavailable") return {
369
+ ok: false,
370
+ reason: capability.reason
371
+ };
372
+ if (input.action === "merge") {
373
+ if (capability.kind !== "direct" || !capability.methods.includes(input.mergeMethod)) return {
374
+ ok: false,
375
+ reason: "blocked"
376
+ };
377
+ return sendMutation(transport, "merged", repository.id, {
378
+ pullRequestId: node.id,
379
+ expectedHeadOid: node.headRefOid,
380
+ mergeMethod: input.mergeMethod.toUpperCase()
381
+ }, node);
382
+ }
383
+ if (capability.kind !== "queue") return {
384
+ ok: false,
385
+ reason: "blocked"
386
+ };
387
+ if (!await transport.isSessionCurrent()) return {
388
+ ok: false,
389
+ reason: "no-connection"
390
+ };
391
+ try {
392
+ const result = await transport.enqueue(node.id, node.headRefOid);
393
+ if (result.status === "queued" && result.entry != null) return {
394
+ ok: true,
395
+ status: "queued",
396
+ pullRequest: toSnapshot(node)
397
+ };
398
+ if (result.status !== "failed") return {
399
+ ok: false,
400
+ reason: "outcome-unknown"
401
+ };
402
+ switch (result.reason) {
403
+ case "permission": return {
404
+ ok: false,
405
+ reason: "forbidden"
406
+ };
407
+ case "already-queued":
408
+ case "not-allowed": return {
409
+ ok: false,
410
+ reason: "blocked"
411
+ };
412
+ case "head-changed":
413
+ case "unsupported": return {
414
+ ok: false,
415
+ reason: result.reason
416
+ };
417
+ default: return {
418
+ ok: false,
419
+ reason: "outcome-unknown"
420
+ };
421
+ }
422
+ } catch (ex) {
423
+ return pullRequestWriteFailure(ex, "enqueue");
424
+ }
425
+ }
426
+ async function writeGitHubPullRequest(input, transport) {
427
+ if (!isValidWrite(input)) return {
428
+ ok: false,
429
+ reason: "invalid-input"
430
+ };
431
+ try {
432
+ if (input.action === "create") return await createPullRequest(input, transport);
433
+ const resolved = await resolveNode(input, transport.graphql);
434
+ if (!resolved.ok) return resolved;
435
+ const { node, repository } = resolved;
436
+ if (!isRepositoryWritable(repository)) return {
437
+ ok: false,
438
+ reason: "blocked"
439
+ };
440
+ if (input.action === "merge" || input.action === "enqueue") return await mergePullRequest(input, resolved, transport);
441
+ if (input.action === "edit") {
442
+ if (!node.viewerCanUpdate) return {
443
+ ok: false,
444
+ reason: "forbidden"
445
+ };
446
+ return await sendMutation(transport, "updated", repository.id, {
447
+ pullRequestId: node.id,
448
+ title: input.title,
449
+ body: input.body
450
+ }, node);
451
+ }
452
+ const close = input.state === "closed";
453
+ if (node.state !== (close ? "OPEN" : "CLOSED")) return {
454
+ ok: false,
455
+ reason: "blocked"
456
+ };
457
+ if (close ? !node.viewerCanClose : !node.viewerCanReopen) return {
458
+ ok: false,
459
+ reason: "forbidden"
460
+ };
461
+ return await sendMutation(transport, close ? "closed" : "reopened", repository.id, { pullRequestId: node.id }, node);
462
+ } catch (ex) {
463
+ return pullRequestWriteFailure(ex);
464
+ }
465
+ }
466
+ //#endregion
467
+ export { getGitHubPullRequestCreateCapability, pullRequestWriteFailure, resolveGitHubPullRequestWriteTarget, writeGitHubPullRequest };
468
+
469
+ //# sourceMappingURL=pullRequestWrites.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pullRequestWrites.js","names":[],"sources":["../../../../../plus/git-github/src/api/pullRequestWrites.ts"],"sourcesContent":["import { GraphqlResponseError } from '@octokit/graphql';\nimport type { RequestParameters } from '@octokit/types';\nimport { AuthenticationError, AuthenticationErrorReason, RequestNotFoundError } from '@gitlens/git/errors.js';\nimport type { PullRequestMergeMethod, PullRequestMergeQueueActionResult } from '@gitlens/git/models/pullRequest.js';\nimport { issueWriteFailure } from './issueWrites.js';\n\ntype MergeMethod = `${PullRequestMergeMethod}`;\nexport type GitHubPullRequestCreateTarget = { owner: string; repo: string };\n\nexport type GitHubPullRequestWriteTarget = GitHubPullRequestCreateTarget & { number: number; expectedNodeId: string };\nexport type GitHubPullRequestWrite =\n\t| (GitHubPullRequestCreateTarget & {\n\t\t\taction: 'create';\n\t\t\ttitle: string;\n\t\t\tbody?: string;\n\t\t\theadRef: string;\n\t\t\tbaseRef: string;\n\t\t\texpectedRepositoryId?: string;\n\t })\n\t| (GitHubPullRequestWriteTarget &\n\t\t\t(\n\t\t\t\t| { action: 'edit'; title?: string; body?: string }\n\t\t\t\t| { action: 'set-state'; state: 'open' | 'closed' }\n\t\t\t\t| ({ expectedHeadSha: string; expectedBaseRef: string } & (\n\t\t\t\t\t\t| { action: 'merge'; mergeMethod: MergeMethod }\n\t\t\t\t\t\t| { action: 'enqueue' }\n\t\t\t\t ))\n\t\t\t));\n\nexport type PullRequestWriteFailure = {\n\tok: false;\n\treason:\n\t\t| 'unsupported'\n\t\t| 'no-connection'\n\t\t| 'forbidden'\n\t\t| 'not-found'\n\t\t| 'invalid-input'\n\t\t| 'rate-limit'\n\t\t| 'blocked'\n\t\t| 'head-changed'\n\t\t| 'base-changed'\n\t\t| 'unknown'\n\t\t| 'outcome-unknown';\n};\n\nexport type PullRequestWriteSnapshot = {\n\towner: string;\n\trepo: string;\n\tnumber: number;\n\tnodeId: string;\n\turl: string;\n\ttitle: string;\n\tbody: string;\n\tstate: 'open' | 'closed' | 'merged';\n\tclosedAt?: string;\n\tupdatedAt?: string;\n\theadSha: string;\n\tbaseRef: string;\n};\n\nexport type PullRequestCreateCapabilityResult =\n\t| { ok: true; repositoryId: string; canCreate: boolean | undefined }\n\t| PullRequestWriteFailure;\n\ntype MergeCapability =\n\t| { kind: 'direct'; methods: MergeMethod[]; defaultMethod?: MergeMethod }\n\t| { kind: 'queue' }\n\t| { kind: 'unavailable'; reason: PullRequestWriteFailure['reason'] };\n\nexport type PullRequestWriteTargetResult =\n\t| {\n\t\t\tok: true;\n\t\t\tpullRequest: PullRequestWriteSnapshot;\n\t\t\tcapabilities: { edit: boolean; close: boolean; reopen: boolean; merge: MergeCapability };\n\t }\n\t| PullRequestWriteFailure;\n\nexport type PullRequestWriteResult =\n\t| {\n\t\t\tok: true;\n\t\t\tstatus: 'created' | 'updated' | 'closed' | 'reopened' | 'merged' | 'queued';\n\t\t\tpullRequest: PullRequestWriteSnapshot;\n\t }\n\t| PullRequestWriteFailure;\n\ntype RepositoryIdentity = {\n\tid: string;\n\towner: { login: string };\n\tname: string;\n};\n\ntype RepositoryNode = RepositoryIdentity & {\n\tisArchived: boolean;\n\tisDisabled: boolean;\n\tisLocked: boolean;\n\tviewerPermission: 'ADMIN' | 'MAINTAIN' | 'WRITE' | 'MODERATE' | 'TRIAGE' | 'READ' | null;\n};\n\ntype PullRequestNode = {\n\tid: string;\n\tnumber: number;\n\turl: string;\n\ttitle: string;\n\tbody: string;\n\tstate: 'OPEN' | 'CLOSED' | 'MERGED';\n\tclosedAt: string | null;\n\tmergedAt: string | null;\n\tupdatedAt: string;\n\theadRefOid: string;\n\tbaseRefName: string;\n\trepository: RepositoryIdentity;\n};\n\ntype WriteNode = PullRequestNode & {\n\t__typename: 'PullRequest';\n\tviewerCanUpdate: boolean;\n\tviewerCanClose: boolean;\n\tviewerCanReopen: boolean;\n\tisDraft: boolean;\n\tisInMergeQueue: boolean;\n\tisMergeQueueEnabled: boolean;\n\tstack: { id: string } | null;\n\tbaseRef: { id: string } | null;\n};\n\ntype MergeRepository = RepositoryNode & {\n\tmergeCommitAllowed: boolean;\n\tsquashMergeAllowed: boolean;\n\trebaseMergeAllowed: boolean;\n\tviewerDefaultMergeMethod: string;\n};\n\ntype ResolvedPullRequest = { ok: true; node: WriteNode; repository: MergeRepository };\ntype GraphqlRequest = <T>(query: string, variables: RequestParameters) => Promise<T | undefined>;\ntype BranchRule = {\n\ttype: string;\n\tparameters: { allowedMergeMethods?: readonly Uppercase<MergeMethod>[] | null } | null;\n};\n\nconst repositoryIdentity = 'id owner { login } name';\nconst repositoryFields = `${repositoryIdentity} isArchived isDisabled isLocked viewerPermission`;\nconst pullRequestFields = `\n\tid number url title body state closedAt mergedAt updatedAt headRefOid baseRefName\n\trepository { ${repositoryIdentity} }\n`;\nconst mergeMethods: readonly MergeMethod[] = ['merge', 'squash', 'rebase'];\n\nfunction isValidRepository({ owner, repo }: GitHubPullRequestCreateTarget): boolean {\n\treturn (\n\t\ttypeof owner === 'string' &&\n\t\t/^[a-z\\d_-]+$/i.test(owner) &&\n\t\ttypeof repo === 'string' &&\n\t\t/^[a-z\\d._-]+$/i.test(repo) &&\n\t\trepo !== '.' &&\n\t\trepo !== '..'\n\t);\n}\n\nfunction isValidTarget(input: GitHubPullRequestWriteTarget): boolean {\n\treturn (\n\t\tisValidRepository(input) &&\n\t\tNumber.isInteger(input.number) &&\n\t\tinput.number >= 1 &&\n\t\tinput.number <= 2147483647 &&\n\t\ttypeof input.expectedNodeId === 'string' &&\n\t\tinput.expectedNodeId.trim().length > 0\n\t);\n}\n\nfunction isBranchName(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === 'string' &&\n\t\tvalue.length > 0 &&\n\t\tvalue.trim() === value &&\n\t\t!value.includes(':') &&\n\t\t!value.startsWith('refs/') &&\n\t\t!value.startsWith('-')\n\t);\n}\n\nfunction isTitle(value: unknown): value is string {\n\treturn typeof value === 'string' && value.trim().length > 0;\n}\n\nfunction isValidWrite(input: GitHubPullRequestWrite): boolean {\n\tif (input.action === 'create') {\n\t\treturn (\n\t\t\tisValidRepository(input) &&\n\t\t\tisTitle(input.title) &&\n\t\t\t(input.body === undefined || typeof input.body === 'string') &&\n\t\t\t(input.expectedRepositoryId === undefined ||\n\t\t\t\t(typeof input.expectedRepositoryId === 'string' && input.expectedRepositoryId.trim().length > 0)) &&\n\t\t\tisBranchName(input.headRef) &&\n\t\t\tisBranchName(input.baseRef) &&\n\t\t\tinput.headRef !== input.baseRef\n\t\t);\n\t}\n\n\tif (!isValidTarget(input)) return false;\n\n\tswitch (input.action) {\n\t\tcase 'edit':\n\t\t\treturn (\n\t\t\t\t(input.title !== undefined || input.body !== undefined) &&\n\t\t\t\t(input.title === undefined || isTitle(input.title)) &&\n\t\t\t\t(input.body === undefined || typeof input.body === 'string')\n\t\t\t);\n\t\tcase 'set-state':\n\t\t\treturn input.state === 'open' || input.state === 'closed';\n\t\tcase 'merge':\n\t\tcase 'enqueue':\n\t\t\treturn (\n\t\t\t\t(input.action === 'enqueue' || mergeMethods.includes(input.mergeMethod)) &&\n\t\t\t\tisBranchName(input.expectedBaseRef) &&\n\t\t\t\ttypeof input.expectedHeadSha === 'string' &&\n\t\t\t\t/^[a-f\\d]{40}$/i.test(input.expectedHeadSha)\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nexport function pullRequestWriteFailure(ex: unknown, phase?: 'write' | 'merge' | 'enqueue'): PullRequestWriteFailure {\n\tif (ex instanceof RequestNotFoundError) return { ok: false, reason: 'not-found' };\n\tif (ex instanceof AuthenticationError) {\n\t\tif (ex.reason === AuthenticationErrorReason.Forbidden) return { ok: false, reason: 'forbidden' };\n\t\treturn { ok: false, reason: 'no-connection' };\n\t}\n\n\tconst failure = issueWriteFailure(ex);\n\tif (failure.reason === 'rate-limit') return failure;\n\n\tif (phase === 'merge' || phase === 'enqueue') {\n\t\tconst error = ex instanceof GraphqlResponseError ? ex.errors?.[0] : undefined;\n\t\tif (error?.type === 'UNPROCESSABLE') {\n\t\t\tif (/\\b(?:expected head oid|head sha) does not match\\b/i.test(error.message)) {\n\t\t\t\treturn { ok: false, reason: 'head-changed' };\n\t\t\t}\n\n\t\t\treturn { ok: false, reason: 'blocked' };\n\t\t}\n\t}\n\n\treturn phase != null && failure.reason === 'unknown' ? { ok: false, reason: 'outcome-unknown' } : failure;\n}\n\nfunction hasWritePermission(repository: RepositoryNode): boolean | undefined {\n\tconst { viewerPermission } = repository;\n\treturn viewerPermission == null\n\t\t? undefined\n\t\t: viewerPermission === 'ADMIN' || viewerPermission === 'MAINTAIN' || viewerPermission === 'WRITE';\n}\n\nfunction isRepositoryWritable(repository: RepositoryNode): boolean {\n\treturn !repository.isArchived && !repository.isDisabled && !repository.isLocked;\n}\n\nfunction sameRepository(a: GitHubPullRequestCreateTarget, b: RepositoryIdentity): boolean {\n\treturn a.owner.toLowerCase() === b.owner.login.toLowerCase() && a.repo.toLowerCase() === b.name.toLowerCase();\n}\n\nfunction toSnapshot(node: PullRequestNode): PullRequestWriteSnapshot {\n\tconst closedAt = node.state === 'MERGED' ? (node.mergedAt ?? node.closedAt) : node.closedAt;\n\treturn {\n\t\towner: node.repository.owner.login,\n\t\trepo: node.repository.name,\n\t\tnumber: node.number,\n\t\tnodeId: node.id,\n\t\turl: node.url,\n\t\ttitle: node.title,\n\t\tbody: node.body,\n\t\tstate: node.state === 'OPEN' ? 'open' : node.state === 'CLOSED' ? 'closed' : 'merged',\n\t\t...(node.state !== 'OPEN' && typeof closedAt === 'string' ? { closedAt: closedAt } : {}),\n\t\t...(typeof node.updatedAt === 'string' ? { updatedAt: node.updatedAt } : {}),\n\t\theadSha: node.headRefOid,\n\t\tbaseRef: node.baseRefName,\n\t};\n}\n\nasync function resolveNode(\n\tinput: GitHubPullRequestWriteTarget,\n\tgraphql: GraphqlRequest,\n): Promise<ResolvedPullRequest | PullRequestWriteFailure> {\n\tconst { owner, repo, expectedNodeId, number } = input;\n\tconst result = await graphql<{ repository: MergeRepository | null; node: WriteNode | null }>(\n\t\t`query PullRequestWriteTarget($owner: String!, $repo: String!, $expectedNodeId: ID!) {\n\t\t\trepository(owner: $owner, name: $repo, followRenames: false) {\n\t\t\t\t${repositoryFields}\n\t\t\t\tmergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerDefaultMergeMethod\n\t\t\t}\n\t\t\tnode(id: $expectedNodeId) {\n\t\t\t\t__typename\n\t\t\t\t... on PullRequest {\n\t\t\t\t\t${pullRequestFields}\n\t\t\t\t\tviewerCanUpdate viewerCanClose viewerCanReopen\n\t\t\t\t\tisDraft isInMergeQueue isMergeQueueEnabled\n\t\t\t\t\tstack { id }\n\t\t\t\t\tbaseRef { id }\n\t\t\t\t}\n\t\t\t}\n\t\t}`,\n\t\t{ owner: owner, repo: repo, expectedNodeId: expectedNodeId },\n\t);\n\tconst repository = result?.repository;\n\tconst node = result?.node;\n\tif (\n\t\trepository == null ||\n\t\t!sameRepository(input, repository) ||\n\t\tnode?.__typename !== 'PullRequest' ||\n\t\tnode.number !== number ||\n\t\tnode.repository.id !== repository.id\n\t) {\n\t\treturn { ok: false, reason: 'not-found' };\n\t}\n\n\treturn { ok: true, node: node, repository: repository };\n}\n\nasync function readBranchRules(\n\trefId: string,\n\tgraphql: GraphqlRequest,\n): Promise<{ rules: BranchRule[]; requiresLinearHistory: boolean } | undefined> {\n\ttype Response = {\n\t\tnode: {\n\t\t\tid: string;\n\t\t\trefUpdateRule: { requiresLinearHistory: boolean } | null;\n\t\t\trules: {\n\t\t\t\tnodes: (BranchRule | null)[] | null;\n\t\t\t\tpageInfo: { hasNextPage: boolean; endCursor: string | null };\n\t\t\t};\n\t\t} | null;\n\t};\n\tconst rules: BranchRule[] = [];\n\tconst seen = new Set<string>();\n\tlet requiresLinearHistory = false;\n\tlet cursor: string | undefined;\n\tfor (;;) {\n\t\tconst response = await graphql<Response>(\n\t\t\t`\n\t\t\t\tquery PullRequestBranchRules($id: ID!, $cursor: String) {\n\t\t\t\t\tnode(id: $id) {\n\t\t\t\t\t\t... on Ref {\n\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\trefUpdateRule {\n\t\t\t\t\t\t\t\trequiresLinearHistory\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trules(first: 100, after: $cursor) {\n\t\t\t\t\t\t\t\tnodes {\n\t\t\t\t\t\t\t\t\ttype\n\t\t\t\t\t\t\t\t\tparameters {\n\t\t\t\t\t\t\t\t\t\t... on PullRequestParameters {\n\t\t\t\t\t\t\t\t\t\t\tallowedMergeMethods\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpageInfo {\n\t\t\t\t\t\t\t\t\thasNextPage\n\t\t\t\t\t\t\t\t\tendCursor\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t`,\n\t\t\t{ id: refId, cursor: cursor },\n\t\t);\n\t\tconst ref = response?.node;\n\t\tconst page = ref?.rules;\n\t\tif (ref?.id !== refId || page?.nodes == null) return undefined;\n\n\t\trequiresLinearHistory ||= ref.refUpdateRule?.requiresLinearHistory === true;\n\n\t\tfor (const rule of page.nodes) {\n\t\t\tif (rule == null) return undefined;\n\n\t\t\trules.push(rule);\n\t\t}\n\n\t\tif (!page.pageInfo.hasNextPage) return { rules: rules, requiresLinearHistory: requiresLinearHistory };\n\n\t\tconst nextCursor = page.pageInfo.endCursor;\n\t\tif (nextCursor == null || seen.has(nextCursor)) return undefined;\n\n\t\tseen.add(nextCursor);\n\t\tcursor = nextCursor;\n\t}\n}\n\nasync function getMergeCapability(\n\t{ node, repository }: ResolvedPullRequest,\n\tgraphql: GraphqlRequest,\n): Promise<MergeCapability> {\n\tif (\n\t\t!isRepositoryWritable(repository) ||\n\t\tnode.state !== 'OPEN' ||\n\t\tnode.isDraft ||\n\t\tnode.isInMergeQueue ||\n\t\tnode.baseRef == null\n\t) {\n\t\treturn { kind: 'unavailable', reason: 'blocked' };\n\t}\n\n\tconst canWrite = hasWritePermission(repository);\n\tif (canWrite !== true) return { kind: 'unavailable', reason: canWrite === false ? 'forbidden' : 'unknown' };\n\tif (node.stack != null) return { kind: 'unavailable', reason: 'unsupported' };\n\tif (node.isMergeQueueEnabled) return { kind: 'queue' };\n\n\ttry {\n\t\tconst branch = await readBranchRules(node.baseRef.id, graphql);\n\t\tif (branch == null) return { kind: 'unavailable', reason: 'unknown' };\n\n\t\tconst { rules, requiresLinearHistory } = branch;\n\t\tif (rules.some(rule => rule.type === 'MERGE_QUEUE')) return { kind: 'queue' };\n\n\t\tconst linearHistory = requiresLinearHistory || rules.some(rule => rule.type === 'REQUIRED_LINEAR_HISTORY');\n\t\tconst methods = mergeMethods.filter(method => {\n\t\t\tconst allowed =\n\t\t\t\tmethod === 'merge'\n\t\t\t\t\t? repository.mergeCommitAllowed && !linearHistory\n\t\t\t\t\t: method === 'squash'\n\t\t\t\t\t\t? repository.squashMergeAllowed\n\t\t\t\t\t\t: repository.rebaseMergeAllowed;\n\t\t\treturn (\n\t\t\t\tallowed &&\n\t\t\t\trules.every(rule => {\n\t\t\t\t\tconst permitted = rule.type === 'PULL_REQUEST' ? rule.parameters?.allowedMergeMethods : undefined;\n\t\t\t\t\treturn permitted == null || permitted.some(allowedMethod => allowedMethod.toLowerCase() === method);\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\t\tif (methods.length === 0) return { kind: 'unavailable', reason: 'blocked' };\n\n\t\tconst preference = repository.viewerDefaultMergeMethod.toLowerCase();\n\t\tconst defaultMethod = methods.find(method => method === preference);\n\t\treturn { kind: 'direct', methods: methods, defaultMethod: defaultMethod };\n\t} catch (ex) {\n\t\treturn { kind: 'unavailable', reason: pullRequestWriteFailure(ex).reason };\n\t}\n}\n\nexport async function resolveGitHubPullRequestWriteTarget(\n\tinput: GitHubPullRequestWriteTarget,\n\tgraphql: GraphqlRequest,\n): Promise<PullRequestWriteTargetResult> {\n\tif (!isValidTarget(input)) return { ok: false, reason: 'invalid-input' };\n\n\ttry {\n\t\tconst resolved = await resolveNode(input, graphql);\n\t\tif (!resolved.ok) return resolved;\n\n\t\tconst { node, repository } = resolved;\n\t\tconst writable = isRepositoryWritable(repository);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tpullRequest: toSnapshot(node),\n\t\t\tcapabilities: {\n\t\t\t\tedit: writable && node.viewerCanUpdate,\n\t\t\t\tclose: writable && node.state === 'OPEN' && node.viewerCanClose,\n\t\t\t\treopen: writable && node.state === 'CLOSED' && node.viewerCanReopen,\n\t\t\t\tmerge: await getMergeCapability(resolved, graphql),\n\t\t\t},\n\t\t};\n\t} catch (ex) {\n\t\treturn pullRequestWriteFailure(ex);\n\t}\n}\n\nexport async function getGitHubPullRequestCreateCapability(\n\tinput: GitHubPullRequestCreateTarget,\n\tgraphql: GraphqlRequest,\n): Promise<PullRequestCreateCapabilityResult> {\n\tif (!isValidRepository(input)) return { ok: false, reason: 'invalid-input' };\n\n\ttry {\n\t\tconst result = await graphql<{ repository: RepositoryNode | null }>(\n\t\t\t`query PullRequestCreateCapability($owner: String!, $repo: String!) {\n\t\t\t\trepository(owner: $owner, name: $repo, followRenames: false) {\n\t\t\t\t\t${repositoryFields}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\t{ owner: input.owner, repo: input.repo },\n\t\t);\n\t\tconst repository = result?.repository;\n\t\tif (repository == null || !sameRepository(input, repository)) return { ok: false, reason: 'not-found' };\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\trepositoryId: repository.id,\n\t\t\t// A repository role only establishes read access. GitHub checks the chosen head branch and organization\n\t\t\t// membership when the pull request is created.\n\t\t\tcanCreate: isRepositoryWritable(repository) && (repository.viewerPermission == null ? undefined : true),\n\t\t};\n\t} catch (ex) {\n\t\treturn pullRequestWriteFailure(ex);\n\t}\n}\n\ntype WriteTransport = {\n\tgraphql: GraphqlRequest;\n\tisSessionCurrent: () => Promise<boolean>;\n\tenqueue: (nodeId: string, headSha: string) => Promise<PullRequestMergeQueueActionResult>;\n};\n\nconst mutations = {\n\tcreated: ['createPullRequest', 'CreatePullRequestInput'],\n\tupdated: ['updatePullRequest', 'UpdatePullRequestInput'],\n\tclosed: ['closePullRequest', 'ClosePullRequestInput'],\n\treopened: ['reopenPullRequest', 'ReopenPullRequestInput'],\n\tmerged: ['mergePullRequest', 'MergePullRequestInput'],\n} as const;\n\nasync function sendMutation(\n\ttransport: WriteTransport,\n\tstatus: keyof typeof mutations,\n\trepositoryId: string,\n\tvalues: Record<string, string | undefined>,\n\tprevious?: PullRequestNode,\n): Promise<PullRequestWriteResult> {\n\tif (!(await transport.isSessionCurrent())) return { ok: false, reason: 'no-connection' };\n\n\tconst [mutation, inputType] = mutations[status];\n\ttype Payload = { change: { pullRequest: PullRequestNode | null } | null };\n\tlet node: PullRequestNode | null | undefined;\n\ttry {\n\t\tconst response = await transport.graphql<Payload>(\n\t\t\t`mutation WritePullRequest($input: ${inputType}!) {\n\t\t\t\tchange: ${mutation}(input: $input) { pullRequest { ${pullRequestFields} } }\n\t\t\t}`,\n\t\t\t{ input: values },\n\t\t);\n\t\tnode = response?.change?.pullRequest;\n\t} catch (ex) {\n\t\tif (ex instanceof GraphqlResponseError) {\n\t\t\tnode = (ex.data as Payload | undefined)?.change?.pullRequest;\n\t\t\tif (node == null && ex.errors?.some(error => error.path?.[0] === 'change' && error.path.length > 1)) {\n\t\t\t\treturn { ok: false, reason: 'outcome-unknown' };\n\t\t\t}\n\t\t}\n\n\t\tif (node == null) return pullRequestWriteFailure(ex, status === 'merged' ? 'merge' : 'write');\n\t}\n\n\tconst expectedState =\n\t\tstatus === 'created' || status === 'reopened'\n\t\t\t? 'OPEN'\n\t\t\t: status === 'closed'\n\t\t\t\t? 'CLOSED'\n\t\t\t\t: status === 'merged'\n\t\t\t\t\t? 'MERGED'\n\t\t\t\t\t: undefined;\n\tif (\n\t\tnode?.repository?.id !== repositoryId ||\n\t\t(previous != null && (node.id !== previous.id || node.number !== previous.number)) ||\n\t\t(expectedState != null && node.state !== expectedState) ||\n\t\ttypeof node.repository.owner?.login !== 'string' ||\n\t\ttypeof node.repository.name !== 'string' ||\n\t\ttypeof node.id !== 'string' ||\n\t\t!Number.isInteger(node.number) ||\n\t\ttypeof node.url !== 'string' ||\n\t\ttypeof node.title !== 'string' ||\n\t\ttypeof node.body !== 'string' ||\n\t\ttypeof node.headRefOid !== 'string' ||\n\t\ttypeof node.baseRefName !== 'string' ||\n\t\t(node.state !== 'OPEN' && node.state !== 'CLOSED' && node.state !== 'MERGED')\n\t) {\n\t\treturn { ok: false, reason: 'outcome-unknown' };\n\t}\n\n\treturn { ok: true, status: status, pullRequest: toSnapshot(node) };\n}\n\nasync function createPullRequest(\n\tinput: Extract<GitHubPullRequestWrite, { action: 'create' }>,\n\ttransport: WriteTransport,\n): Promise<PullRequestWriteResult> {\n\ttype CreateRepository = RepositoryNode & { base: { id: string } | null; head: { id: string } | null };\n\tconst result = await transport.graphql<{ repository: CreateRepository | null }>(\n\t\t`query PullRequestCreateTarget($owner: String!, $repo: String!, $base: String!, $head: String!) {\n\t\t\trepository(owner: $owner, name: $repo, followRenames: false) {\n\t\t\t\t${repositoryFields}\n\t\t\t\tbase: ref(qualifiedName: $base) { id }\n\t\t\t\thead: ref(qualifiedName: $head) { id }\n\t\t\t}\n\t\t}`,\n\t\t{\n\t\t\towner: input.owner,\n\t\t\trepo: input.repo,\n\t\t\tbase: `refs/heads/${input.baseRef}`,\n\t\t\thead: `refs/heads/${input.headRef}`,\n\t\t},\n\t);\n\tconst repository = result?.repository;\n\tif (\n\t\trepository == null ||\n\t\t!sameRepository(input, repository) ||\n\t\t(input.expectedRepositoryId != null && input.expectedRepositoryId !== repository.id)\n\t) {\n\t\treturn { ok: false, reason: 'not-found' };\n\t}\n\n\tif (!isRepositoryWritable(repository)) return { ok: false, reason: 'blocked' };\n\tif (repository.base == null || repository.head == null) return { ok: false, reason: 'invalid-input' };\n\n\treturn sendMutation(transport, 'created', repository.id, {\n\t\trepositoryId: repository.id,\n\t\tbaseRefName: input.baseRef,\n\t\theadRefName: input.headRef,\n\t\ttitle: input.title,\n\t\tbody: input.body,\n\t});\n}\n\nasync function mergePullRequest(\n\tinput: Extract<GitHubPullRequestWrite, { action: 'merge' | 'enqueue' }>,\n\tresolved: ResolvedPullRequest,\n\ttransport: WriteTransport,\n): Promise<PullRequestWriteResult> {\n\tconst { node, repository } = resolved;\n\tif (node.headRefOid.toLowerCase() !== input.expectedHeadSha.toLowerCase()) {\n\t\treturn { ok: false, reason: 'head-changed' };\n\t}\n\n\tif (node.baseRefName !== input.expectedBaseRef) return { ok: false, reason: 'base-changed' };\n\n\tconst capability = await getMergeCapability(resolved, transport.graphql);\n\tif (capability.kind === 'unavailable') return { ok: false, reason: capability.reason };\n\n\tif (input.action === 'merge') {\n\t\tif (capability.kind !== 'direct' || !capability.methods.includes(input.mergeMethod)) {\n\t\t\treturn { ok: false, reason: 'blocked' };\n\t\t}\n\n\t\treturn sendMutation(\n\t\t\ttransport,\n\t\t\t'merged',\n\t\t\trepository.id,\n\t\t\t{ pullRequestId: node.id, expectedHeadOid: node.headRefOid, mergeMethod: input.mergeMethod.toUpperCase() },\n\t\t\tnode,\n\t\t);\n\t}\n\n\tif (capability.kind !== 'queue') return { ok: false, reason: 'blocked' };\n\tif (!(await transport.isSessionCurrent())) return { ok: false, reason: 'no-connection' };\n\n\ttry {\n\t\tconst result = await transport.enqueue(node.id, node.headRefOid);\n\t\tif (result.status === 'queued' && result.entry != null) {\n\t\t\treturn { ok: true, status: 'queued', pullRequest: toSnapshot(node) };\n\t\t}\n\n\t\tif (result.status !== 'failed') return { ok: false, reason: 'outcome-unknown' };\n\n\t\tswitch (result.reason) {\n\t\t\tcase 'permission':\n\t\t\t\treturn { ok: false, reason: 'forbidden' };\n\t\t\tcase 'already-queued':\n\t\t\tcase 'not-allowed':\n\t\t\t\treturn { ok: false, reason: 'blocked' };\n\t\t\tcase 'head-changed':\n\t\t\tcase 'unsupported':\n\t\t\t\treturn { ok: false, reason: result.reason };\n\t\t\tdefault:\n\t\t\t\treturn { ok: false, reason: 'outcome-unknown' };\n\t\t}\n\t} catch (ex) {\n\t\treturn pullRequestWriteFailure(ex, 'enqueue');\n\t}\n}\n\nexport async function writeGitHubPullRequest(\n\tinput: GitHubPullRequestWrite,\n\ttransport: WriteTransport,\n): Promise<PullRequestWriteResult> {\n\tif (!isValidWrite(input)) return { ok: false, reason: 'invalid-input' };\n\n\ttry {\n\t\tif (input.action === 'create') return await createPullRequest(input, transport);\n\n\t\tconst resolved = await resolveNode(input, transport.graphql);\n\t\tif (!resolved.ok) return resolved;\n\n\t\tconst { node, repository } = resolved;\n\t\tif (!isRepositoryWritable(repository)) return { ok: false, reason: 'blocked' };\n\t\tif (input.action === 'merge' || input.action === 'enqueue') {\n\t\t\treturn await mergePullRequest(input, resolved, transport);\n\t\t}\n\n\t\tif (input.action === 'edit') {\n\t\t\tif (!node.viewerCanUpdate) return { ok: false, reason: 'forbidden' };\n\n\t\t\treturn await sendMutation(\n\t\t\t\ttransport,\n\t\t\t\t'updated',\n\t\t\t\trepository.id,\n\t\t\t\t{ pullRequestId: node.id, title: input.title, body: input.body },\n\t\t\t\tnode,\n\t\t\t);\n\t\t}\n\n\t\tconst close = input.state === 'closed';\n\t\tif (node.state !== (close ? 'OPEN' : 'CLOSED')) return { ok: false, reason: 'blocked' };\n\t\tif (close ? !node.viewerCanClose : !node.viewerCanReopen) return { ok: false, reason: 'forbidden' };\n\n\t\treturn await sendMutation(\n\t\t\ttransport,\n\t\t\tclose ? 'closed' : 'reopened',\n\t\t\trepository.id,\n\t\t\t{ pullRequestId: node.id },\n\t\t\tnode,\n\t\t);\n\t} catch (ex) {\n\t\treturn pullRequestWriteFailure(ex);\n\t}\n}\n"],"mappings":";;;;AA2IA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB,GAAG,mBAAmB;AAC/C,MAAM,oBAAoB;;gBAEV,mBAAmB;;AAEnC,MAAM,eAAuC;CAAC;CAAS;CAAU;AAAQ;AAEzE,SAAS,kBAAkB,EAAE,OAAO,QAAgD;CACnF,OACC,OAAO,UAAU,YACjB,gBAAgB,KAAK,KAAK,KAC1B,OAAO,SAAS,YAChB,iBAAiB,KAAK,IAAI,KAC1B,SAAS,OACT,SAAS;AAEX;AAEA,SAAS,cAAc,OAA8C;CACpE,OACC,kBAAkB,KAAK,KACvB,OAAO,UAAU,MAAM,MAAM,KAC7B,MAAM,UAAU,KAChB,MAAM,UAAU,cAChB,OAAO,MAAM,mBAAmB,YAChC,MAAM,eAAe,KAAK,CAAC,CAAC,SAAS;AAEvC;AAEA,SAAS,aAAa,OAAiC;CACtD,OACC,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,KAAK,MAAM,SACjB,CAAC,MAAM,SAAS,GAAG,KACnB,CAAC,MAAM,WAAW,OAAO,KACzB,CAAC,MAAM,WAAW,GAAG;AAEvB;AAEA,SAAS,QAAQ,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC3D;AAEA,SAAS,aAAa,OAAwC;CAC7D,IAAI,MAAM,WAAW,UACpB,OACC,kBAAkB,KAAK,KACvB,QAAQ,MAAM,KAAK,MAClB,MAAM,SAAS,KAAA,KAAa,OAAO,MAAM,SAAS,cAClD,MAAM,yBAAyB,KAAA,K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IAAI,KAAK,WAAW,QAAQ,SAAS,WAAW,OAAO;GAAE,IAAI;GAAO,QAAQ;EAAU;EACtF,IAAI,QAAQ,CAAC,KAAK,iBAAiB,CAAC,KAAK,iBAAiB,OAAO;GAAE,IAAI;GAAO,QAAQ;EAAY;EAElG,OAAO,MAAM,aACZ,WACA,QAAQ,WAAW,YACnB,WAAW,IACX,EAAE,eAAe,KAAK,GAAG,GACzB,IACD;CACD,SAAS,IAAI;EACZ,OAAO,wBAAwB,EAAE;CAClC;AACD"}
@@ -28,7 +28,7 @@ export declare class ConfiguredIntegrationService implements Disposable {
28
28
  private readonly _locks;
29
29
  /** Monotonic across providers; see {@link getSignOutMark}. */
30
30
  private _signOutEpoch;
31
- /** The epoch of the latest sign-out per scope: a provider, a self-managed host, or a single connection. */
31
+ /** The latest retirement of pending stores per provider, self-managed host, or connection. */
32
32
  private readonly _signOuts;
33
33
  get onDidChange(): Event<ConfiguredIntegrationsChangeEvent>;
34
34
  get onWillChangeSession(): Event<IntegrationSessionChangeEvent>;
@@ -46,21 +46,21 @@ export declare class ConfiguredIntegrationService implements Disposable {
46
46
  private removeConfigured;
47
47
  private withLock;
48
48
  /**
49
- * Taken before a token is read or fetched, and handed to {@link storeSession}: a sign-out that lands after it
50
- * (a disconnect, a reauthentication, the connection being removed) refuses the store, so a token fetched across
51
- * it is not written back and reconnected on the next resolution (gitkraken/kepler#3546).
49
+ * Taken before a token is read or fetched and handed to {@link storeSession}. A later sign-out or a recovery
50
+ * that replaces the credential invalidates the pending store.
52
51
  */
53
52
  getSignOutMark(): number;
54
- private markSignOut;
53
+ private retirePendingStores;
55
54
  private getHostScope;
56
- private isSignedOutSince;
55
+ isSessionRetiredSince(id: IntegrationIds, session: Pick<ProviderAuthenticationSession, 'id' | 'domain'>, mark: number): boolean;
57
56
  /**
58
- * Stores the session's secret and descriptor together. With a `signOutMark`, nothing is stored, and `false` is
59
- * returned, when a sign-out covering the session landed after the mark was taken.
57
+ * Stores the session's secret and descriptor together. A pending store can be invalidated by a sign-out or a
58
+ * credential recovery. A recovery must still own the stored credential when it publishes its replacement.
60
59
  */
61
60
  storeSession(id: IntegrationIds, session: ProviderAuthenticationSession, options?: {
62
61
  signOutMark?: number;
63
62
  resource?: ConnectionResource;
63
+ expectedStoredAccessToken?: string;
64
64
  }): Promise<boolean>;
65
65
  getStoredSession(id: IntegrationIds, descriptor: IntegrationAuthenticationSessionDescriptor): Promise<ProviderAuthenticationSession | undefined>;
66
66
  /**
@@ -71,7 +71,8 @@ export declare class ConfiguredIntegrationService implements Disposable {
71
71
  deleteStoredSessions(id: IntegrationIds, descriptor: IntegrationAuthenticationSessionDescriptor, cloud?: boolean, options?: {
72
72
  preserveConfigured?: boolean;
73
73
  signOut?: boolean;
74
- }): Promise<void>;
74
+ signOutMark?: number;
75
+ }): Promise<boolean>;
75
76
  /** Signs out of every stored session of the provider, or of one self-managed host when `domain` is given. */
76
77
  deleteAllStoredSessions(id: IntegrationIds, cloud?: boolean, domain?: string): Promise<void>;
77
78
  /**