@gitkraken/core-gitlens 0.65.0 → 0.67.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.
- package/CHANGELOG.md +12 -0
- package/dist/plus/integrations/extensionManager.js.map +1 -1
- package/dist/plus/integrations/index.d.ts +2 -1
- package/dist/plus/integrations/index.js +12 -2
- package/dist/plus/integrations/index.js.map +1 -1
- package/dist/plus/integrations/integrationService.d.ts +20 -6
- package/dist/plus/integrations/integrationService.js +62 -9
- package/dist/plus/integrations/integrationService.js.map +1 -1
- package/dist/plus/integrations/manager.d.ts +7 -4
- package/dist/plus/integrations/models/gitlabMergeRequestWrites.d.ts +3 -9
- package/dist/plus/integrations/models/linearIssueWrites.d.ts +101 -0
- package/dist/plus/integrations/models/linearIssueWrites.js +0 -0
- package/dist/plus/integrations/models/publicIntegration.d.ts +1 -0
- package/dist/plus/integrations/providers/azure/azure.js +1 -1
- package/dist/plus/integrations/providers/gitlab/mergeRequestPermissions.d.ts +36 -0
- package/dist/plus/integrations/providers/gitlab/mergeRequestPermissions.js +36 -0
- package/dist/plus/integrations/providers/gitlab/mergeRequestPermissions.js.map +1 -0
- package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.d.ts +1 -2
- package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.js +93 -73
- package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.js.map +1 -1
- package/dist/plus/integrations/providers/gitlab/writeTransport.d.ts +7 -1
- package/dist/plus/integrations/providers/gitlab/writeTransport.js +21 -2
- package/dist/plus/integrations/providers/gitlab/writeTransport.js.map +1 -1
- package/dist/plus/integrations/providers/issueSorts.d.ts +1 -0
- package/dist/plus/integrations/providers/linear.d.ts +6 -6
- package/dist/plus/integrations/providers/linear.js +36 -14
- package/dist/plus/integrations/providers/linear.js.map +1 -1
- package/dist/plus/integrations/providers/linearIssueWriteTransport.d.ts +27 -0
- package/dist/plus/integrations/providers/linearIssueWriteTransport.js +110 -0
- package/dist/plus/integrations/providers/linearIssueWriteTransport.js.map +1 -0
- package/dist/plus/integrations/providers/linearIssueWrites.d.ts +27 -0
- package/dist/plus/integrations/providers/linearIssueWrites.js +310 -0
- package/dist/plus/integrations/providers/linearIssueWrites.js.map +1 -0
- package/dist/plus/integrations/providers/linearIssuesEtag.d.ts +2 -0
- package/dist/plus/integrations/providers/linearIssuesEtag.js +27 -1
- package/dist/plus/integrations/providers/linearIssuesEtag.js.map +1 -1
- package/dist/plus/integrations/providers/providerApiClient.d.ts +2 -2
- package/dist/plus/integrations/providers/providerApiClient.js +5 -5
- package/dist/plus/integrations/providers/providerApiClient.js.map +1 -1
- package/dist/plus/integrations/providers/providerErrors.d.ts +9 -0
- package/dist/plus/integrations/providers/providerErrors.js +1 -1
- package/dist/plus/integrations/providers/providerErrors.js.map +1 -1
- package/dist/plus/integrations/providers/providersApi.d.ts +1 -0
- package/dist/plus/integrations/providers/providersApi.js +8 -1
- package/dist/plus/integrations/providers/providersApi.js.map +1 -1
- package/dist/plus/integrations/reads/drains.d.ts +1 -0
- package/docs/integrations.md +92 -14
- package/package.json +1 -1
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { LinearIssueWriteError } from "./linearIssueWriteTransport.js";
|
|
2
|
+
//#region ../plus/integrations/src/providers/linearIssueWrites.ts
|
|
3
|
+
const identityQuery = `
|
|
4
|
+
query GetLinearIssueWriteIdentity {
|
|
5
|
+
viewer { id }
|
|
6
|
+
organization { id urlKey name }
|
|
7
|
+
}
|
|
8
|
+
`;
|
|
9
|
+
const teamByKeyQuery = `
|
|
10
|
+
query GetLinearIssueWriteTeam($key: String!) {
|
|
11
|
+
teams(first: 2, filter: { key: { eq: $key } }) {
|
|
12
|
+
nodes { id key }
|
|
13
|
+
pageInfo { hasNextPage }
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
`;
|
|
17
|
+
const teamStatesQuery = `
|
|
18
|
+
query GetLinearIssueWriteStates($id: String!, $after: String, $includeStates: Boolean!) {
|
|
19
|
+
team(id: $id) {
|
|
20
|
+
id key name
|
|
21
|
+
states(first: 100, after: $after) @include(if: $includeStates) {
|
|
22
|
+
nodes { id name type }
|
|
23
|
+
pageInfo { hasNextPage endCursor }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
`;
|
|
28
|
+
const issueFields = `
|
|
29
|
+
id identifier url title updatedAt archivedAt trashed
|
|
30
|
+
team { id key name }
|
|
31
|
+
state { id name type }
|
|
32
|
+
`;
|
|
33
|
+
const issueQuery = `
|
|
34
|
+
query ResolveLinearIssueWriteTarget($id: String!) {
|
|
35
|
+
issue(id: $id) { ${issueFields} }
|
|
36
|
+
}
|
|
37
|
+
`;
|
|
38
|
+
const createMutation = `
|
|
39
|
+
mutation CreateLinearIssue($input: IssueCreateInput!) {
|
|
40
|
+
issueCreate(input: $input) { success issue { ${issueFields} } }
|
|
41
|
+
}
|
|
42
|
+
`;
|
|
43
|
+
const updateMutation = `
|
|
44
|
+
mutation UpdateLinearIssue($id: String!, $input: IssueUpdateInput!) {
|
|
45
|
+
issueUpdate(id: $id, input: $input) { success issue { ${issueFields} } }
|
|
46
|
+
}
|
|
47
|
+
`;
|
|
48
|
+
const deleteMutation = `
|
|
49
|
+
mutation DeleteLinearIssue($id: String!) {
|
|
50
|
+
issueDelete(id: $id) { success entity { archivedAt } }
|
|
51
|
+
}
|
|
52
|
+
`;
|
|
53
|
+
const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
|
|
54
|
+
const issueIdentifier = /^[A-Z0-9]+-[0-9]+$/i;
|
|
55
|
+
const teamKey = /^[A-Z0-9]+$/;
|
|
56
|
+
function isUuid(value) {
|
|
57
|
+
return typeof value === "string" && uuid.test(value);
|
|
58
|
+
}
|
|
59
|
+
function isLinearIssueWriteScope(scope, requireTeam) {
|
|
60
|
+
return typeof scope.connectionId === "string" && scope.connectionId.length !== 0 && scope.connectionId.trim() === scope.connectionId && isUuid(scope.organizationId) && (!requireTeam && scope.teamId === void 0 || isUuid(scope.teamId)) && (scope.expectedAccountId === void 0 || isUuid(scope.expectedAccountId)) && (scope.expectedOrganizationUrlKey === void 0 || typeof scope.expectedOrganizationUrlKey === "string" && scope.expectedOrganizationUrlKey.length !== 0 && scope.expectedOrganizationUrlKey.trim() === scope.expectedOrganizationUrlKey);
|
|
61
|
+
}
|
|
62
|
+
function isLinearIssueCreateOptions(options) {
|
|
63
|
+
return options.teamKey !== void 0 ? options.teamId === void 0 && typeof options.teamKey === "string" && teamKey.test(options.teamKey) : isUuid(options.teamId);
|
|
64
|
+
}
|
|
65
|
+
function validateTarget(options, mutation = false) {
|
|
66
|
+
if ((mutation || options.teamId !== void 0) && !isUuid(options.teamId) || typeof options.issue !== "string" || !isUuid(options.issue) && !issueIdentifier.test(options.issue) || (mutation || options.expectedIssueId !== void 0) && !isUuid(options.expectedIssueId)) throw new LinearIssueWriteError("invalid-input");
|
|
67
|
+
}
|
|
68
|
+
function isTitle(title) {
|
|
69
|
+
return typeof title === "string" && title.trim().length !== 0;
|
|
70
|
+
}
|
|
71
|
+
function isTeam(team) {
|
|
72
|
+
return isUuid(team?.id) && typeof team.key === "string" && typeof team.name === "string";
|
|
73
|
+
}
|
|
74
|
+
function isState(state) {
|
|
75
|
+
return isUuid(state?.id) && typeof state.name === "string" && typeof state.type === "string";
|
|
76
|
+
}
|
|
77
|
+
function isIssue(issue) {
|
|
78
|
+
return isUuid(issue?.id) && typeof issue.identifier === "string" && issueIdentifier.test(issue.identifier) && typeof issue.url === "string" && typeof issue.updatedAt === "string" && (issue.archivedAt === null || typeof issue.archivedAt === "string") && (issue.trashed === null || typeof issue.trashed === "boolean") && isTitle(issue.title) && isTeam(issue.team) && isState(issue.state);
|
|
79
|
+
}
|
|
80
|
+
function workflowState(state) {
|
|
81
|
+
let category = "TO_DO";
|
|
82
|
+
switch (state.type) {
|
|
83
|
+
case "started":
|
|
84
|
+
category = "IN_PROGRESS";
|
|
85
|
+
break;
|
|
86
|
+
case "completed":
|
|
87
|
+
category = "DONE";
|
|
88
|
+
break;
|
|
89
|
+
case "canceled":
|
|
90
|
+
case "duplicate": category = "CANCELED";
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
id: state.id,
|
|
94
|
+
name: state.name,
|
|
95
|
+
type: state.type,
|
|
96
|
+
category
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function teamReceipt(team) {
|
|
100
|
+
return {
|
|
101
|
+
id: team.id,
|
|
102
|
+
key: team.key,
|
|
103
|
+
name: team.name
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
function issueReceipt(issue) {
|
|
107
|
+
return {
|
|
108
|
+
id: issue.id,
|
|
109
|
+
identifier: issue.identifier,
|
|
110
|
+
url: issue.url,
|
|
111
|
+
title: issue.title,
|
|
112
|
+
updatedAt: issue.updatedAt,
|
|
113
|
+
...issue.archivedAt !== null && { archivedAt: issue.archivedAt },
|
|
114
|
+
...issue.trashed === true && { trashed: true },
|
|
115
|
+
team: teamReceipt(issue.team),
|
|
116
|
+
state: workflowState(issue.state)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function checkSuccess(payload) {
|
|
120
|
+
if (payload?.success === false) throw new LinearIssueWriteError("unknown", "rejected");
|
|
121
|
+
if (payload?.success !== true) throw new LinearIssueWriteError("unknown", "uncertain");
|
|
122
|
+
}
|
|
123
|
+
var LinearIssueWriter = class {
|
|
124
|
+
transport;
|
|
125
|
+
constructor(transport) {
|
|
126
|
+
this.transport = transport;
|
|
127
|
+
}
|
|
128
|
+
verify() {
|
|
129
|
+
return this.transport.verify();
|
|
130
|
+
}
|
|
131
|
+
async getCreateOptions(options) {
|
|
132
|
+
if (!isLinearIssueCreateOptions(options)) throw new LinearIssueWriteError("invalid-input");
|
|
133
|
+
const identity = await this.getIdentity(options);
|
|
134
|
+
const team = await this.getTeamStates(options.teamId ?? await this.getTeamId(options.teamKey));
|
|
135
|
+
return {
|
|
136
|
+
...identity,
|
|
137
|
+
...team
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
async getIssueOptions(options) {
|
|
141
|
+
const target = await this.resolveTarget(options);
|
|
142
|
+
const { states } = await this.getTeamStates(target.issue.team.id);
|
|
143
|
+
return {
|
|
144
|
+
...target,
|
|
145
|
+
states,
|
|
146
|
+
permissions: {
|
|
147
|
+
edit: "unknown",
|
|
148
|
+
delete: "unknown"
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
async resolveTarget(options) {
|
|
153
|
+
validateTarget(options);
|
|
154
|
+
const identity = await this.getIdentity(options);
|
|
155
|
+
const issue = await this.getIssue(options);
|
|
156
|
+
return {
|
|
157
|
+
...identity,
|
|
158
|
+
issue: issueReceipt(issue)
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
async write(options) {
|
|
162
|
+
switch (options.action) {
|
|
163
|
+
case "create": return this.create(options);
|
|
164
|
+
case "edit":
|
|
165
|
+
case "transition": return this.update(options);
|
|
166
|
+
default: throw new LinearIssueWriteError("invalid-input");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async delete(options) {
|
|
170
|
+
validateTarget(options, true);
|
|
171
|
+
if (!isUuid(options.expectedAccountId) || options.expectedOrganizationUrlKey === void 0) throw new LinearIssueWriteError("invalid-input");
|
|
172
|
+
const identity = await this.getIdentity(options);
|
|
173
|
+
const issue = await this.getIssue(options);
|
|
174
|
+
const data = await this.transport.mutate(deleteMutation, { id: issue.id });
|
|
175
|
+
checkSuccess(data.issueDelete);
|
|
176
|
+
const archivedAt = data.issueDelete?.entity?.archivedAt;
|
|
177
|
+
return {
|
|
178
|
+
...identity,
|
|
179
|
+
issue: issueReceipt(issue),
|
|
180
|
+
deletion: {
|
|
181
|
+
trashed: true,
|
|
182
|
+
...typeof archivedAt === "string" && { archivedAt }
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
async create(options) {
|
|
187
|
+
const { title, description, teamId, stateId } = options;
|
|
188
|
+
if (!isUuid(teamId) || !isTitle(title) || description !== void 0 && typeof description !== "string" || stateId !== void 0 && !isUuid(stateId)) throw new LinearIssueWriteError("invalid-input");
|
|
189
|
+
const identity = await this.getIdentity(options);
|
|
190
|
+
if (stateId === void 0) await this.getTeam(teamId, void 0, false);
|
|
191
|
+
else await this.validateTeamState(teamId, stateId);
|
|
192
|
+
const data = await this.transport.mutate(createMutation, { input: {
|
|
193
|
+
teamId,
|
|
194
|
+
title,
|
|
195
|
+
description,
|
|
196
|
+
stateId
|
|
197
|
+
} });
|
|
198
|
+
return {
|
|
199
|
+
...identity,
|
|
200
|
+
issue: this.mutationReceipt(data.issueCreate, teamId)
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
async update(options) {
|
|
204
|
+
validateTarget(options, true);
|
|
205
|
+
let input;
|
|
206
|
+
if (options.action === "edit") {
|
|
207
|
+
const { title, description } = options;
|
|
208
|
+
if (title === void 0 && description === void 0 || title !== void 0 && !isTitle(title) || description !== void 0 && typeof description !== "string") throw new LinearIssueWriteError("invalid-input");
|
|
209
|
+
input = {
|
|
210
|
+
title,
|
|
211
|
+
description
|
|
212
|
+
};
|
|
213
|
+
} else {
|
|
214
|
+
if (!isUuid(options.stateId)) throw new LinearIssueWriteError("invalid-input");
|
|
215
|
+
input = { stateId: options.stateId };
|
|
216
|
+
}
|
|
217
|
+
const identity = await this.getIdentity(options);
|
|
218
|
+
if (input.stateId !== void 0) await this.validateTeamState(options.teamId, input.stateId);
|
|
219
|
+
const issue = await this.getIssue(options);
|
|
220
|
+
const data = await this.transport.mutate(updateMutation, {
|
|
221
|
+
id: issue.id,
|
|
222
|
+
input
|
|
223
|
+
});
|
|
224
|
+
return {
|
|
225
|
+
...identity,
|
|
226
|
+
issue: this.mutationReceipt(data.issueUpdate, options.teamId, issue.id)
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
async getIdentity(options) {
|
|
230
|
+
const { viewer, organization } = await this.transport.query(identityQuery);
|
|
231
|
+
if (!isUuid(viewer?.id) || !isUuid(organization?.id) || typeof organization.urlKey !== "string" || typeof organization.name !== "string") throw new LinearIssueWriteError("unknown");
|
|
232
|
+
if (organization.id !== options.organizationId) throw new LinearIssueWriteError("no-connection");
|
|
233
|
+
if (options.expectedAccountId !== void 0 && viewer.id !== options.expectedAccountId) throw new LinearIssueWriteError("forbidden");
|
|
234
|
+
if (options.expectedOrganizationUrlKey !== void 0 && organization.urlKey.toLowerCase() !== options.expectedOrganizationUrlKey.toLowerCase()) throw new LinearIssueWriteError("conflict");
|
|
235
|
+
return {
|
|
236
|
+
ok: true,
|
|
237
|
+
accountId: viewer.id,
|
|
238
|
+
organization: {
|
|
239
|
+
id: organization.id,
|
|
240
|
+
urlKey: organization.urlKey,
|
|
241
|
+
url: `https://linear.app/${encodeURIComponent(organization.urlKey)}`,
|
|
242
|
+
name: organization.name
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
async getIssue(options) {
|
|
247
|
+
const uuidAddress = isUuid(options.issue);
|
|
248
|
+
const address = uuidAddress ? options.issue : options.issue.toUpperCase();
|
|
249
|
+
const { issue } = await this.transport.query(issueQuery, { id: address });
|
|
250
|
+
if (issue === null || issue?.trashed === true) throw new LinearIssueWriteError("not-found");
|
|
251
|
+
if (!isIssue(issue)) throw new LinearIssueWriteError("unknown");
|
|
252
|
+
if (options.teamId !== void 0 && issue.team.id !== options.teamId || options.expectedIssueId !== void 0 && issue.id !== options.expectedIssueId || (uuidAddress ? issue.id !== address : issue.identifier.toUpperCase() !== address)) throw new LinearIssueWriteError("conflict");
|
|
253
|
+
return issue;
|
|
254
|
+
}
|
|
255
|
+
async getTeamId(key) {
|
|
256
|
+
const { teams } = await this.transport.query(teamByKeyQuery, { key });
|
|
257
|
+
if (!Array.isArray(teams?.nodes) || teams.pageInfo?.hasNextPage !== false) throw new LinearIssueWriteError("unknown");
|
|
258
|
+
if (teams.nodes.length === 0) throw new LinearIssueWriteError("not-found");
|
|
259
|
+
const [team] = teams.nodes;
|
|
260
|
+
if (teams.nodes.length !== 1 || team?.key !== key || !isUuid(team.id)) throw new LinearIssueWriteError("conflict");
|
|
261
|
+
return team.id;
|
|
262
|
+
}
|
|
263
|
+
async getTeamStates(teamId) {
|
|
264
|
+
const states = [];
|
|
265
|
+
const seen = /* @__PURE__ */ new Set();
|
|
266
|
+
let after;
|
|
267
|
+
for (let page = 0; page < 10; page++) {
|
|
268
|
+
const team = await this.getTeam(teamId, after);
|
|
269
|
+
if (!Array.isArray(team.states?.nodes)) throw new LinearIssueWriteError("unknown");
|
|
270
|
+
for (const state of team.states.nodes) {
|
|
271
|
+
if (!isState(state)) throw new LinearIssueWriteError("unknown");
|
|
272
|
+
if (state.type !== "duplicate") states.push(workflowState(state));
|
|
273
|
+
}
|
|
274
|
+
const { hasNextPage, endCursor } = team.states.pageInfo ?? {};
|
|
275
|
+
if (hasNextPage === false) return {
|
|
276
|
+
team: teamReceipt(team),
|
|
277
|
+
states
|
|
278
|
+
};
|
|
279
|
+
if (hasNextPage !== true || !endCursor || seen.has(endCursor)) throw new LinearIssueWriteError("unknown");
|
|
280
|
+
seen.add(endCursor);
|
|
281
|
+
after = endCursor;
|
|
282
|
+
}
|
|
283
|
+
throw new LinearIssueWriteError("unknown");
|
|
284
|
+
}
|
|
285
|
+
async getTeam(teamId, after, includeStates = true) {
|
|
286
|
+
const { team } = await this.transport.query(teamStatesQuery, {
|
|
287
|
+
id: teamId,
|
|
288
|
+
after,
|
|
289
|
+
includeStates
|
|
290
|
+
});
|
|
291
|
+
if (team === null) throw new LinearIssueWriteError("not-found");
|
|
292
|
+
if (!isTeam(team)) throw new LinearIssueWriteError("unknown");
|
|
293
|
+
if (team.id !== teamId) throw new LinearIssueWriteError("conflict");
|
|
294
|
+
return team;
|
|
295
|
+
}
|
|
296
|
+
async validateTeamState(teamId, stateId) {
|
|
297
|
+
const { states } = await this.getTeamStates(teamId);
|
|
298
|
+
if (!states.some((state) => state.id === stateId)) throw new LinearIssueWriteError("transition-unavailable");
|
|
299
|
+
}
|
|
300
|
+
mutationReceipt(payload, teamId, issueId) {
|
|
301
|
+
checkSuccess(payload);
|
|
302
|
+
const issue = payload?.issue;
|
|
303
|
+
if (!isIssue(issue) || issue.team.id !== teamId || issueId !== void 0 && issue.id !== issueId) throw new LinearIssueWriteError("unknown", "uncertain");
|
|
304
|
+
return issueReceipt(issue);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
//#endregion
|
|
308
|
+
export { LinearIssueWriter, isLinearIssueWriteScope };
|
|
309
|
+
|
|
310
|
+
//# sourceMappingURL=linearIssueWrites.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"linearIssueWrites.js","names":[],"sources":["../../../../../plus/integrations/src/providers/linearIssueWrites.ts"],"sourcesContent":["import type {\n\tLinearIssueCreateOptions,\n\tLinearIssueCreateOptionsResult,\n\tLinearIssueDeleteOptions,\n\tLinearIssueDeleteResult,\n\tLinearIssueReceipt,\n\tLinearIssueWorkflowState,\n\tLinearIssueWriteOptions,\n\tLinearIssueWriteOptionsResult,\n\tLinearIssueWriteResult,\n\tLinearIssueWriteScope,\n\tLinearIssueWriteSuccess,\n\tLinearIssueWriteTargetOptions,\n} from '../models/linearIssueWrites.js';\nimport { LinearIssueWriteError } from './linearIssueWriteTransport.js';\nimport type { LinearIssueWriteTransport } from './linearIssueWriteTransport.js';\n\nconst identityQuery = `\n\tquery GetLinearIssueWriteIdentity {\n\t\tviewer { id }\n\t\torganization { id urlKey name }\n\t}\n`;\n\nconst teamByKeyQuery = `\n\tquery GetLinearIssueWriteTeam($key: String!) {\n\t\tteams(first: 2, filter: { key: { eq: $key } }) {\n\t\t\tnodes { id key }\n\t\t\tpageInfo { hasNextPage }\n\t\t}\n\t}\n`;\n\nconst teamStatesQuery = `\n\tquery GetLinearIssueWriteStates($id: String!, $after: String, $includeStates: Boolean!) {\n\t\tteam(id: $id) {\n\t\t\tid key name\n\t\t\tstates(first: 100, after: $after) @include(if: $includeStates) {\n\t\t\t\tnodes { id name type }\n\t\t\t\tpageInfo { hasNextPage endCursor }\n\t\t\t}\n\t\t}\n\t}\n`;\n\nconst issueFields = `\n\tid identifier url title updatedAt archivedAt trashed\n\tteam { id key name }\n\tstate { id name type }\n`;\n\nconst issueQuery = `\n\tquery ResolveLinearIssueWriteTarget($id: String!) {\n\t\tissue(id: $id) { ${issueFields} }\n\t}\n`;\n\nconst createMutation = `\n\tmutation CreateLinearIssue($input: IssueCreateInput!) {\n\t\tissueCreate(input: $input) { success issue { ${issueFields} } }\n\t}\n`;\n\nconst updateMutation = `\n\tmutation UpdateLinearIssue($id: String!, $input: IssueUpdateInput!) {\n\t\tissueUpdate(id: $id, input: $input) { success issue { ${issueFields} } }\n\t}\n`;\n\nconst deleteMutation = `\n\tmutation DeleteLinearIssue($id: String!) {\n\t\tissueDelete(id: $id) { success entity { archivedAt } }\n\t}\n`;\n\ntype LinearState = Omit<LinearIssueWorkflowState, 'category'>;\ntype LinearIssue = Omit<LinearIssueReceipt, 'archivedAt' | 'trashed' | 'state'> & {\n\tarchivedAt: string | null;\n\ttrashed: boolean | null;\n\tstate: LinearState;\n};\ntype LinearTeam = LinearIssueReceipt['team'];\ntype LinearTeamWithStates = LinearTeam & {\n\tstates?: { nodes: LinearState[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } };\n};\ntype Identity = {\n\tviewer: { id: string };\n\torganization: { id: string; urlKey: string; name: string };\n};\ntype MutationPayload = { success: boolean; issue?: LinearIssue | null };\n\nconst uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;\nconst issueIdentifier = /^[A-Z0-9]+-[0-9]+$/i;\nconst teamKey = /^[A-Z0-9]+$/;\n\nfunction isUuid(value: unknown): value is string {\n\treturn typeof value === 'string' && uuid.test(value);\n}\n\nexport function isLinearIssueWriteScope(\n\tscope: Omit<LinearIssueWriteScope, 'teamId'> & { teamId?: string },\n\trequireTeam: boolean,\n): boolean {\n\treturn (\n\t\ttypeof scope.connectionId === 'string' &&\n\t\tscope.connectionId.length !== 0 &&\n\t\tscope.connectionId.trim() === scope.connectionId &&\n\t\tisUuid(scope.organizationId) &&\n\t\t((!requireTeam && scope.teamId === undefined) || isUuid(scope.teamId)) &&\n\t\t(scope.expectedAccountId === undefined || isUuid(scope.expectedAccountId)) &&\n\t\t(scope.expectedOrganizationUrlKey === undefined ||\n\t\t\t(typeof scope.expectedOrganizationUrlKey === 'string' &&\n\t\t\t\tscope.expectedOrganizationUrlKey.length !== 0 &&\n\t\t\t\tscope.expectedOrganizationUrlKey.trim() === scope.expectedOrganizationUrlKey))\n\t);\n}\n\nfunction isLinearIssueCreateOptions(options: LinearIssueCreateOptions): boolean {\n\treturn options.teamKey !== undefined\n\t\t? options.teamId === undefined && typeof options.teamKey === 'string' && teamKey.test(options.teamKey)\n\t\t: isUuid(options.teamId);\n}\n\nfunction validateTarget(options: LinearIssueWriteTargetOptions, mutation = false): void {\n\tif (\n\t\t((mutation || options.teamId !== undefined) && !isUuid(options.teamId)) ||\n\t\ttypeof options.issue !== 'string' ||\n\t\t(!isUuid(options.issue) && !issueIdentifier.test(options.issue)) ||\n\t\t((mutation || options.expectedIssueId !== undefined) && !isUuid(options.expectedIssueId))\n\t) {\n\t\tthrow new LinearIssueWriteError('invalid-input');\n\t}\n}\n\nfunction isTitle(title: unknown): title is string {\n\treturn typeof title === 'string' && title.trim().length !== 0;\n}\n\nfunction isTeam(team: LinearTeam | null | undefined): team is LinearTeam {\n\treturn isUuid(team?.id) && typeof team.key === 'string' && typeof team.name === 'string';\n}\n\nfunction isState(state: LinearState | null | undefined): state is LinearState {\n\treturn isUuid(state?.id) && typeof state.name === 'string' && typeof state.type === 'string';\n}\n\nfunction isIssue(issue: LinearIssue | null | undefined): issue is LinearIssue {\n\treturn (\n\t\tisUuid(issue?.id) &&\n\t\ttypeof issue.identifier === 'string' &&\n\t\tissueIdentifier.test(issue.identifier) &&\n\t\ttypeof issue.url === 'string' &&\n\t\ttypeof issue.updatedAt === 'string' &&\n\t\t(issue.archivedAt === null || typeof issue.archivedAt === 'string') &&\n\t\t(issue.trashed === null || typeof issue.trashed === 'boolean') &&\n\t\tisTitle(issue.title) &&\n\t\tisTeam(issue.team) &&\n\t\tisState(issue.state)\n\t);\n}\n\nfunction workflowState(state: LinearState): LinearIssueWorkflowState {\n\tlet category: LinearIssueWorkflowState['category'] = 'TO_DO';\n\tswitch (state.type) {\n\t\tcase 'started':\n\t\t\tcategory = 'IN_PROGRESS';\n\t\t\tbreak;\n\t\tcase 'completed':\n\t\t\tcategory = 'DONE';\n\t\t\tbreak;\n\t\tcase 'canceled':\n\t\tcase 'duplicate':\n\t\t\tcategory = 'CANCELED';\n\t\t\tbreak;\n\t}\n\n\treturn { id: state.id, name: state.name, type: state.type, category: category };\n}\n\nfunction teamReceipt(team: LinearTeam): LinearTeam {\n\treturn { id: team.id, key: team.key, name: team.name };\n}\n\nfunction issueReceipt(issue: LinearIssue): LinearIssueReceipt {\n\treturn {\n\t\tid: issue.id,\n\t\tidentifier: issue.identifier,\n\t\turl: issue.url,\n\t\ttitle: issue.title,\n\t\tupdatedAt: issue.updatedAt,\n\t\t...(issue.archivedAt !== null && { archivedAt: issue.archivedAt }),\n\t\t...(issue.trashed === true && { trashed: true }),\n\t\tteam: teamReceipt(issue.team),\n\t\tstate: workflowState(issue.state),\n\t};\n}\n\nfunction checkSuccess(payload: MutationPayload | null | undefined): void {\n\tif (payload?.success === false) throw new LinearIssueWriteError('unknown', 'rejected');\n\tif (payload?.success !== true) throw new LinearIssueWriteError('unknown', 'uncertain');\n}\n\nexport class LinearIssueWriter {\n\tconstructor(private readonly transport: LinearIssueWriteTransport) {}\n\n\tverify(): Promise<void> {\n\t\treturn this.transport.verify();\n\t}\n\n\tasync getCreateOptions(options: LinearIssueCreateOptions): Promise<LinearIssueCreateOptionsResult> {\n\t\tif (!isLinearIssueCreateOptions(options)) throw new LinearIssueWriteError('invalid-input');\n\n\t\tconst identity = await this.getIdentity(options);\n\t\tconst team = await this.getTeamStates(options.teamId ?? (await this.getTeamId(options.teamKey)));\n\t\treturn { ...identity, ...team };\n\t}\n\n\tasync getIssueOptions(options: LinearIssueWriteTargetOptions): Promise<LinearIssueWriteOptionsResult> {\n\t\tconst target = await this.resolveTarget(options);\n\t\tconst { states } = await this.getTeamStates(target.issue.team.id);\n\t\treturn { ...target, states: states, permissions: { edit: 'unknown', delete: 'unknown' } };\n\t}\n\n\tasync resolveTarget(options: LinearIssueWriteTargetOptions): Promise<LinearIssueWriteSuccess> {\n\t\tvalidateTarget(options);\n\t\tconst identity = await this.getIdentity(options);\n\t\tconst issue = await this.getIssue(options);\n\t\treturn { ...identity, issue: issueReceipt(issue) };\n\t}\n\n\tasync write(options: LinearIssueWriteOptions): Promise<LinearIssueWriteResult> {\n\t\tswitch (options.action) {\n\t\t\tcase 'create':\n\t\t\t\treturn this.create(options);\n\t\t\tcase 'edit':\n\t\t\tcase 'transition':\n\t\t\t\treturn this.update(options);\n\t\t\tdefault:\n\t\t\t\tthrow new LinearIssueWriteError('invalid-input');\n\t\t}\n\t}\n\n\tasync delete(options: LinearIssueDeleteOptions): Promise<LinearIssueDeleteResult> {\n\t\tvalidateTarget(options, true);\n\t\tif (!isUuid(options.expectedAccountId) || options.expectedOrganizationUrlKey === undefined) {\n\t\t\tthrow new LinearIssueWriteError('invalid-input');\n\t\t}\n\n\t\tconst identity = await this.getIdentity(options);\n\t\tconst issue = await this.getIssue(options);\n\t\tconst data = await this.transport.mutate<{\n\t\t\tissueDelete?: MutationPayload & { entity?: { archivedAt?: string | null } | null };\n\t\t}>(deleteMutation, { id: issue.id });\n\t\tcheckSuccess(data.issueDelete);\n\t\tconst archivedAt = data.issueDelete?.entity?.archivedAt;\n\t\treturn {\n\t\t\t...identity,\n\t\t\tissue: issueReceipt(issue),\n\t\t\tdeletion: { trashed: true, ...(typeof archivedAt === 'string' && { archivedAt: archivedAt }) },\n\t\t};\n\t}\n\n\tprivate async create(\n\t\toptions: Extract<LinearIssueWriteOptions, { action: 'create' }>,\n\t): Promise<LinearIssueWriteResult> {\n\t\tconst { title, description, teamId, stateId } = options;\n\t\tif (\n\t\t\t!isUuid(teamId) ||\n\t\t\t!isTitle(title) ||\n\t\t\t(description !== undefined && typeof description !== 'string') ||\n\t\t\t(stateId !== undefined && !isUuid(stateId))\n\t\t) {\n\t\t\tthrow new LinearIssueWriteError('invalid-input');\n\t\t}\n\n\t\tconst identity = await this.getIdentity(options);\n\t\tif (stateId === undefined) {\n\t\t\tawait this.getTeam(teamId, undefined, false);\n\t\t} else {\n\t\t\tawait this.validateTeamState(teamId, stateId);\n\t\t}\n\n\t\tconst data = await this.transport.mutate<{ issueCreate?: MutationPayload }>(createMutation, {\n\t\t\tinput: { teamId: teamId, title: title, description: description, stateId: stateId },\n\t\t});\n\t\treturn { ...identity, issue: this.mutationReceipt(data.issueCreate, teamId) };\n\t}\n\n\tprivate async update(\n\t\toptions: Exclude<LinearIssueWriteOptions, { action: 'create' }>,\n\t): Promise<LinearIssueWriteResult> {\n\t\tvalidateTarget(options, true);\n\t\tlet input: { title?: string; description?: string; stateId?: string };\n\t\tif (options.action === 'edit') {\n\t\t\tconst { title, description } = options;\n\t\t\tif (\n\t\t\t\t(title === undefined && description === undefined) ||\n\t\t\t\t(title !== undefined && !isTitle(title)) ||\n\t\t\t\t(description !== undefined && typeof description !== 'string')\n\t\t\t) {\n\t\t\t\tthrow new LinearIssueWriteError('invalid-input');\n\t\t\t}\n\n\t\t\tinput = { title: title, description: description };\n\t\t} else {\n\t\t\tif (!isUuid(options.stateId)) throw new LinearIssueWriteError('invalid-input');\n\n\t\t\tinput = { stateId: options.stateId };\n\t\t}\n\n\t\tconst identity = await this.getIdentity(options);\n\t\tif (input.stateId !== undefined) {\n\t\t\tawait this.validateTeamState(options.teamId, input.stateId);\n\t\t}\n\n\t\tconst issue = await this.getIssue(options);\n\t\tconst data = await this.transport.mutate<{ issueUpdate?: MutationPayload }>(updateMutation, {\n\t\t\tid: issue.id,\n\t\t\tinput: input,\n\t\t});\n\t\treturn { ...identity, issue: this.mutationReceipt(data.issueUpdate, options.teamId, issue.id) };\n\t}\n\n\tprivate async getIdentity(options: Omit<LinearIssueWriteScope, 'teamId'>) {\n\t\tconst { viewer, organization } = await this.transport.query<Identity>(identityQuery);\n\t\tif (\n\t\t\t!isUuid(viewer?.id) ||\n\t\t\t!isUuid(organization?.id) ||\n\t\t\ttypeof organization.urlKey !== 'string' ||\n\t\t\ttypeof organization.name !== 'string'\n\t\t) {\n\t\t\tthrow new LinearIssueWriteError('unknown');\n\t\t}\n\t\tif (organization.id !== options.organizationId) throw new LinearIssueWriteError('no-connection');\n\t\tif (options.expectedAccountId !== undefined && viewer.id !== options.expectedAccountId) {\n\t\t\tthrow new LinearIssueWriteError('forbidden');\n\t\t}\n\t\tif (\n\t\t\toptions.expectedOrganizationUrlKey !== undefined &&\n\t\t\torganization.urlKey.toLowerCase() !== options.expectedOrganizationUrlKey.toLowerCase()\n\t\t) {\n\t\t\tthrow new LinearIssueWriteError('conflict');\n\t\t}\n\n\t\treturn {\n\t\t\tok: true as const,\n\t\t\taccountId: viewer.id,\n\t\t\torganization: {\n\t\t\t\tid: organization.id,\n\t\t\t\turlKey: organization.urlKey,\n\t\t\t\turl: `https://linear.app/${encodeURIComponent(organization.urlKey)}`,\n\t\t\t\tname: organization.name,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async getIssue(options: LinearIssueWriteTargetOptions): Promise<LinearIssue> {\n\t\tconst uuidAddress = isUuid(options.issue);\n\t\tconst address = uuidAddress ? options.issue : options.issue.toUpperCase();\n\t\tconst { issue } = await this.transport.query<{ issue: LinearIssue | null }>(issueQuery, { id: address });\n\t\tif (issue === null || issue?.trashed === true) throw new LinearIssueWriteError('not-found');\n\t\tif (!isIssue(issue)) throw new LinearIssueWriteError('unknown');\n\t\tif (\n\t\t\t(options.teamId !== undefined && issue.team.id !== options.teamId) ||\n\t\t\t(options.expectedIssueId !== undefined && issue.id !== options.expectedIssueId) ||\n\t\t\t(uuidAddress ? issue.id !== address : issue.identifier.toUpperCase() !== address)\n\t\t) {\n\t\t\tthrow new LinearIssueWriteError('conflict');\n\t\t}\n\n\t\treturn issue;\n\t}\n\n\tprivate async getTeamId(key: string): Promise<string> {\n\t\tconst { teams } = await this.transport.query<{\n\t\t\tteams: { nodes: { id: string; key: string }[]; pageInfo: { hasNextPage: boolean } };\n\t\t}>(teamByKeyQuery, { key: key });\n\t\tif (!Array.isArray(teams?.nodes) || teams.pageInfo?.hasNextPage !== false) {\n\t\t\tthrow new LinearIssueWriteError('unknown');\n\t\t}\n\t\tif (teams.nodes.length === 0) throw new LinearIssueWriteError('not-found');\n\n\t\tconst [team] = teams.nodes;\n\t\tif (teams.nodes.length !== 1 || team?.key !== key || !isUuid(team.id)) {\n\t\t\tthrow new LinearIssueWriteError('conflict');\n\t\t}\n\n\t\treturn team.id;\n\t}\n\n\tprivate async getTeamStates(teamId: string): Promise<{ team: LinearTeam; states: LinearIssueWorkflowState[] }> {\n\t\tconst states: LinearIssueWorkflowState[] = [];\n\t\tconst seen = new Set<string>();\n\t\tlet after: string | undefined;\n\t\tfor (let page = 0; page < 10; page++) {\n\t\t\tconst team = await this.getTeam(teamId, after);\n\t\t\tif (!Array.isArray(team.states?.nodes)) throw new LinearIssueWriteError('unknown');\n\n\t\t\tfor (const state of team.states.nodes) {\n\t\t\t\tif (!isState(state)) throw new LinearIssueWriteError('unknown');\n\n\t\t\t\tif (state.type !== 'duplicate') {\n\t\t\t\t\tstates.push(workflowState(state));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { hasNextPage, endCursor } = team.states.pageInfo ?? {};\n\t\t\tif (hasNextPage === false) return { team: teamReceipt(team), states: states };\n\t\t\tif (hasNextPage !== true || !endCursor || seen.has(endCursor)) throw new LinearIssueWriteError('unknown');\n\n\t\t\tseen.add(endCursor);\n\t\t\tafter = endCursor;\n\t\t}\n\n\t\tthrow new LinearIssueWriteError('unknown');\n\t}\n\n\tprivate async getTeam(teamId: string, after?: string, includeStates = true): Promise<LinearTeamWithStates> {\n\t\tconst { team } = await this.transport.query<{ team: LinearTeamWithStates | null }>(teamStatesQuery, {\n\t\t\tid: teamId,\n\t\t\tafter: after,\n\t\t\tincludeStates: includeStates,\n\t\t});\n\t\tif (team === null) throw new LinearIssueWriteError('not-found');\n\t\tif (!isTeam(team)) throw new LinearIssueWriteError('unknown');\n\t\tif (team.id !== teamId) throw new LinearIssueWriteError('conflict');\n\n\t\treturn team;\n\t}\n\n\tprivate async validateTeamState(teamId: string, stateId: string): Promise<void> {\n\t\tconst { states } = await this.getTeamStates(teamId);\n\t\tif (!states.some(state => state.id === stateId)) {\n\t\t\tthrow new LinearIssueWriteError('transition-unavailable');\n\t\t}\n\t}\n\n\tprivate mutationReceipt(\n\t\tpayload: MutationPayload | undefined,\n\t\tteamId: string,\n\t\tissueId?: string,\n\t): LinearIssueReceipt {\n\t\tcheckSuccess(payload);\n\t\tconst issue = payload?.issue;\n\t\tif (!isIssue(issue) || issue.team.id !== teamId || (issueId !== undefined && issue.id !== issueId)) {\n\t\t\tthrow new LinearIssueWriteError('unknown', 'uncertain');\n\t\t}\n\n\t\treturn issueReceipt(issue);\n\t}\n}\n"],"mappings":";;AAiBA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,iBAAiB;;;;;;;;AASvB,MAAM,kBAAkB;;;;;;;;;;;AAYxB,MAAM,cAAc;;;;;AAMpB,MAAM,aAAa;;qBAEE,YAAY;;;AAIjC,MAAM,iBAAiB;;iDAE0B,YAAY;;;AAI7D,MAAM,iBAAiB;;0DAEmC,YAAY;;;AAItE,MAAM,iBAAiB;;;;;AAsBvB,MAAM,OAAO;AACb,MAAM,kBAAkB;AACxB,MAAM,UAAU;AAEhB,SAAS,OAAO,OAAiC;CAChD,OAAO,OAAO,UAAU,YAAY,KAAK,KAAK,KAAK;AACpD;AAEA,SAAgB,wBACf,OACA,aACU;CACV,OACC,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OAAO,YAAY,CAAC;GAC5D,IAAI,gBAAgB,OAAO,OAAO;IAAE,MAAM,YAAY,IAAI;IAAW;GAAO;GAC5E,IAAI,gBAAgB,QAAQ,CAAC,aAAa,KAAK,IAAI,SAAS,GAAG,MAAM,IAAI,sBAAsB,SAAS;GAExG,KAAK,IAAI,SAAS;GAClB,QAAQ;EACT;EAEA,MAAM,IAAI,sBAAsB,SAAS;CAC1C;CAEA,MAAc,QAAQ,QAAgB,OAAgB,gBAAgB,MAAqC;EAC1G,MAAM,EAAE,SAAS,MAAM,KAAK,UAAU,MAA6C,iBAAiB;GACnG,IAAI;GACG;GACQ;EAChB,CAAC;EACD,IAAI,SAAS,MAAM,MAAM,IAAI,sBAAsB,WAAW;EAC9D,IAAI,CAAC,OAAO,IAAI,GAAG,MAAM,IAAI,sBAAsB,SAAS;EAC5D,IAAI,KAAK,OAAO,QAAQ,MAAM,IAAI,sBAAsB,UAAU;EAElE,OAAO;CACR;CAEA,MAAc,kBAAkB,QAAgB,SAAgC;EAC/E,MAAM,EAAE,WAAW,MAAM,KAAK,cAAc,MAAM;EAClD,IAAI,CAAC,OAAO,MAAK,UAAS,MAAM,OAAO,OAAO,GAC7C,MAAM,IAAI,sBAAsB,wBAAwB;CAE1D;CAEA,gBACC,SACA,QACA,SACqB;EACrB,aAAa,OAAO;EACpB,MAAM,QAAQ,SAAS;EACvB,IAAI,CAAC,QAAQ,KAAK,KAAK,MAAM,KAAK,OAAO,UAAW,YAAY,KAAA,KAAa,MAAM,OAAO,SACzF,MAAM,IAAI,sBAAsB,WAAW,WAAW;EAGvD,OAAO,aAAa,KAAK;CAC1B;AACD"}
|
|
@@ -8,6 +8,7 @@ export type LinearIssueEtagNode = {
|
|
|
8
8
|
number: number;
|
|
9
9
|
updatedAt?: string | null;
|
|
10
10
|
archivedAt?: string | null;
|
|
11
|
+
trashed?: boolean | null;
|
|
11
12
|
state?: {
|
|
12
13
|
type?: string | null;
|
|
13
14
|
} | null;
|
|
@@ -21,6 +22,7 @@ export type LinearIssueEtagNode = {
|
|
|
21
22
|
} | null;
|
|
22
23
|
}[] | null;
|
|
23
24
|
};
|
|
25
|
+
export declare function requestLinearIssueTrashed(request: ProviderRequestFunction, accessToken: string, id: string): Promise<boolean>;
|
|
24
26
|
/**
|
|
25
27
|
* The cheap check behind the batch issue read's etags: the change state of up to {@link linearIssuesEtagMaxNumbers}
|
|
26
28
|
* issues of one team in ONE GraphQL request, where the full read sends provider-apis' `issue(id:)` once per issue.
|
|
@@ -23,6 +23,7 @@ const linearIssuesEtagQuery = `
|
|
|
23
23
|
number
|
|
24
24
|
updatedAt
|
|
25
25
|
archivedAt
|
|
26
|
+
trashed
|
|
26
27
|
state {
|
|
27
28
|
type
|
|
28
29
|
}
|
|
@@ -41,6 +42,30 @@ const linearIssuesEtagQuery = `
|
|
|
41
42
|
}
|
|
42
43
|
}
|
|
43
44
|
`;
|
|
45
|
+
const linearIssueTrashQuery = `
|
|
46
|
+
query GetLinearIssueTrashStatus($id: String!) {
|
|
47
|
+
issue(id: $id) { id trashed }
|
|
48
|
+
}
|
|
49
|
+
`;
|
|
50
|
+
async function requestLinearIssueTrashed(request, accessToken, id) {
|
|
51
|
+
const response = await request({
|
|
52
|
+
url: linearGraphQLUrl,
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: {
|
|
55
|
+
Authorization: accessToken,
|
|
56
|
+
"Content-Type": "application/json"
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
query: linearIssueTrashQuery,
|
|
60
|
+
variables: { id }
|
|
61
|
+
})
|
|
62
|
+
});
|
|
63
|
+
const { data, errors } = response.body ?? {};
|
|
64
|
+
if (errors != null && (!Array.isArray(errors) || errors.length !== 0)) throw Object.assign(/* @__PURE__ */ new Error("Linear could not read issue trash status"), { response });
|
|
65
|
+
const issue = data?.issue;
|
|
66
|
+
if (issue?.id !== id || issue.trashed !== null && typeof issue.trashed !== "boolean") throw new Error("Linear did not return trash status for the requested issue");
|
|
67
|
+
return issue.trashed === true;
|
|
68
|
+
}
|
|
44
69
|
/**
|
|
45
70
|
* The cheap check behind the batch issue read's etags: the change state of up to {@link linearIssuesEtagMaxNumbers}
|
|
46
71
|
* issues of one team in ONE GraphQL request, where the full read sends provider-apis' `issue(id:)` once per issue.
|
|
@@ -101,6 +126,7 @@ async function requestLinearIssuesEtagFields(request, accessToken, teamKey, numb
|
|
|
101
126
|
* read while Linear could resolve it, nor one read while it couldn't, which would keep that row unknown.
|
|
102
127
|
*/
|
|
103
128
|
function toLinearIssueEtagFields(issue) {
|
|
129
|
+
if (issue.archivedAt && issue.trashed !== null && issue.trashed !== false) throw new Error(`Linear did not return trash status for ${issue.identifier}`);
|
|
104
130
|
const updatedDate = new Date(issue.updatedAt || NaN);
|
|
105
131
|
if (Number.isNaN(updatedDate.getTime())) throw new Error(`Linear returned no update time for ${issue.identifier}`);
|
|
106
132
|
if (issue.syncedWith == null) throw new Error(`Linear could not resolve the sync links of ${issue.identifier}`);
|
|
@@ -125,6 +151,6 @@ function toLinearIssueEtagFields(issue) {
|
|
|
125
151
|
};
|
|
126
152
|
}
|
|
127
153
|
//#endregion
|
|
128
|
-
export { linearIssuesEtagMaxNumbers, requestLinearIssuesEtagFields, toLinearIssueEtagFields };
|
|
154
|
+
export { linearIssuesEtagMaxNumbers, requestLinearIssueTrashed, requestLinearIssuesEtagFields, toLinearIssueEtagFields };
|
|
129
155
|
|
|
130
156
|
//# sourceMappingURL=linearIssuesEtag.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linearIssuesEtag.js","names":[],"sources":["../../../../../plus/integrations/src/providers/linearIssuesEtag.ts"],"sourcesContent":["import type { IssueSyncedWith } from '@gitlens/git/models/issue.js';\nimport type { IssueEtagFields } from '../reads/etag.js';\nimport { linearSyncedWithEtagKeys } from '../reads/etag.js';\nimport type { ProviderRequestFunction } from './models.js';\nimport { isLinearRateLimitedBody } from './providerErrors.js';\n\nconst linearGraphQLUrl = 'https://api.linear.app/graphql';\n\n/** The most issue numbers one cheap check asks of one team. */\nexport const linearIssuesEtagMaxNumbers = 50;\n\n/**\n * Archived issues are left out of Linear's `issues` connection unless asked for, so `includeArchived` keeps an archived\n * issue answerable here as the full read's `issue(id:)` answers it.\n */\nconst linearIssuesEtagQuery = `\n\tquery GetIssuesEtagFields($teamKey: String!, $numbers: [Float!]!) {\n\t\tissues(\n\t\t\tfirst: ${linearIssuesEtagMaxNumbers}\n\t\t\tincludeArchived: true\n\t\t\tfilter: { team: { key: { eq: $teamKey } }, number: { in: $numbers } }\n\t\t) {\n\t\t\tpageInfo {\n\t\t\t\thasNextPage\n\t\t\t}\n\t\t\tnodes {\n\t\t\t\tidentifier\n\t\t\t\tnumber\n\t\t\t\tupdatedAt\n\t\t\t\tarchivedAt\n\t\t\t\tstate {\n\t\t\t\t\ttype\n\t\t\t\t}\n\t\t\t\tsyncedWith {\n\t\t\t\t\tid\n\t\t\t\t\tservice\n\t\t\t\t\tmetadata {\n\t\t\t\t\t\t... on ExternalEntityInfoGithubMetadata {\n\t\t\t\t\t\t\towner\n\t\t\t\t\t\t\trepo\n\t\t\t\t\t\t\tnumber\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}\n\t}\n`;\n\nexport type LinearIssueEtagNode = {\n\tidentifier: string;\n\tnumber: number;\n\tupdatedAt?: string | null;\n\tarchivedAt?: string | null;\n\tstate?: { type?: string | null } | null;\n\tsyncedWith?:\n\t\t| {\n\t\t\t\tid?: string | null;\n\t\t\t\tservice?: string | null;\n\t\t\t\tmetadata?: { owner?: string | null; repo?: string | null; number?: number | null } | null;\n\t\t }[]\n\t\t| null;\n};\n\ntype LinearIssuesEtagResponse = {\n\tdata?: {\n\t\tissues?: { pageInfo?: { hasNextPage?: boolean }; nodes?: LinearIssueEtagNode[] } | null;\n\t} | null;\n\terrors?: unknown[];\n};\n\n/**\n * The cheap check behind the batch issue read's etags: the change state of up to {@link linearIssuesEtagMaxNumbers}\n * issues of one team in ONE GraphQL request, where the full read sends provider-apis' `issue(id:)` once per issue.\n * Linear returns only the issues it found, in its own order, so a caller matches them by number, never by position.\n *\n * Sent as provider-apis sends every Linear request: the token as the whole `Authorization` header, with no scheme.\n * GraphQL `errors` reject the whole request, as provider-apis rejects them, but keep the response so a throttling\n * code is still classified as one. The exception is the one provider-apis makes too: errors that all sit under\n * `syncedWith`, a nullable list, leave every other field whole. An issue whose list Linear failed to resolve falls\n * through to its full read (see {@link toLinearIssueEtagFields}); one whose list resolved but a link's coordinates\n * didn't keys that link without them, as the full read's row carries it. Unlike provider-apis, a throttled response\n * still throws here, so it is classified as a rate limit. A next page also rejects it: with every number unique within\n * a team, more issues than were asked for means the filter was not applied as written.\n */\nexport async function requestLinearIssuesEtagFields(\n\trequest: ProviderRequestFunction,\n\taccessToken: string,\n\tteamKey: string,\n\tnumbers: readonly number[],\n): Promise<LinearIssueEtagNode[]> {\n\tconst response = await request<LinearIssuesEtagResponse | null>({\n\t\turl: linearGraphQLUrl,\n\t\tmethod: 'POST',\n\t\theaders: { Authorization: accessToken, 'Content-Type': 'application/json' },\n\t\tbody: JSON.stringify({ query: linearIssuesEtagQuery, variables: { teamKey: teamKey, numbers: numbers } }),\n\t});\n\n\tconst body = response.body;\n\tconst syncedWithOnly =\n\t\tbody?.data != null &&\n\t\tArray.isArray(body.errors) &&\n\t\tbody.errors.every(\n\t\t\te =>\n\t\t\t\ttypeof e === 'object' &&\n\t\t\t\te != null &&\n\t\t\t\t'path' in e &&\n\t\t\t\tArray.isArray(e.path) &&\n\t\t\t\te.path.includes('syncedWith'),\n\t\t) &&\n\t\t!isLinearRateLimitedBody(body);\n\tif (body?.errors != null && !syncedWithOnly) {\n\t\tconst error = new Error(`Linear GraphQL errors: ${JSON.stringify(body.errors)}`);\n\t\tObject.assign(error, { response: response });\n\t\tthrow error;\n\t}\n\n\tconst issues = body?.data?.issues;\n\tif (!Array.isArray(issues?.nodes)) throw new Error('Linear returned no issues');\n\tif (issues.pageInfo?.hasNextPage !== false) throw new Error('Linear returned more issues than were asked for');\n\n\treturn issues.nodes;\n}\n\n/**\n * A cheap-checked issue's change state, as the fields the full row's etag reads. The full read's row is provider-apis'\n * Linear issue normalizer (0.65.0, `syncedWith` since GKDEV-3662) then `fromProviderIssue`, so this mirrors both:\n *\n * - provider-apis maps `state.type` to a category — `completed` to `DONE`, `canceled` and `duplicate` to `CANCELED`,\n * `started` to `IN_PROGRESS`, anything else (`backlog`, `unstarted`, `triage`) to `TO_DO`, and no state to none —\n * and sets `closedDate` from `archivedAt` (a falsy value reads as none);\n * - `fromProviderIssue` closes an issue that has a `closedDate` or a terminal category, so an archived issue is closed\n * whatever its state.\n * - provider-apis keeps a `syncedWith` entry for a GitHub link with an id, with its coordinates only when owner, repo\n * and a positive integer number are all there, so the etag lists each such link the same way.\n *\n * Throws on a missing or unparseable `updatedAt`, so the target falls through to the full read rather than matching an\n * etag the full row would compute from a fallback date (`fromProviderIssue` falls back to `closedDate`, then\n * `createdDate`). Throws on a `syncedWith` Linear failed to resolve too: an unknown list must not match a full row\n * read while Linear could resolve it, nor one read while it couldn't, which would keep that row unknown.\n */\nexport function toLinearIssueEtagFields(issue: LinearIssueEtagNode): IssueEtagFields {\n\tconst updatedDate = new Date(issue.updatedAt || Number.NaN);\n\tif (Number.isNaN(updatedDate.getTime())) {\n\t\tthrow new Error(`Linear returned no update time for ${issue.identifier}`);\n\t}\n\n\tif (issue.syncedWith == null) {\n\t\tthrow new Error(`Linear could not resolve the sync links of ${issue.identifier}`);\n\t}\n\n\tconst type = issue.state?.type;\n\tconst closed = Boolean(issue.archivedAt) || type === 'completed' || type === 'canceled' || type === 'duplicate';\n\treturn {\n\t\tstate: closed ? 'closed' : 'opened',\n\t\tupdatedDate: updatedDate,\n\t\tsyncedWithKeys: linearSyncedWithEtagKeys(\n\t\t\tissue.syncedWith.flatMap((synced): IssueSyncedWith[] => {\n\t\t\t\tif (synced.service !== 'github' || !synced.id) return [];\n\n\t\t\t\tconst { owner, repo, number } = synced.metadata ?? {};\n\t\t\t\treturn [\n\t\t\t\t\towner && repo && typeof number === 'number' && Number.isInteger(number) && number > 0\n\t\t\t\t\t\t? { provider: 'github', id: synced.id, owner: owner, repo: repo, number: number }\n\t\t\t\t\t\t: { provider: 'github', id: synced.id },\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t};\n}\n"],"mappings":";;;AAMA,MAAM,mBAAmB;;AAGzB,MAAa,6BAA6B;;;;;AAM1C,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsE9B,eAAsB,8BACrB,SACA,aACA,SACA,SACiC;CACjC,MAAM,WAAW,MAAM,QAAyC;EAC/D,KAAK;EACL,QAAQ;EACR,SAAS;GAAE,eAAe;GAAa,gBAAgB;EAAmB;EAC1E,MAAM,KAAK,UAAU;GAAE,OAAO;GAAuB,WAAW;IAAW;IAAkB;GAAQ;EAAE,CAAC;CACzG,CAAC;CAED,MAAM,OAAO,SAAS;CACtB,MAAM,iBACL,MAAM,QAAQ,QACd,MAAM,QAAQ,KAAK,MAAM,KACzB,KAAK,OAAO,OACX,MACC,OAAO,MAAM,YACb,KAAK,QACL,UAAU,KACV,MAAM,QAAQ,EAAE,IAAI,KACpB,EAAE,KAAK,SAAS,YAAY,CAC9B,KACA,CAAC,wBAAwB,IAAI;CAC9B,IAAI,MAAM,UAAU,QAAQ,CAAC,gBAAgB;EAC5C,MAAM,wBAAQ,IAAI,MAAM,0BAA0B,KAAK,UAAU,KAAK,MAAM,GAAG;EAC/E,OAAO,OAAO,OAAO,EAAY,SAAS,CAAC;EAC3C,MAAM;CACP;CAEA,MAAM,SAAS,MAAM,MAAM;CAC3B,IAAI,CAAC,MAAM,QAAQ,QAAQ,KAAK,GAAG,MAAM,IAAI,MAAM,2BAA2B;CAC9E,IAAI,OAAO,UAAU,gBAAgB,OAAO,MAAM,IAAI,MAAM,iDAAiD;CAE7G,OAAO,OAAO;AACf;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,wBAAwB,OAA6C;CACpF,MAAM,cAAc,IAAI,KAAK,MAAM,aAAa,GAAU;CAC1D,IAAI,OAAO,MAAM,YAAY,QAAQ,CAAC,GACrC,MAAM,IAAI,MAAM,sCAAsC,MAAM,YAAY;CAGzE,IAAI,MAAM,cAAc,MACvB,MAAM,IAAI,MAAM,8CAA8C,MAAM,YAAY;CAGjF,MAAM,OAAO,MAAM,OAAO;CAE1B,OAAO;EACN,OAFc,QAAQ,MAAM,UAAU,KAAK,SAAS,eAAe,SAAS,cAAc,SAAS,cAEnF,WAAW;EACd;EACb,gBAAgB,yBACf,MAAM,WAAW,SAAS,WAA8B;GACvD,IAAI,OAAO,YAAY,YAAY,CAAC,OAAO,IAAI,OAAO,CAAC;GAEvD,MAAM,EAAE,OAAO,MAAM,WAAW,OAAO,YAAY,CAAC;GACpD,OAAO,CACN,SAAS,QAAQ,OAAO,WAAW,YAAY,OAAO,UAAU,MAAM,KAAK,SAAS,IACjF;IAAE,UAAU;IAAU,IAAI,OAAO;IAAW;IAAa;IAAc;GAAO,IAC9E;IAAE,UAAU;IAAU,IAAI,OAAO;GAAG,CACxC;EACD,CAAC,CACF;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"linearIssuesEtag.js","names":[],"sources":["../../../../../plus/integrations/src/providers/linearIssuesEtag.ts"],"sourcesContent":["import type { IssueSyncedWith } from '@gitlens/git/models/issue.js';\nimport type { IssueEtagFields } from '../reads/etag.js';\nimport { linearSyncedWithEtagKeys } from '../reads/etag.js';\nimport type { ProviderRequestFunction } from './models.js';\nimport { isLinearRateLimitedBody } from './providerErrors.js';\n\nconst linearGraphQLUrl = 'https://api.linear.app/graphql';\n\n/** The most issue numbers one cheap check asks of one team. */\nexport const linearIssuesEtagMaxNumbers = 50;\n\n/**\n * Archived issues are left out of Linear's `issues` connection unless asked for, so `includeArchived` keeps an archived\n * issue answerable here as the full read's `issue(id:)` answers it.\n */\nconst linearIssuesEtagQuery = `\n\tquery GetIssuesEtagFields($teamKey: String!, $numbers: [Float!]!) {\n\t\tissues(\n\t\t\tfirst: ${linearIssuesEtagMaxNumbers}\n\t\t\tincludeArchived: true\n\t\t\tfilter: { team: { key: { eq: $teamKey } }, number: { in: $numbers } }\n\t\t) {\n\t\t\tpageInfo {\n\t\t\t\thasNextPage\n\t\t\t}\n\t\t\tnodes {\n\t\t\t\tidentifier\n\t\t\t\tnumber\n\t\t\t\tupdatedAt\n\t\t\t\tarchivedAt\n\t\t\t\ttrashed\n\t\t\t\tstate {\n\t\t\t\t\ttype\n\t\t\t\t}\n\t\t\t\tsyncedWith {\n\t\t\t\t\tid\n\t\t\t\t\tservice\n\t\t\t\t\tmetadata {\n\t\t\t\t\t\t... on ExternalEntityInfoGithubMetadata {\n\t\t\t\t\t\t\towner\n\t\t\t\t\t\t\trepo\n\t\t\t\t\t\t\tnumber\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}\n\t}\n`;\n\nexport type LinearIssueEtagNode = {\n\tidentifier: string;\n\tnumber: number;\n\tupdatedAt?: string | null;\n\tarchivedAt?: string | null;\n\ttrashed?: boolean | null;\n\tstate?: { type?: string | null } | null;\n\tsyncedWith?:\n\t\t| {\n\t\t\t\tid?: string | null;\n\t\t\t\tservice?: string | null;\n\t\t\t\tmetadata?: { owner?: string | null; repo?: string | null; number?: number | null } | null;\n\t\t }[]\n\t\t| null;\n};\n\nconst linearIssueTrashQuery = `\n\tquery GetLinearIssueTrashStatus($id: String!) {\n\t\tissue(id: $id) { id trashed }\n\t}\n`;\n\nexport async function requestLinearIssueTrashed(\n\trequest: ProviderRequestFunction,\n\taccessToken: string,\n\tid: string,\n): Promise<boolean> {\n\tconst response = await request<{\n\t\tdata?: { issue?: { id: string; trashed: boolean | null } | null } | null;\n\t\terrors?: unknown;\n\t} | null>({\n\t\turl: linearGraphQLUrl,\n\t\tmethod: 'POST',\n\t\theaders: { Authorization: accessToken, 'Content-Type': 'application/json' },\n\t\tbody: JSON.stringify({ query: linearIssueTrashQuery, variables: { id: id } }),\n\t});\n\tconst { data, errors } = response.body ?? {};\n\tif (errors != null && (!Array.isArray(errors) || errors.length !== 0)) {\n\t\tthrow Object.assign(new Error('Linear could not read issue trash status'), { response: response });\n\t}\n\n\tconst issue = data?.issue;\n\tif (issue?.id !== id || (issue.trashed !== null && typeof issue.trashed !== 'boolean')) {\n\t\tthrow new Error('Linear did not return trash status for the requested issue');\n\t}\n\n\treturn issue.trashed === true;\n}\n\ntype LinearIssuesEtagResponse = {\n\tdata?: {\n\t\tissues?: { pageInfo?: { hasNextPage?: boolean }; nodes?: LinearIssueEtagNode[] } | null;\n\t} | null;\n\terrors?: unknown[];\n};\n\n/**\n * The cheap check behind the batch issue read's etags: the change state of up to {@link linearIssuesEtagMaxNumbers}\n * issues of one team in ONE GraphQL request, where the full read sends provider-apis' `issue(id:)` once per issue.\n * Linear returns only the issues it found, in its own order, so a caller matches them by number, never by position.\n *\n * Sent as provider-apis sends every Linear request: the token as the whole `Authorization` header, with no scheme.\n * GraphQL `errors` reject the whole request, as provider-apis rejects them, but keep the response so a throttling\n * code is still classified as one. The exception is the one provider-apis makes too: errors that all sit under\n * `syncedWith`, a nullable list, leave every other field whole. An issue whose list Linear failed to resolve falls\n * through to its full read (see {@link toLinearIssueEtagFields}); one whose list resolved but a link's coordinates\n * didn't keys that link without them, as the full read's row carries it. Unlike provider-apis, a throttled response\n * still throws here, so it is classified as a rate limit. A next page also rejects it: with every number unique within\n * a team, more issues than were asked for means the filter was not applied as written.\n */\nexport async function requestLinearIssuesEtagFields(\n\trequest: ProviderRequestFunction,\n\taccessToken: string,\n\tteamKey: string,\n\tnumbers: readonly number[],\n): Promise<LinearIssueEtagNode[]> {\n\tconst response = await request<LinearIssuesEtagResponse | null>({\n\t\turl: linearGraphQLUrl,\n\t\tmethod: 'POST',\n\t\theaders: { Authorization: accessToken, 'Content-Type': 'application/json' },\n\t\tbody: JSON.stringify({ query: linearIssuesEtagQuery, variables: { teamKey: teamKey, numbers: numbers } }),\n\t});\n\n\tconst body = response.body;\n\tconst syncedWithOnly =\n\t\tbody?.data != null &&\n\t\tArray.isArray(body.errors) &&\n\t\tbody.errors.every(\n\t\t\te =>\n\t\t\t\ttypeof e === 'object' &&\n\t\t\t\te != null &&\n\t\t\t\t'path' in e &&\n\t\t\t\tArray.isArray(e.path) &&\n\t\t\t\te.path.includes('syncedWith'),\n\t\t) &&\n\t\t!isLinearRateLimitedBody(body);\n\tif (body?.errors != null && !syncedWithOnly) {\n\t\tconst error = new Error(`Linear GraphQL errors: ${JSON.stringify(body.errors)}`);\n\t\tObject.assign(error, { response: response });\n\t\tthrow error;\n\t}\n\n\tconst issues = body?.data?.issues;\n\tif (!Array.isArray(issues?.nodes)) throw new Error('Linear returned no issues');\n\tif (issues.pageInfo?.hasNextPage !== false) throw new Error('Linear returned more issues than were asked for');\n\n\treturn issues.nodes;\n}\n\n/**\n * A cheap-checked issue's change state, as the fields the full row's etag reads. The full read's row is provider-apis'\n * Linear issue normalizer (0.65.0, `syncedWith` since GKDEV-3662) then `fromProviderIssue`, so this mirrors both:\n *\n * - provider-apis maps `state.type` to a category — `completed` to `DONE`, `canceled` and `duplicate` to `CANCELED`,\n * `started` to `IN_PROGRESS`, anything else (`backlog`, `unstarted`, `triage`) to `TO_DO`, and no state to none —\n * and sets `closedDate` from `archivedAt` (a falsy value reads as none);\n * - `fromProviderIssue` closes an issue that has a `closedDate` or a terminal category, so an archived issue is closed\n * whatever its state.\n * - provider-apis keeps a `syncedWith` entry for a GitHub link with an id, with its coordinates only when owner, repo\n * and a positive integer number are all there, so the etag lists each such link the same way.\n *\n * Throws on a missing or unparseable `updatedAt`, so the target falls through to the full read rather than matching an\n * etag the full row would compute from a fallback date (`fromProviderIssue` falls back to `closedDate`, then\n * `createdDate`). Throws on a `syncedWith` Linear failed to resolve too: an unknown list must not match a full row\n * read while Linear could resolve it, nor one read while it couldn't, which would keep that row unknown.\n */\nexport function toLinearIssueEtagFields(issue: LinearIssueEtagNode): IssueEtagFields {\n\tif (issue.archivedAt && issue.trashed !== null && issue.trashed !== false) {\n\t\tthrow new Error(`Linear did not return trash status for ${issue.identifier}`);\n\t}\n\n\tconst updatedDate = new Date(issue.updatedAt || Number.NaN);\n\tif (Number.isNaN(updatedDate.getTime())) {\n\t\tthrow new Error(`Linear returned no update time for ${issue.identifier}`);\n\t}\n\n\tif (issue.syncedWith == null) {\n\t\tthrow new Error(`Linear could not resolve the sync links of ${issue.identifier}`);\n\t}\n\n\tconst type = issue.state?.type;\n\tconst closed = Boolean(issue.archivedAt) || type === 'completed' || type === 'canceled' || type === 'duplicate';\n\treturn {\n\t\tstate: closed ? 'closed' : 'opened',\n\t\tupdatedDate: updatedDate,\n\t\tsyncedWithKeys: linearSyncedWithEtagKeys(\n\t\t\tissue.syncedWith.flatMap((synced): IssueSyncedWith[] => {\n\t\t\t\tif (synced.service !== 'github' || !synced.id) return [];\n\n\t\t\t\tconst { owner, repo, number } = synced.metadata ?? {};\n\t\t\t\treturn [\n\t\t\t\t\towner && repo && typeof number === 'number' && Number.isInteger(number) && number > 0\n\t\t\t\t\t\t? { provider: 'github', id: synced.id, owner: owner, repo: repo, number: number }\n\t\t\t\t\t\t: { provider: 'github', id: synced.id },\n\t\t\t\t];\n\t\t\t}),\n\t\t),\n\t};\n}\n"],"mappings":";;;AAMA,MAAM,mBAAmB;;AAGzB,MAAa,6BAA6B;;;;;AAM1C,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmD9B,MAAM,wBAAwB;;;;;AAM9B,eAAsB,0BACrB,SACA,aACA,IACmB;CACnB,MAAM,WAAW,MAAM,QAGb;EACT,KAAK;EACL,QAAQ;EACR,SAAS;GAAE,eAAe;GAAa,gBAAgB;EAAmB;EAC1E,MAAM,KAAK,UAAU;GAAE,OAAO;GAAuB,WAAW,EAAM,GAAG;EAAE,CAAC;CAC7E,CAAC;CACD,MAAM,EAAE,MAA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,wBAAwB,OAA6C;CACpF,IAAI,MAAM,cAAc,MAAM,YAAY,QAAQ,MAAM,YAAY,OACnE,MAAM,IAAI,MAAM,0CAA0C,MAAM,YAAY;CAG7E,MAAM,cAAc,IAAI,KAAK,MAAM,aAAa,GAAU;CAC1D,IAAI,OAAO,MAAM,YAAY,QAAQ,CAAC,GACrC,MAAM,IAAI,MAAM,sCAAsC,MAAM,YAAY;CAGzE,IAAI,MAAM,cAAc,MACvB,MAAM,IAAI,MAAM,8CAA8C,MAAM,YAAY;CAGjF,MAAM,OAAO,MAAM,OAAO;CAE1B,OAAO;EACN,OAFc,QAAQ,MAAM,UAAU,KAAK,SAAS,eAAe,SAAS,cAAc,SAAS,cAEnF,WAAW;EACd;EACb,gBAAgB,yBACf,MAAM,WAAW,SAAS,WAA8B;GACvD,IAAI,OAAO,YAAY,YAAY,CAAC,OAAO,IAAI,OAAO,CAAC;GAEvD,MAAM,EAAE,OAAO,MAAM,WAAW,OAAO,YAAY,CAAC;GACpD,OAAO,CACN,SAAS,QAAQ,OAAO,WAAW,YAAY,OAAO,UAAU,MAAM,KAAK,SAAS,IACjF;IAAE,UAAU;IAAU,IAAI,OAAO;IAAW;IAAa;IAAc;GAAO,IAC9E;IAAE,UAAU;IAAU,IAAI,OAAO;GAAG,CACxC;EACD,CAAC,CACF;CACD;AACD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProviderRequestFunction, ProviderRequestResponse } from "./models.js";
|
|
2
2
|
//#region ../plus/integrations/src/providers/providerApiClient.d.ts
|
|
3
|
-
export declare function createProviderApiRequest(fetch: (input: string | URL, init?: RequestInit) => Promise<Response>, userAgent?: string): ProviderRequestFunction;
|
|
4
|
-
export declare function parseFetchResponseForApi<T>(response: Response, sentCredential?: () => boolean, requestUrl?: string): Promise<ProviderRequestResponse<T>>;
|
|
3
|
+
export declare function createProviderApiRequest(fetch: (input: string | URL, init?: RequestInit) => Promise<Response>, userAgent?: string, parseGraphQLErrorBody?: boolean): ProviderRequestFunction;
|
|
4
|
+
export declare function parseFetchResponseForApi<T>(response: Response, sentCredential?: () => boolean, requestUrl?: string, parseGraphQLErrorBody?: boolean): Promise<ProviderRequestResponse<T>>;
|
|
5
5
|
//#endregion
|
|
6
6
|
//# sourceMappingURL=providerApiClient.d.ts.map
|
|
@@ -2,7 +2,7 @@ import { getAuthenticatedUser } from "../errors.js";
|
|
|
2
2
|
import { AnonymousResponseError, UnexpectedHtmlResponseError, getProviderResponseBodyMessage, markRequestError } from "./providerErrors.js";
|
|
3
3
|
import { captureProviderRead } from "@gitkraken/provider-apis/read-provenance";
|
|
4
4
|
//#region ../plus/integrations/src/providers/providerApiClient.ts
|
|
5
|
-
function createProviderApiRequest(fetch, userAgent) {
|
|
5
|
+
function createProviderApiRequest(fetch, userAgent, parseGraphQLErrorBody = false) {
|
|
6
6
|
return async ({ url, ...options }) => {
|
|
7
7
|
try {
|
|
8
8
|
return await captureProviderRead(async () => {
|
|
@@ -12,7 +12,7 @@ function createProviderApiRequest(fetch, userAgent) {
|
|
|
12
12
|
...userAgent != null ? { "User-Agent": userAgent } : {},
|
|
13
13
|
...options.headers
|
|
14
14
|
}
|
|
15
|
-
}), () => hasAuthorization(options.headers), url);
|
|
15
|
+
}), () => hasAuthorization(options.headers), url, parseGraphQLErrorBody);
|
|
16
16
|
});
|
|
17
17
|
} catch (ex) {
|
|
18
18
|
throw markRequestError(ex, {
|
|
@@ -22,7 +22,7 @@ function createProviderApiRequest(fetch, userAgent) {
|
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
async function parseFetchResponseForApi(response, sentCredential, requestUrl = response.url) {
|
|
25
|
+
async function parseFetchResponseForApi(response, sentCredential, requestUrl = response.url, parseGraphQLErrorBody = false) {
|
|
26
26
|
const contentType = (response.headers.get("content-type") || "").toLowerCase();
|
|
27
27
|
if (response.status !== 401 && response.status !== 429 && response.status < 500 && getAuthenticatedUser(response.headers) === "anonymous" && sentCredential?.() === true) {
|
|
28
28
|
response.body?.cancel().catch(() => void 0);
|
|
@@ -35,9 +35,9 @@ async function parseFetchResponseForApi(response, sentCredential, requestUrl = r
|
|
|
35
35
|
let servedHtml = false;
|
|
36
36
|
const headers = Object.fromEntries(response.headers.entries());
|
|
37
37
|
try {
|
|
38
|
-
if (!response.ok && requestUrl === "https://api.github.com/graphql") {
|
|
38
|
+
if (!response.ok && (parseGraphQLErrorBody || requestUrl === "https://api.github.com/graphql")) {
|
|
39
39
|
body = await response.json();
|
|
40
|
-
if (body == null || typeof body !== "object" || Array.isArray(body)) throw new Error("Expected a
|
|
40
|
+
if (body == null || typeof body !== "object" || Array.isArray(body)) throw new Error("Expected a GraphQL response object.");
|
|
41
41
|
} else if (contentType.startsWith("application/json")) {
|
|
42
42
|
const text = await response.text();
|
|
43
43
|
if (text.trimStart().startsWith("<")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providerApiClient.js","names":[],"sources":["../../../../../plus/integrations/src/providers/providerApiClient.ts"],"sourcesContent":["import { captureProviderRead } from '@gitkraken/provider-apis/read-provenance';\nimport { getAuthenticatedUser } from '../errors.js';\nimport type { ProviderRequestFunction, ProviderRequestOptions, ProviderRequestResponse } from './models.js';\nimport {\n\tAnonymousResponseError,\n\tgetProviderResponseBodyMessage,\n\tmarkRequestError,\n\tUnexpectedHtmlResponseError,\n} from './providerErrors.js';\n\nexport function createProviderApiRequest(\n\tfetch: (input: string | URL, init?: RequestInit) => Promise<Response>,\n\tuserAgent?: string,\n): ProviderRequestFunction {\n\treturn async <T>({ url, ...options }: ProviderRequestOptions): Promise<ProviderRequestResponse<T>> => {\n\t\ttry {\n\t\t\treturn await captureProviderRead(async () => {\n\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: { ...(userAgent != null ? { 'User-Agent': userAgent } : {}), ...options.headers },\n\t\t\t\t});\n\t\t\t\treturn parseFetchResponseForApi<T>(
|
|
1
|
+
{"version":3,"file":"providerApiClient.js","names":[],"sources":["../../../../../plus/integrations/src/providers/providerApiClient.ts"],"sourcesContent":["import { captureProviderRead } from '@gitkraken/provider-apis/read-provenance';\nimport { getAuthenticatedUser } from '../errors.js';\nimport type { ProviderRequestFunction, ProviderRequestOptions, ProviderRequestResponse } from './models.js';\nimport {\n\tAnonymousResponseError,\n\tgetProviderResponseBodyMessage,\n\tmarkRequestError,\n\tUnexpectedHtmlResponseError,\n} from './providerErrors.js';\n\nexport function createProviderApiRequest(\n\tfetch: (input: string | URL, init?: RequestInit) => Promise<Response>,\n\tuserAgent?: string,\n\tparseGraphQLErrorBody = false,\n): ProviderRequestFunction {\n\treturn async <T>({ url, ...options }: ProviderRequestOptions): Promise<ProviderRequestResponse<T>> => {\n\t\ttry {\n\t\t\treturn await captureProviderRead(async () => {\n\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: { ...(userAgent != null ? { 'User-Agent': userAgent } : {}), ...options.headers },\n\t\t\t\t});\n\t\t\t\treturn parseFetchResponseForApi<T>(\n\t\t\t\t\tresponse,\n\t\t\t\t\t() => hasAuthorization(options.headers),\n\t\t\t\t\turl,\n\t\t\t\t\tparseGraphQLErrorBody,\n\t\t\t\t);\n\t\t\t});\n\t\t} catch (ex) {\n\t\t\tthrow markRequestError(ex, { url: url, method: options.method });\n\t\t}\n\t};\n}\n\nexport async function parseFetchResponseForApi<T>(\n\tresponse: Response,\n\tsentCredential?: () => boolean,\n\trequestUrl = response.url,\n\tparseGraphQLErrorBody = false,\n): Promise<ProviderRequestResponse<T>> {\n\tconst contentType = (response.headers.get('content-type') || '').toLowerCase();\n\n\tif (\n\t\tresponse.status !== 401 &&\n\t\tresponse.status !== 429 &&\n\t\tresponse.status < 500 &&\n\t\tgetAuthenticatedUser(response.headers) === 'anonymous' &&\n\t\tsentCredential?.() === true\n\t) {\n\t\tvoid response.body?.cancel().catch(() => undefined);\n\t\tthrow new AnonymousResponseError(response.status, {\n\t\t\theaders: Object.fromEntries(response.headers.entries()),\n\t\t\tstatus: response.status,\n\t\t});\n\t}\n\n\tlet body;\n\tlet servedHtml = false;\n\n\tconst headers = Object.fromEntries(response.headers.entries());\n\ttry {\n\t\tif (!response.ok && (parseGraphQLErrorBody || requestUrl === 'https://api.github.com/graphql')) {\n\t\t\t// KEEP: GraphQL execution evidence can arrive with a missing or incorrect media type.\n\t\t\tbody = await response.json();\n\t\t\tif (body == null || typeof body !== 'object' || Array.isArray(body)) {\n\t\t\t\tthrow new Error('Expected a GraphQL response object.');\n\t\t\t}\n\t\t} else if (contentType.startsWith('application/json')) {\n\t\t\tconst text = await response.text();\n\t\t\tif (text.trimStart().startsWith('<')) {\n\t\t\t\tservedHtml = true;\n\t\t\t\tbody = text;\n\t\t\t} else {\n\t\t\t\tbody = text.trim().length > 0 ? JSON.parse(text) : null;\n\t\t\t}\n\t\t} else if (contentType.startsWith('text/') || contentType === '') {\n\t\t\tbody = await response.text();\n\t\t\tservedHtml = contentType.startsWith('text/html') && body.trim().length > 0;\n\t\t} else if (contentType.startsWith('application/vnd.github.raw+json')) {\n\t\t\tbody = await response.arrayBuffer();\n\t\t} else {\n\t\t\tvoid response.body?.cancel().catch(() => undefined);\n\t\t\tthrow new Error(`Unsupported content-type: ${contentType}`);\n\t\t}\n\t} catch (ex) {\n\t\tif (response.ok) throw ex;\n\n\t\tconst header = response.status === 401 ? 'x-ausername' : 'retry-after';\n\t\tconst value = response.status === 401 || response.status === 403 ? response.headers.get(header) : null;\n\t\tconst insufficientScope =\n\t\t\t(response.status === 401 || response.status === 403) &&\n\t\t\t/\\binsufficient[_ -]scope\\b|scope does not match|does not have (?:the )?required scope/i.test(\n\t\t\t\tresponse.headers.get('www-authenticate') ?? '',\n\t\t\t);\n\t\tthrow Object.assign(new Error(`(${response.status}) Unable to decode the provider response.`), {\n\t\t\tstatusCode: response.status,\n\t\t\t...((value != null || insufficientScope) && {\n\t\t\t\tresponse: {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t...(value != null && { [header]: value }),\n\t\t\t\t\t\t...(insufficientScope && { 'www-authenticate': 'Bearer error=\"insufficient_scope\"' }),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t}\n\n\tconst result = {\n\t\tbody: body,\n\t\theaders: headers,\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t};\n\n\tif (response.ok && servedHtml) {\n\t\tthrow new UnexpectedHtmlResponseError(response.status, contentType, result);\n\t}\n\n\tif (!response.ok) {\n\t\tconst status = `(${response.status})${response.statusText ? ` ${response.statusText}` : ''}.`;\n\t\tconst detail = getProviderResponseBodyMessage(body);\n\t\tconst error = new Error(detail != null ? `${status} ${detail}` : status);\n\t\tObject.assign(error, { response: result });\n\t\tthrow error;\n\t}\n\n\treturn result;\n}\n\nfunction hasAuthorization(headers: ProviderRequestOptions['headers']): boolean {\n\tif (headers == null) return false;\n\n\treturn Object.entries(headers).some(([name, value]) => name.toLowerCase() === 'authorization' && Boolean(value));\n}\n"],"mappings":";;;;AAUA,SAAgB,yBACf,OACA,WACA,wBAAwB,OACE;CAC1B,OAAO,OAAU,EAAE,KAAK,GAAG,cAA2E;EACrG,IAAI;GACH,OAAO,MAAM,oBAAoB,YAAY;IAK5C,OAAO,yBACN,MALsB,MAAM,KAAK;KACjC,GAAG;KACH,SAAS;MAAE,GAAI,aAAa,OAAO,EAAE,cAAc,UAAU,IAAI,CAAC;MAAI,GAAG,QAAQ;KAAQ;IAC1F,CAAC,SAGM,iBAAiB,QAAQ,OAAO,GACtC,KACA,qBACD;GACD,CAAC;EACF,SAAS,IAAI;GACZ,MAAM,iBAAiB,IAAI;IAAO;IAAK,QAAQ,QAAQ;GAAO,CAAC;EAChE;CACD;AACD;AAEA,eAAsB,yBACrB,UACA,gBACA,aAAa,SAAS,KACtB,wBAAwB,OACc;CACtC,MAAM,eAAe,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CAAI,YAAY;CAE7E,IACC,SA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AM,QAAQ,SAAS,WAAW,OAAO,SAAS,WAAW,MAAM,SAAS,QAAQ,IAAI,MAAM,IAAI;EAClG,MAAM,qBACJ,SAAS,WAAW,OAAO,SAAS,WAAW,QAChD,yFAAyF,KACxF,SAAS,QAAQ,IAAI,kBAAkB,KAAK,EAC7C;EACD,MAAM,OAAO,uBAAO,IAAI,MAAM,IAAI,SAAS,OAAO,0CAA0C,GAAG;GAC9F,YAAY,SAAS;GACrB,IAAK,SAAS,QAAQ,sBAAsB,EAC3C,UAAU;IACT,QAAQ,SAAS;IACjB,SAAS;KACR,GAAI,SAAS,QAAQ,GAAG,SAAS,MAAM;KACvC,GAAI,qBAAqB,EAAE,oBAAoB,sCAAoC;IACpF;GACD,EACD;EACD,CAAC;CACF;CAEA,MAAM,SAAS;EACR;EACG;EACT,QAAQ,SAAS;EACjB,YAAY,SAAS;CACtB;CAEA,IAAI,SAAS,MAAM,YAClB,MAAM,IAAI,4BAA4B,SAAS,QAAQ,aAAa,MAAM;CAG3E,IAAI,CAAC,SAAS,IAAI;EACjB,MAAM,SAAS,IAAI,SAAS,OAAO,GAAG,SAAS,aAAa,IAAI,SAAS,eAAe,GAAG;EAC3F,MAAM,SAAS,+BAA+B,IAAI;EAClD,MAAM,QAAQ,IAAI,MAAM,UAAU,OAAO,GAAG,OAAO,GAAG,WAAW,MAAM;EACvE,OAAO,OAAO,OAAO,EAAE,UAAU,OAAO,CAAC;EACzC,MAAM;CACP;CAEA,OAAO;AACR;AAEA,SAAS,iBAAiB,SAAqD;CAC9E,IAAI,WAAW,MAAM,OAAO;CAE5B,OAAO,OAAO,QAAQ,OAAO,CAAC,CAAC,MAAM,CAAC,MAAM,WAAW,KAAK,YAAY,MAAM,mBAAmB,QAAQ,KAAK,CAAC;AAChH"}
|
|
@@ -77,6 +77,15 @@ type SanitizedErrorResponse = {
|
|
|
77
77
|
status: number;
|
|
78
78
|
};
|
|
79
79
|
export declare function sanitizeErrorResponse(status: number, response: ProviderErrorResponse | undefined): SanitizedErrorResponse;
|
|
80
|
+
type ProviderGraphQLError = {
|
|
81
|
+
message?: unknown;
|
|
82
|
+
path?: unknown;
|
|
83
|
+
extensions?: {
|
|
84
|
+
code?: unknown;
|
|
85
|
+
type?: unknown;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
export declare function getProviderGraphQLErrors(body: unknown): ProviderGraphQLError[];
|
|
80
89
|
export declare function isAzureProviderId(providerId: IntegrationIds): providerId is GitCloudHostIntegrationId.AzureDevOps | GitSelfManagedHostIntegrationId.AzureDevOpsServer;
|
|
81
90
|
export declare function isGitHubProviderId(providerId: IntegrationIds): providerId is GitCloudHostIntegrationId.GitHub | GitSelfManagedHostIntegrationId.CloudGitHubEnterprise;
|
|
82
91
|
/**
|
|
@@ -273,6 +273,6 @@ function getProviderResponseBodyMessage(body) {
|
|
|
273
273
|
return message ? message.slice(0, maxProviderErrorBodyLength) : void 0;
|
|
274
274
|
}
|
|
275
275
|
//#endregion
|
|
276
|
-
export { AnonymousResponseError, CommitReadRefusedError, UnexpectedHtmlResponseError, UnexpectedResponseError, getProviderResponseBodyMessage, githubGraphQLInt32Max, isAzureProviderId, isCommitReadRefusal, isGitHubProviderId, isJiraMissingProjectError, isJiraServerMissingProjectError, isLinearRateLimitedBody, isNotFoundResponse, isProviderIssueNotFoundError, markRequestError, sanitizeErrorResponse, throwProviderError };
|
|
276
|
+
export { AnonymousResponseError, CommitReadRefusedError, UnexpectedHtmlResponseError, UnexpectedResponseError, getProviderGraphQLErrors, getProviderResponseBodyMessage, githubGraphQLInt32Max, isAzureProviderId, isCommitReadRefusal, isGitHubProviderId, isJiraMissingProjectError, isJiraServerMissingProjectError, isLinearRateLimitedBody, isNotFoundResponse, isProviderIssueNotFoundError, markRequestError, sanitizeErrorResponse, throwProviderError };
|
|
277
277
|
|
|
278
278
|
//# sourceMappingURL=providerErrors.js.map
|