@gitkraken/core-gitlens 0.51.1 → 0.53.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 (71) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/_types/provider-apis/types/exportedTypes/github.d.ts +75 -0
  3. package/dist/_types/provider-apis/types/exportedTypes/types.d.ts +7 -0
  4. package/dist/git-cli/providers/config.js +2 -2
  5. package/dist/git-cli/providers/pausedOperations.js +2 -2
  6. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  7. package/dist/git-cli/providers/staging.js +1 -1
  8. package/dist/ipc/discovery.js +1 -1
  9. package/dist/plus/agents/providers/claudeCodeTranscript.js +6 -6
  10. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -1
  11. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -1
  12. package/dist/plus/git-github/api/issueWrites.js +1 -1
  13. package/dist/plus/git-github/api/issueWrites.js.map +1 -1
  14. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.d.ts +10 -1
  15. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js +75 -23
  16. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js.map +1 -1
  17. package/dist/plus/integrations/authentication/cloudIntegrationObservations.d.ts +49 -0
  18. package/dist/plus/integrations/authentication/cloudIntegrationObservations.js +118 -0
  19. package/dist/plus/integrations/authentication/cloudIntegrationObservations.js.map +1 -0
  20. package/dist/plus/integrations/authentication/configuredIntegrationService.d.ts +45 -25
  21. package/dist/plus/integrations/authentication/configuredIntegrationService.js +409 -141
  22. package/dist/plus/integrations/authentication/configuredIntegrationService.js.map +1 -1
  23. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +12 -3
  24. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +39 -7
  25. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  26. package/dist/plus/integrations/authentication/models.d.ts +6 -0
  27. package/dist/plus/integrations/authentication/models.js +9 -1
  28. package/dist/plus/integrations/authentication/models.js.map +1 -1
  29. package/dist/plus/integrations/authentication/observedAuthenticationProvider.d.ts +17 -2
  30. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js +84 -16
  31. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js.map +1 -1
  32. package/dist/plus/integrations/index.d.ts +3 -2
  33. package/dist/plus/integrations/index.js.map +1 -1
  34. package/dist/plus/integrations/integrationService.d.ts +9 -0
  35. package/dist/plus/integrations/integrationService.js +182 -39
  36. package/dist/plus/integrations/integrationService.js.map +1 -1
  37. package/dist/plus/integrations/manager.d.ts +3 -0
  38. package/dist/plus/integrations/models/integration.d.ts +4 -0
  39. package/dist/plus/integrations/models/integration.js +61 -16
  40. package/dist/plus/integrations/models/integration.js.map +1 -1
  41. package/dist/plus/integrations/models/issueRelationships.d.ts +31 -0
  42. package/dist/plus/integrations/models/issueRelationships.js +0 -0
  43. package/dist/plus/integrations/models/workItemWrites.d.ts +34 -2
  44. package/dist/plus/integrations/providers/azure/azure.js +1 -1
  45. package/dist/plus/integrations/providers/azureDevOps.d.ts +4 -3
  46. package/dist/plus/integrations/providers/azureDevOps.js +6 -6
  47. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  48. package/dist/plus/integrations/providers/azureDevOpsServer.d.ts +3 -0
  49. package/dist/plus/integrations/providers/azureDevOpsServer.js +14 -0
  50. package/dist/plus/integrations/providers/azureDevOpsServer.js.map +1 -1
  51. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.d.ts +4 -0
  52. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js +34 -2
  53. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js.map +1 -1
  54. package/dist/plus/integrations/providers/azureWorkItemWrites.d.ts +5 -2
  55. package/dist/plus/integrations/providers/azureWorkItemWrites.js +57 -14
  56. package/dist/plus/integrations/providers/azureWorkItemWrites.js.map +1 -1
  57. package/dist/plus/integrations/providers/github.d.ts +8 -0
  58. package/dist/plus/integrations/providers/github.js +162 -2
  59. package/dist/plus/integrations/providers/github.js.map +1 -1
  60. package/dist/plus/integrations/providers/providerApiClient.d.ts +1 -1
  61. package/dist/plus/integrations/providers/providerApiClient.js +33 -14
  62. package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
  63. package/dist/plus/integrations/providers/providerErrors.d.ts +1 -0
  64. package/dist/plus/integrations/providers/providerErrors.js +1 -2
  65. package/dist/plus/integrations/providers/providerErrors.js.map +1 -1
  66. package/dist/plus/integrations/providers/providersApi.d.ts +10 -4
  67. package/dist/plus/integrations/providers/providersApi.js +21 -0
  68. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  69. package/dist/utils/env/node/exec.js +2 -2
  70. package/docs/integrations.md +61 -0
  71. package/package.json +2 -2
@@ -1,33 +1,29 @@
1
1
  import { flatten } from "../../../utils/iterable.js";
2
2
  import { Emitter } from "../../../utils/event.js";
3
3
  import { debounce } from "../../../utils/debounce.js";
4
+ import "../constants.js";
4
5
  import { providersMetadata } from "../providers/metadata.js";
5
6
  import { areDomainsOnSameHost, baseUrlFromDomain, hostFromDomain, sameConfiguredBaseUrl } from "../utils/domain.utils.js";
6
7
  import { isSelfManagedHostIntegrationId } from "../utils/integration.utils.js";
7
- import { getSessionIdentity } from "./models.js";
8
+ import { getSessionIdentity, getSupportedCloudIntegrationIds, isSameAuthenticationSession, sessionExpiry } from "./models.js";
9
+ import { CloudIntegrationObservations } from "./cloudIntegrationObservations.js";
8
10
  //#region ../plus/integrations/src/authentication/configuredIntegrationService.ts
9
- const storedWriteRetirements = /* @__PURE__ */ new WeakMap();
11
+ const cloudLogoutKey = "integrations:cloudLogout";
12
+ const configuredStorageState = /* @__PURE__ */ new WeakMap();
10
13
  var ConfiguredIntegrationService = class {
11
14
  ctx;
12
15
  _onDidChange = new Emitter();
13
16
  _onWillChangeSession = new Emitter();
14
17
  _onWillRemoveSessions = new Emitter();
15
- storeConfiguredQueue = Promise.resolve();
16
- /**
17
- * One provider's secret and descriptor mutations run one at a time, so a sign-out never interleaves with a
18
- * token being stored: storing writes the secret and then registers its descriptor, and a delete in between would
19
- * miss a connection it cannot see yet, or be undone by the pending write (#5948).
20
- */
21
- _locks = /* @__PURE__ */ new Map();
22
- /** Monotonic across providers; see {@link getSignOutMark}. */
23
- _signOutEpoch = 0;
24
- /** The latest retirement of pending stores per provider, self-managed host, or connection. */
25
- _signOuts = /* @__PURE__ */ new Map();
26
- _storedWriteRetirements;
18
+ _acquisitions = /* @__PURE__ */ new Map();
19
+ state;
27
20
  _disposed = false;
28
21
  get onDidChange() {
29
22
  return this._onDidChange.event;
30
23
  }
24
+ get onCloudLogout() {
25
+ return this.state.onCloudLogout.event;
26
+ }
31
27
  get onWillChangeSession() {
32
28
  return this._onWillChangeSession.event;
33
29
  }
@@ -36,15 +32,23 @@ var ConfiguredIntegrationService = class {
36
32
  }
37
33
  constructor(ctx) {
38
34
  this.ctx = ctx;
39
- let retirements = storedWriteRetirements.get(ctx.storage);
40
- if (retirements == null) {
41
- retirements = {
35
+ let state = configuredStorageState.get(ctx.storage);
36
+ if (state == null) {
37
+ state = {
38
+ persistence: Promise.resolve(),
39
+ locks: /* @__PURE__ */ new Map(),
42
40
  epoch: 0,
43
- scopes: /* @__PURE__ */ new Map()
41
+ scopes: /* @__PURE__ */ new Map(),
42
+ signOuts: /* @__PURE__ */ new Map(),
43
+ publications: /* @__PURE__ */ new Map(),
44
+ removals: /* @__PURE__ */ new Map(),
45
+ cloud: new CloudIntegrationObservations(ctx.storage.get(cloudLogoutKey)),
46
+ onCloudLogout: new Emitter(),
47
+ expiries: /* @__PURE__ */ new Map()
44
48
  };
45
- storedWriteRetirements.set(ctx.storage, retirements);
49
+ configuredStorageState.set(ctx.storage, state);
46
50
  }
47
- this._storedWriteRetirements = retirements;
51
+ this.state = state;
48
52
  }
49
53
  dispose() {
50
54
  this._disposed = true;
@@ -52,10 +56,9 @@ var ConfiguredIntegrationService = class {
52
56
  this._onWillChangeSession.dispose();
53
57
  this._onWillRemoveSessions.dispose();
54
58
  }
55
- _configured;
56
59
  get configured() {
57
- if (this._configured == null) {
58
- this._configured = /* @__PURE__ */ new Map();
60
+ if (this.state.configured == null) {
61
+ this.state.configured = /* @__PURE__ */ new Map();
59
62
  const storedConfigured = this.ctx.storage.get("integrations:configured");
60
63
  for (const [id, configured] of Object.entries(storedConfigured ?? {})) {
61
64
  if (configured == null) continue;
@@ -66,10 +69,10 @@ var ConfiguredIntegrationService = class {
66
69
  id: d.id || d.domain || providersMetadata[id]?.domain || id,
67
70
  expiresAt: d.expiresAt ? new Date(d.expiresAt) : void 0
68
71
  }));
69
- this._configured.set(id, descriptors);
72
+ this.state.configured.set(id, descriptors);
70
73
  }
71
74
  }
72
- return this._configured;
75
+ return this.state.configured;
73
76
  }
74
77
  getConfigured(id, options) {
75
78
  const descriptors = [];
@@ -82,15 +85,21 @@ var ConfiguredIntegrationService = class {
82
85
  else descriptors.push(...configured);
83
86
  return descriptors;
84
87
  }
85
- async storeConfigured() {
86
- const configured = {};
87
- for (const [id, descriptors] of this.configured) configured[id] = descriptors.map((d) => ({
88
- ...d,
89
- expiresAt: d.expiresAt ? d.expiresAt instanceof Date ? d.expiresAt.toISOString() : d.expiresAt : void 0
90
- }));
91
- const pending = this.storeConfiguredQueue.then(() => this.ctx.storage.store("integrations:configured", configured));
92
- this.storeConfiguredQueue = pending.catch(() => {});
93
- await pending;
88
+ storeConfigured(id, descriptors) {
89
+ const pending = this.state.persistence.then(async () => {
90
+ const updated = new Map(this.configured);
91
+ if (descriptors == null) updated.delete(id);
92
+ else updated.set(id, descriptors);
93
+ const record = {};
94
+ for (const [providerId, connections] of updated) record[providerId] = connections.map((connection) => ({
95
+ ...connection,
96
+ expiresAt: connection.expiresAt instanceof Date ? connection.expiresAt.toISOString() : connection.expiresAt
97
+ }));
98
+ await this.ctx.storage.store("integrations:configured", record);
99
+ this.state.configured = updated;
100
+ });
101
+ this.state.persistence = pending.catch(() => {});
102
+ return pending;
94
103
  }
95
104
  async addOrUpdateConfigured(descriptor) {
96
105
  descriptor = {
@@ -98,7 +107,7 @@ var ConfiguredIntegrationService = class {
98
107
  baseUrl: isSelfManagedHostIntegrationId(descriptor.integrationId) ? getStoredBaseUrl(descriptor.baseUrl, descriptor.domain) : descriptor.baseUrl,
99
108
  domain: this.normalizeConfiguredDomain(descriptor.integrationId, descriptor.domain)
100
109
  };
101
- const descriptors = this.configured.get(descriptor.integrationId) ?? [];
110
+ const descriptors = [...this.configured.get(descriptor.integrationId) ?? []];
102
111
  const existing = descriptors.find((d) => d.id === descriptor.id && d.cloud === descriptor.cloud);
103
112
  const primaryScope = this.getPrimaryScope(descriptor.integrationId, descriptors, descriptor.domain);
104
113
  const primary = descriptor.primary ?? existing?.primary ?? !primaryScope.some((d) => d.primary);
@@ -120,9 +129,8 @@ var ConfiguredIntegrationService = class {
120
129
  descriptors.splice(descriptors.indexOf(existing), 1);
121
130
  } else changed = true;
122
131
  descriptors.push(normalized);
123
- this.configured.set(descriptor.integrationId, descriptors);
132
+ await this.storeConfigured(descriptor.integrationId, descriptors);
124
133
  if (changed) this.fireChange(descriptor.integrationId);
125
- await this.storeConfigured();
126
134
  }
127
135
  async removeConfigured(id, options) {
128
136
  const existing = this.configured.get(id);
@@ -145,16 +153,47 @@ var ConfiguredIntegrationService = class {
145
153
  primary: true
146
154
  };
147
155
  }
148
- this.configured.set(id, descriptors);
156
+ await this.storeConfigured(id, descriptors);
149
157
  this.fireChange(void 0, id);
150
- await this.storeConfigured();
151
158
  }
152
159
  withLock(id, fn) {
153
- const run = (this._locks.get(id) ?? Promise.resolve()).then(fn);
160
+ const locks = this.state.locks;
161
+ const run = (locks.get(id) ?? Promise.resolve()).then(fn);
154
162
  const settled = run.then(() => void 0, () => void 0);
155
- this._locks.set(id, settled);
163
+ locks.set(id, settled);
156
164
  settled.then(() => {
157
- if (this._locks.get(id) === settled) this._locks.delete(id);
165
+ if (locks.get(id) === settled) locks.delete(id);
166
+ });
167
+ return run;
168
+ }
169
+ serializesCredentialAcquisition(id) {
170
+ return id === "azure-devops-server";
171
+ }
172
+ /**
173
+ * KEEP: not reentrant. A `connectionId` acquisition waits for that connection's and every earlier unscoped one;
174
+ * an unscoped acquisition waits for every earlier acquisition of `id`.
175
+ */
176
+ withCredentialAcquisition(id, connectionId, fn) {
177
+ if (!this.serializesCredentialAcquisition(id)) return fn();
178
+ let queue = this._acquisitions.get(id);
179
+ if (queue == null) {
180
+ queue = { connections: /* @__PURE__ */ new Map() };
181
+ this._acquisitions.set(id, queue);
182
+ }
183
+ const predecessors = (connectionId != null ? [queue.unscoped, queue.connections.get(connectionId)] : [queue.unscoped, ...queue.connections.values()]).filter((p) => p != null);
184
+ const run = Promise.all(predecessors).then(() => fn());
185
+ const settled = run.then(() => void 0, () => void 0);
186
+ if (connectionId != null) queue.connections.set(connectionId, settled);
187
+ else {
188
+ queue.unscoped = settled;
189
+ queue.connections.clear();
190
+ }
191
+ const current = queue;
192
+ settled.then(() => {
193
+ if (connectionId != null) {
194
+ if (current.connections.get(connectionId) === settled) current.connections.delete(connectionId);
195
+ } else if (current.unscoped === settled) current.unscoped = void 0;
196
+ if (current.unscoped == null && current.connections.size === 0 && this._acquisitions.get(id) === current) this._acquisitions.delete(id);
158
197
  });
159
198
  return run;
160
199
  }
@@ -163,30 +202,180 @@ var ConfiguredIntegrationService = class {
163
202
  * that replaces the credential invalidates the pending store.
164
203
  */
165
204
  getSignOutMark() {
166
- return this._signOutEpoch;
205
+ return ++this.state.epoch;
206
+ }
207
+ retirePendingStores(scope, cloud) {
208
+ this.retireStoredWrites(scope, cloud);
209
+ this.state.signOuts.set(cloud == null ? scope : `${scope}|${cloud}`, this.getStoredWriteMark());
210
+ }
211
+ beginCloudSync() {
212
+ return ++this.state.epoch;
213
+ }
214
+ get lastCloudLogout() {
215
+ return this.state.cloud.lastLogout;
216
+ }
217
+ get hasCloudLogout() {
218
+ return this.state.cloud.hasLogout;
219
+ }
220
+ async retireCloudAccount(mark) {
221
+ if (this._disposed) return void 0;
222
+ const connections = this.getConfigured(void 0, { cloud: true });
223
+ const sync = this.state.cloud.acceptLogout(mark, ++this.state.epoch, connections);
224
+ if (sync == null) return void 0;
225
+ const persist = this.persistCloudLogout();
226
+ const departing = connections.map((c) => ({
227
+ ...c,
228
+ retained: this.state.cloud.acquiredAfter(`${c.integrationId}|connection:${c.id}`, mark)
229
+ }));
230
+ const cleanup = getSupportedCloudIntegrationIds().map((id) => this.withLock(id, () => this.clearDepartedCloudCredentials(id, mark, sync.mark)));
231
+ this.state.onCloudLogout.fire(departing);
232
+ const failure = (await Promise.allSettled([persist, ...cleanup])).find((result) => result.status === "rejected");
233
+ if (failure != null) throw failure.reason;
234
+ return this._disposed ? void 0 : sync;
235
+ }
236
+ persistCloudLogout() {
237
+ const pending = this.state.persistence.then(() => this.ctx.storage.store(cloudLogoutKey, this.state.cloud.snapshotLogout()));
238
+ this.state.persistence = pending.catch(() => {});
239
+ return pending;
240
+ }
241
+ async clearDepartedCloudCredentials(id, cutoff, logout) {
242
+ const connections = this.getConfigured(id);
243
+ const ids = new Set(connections.map((c) => c.id));
244
+ ids.add(providersMetadata[id]?.domain || id);
245
+ const failures = [];
246
+ for (const connectionId of ids) try {
247
+ const localKey = this.getLocalSecretKey(id, connectionId);
248
+ const raw = await this.ctx.storage.getSecret(localKey);
249
+ if (raw != null && isLegacyCloudSecret(raw)) {
250
+ await this.ctx.storage.deleteSecret(localKey);
251
+ await this.removeConfigured(id, {
252
+ connectionId,
253
+ cloud: false
254
+ });
255
+ }
256
+ const scope = `${id}|connection:${connectionId}`;
257
+ if (this.state.cloud.acquiredAfter(scope, cutoff)) continue;
258
+ const departed = connections.find((c) => c.id === connectionId && c.cloud);
259
+ if (departed != null && this.state.cloud.depart(id, departed.domain, connectionId, logout)) await this.persistCloudLogout();
260
+ try {
261
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
262
+ } finally {
263
+ this.state.cloud.remove(scope);
264
+ await this.removeConfigured(id, {
265
+ connectionId,
266
+ cloud: true
267
+ });
268
+ }
269
+ } catch (ex) {
270
+ failures.push(ex);
271
+ }
272
+ if (failures.length) throw new AggregateError(failures, "Unable to clear retired cloud credentials.");
273
+ }
274
+ getCloudDeparture(id, session) {
275
+ return session.cloud ? this.state.cloud.departedAt(id, session.domain, session.id) : void 0;
276
+ }
277
+ confirmHostCloudSession(id, session, logout) {
278
+ return this.withLock(id, async () => {
279
+ if (this._disposed) return false;
280
+ const departure = this.getCloudDeparture(id, session);
281
+ if (departure != null && logout < departure) return false;
282
+ const stored = await this.peekSecret(id, session.id, true, session.domain);
283
+ if (this._disposed || logout !== this.lastCloudLogout || stored === null) return false;
284
+ if (stored === void 0) return departure == null && !this.getConfigured(id, {
285
+ cloud: true,
286
+ domain: isSelfManagedHostIntegrationId(id) ? session.domain : void 0
287
+ }).some((c) => c.id === session.id);
288
+ return stored.id === session.id && stored.cloud && stored.accessToken === session.accessToken && (!stored.account.id || stored.account.id === session.account.id);
289
+ });
167
290
  }
168
- retirePendingStores(scope) {
169
- this._signOuts.set(scope, ++this._signOutEpoch);
170
- this.retireStoredWrites(scope);
291
+ async acceptCloudSync(mark, connections) {
292
+ if (this._disposed) return void 0;
293
+ const sync = this.state.cloud.accept(mark, connections);
294
+ if (sync == null) return void 0;
295
+ await Promise.all(this.state.locks.values());
296
+ return !this._disposed && sync.isCurrent() ? sync : void 0;
297
+ }
298
+ supersedingPrimary(id, session, mark) {
299
+ return this.state.cloud.supersedingPrimary(id, session.domain, session.id, mark);
300
+ }
301
+ hasNewCloudConnection(id, domain, mark) {
302
+ const scopedDomain = isSelfManagedHostIntegrationId(id) ? domain : void 0;
303
+ return this.getConfigured(id, {
304
+ cloud: true,
305
+ domain: scopedDomain
306
+ }).some((c) => this.state.cloud.observedSince(`${id}|connection:${c.id}`, mark));
307
+ }
308
+ async dispatchHostListRetirement(id, domain, sync, retire) {
309
+ const dispatched = await this.withLock(id, () => {
310
+ if (this._disposed || !sync.isCurrent() || this.hasNewCloudConnection(id, domain, sync.mark)) return;
311
+ return { settled: retire() };
312
+ });
313
+ if (dispatched == null) return false;
314
+ await dispatched.settled;
315
+ return !this._disposed && sync.isCurrent() && !this.hasNewCloudConnection(id, domain, sync.mark);
171
316
  }
172
317
  getStoredWriteMark() {
173
- return this._storedWriteRetirements.epoch;
318
+ return this.state.epoch;
174
319
  }
175
320
  isStoredWriteRetiredSince(id, session, mark) {
176
- return this._disposed || this.hasRetirement(this._storedWriteRetirements.scopes, id, session, mark);
321
+ return this._disposed || session.cloud && this.state.cloud.loggedOutSince(mark) || this.hasRetirement(this.state.scopes, id, session, mark);
322
+ }
323
+ async captureConfiguredConnection(id, connectionId) {
324
+ const matches = this.getConfigured(id).filter((connection) => connection.id === connectionId);
325
+ const selected = matches.find((connection) => connection.cloud) ?? matches[0];
326
+ if (selected == null) return void 0;
327
+ const mark = this.state.epoch;
328
+ const scope = {
329
+ id: connectionId,
330
+ domain: selected.domain ?? "",
331
+ cloud: selected.cloud
332
+ };
333
+ const current = () => !this._disposed && !(selected.cloud && this.state.cloud.loggedOutSince(mark)) && !this.hasRetirement(this.state.removals, id, scope, mark) && this.configured.get(id)?.some((connection) => connection.id === connectionId && connection.cloud === selected.cloud) === true;
334
+ return this.withLock(id, async () => {
335
+ if (selected.cloud && this.hasCloudLogout && await this.peekSecret(id, connectionId, true, scope.domain) == null) return;
336
+ return current() ? current : void 0;
337
+ });
177
338
  }
178
- retireStoredWrites(scope) {
179
- const retirements = this._storedWriteRetirements;
180
- retirements.scopes.set(scope, ++retirements.epoch);
339
+ async duringRemoval(scope, cloud, remove) {
340
+ const key = cloud == null ? scope : `${scope}|${cloud}`;
341
+ this.retirePendingStores(scope, cloud);
342
+ this.state.removals.set(key, Infinity);
343
+ try {
344
+ await remove();
345
+ } finally {
346
+ const mark = ++this.state.epoch;
347
+ this.state.removals.set(key, mark);
348
+ this.state.signOuts.set(key, mark);
349
+ }
350
+ }
351
+ captureStoredRelationshipCurrency(id, session) {
352
+ return this.withLock(id, async () => {
353
+ const mark = this.getStoredWriteMark();
354
+ const stored = await this.peekSecret(id, session.id, session.cloud, session.domain);
355
+ if (this.isStoredWriteRetiredSince(id, session, mark) || stored == null || !isSameAuthenticationSession(stored, session)) return;
356
+ const scope = `${id}|connection:${session.id}|${session.cloud}`;
357
+ const expiries = this.state.expiries;
358
+ if (expiries.get(scope) === null) return void 0;
359
+ expiries.set(scope, sessionExpiry(stored.expiresAt));
360
+ return () => !this.isStoredWriteRetiredSince(id, session, mark) && (expiries.get(scope) ?? 0) > Date.now();
361
+ });
362
+ }
363
+ retireStoredWrites(scope, cloud) {
364
+ const retirements = this.state;
365
+ retirements.scopes.set(cloud == null ? scope : `${scope}|${cloud}`, ++retirements.epoch);
366
+ for (const variant of cloud == null ? [true, false] : [cloud]) {
367
+ const key = `${scope}|${variant}`;
368
+ if (retirements.expiries.get(key) !== null) retirements.expiries.delete(key);
369
+ }
181
370
  }
182
371
  getHostScope(id, domain) {
183
372
  return `${id}|host:${hostFromDomain(domain) ?? domain}`;
184
373
  }
185
- isSessionRetiredSince(id, session, mark) {
186
- return this.hasRetirement(this._signOuts, id, session, mark);
374
+ isSessionRetiredSince(id, session, mark, acquisitionMark = mark) {
375
+ return session.cloud !== false && !this.state.cloud.allows(this.state.cloud.origin(mark)) || this.hasRetirement(this.state.signOuts, id, session, mark) || this.hasRetirement(this.state.publications, id, session, acquisitionMark);
187
376
  }
188
377
  hasRetirement(scopes, id, session, mark) {
189
- const since = (scope) => (scopes.get(scope) ?? 0) > mark;
378
+ const since = (scope) => (scopes.get(scope) ?? 0) > mark || session.cloud !== false && (scopes.get(`${scope}|true`) ?? 0) > mark || session.cloud !== true && (scopes.get(`${scope}|false`) ?? 0) > mark;
190
379
  if (since(id)) return true;
191
380
  if (isSelfManagedHostIntegrationId(id) && session.domain && since(this.getHostScope(id, session.domain))) return true;
192
381
  return since(`${id}|connection:${session.id}`);
@@ -196,57 +385,105 @@ var ConfiguredIntegrationService = class {
196
385
  * credential recovery. A recovery must still own the stored credential when it publishes its replacement.
197
386
  */
198
387
  storeSession(id, session, options) {
388
+ const origin = session.cloud ? this.state.cloud.origin(options?.sync?.mark ?? options?.signOutMark ?? this.getSignOutMark()) : void 0;
199
389
  return this.withLock(id, async () => {
200
- if (options?.signOutMark != null && this.isSessionRetiredSince(id, session, options.signOutMark)) return false;
201
- const previous = await this.readSecret(id, session.id, session.cloud);
202
- if (options?.expectedStoredAccessToken != null && previous?.accessToken !== options.expectedStoredAccessToken) return false;
203
- if (getSessionIdentity(previous) !== getSessionIdentity(session)) {
204
- if (previous != null) this.retireStoredWrites(`${id}|connection:${session.id}`);
205
- this._onWillChangeSession.fire({
206
- integrationId: id,
207
- session,
208
- previousDomain: previous?.domain
209
- });
390
+ const canStore = () => !this._disposed && (origin == null || this.state.cloud.allows(origin)) && options?.sync?.isCurrent() !== false && (options?.signOutMark == null || !this.isSessionRetiredSince(id, session, options.signOutMark, options.acquisitionMark));
391
+ if (!canStore()) return false;
392
+ const scope = `${id}|connection:${session.id}`;
393
+ const expiryScope = `${scope}|${session.cloud}`;
394
+ const expiries = this.state.expiries;
395
+ const previous = await this.peekSecret(id, session.id, session.cloud, session.domain);
396
+ if (options?.primaryResponse === "legacy" && options.signOutMark != null && this.state.cloud.observedSince(scope, options.signOutMark) || !canStore() || options?.expectedStoredAccessToken != null && previous?.accessToken !== options.expectedStoredAccessToken) return false;
397
+ const changed = getSessionIdentity(previous) !== getSessionIdentity(session);
398
+ const replaced = changed || previous?.account?.id !== session.account?.id;
399
+ if (replaced) this.retireStoredWrites(scope, session.cloud);
400
+ if (changed) this._onWillChangeSession.fire({
401
+ integrationId: id,
402
+ session,
403
+ previousDomain: previous?.domain
404
+ });
405
+ if (!canStore()) return false;
406
+ const trackedExpiry = expiries.get(expiryScope);
407
+ const nextExpiry = sessionExpiry(session.expiresAt);
408
+ if (typeof trackedExpiry === "number") expiries.set(expiryScope, Math.min(trackedExpiry, nextExpiry));
409
+ const logoutAtDispatch = this.lastCloudLogout;
410
+ try {
411
+ await this.writeSecret(id, session, options?.resource, origin);
412
+ } catch (ex) {
413
+ if (origin != null && !this.state.cloud.allows(origin)) throw ex;
414
+ this.retirePendingStores(scope, session.cloud);
415
+ if (session.cloud) this.state.cloud.observe(scope, this.state.epoch);
416
+ expiries.set(expiryScope, null);
417
+ throw ex;
418
+ }
419
+ if (origin != null && !this.state.cloud.allows(origin)) return false;
420
+ if (origin != null) this.state.cloud.published(scope, origin.mark);
421
+ if (expiries.has(expiryScope)) expiries.set(expiryScope, nextExpiry);
422
+ if (replaced || nextExpiry !== sessionExpiry(previous?.expiresAt)) {
423
+ const mark = session.cloud && this.lastCloudLogout !== logoutAtDispatch ? this.lastCloudLogout : ++this.state.epoch;
424
+ this.state.publications.set(expiryScope, mark);
425
+ if (options?.expectedStoredAccessToken != null && session.accessToken !== options.expectedStoredAccessToken) this.state.signOuts.set(expiryScope, mark);
426
+ }
427
+ if (session.cloud && options?.primaryResponse !== "legacy") {
428
+ this.state.cloud.observe(scope, options?.sync?.isCurrent() === false ? options.sync.mark : ++this.state.epoch);
429
+ if (options?.primaryResponse === "named" && options.signOutMark != null && options.sync?.isCurrent() !== false && this.supersedingPrimary(id, session, options.signOutMark) == null) {
430
+ const primaryMark = ++this.state.epoch;
431
+ await this.setPrimaryConnectionCore(id, session.id);
432
+ this.state.cloud.observePrimary(id, session.domain, session.id, primaryMark);
433
+ }
210
434
  }
211
- await this.writeSecret(id, session, options?.resource);
212
- if (options?.expectedStoredAccessToken != null && session.accessToken !== options.expectedStoredAccessToken) this.retirePendingStores(`${id}|connection:${session.id}`);
213
435
  return true;
214
436
  });
215
437
  }
216
- async peekStoredSession(id, connectionId, cloud, domain) {
438
+ peekStoredSession(id, connectionId, cloud, domain) {
217
439
  return this.withLock(id, async () => {
218
- const json = await this.ctx.storage.getSecret(this.getSecretKey(id, connectionId, cloud));
219
- if (json == null) return void 0;
220
- try {
221
- return convertStoredSessionToSession(JSON.parse(json), {
222
- connectionId,
223
- domain,
224
- scopes: []
225
- }, cloud);
226
- } catch {
227
- return;
228
- }
440
+ if (this._disposed) return void 0;
441
+ const session = await this.peekSecret(id, connectionId, cloud, domain);
442
+ return this._disposed ? void 0 : session ?? void 0;
229
443
  });
230
444
  }
445
+ async peekSecret(id, connectionId, cloud, domain) {
446
+ const json = await this.ctx.storage.getSecret(this.getSecretKey(id, connectionId, cloud));
447
+ if (json == null) return void 0;
448
+ try {
449
+ const stored = JSON.parse(json);
450
+ if (this.isRetiredSecret(stored, cloud)) return null;
451
+ return convertStoredSessionToSession(stored, {
452
+ connectionId,
453
+ domain,
454
+ scopes: []
455
+ }, cloud);
456
+ } catch {
457
+ return;
458
+ }
459
+ }
460
+ isRetiredSecret(session, cloud) {
461
+ if (!cloud && session.cloud !== false && session.expiresAt != null) return this.hasCloudLogout;
462
+ return (cloud || session.cloud === true) && !this.state.cloud.allows(session.cloudOrigin);
463
+ }
231
464
  getStoredSession(id, descriptor) {
232
465
  return this.withLock(id, async () => {
466
+ if (this._disposed) return void 0;
233
467
  const sessionId = this.resolveConnectionId(id, descriptor);
234
468
  let session = descriptor.cloud === true ? void 0 : await this.readSecret(id, sessionId, false);
469
+ if (this._disposed) return void 0;
235
470
  let cloudIfMissing = false;
236
- if (session != null) {
237
- if (session.expiresAt != null) {
238
- cloudIfMissing = true;
239
- try {
240
- await this.deleteSecrets(id, session.id);
241
- await this.writeSecret(id, session);
242
- } catch {}
243
- }
471
+ if (session != null && session.cloud !== false && session.expiresAt != null) {
472
+ cloudIfMissing = true;
473
+ try {
474
+ await this.deleteSecrets(id, session.id);
475
+ if (this.hasCloudLogout) return void 0;
476
+ await this.writeSecret(id, {
477
+ ...session,
478
+ cloud: true
479
+ });
480
+ } catch {}
244
481
  }
245
482
  if (session == null && descriptor.cloud !== false) {
246
483
  cloudIfMissing = true;
247
484
  session = await this.readSecret(id, sessionId, true);
248
485
  }
249
- return convertStoredSessionToSession(session, descriptor, cloudIfMissing);
486
+ return this._disposed || session != null && this.isRetiredSecret(session, cloudIfMissing) ? void 0 : convertStoredSessionToSession(session, descriptor, cloudIfMissing);
250
487
  });
251
488
  }
252
489
  /**
@@ -256,67 +493,75 @@ var ConfiguredIntegrationService = class {
256
493
  */
257
494
  deleteStoredSessions(id, descriptor, cloud, options) {
258
495
  return this.withLock(id, async () => {
496
+ if (this._disposed || options?.sync?.isCurrent() === false) return false;
259
497
  const connectionId = this.resolveConnectionId(id, descriptor);
498
+ if (options?.unobservedSince != null && this.state.cloud.observedSince(`${id}|connection:${connectionId}`, options.unobservedSince)) return false;
260
499
  if (options?.signOutMark != null && this.isSessionRetiredSince(id, {
261
500
  id: connectionId,
262
- domain: descriptor.domain
501
+ domain: descriptor.domain,
502
+ cloud
263
503
  }, options.signOutMark)) return false;
264
504
  if (options?.signOut) this.retirePendingStores(isSelfManagedHostIntegrationId(id) && descriptor.domain ? this.getHostScope(id, descriptor.domain) : id);
265
- this._onWillRemoveSessions.fire({
266
- integrationId: id,
267
- connectionId,
268
- cloud,
269
- domain: descriptor.domain
505
+ await this.deleteSecrets(id, connectionId, cloud, {
506
+ ...options,
507
+ onRemoving: () => this._onWillRemoveSessions.fire({
508
+ integrationId: id,
509
+ connectionId,
510
+ cloud,
511
+ domain: descriptor.domain
512
+ })
270
513
  });
271
- await this.deleteSecrets(id, connectionId, cloud, options);
272
514
  return true;
273
515
  });
274
516
  }
275
517
  /** Signs out of every stored session of the provider, or of one self-managed host when `domain` is given. */
276
- deleteAllStoredSessions(id, cloud, domain) {
518
+ deleteAllStoredSessions(id, cloud, domain, sync) {
519
+ const scope = isSelfManagedHostIntegrationId(id) && domain != null ? this.getHostScope(id, domain) : id;
277
520
  return this.withLock(id, async () => {
278
- this.retirePendingStores(isSelfManagedHostIntegrationId(id) && domain != null ? this.getHostScope(id, domain) : id);
279
- this._onWillRemoveSessions.fire({
280
- integrationId: id,
281
- cloud,
282
- domain
521
+ if (this._disposed || sync?.isCurrent() === false || sync && this.hasNewCloudConnection(id, domain, sync.mark)) return false;
522
+ await this.duringRemoval(scope, cloud, async () => {
523
+ this._onWillRemoveSessions.fire({
524
+ integrationId: id,
525
+ cloud,
526
+ domain
527
+ });
528
+ if (this._disposed) return;
529
+ await this.deleteAllSecrets(id, cloud, domain);
283
530
  });
284
- await this.deleteAllSecrets(id, cloud, domain);
531
+ return !this._disposed;
285
532
  });
286
533
  }
287
- /**
288
- * Reclaims all stored configuration + secrets for the given (typically retired) integration ids.
289
- * Used to clean up state left behind when an id is removed from the model — e.g. the local
290
- * self-managed `github-enterprise`/`gitlab-self-hosted` ids dropped when integrations went cloud-only.
291
- * Domains are read from the stored config (secrets are keyed by domain); ids with no stored config
292
- * are a no-op.
293
- */
294
534
  async purgeStoredConfiguration(ids) {
295
- const stored = this.ctx.storage.get("integrations:configured");
296
- if (stored == null) return;
297
- let changed = false;
298
- for (const id of ids) {
299
- if (!(id in stored)) continue;
300
- for (const descriptor of stored[id] ?? []) {
301
- const connectionId = descriptor.id || descriptor.domain || providersMetadata[id]?.domain || id;
302
- await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
303
- await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
304
- if (descriptor.domain) await this.ctx.storage.deleteWorkspace(`connected:${id}:${descriptor.domain}`);
305
- }
306
- changed = true;
307
- }
308
- if (!changed) return;
309
- const remaining = Object.fromEntries(Object.entries(stored).filter(([key]) => !ids.includes(key)));
310
- await this.ctx.storage.store("integrations:configured", remaining);
535
+ for (const id of ids) await this.withLock(id, async () => {
536
+ const descriptors = this.ctx.storage.get("integrations:configured")?.[id];
537
+ if (descriptors == null) return;
538
+ await this.duringRemoval(id, void 0, async () => {
539
+ for (const descriptor of descriptors) {
540
+ const key = descriptor.id || descriptor.domain || providersMetadata[id]?.domain || id;
541
+ await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, key));
542
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, key));
543
+ if (descriptor.domain) await this.ctx.storage.deleteWorkspace(`connected:${id}:${descriptor.domain}`);
544
+ }
545
+ await this.storeConfigured(id);
546
+ });
547
+ });
311
548
  }
312
549
  async deleteSecrets(id, connectionId, cloud, options) {
313
- this.retireStoredWrites(`${id}|connection:${connectionId}`);
314
- if (cloud == null || cloud === false) await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
315
- if (cloud == null || cloud === true) await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
316
- if (options?.preserveConfigured) return;
317
- await this.removeConfigured(id, {
318
- connectionId,
319
- cloud
550
+ await this.duringRemoval(`${id}|connection:${connectionId}`, cloud, async () => {
551
+ if (options?.onRemoving != null) {
552
+ options.onRemoving();
553
+ if (this._disposed) return;
554
+ }
555
+ if (cloud == null || cloud === false) await this.ctx.storage.deleteSecret(this.getLocalSecretKey(id, connectionId));
556
+ if (cloud == null || cloud === true) {
557
+ await this.ctx.storage.deleteSecret(this.getCloudSecretKey(id, connectionId));
558
+ this.state.cloud.remove(`${id}|connection:${connectionId}`);
559
+ }
560
+ if (options?.preserveConfigured) return;
561
+ await this.removeConfigured(id, {
562
+ connectionId,
563
+ cloud
564
+ });
320
565
  });
321
566
  }
322
567
  async deleteAllSecrets(id, cloud, domain) {
@@ -329,8 +574,11 @@ var ConfiguredIntegrationService = class {
329
574
  if (domain != null) return;
330
575
  await this.deleteSecrets(id, providersMetadata[id]?.domain || id, cloud);
331
576
  }
332
- async writeSecret(id, session, resource) {
333
- await this.ctx.storage.storeSecret(this.getSecretKey(id, session.id, session.cloud ?? false), JSON.stringify(session));
577
+ async writeSecret(id, session, resource, cloudOrigin) {
578
+ await this.ctx.storage.storeSecret(this.getSecretKey(id, session.id, session.cloud ?? false), JSON.stringify(cloudOrigin == null ? session : {
579
+ ...session,
580
+ cloudOrigin
581
+ }));
334
582
  await this.addOrUpdateConfigured({
335
583
  id: session.id,
336
584
  integrationId: id,
@@ -349,9 +597,11 @@ var ConfiguredIntegrationService = class {
349
597
  let storedSession;
350
598
  try {
351
599
  const sessionJSON = await this.ctx.storage.getSecret(this.getSecretKey(id, sessionId, cloud));
600
+ if (this._disposed) return void 0;
352
601
  if (sessionJSON) {
353
602
  storedSession = JSON.parse(sessionJSON);
354
603
  if (storedSession != null) {
604
+ if (this.isRetiredSecret(storedSession, cloud)) return void 0;
355
605
  const configured = this.configured.get(id);
356
606
  const connectionId = storedSession.id ?? sessionId;
357
607
  const sessionCloud = storedSession.cloud ?? cloud;
@@ -370,6 +620,7 @@ var ConfiguredIntegrationService = class {
370
620
  }
371
621
  }
372
622
  } catch (_ex) {
623
+ if (this._disposed) return void 0;
373
624
  try {
374
625
  await this.deleteSecrets(id, sessionId, cloud);
375
626
  } catch {}
@@ -467,8 +718,19 @@ var ConfiguredIntegrationService = class {
467
718
  * Marks the given connection as the primary/default for the provider and clears the flag on its
468
719
  * siblings. Persists immediately instead of relying on a session re-store to carry the primary flag.
469
720
  */
470
- setPrimaryConnection(id, connectionId) {
471
- return this.withLock(id, () => this.setPrimaryConnectionCore(id, connectionId));
721
+ setPrimaryConnection(id, connectionId, list) {
722
+ return this.withLock(id, async () => {
723
+ if (this._disposed) return;
724
+ if (list != null && (!list.sync.isCurrent() || this.state.cloud.supersedingPrimary(id, list.domain, connectionId, list.sync.mark) != null)) return;
725
+ await this.setPrimaryConnectionCore(id, connectionId);
726
+ if (list != null || this._disposed) return;
727
+ const selected = this.getConfigured(id, { cloud: true }).find((c) => c.id === connectionId && c.primary);
728
+ if (selected != null) {
729
+ const mark = ++this.state.epoch;
730
+ this.state.cloud.observe(`${id}|connection:${connectionId}`, mark);
731
+ this.state.cloud.observePrimary(id, selected.domain, connectionId, mark);
732
+ }
733
+ });
472
734
  }
473
735
  async setPrimaryConnectionCore(id, connectionId) {
474
736
  const descriptors = this.configured.get(id);
@@ -490,9 +752,8 @@ var ConfiguredIntegrationService = class {
490
752
  };
491
753
  });
492
754
  if (!changed) return;
493
- this.configured.set(id, updated);
755
+ await this.storeConfigured(id, updated);
494
756
  this.fireChange(id);
495
- await this.storeConfigured();
496
757
  }
497
758
  /**
498
759
  * Removes a single connection (its secret + configured descriptor). If it was the primary and other
@@ -502,13 +763,12 @@ var ConfiguredIntegrationService = class {
502
763
  */
503
764
  deleteConnection(id, connectionId, cloud) {
504
765
  return this.withLock(id, async () => {
505
- this.retirePendingStores(`${id}|connection:${connectionId}`);
506
- this._onWillRemoveSessions.fire({
766
+ if (this._disposed) return;
767
+ await this.deleteSecrets(id, connectionId, cloud, { onRemoving: () => this._onWillRemoveSessions.fire({
507
768
  integrationId: id,
508
769
  connectionId,
509
770
  cloud
510
- });
511
- await this.deleteSecrets(id, connectionId, cloud);
771
+ }) });
512
772
  });
513
773
  }
514
774
  _addedIds = /* @__PURE__ */ new Set();
@@ -540,6 +800,14 @@ var ConfiguredIntegrationService = class {
540
800
  this._fireChangeDebounced();
541
801
  }
542
802
  };
803
+ function isLegacyCloudSecret(raw) {
804
+ try {
805
+ const session = JSON.parse(raw);
806
+ return session?.cloud === true || session?.cloud !== false && session?.expiresAt != null;
807
+ } catch {
808
+ return false;
809
+ }
810
+ }
543
811
  function convertStoredSessionToSession(storedSession, descriptor, cloudIfMissing) {
544
812
  if (storedSession == null) return void 0;
545
813
  return {