@gitkraken/core-gitlens 0.49.0 → 0.50.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 (30) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +1 -0
  3. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +3 -0
  4. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  5. package/dist/plus/integrations/index.d.ts +3 -2
  6. package/dist/plus/integrations/index.js.map +1 -1
  7. package/dist/plus/integrations/integrationService.d.ts +9 -0
  8. package/dist/plus/integrations/integrationService.js +43 -0
  9. package/dist/plus/integrations/integrationService.js.map +1 -1
  10. package/dist/plus/integrations/manager.d.ts +6 -0
  11. package/dist/plus/integrations/models/workItemWrites.d.ts +136 -0
  12. package/dist/plus/integrations/models/workItemWrites.js +0 -0
  13. package/dist/plus/integrations/providers/azure/workItemWriteMetadata.d.ts +38 -0
  14. package/dist/plus/integrations/providers/azure/workItemWriteMetadata.js +73 -0
  15. package/dist/plus/integrations/providers/azure/workItemWriteMetadata.js.map +1 -0
  16. package/dist/plus/integrations/providers/azureDevOps.d.ts +3 -0
  17. package/dist/plus/integrations/providers/azureDevOps.js +12 -1
  18. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  19. package/dist/plus/integrations/providers/azureDevOpsServer.d.ts +1 -1
  20. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.d.ts +17 -0
  21. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js +100 -0
  22. package/dist/plus/integrations/providers/azureWorkItemWriteErrors.js.map +1 -0
  23. package/dist/plus/integrations/providers/azureWorkItemWrites.d.ts +38 -0
  24. package/dist/plus/integrations/providers/azureWorkItemWrites.js +442 -0
  25. package/dist/plus/integrations/providers/azureWorkItemWrites.js.map +1 -0
  26. package/dist/plus/integrations/providers/providersApi.d.ts +4 -1
  27. package/dist/plus/integrations/providers/providersApi.js +7 -0
  28. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  29. package/docs/integrations.md +64 -0
  30. package/package.json +1 -1
@@ -14,9 +14,9 @@ import { ProviderIssueSearchPage, ProviderSearchCount } from "../models/issueRea
14
14
  import "../models/integration.js";
15
15
  import { ProviderAzureResource, ProviderRepoInput, ProviderReposInput } from "./models.js";
16
16
  import { RepositoryCoordinate } from "../models/gitHostIntegration.js";
17
+ import { AzureDevOpsIntegrationBase, AzureRepositoryTarget } from "./azureDevOps.js";
17
18
  import { IntegrationConnectionChangeEvent } from "../integrationService.js";
18
19
  import { IntegrationAuthenticationService } from "../authentication/integrationAuthenticationService.js";
19
- import { AzureDevOpsIntegrationBase, AzureRepositoryTarget } from "./azureDevOps.js";
20
20
  //#region ../plus/integrations/src/providers/azureDevOpsServer.d.ts
21
21
  export declare class AzureDevOpsServerIntegration extends AzureDevOpsIntegrationBase<GitSelfManagedHostIntegrationId.AzureDevOpsServer> {
22
22
  readonly domain: string;
@@ -0,0 +1,17 @@
1
+ import { IssueTrackerWriteFailure } from "../models/issueTrackerWrites.js";
2
+ import { WorkItemWriteField, WorkItemWriteScope } from "../models/workItemWrites.js";
3
+ //#region ../plus/integrations/src/providers/azureWorkItemWriteErrors.d.ts
4
+ export declare function isWorkItemWriteScope(options: WorkItemWriteScope): boolean;
5
+ export declare function isGuid(value: unknown): value is string;
6
+ export declare function isWorkItemIdentifier(value: unknown): value is string;
7
+ export declare function isWorkItemNumber(value: unknown): value is number;
8
+ export declare class WorkItemWriteError extends Error {
9
+ readonly reason: IssueTrackerWriteFailure['reason'];
10
+ readonly fieldErrors?: Readonly<Record<string, string>> | undefined;
11
+ constructor(reason: IssueTrackerWriteFailure['reason'], fieldErrors?: Readonly<Record<string, string>> | undefined);
12
+ }
13
+ export declare function toWorkItemWriteFailure(ex: unknown, dispatched?: {
14
+ fields: readonly WorkItemWriteField[];
15
+ }): IssueTrackerWriteFailure;
16
+ //#endregion
17
+ //# sourceMappingURL=azureWorkItemWriteErrors.d.ts.map
@@ -0,0 +1,100 @@
1
+ import { AnonymousResponseError, UnexpectedHtmlResponseError, getProviderResponseBodyMessage } from "./providerErrors.js";
2
+ //#region ../plus/integrations/src/providers/azureWorkItemWriteErrors.ts
3
+ const guidPattern = /^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i;
4
+ function isWorkItemWriteScope(options) {
5
+ return isWorkItemIdentifier(options.connectionId) && isGuid(options.organizationId) && typeof options.organizationName === "string" && /^[a-z0-9][a-z0-9-]*$/i.test(options.organizationName) && isGuid(options.projectId) && (options.expectedAccountId === void 0 || isWorkItemIdentifier(options.expectedAccountId));
6
+ }
7
+ function isGuid(value) {
8
+ return typeof value === "string" && guidPattern.test(value);
9
+ }
10
+ function isWorkItemIdentifier(value) {
11
+ return typeof value === "string" && value.length > 0 && value.trim() === value && ![...value].some((character) => character < " " || character === "");
12
+ }
13
+ function isWorkItemNumber(value) {
14
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 2147483647;
15
+ }
16
+ var WorkItemWriteError = class extends Error {
17
+ reason;
18
+ fieldErrors;
19
+ constructor(reason, fieldErrors) {
20
+ super(reason);
21
+ this.reason = reason;
22
+ this.fieldErrors = fieldErrors;
23
+ }
24
+ };
25
+ function getRuleErrors(body, fields) {
26
+ const data = body;
27
+ const rows = data?.ruleValidationErrors ?? data?.customProperties?.ruleValidationErrors ?? data?.customProperties?.RuleValidationErrors;
28
+ const message = getProviderResponseBodyMessage(body);
29
+ const messages = /* @__PURE__ */ new Set();
30
+ const fieldErrors = /* @__PURE__ */ new Map();
31
+ if (message) messages.add(message);
32
+ if (Array.isArray(rows)) for (const row of rows) {
33
+ const error = row;
34
+ if (typeof error?.errorMessage !== "string") continue;
35
+ messages.add(error.errorMessage);
36
+ if (typeof error.fieldReferenceName === "string") fieldErrors.set(error.fieldReferenceName, error.errorMessage);
37
+ }
38
+ const fieldName = /TF401320:\s*Rule Error for field (.+?)\.\s+Error code:/i.exec(message ?? "")?.[1];
39
+ if (fieldName != null) {
40
+ const matches = fields.filter((field) => field.name === fieldName || field.referenceName === fieldName);
41
+ if (matches.length === 1 && message && !fieldErrors.has(matches[0].referenceName)) fieldErrors.set(matches[0].referenceName, message);
42
+ }
43
+ return {
44
+ ...messages.size && { messages: [...messages] },
45
+ ...fieldErrors.size && { fieldErrors: Object.fromEntries(fieldErrors) }
46
+ };
47
+ }
48
+ function toWorkItemWriteFailure(ex, dispatched) {
49
+ if (ex instanceof WorkItemWriteError && dispatched == null) return {
50
+ ok: false,
51
+ reason: ex.reason,
52
+ mutationDispatched: false,
53
+ ...ex.fieldErrors && { fieldErrors: ex.fieldErrors }
54
+ };
55
+ if (dispatched == null && (UnexpectedHtmlResponseError.is(ex) || AnonymousResponseError.is(ex))) return {
56
+ ok: false,
57
+ reason: "no-connection",
58
+ mutationDispatched: false
59
+ };
60
+ const response = ex?.response;
61
+ const status = response?.status;
62
+ const body = response?.body;
63
+ const type = body?.typeKey;
64
+ const message = getProviderResponseBodyMessage(body) ?? "";
65
+ let reason;
66
+ switch (status) {
67
+ case 400:
68
+ case 413:
69
+ case 422:
70
+ reason = type === "WorkItemRevisionMismatchException" ? "conflict" : "invalid-input";
71
+ break;
72
+ case 401:
73
+ case 403:
74
+ if (/\binsufficient[_ -]scope\b|scope does not match|\bvso\.work_write\b/i.test(`${response?.headers?.["www-authenticate"] ?? ""} ${message}`)) reason = "insufficient-scope";
75
+ else reason = status === 401 && dispatched == null ? "no-connection" : "forbidden";
76
+ break;
77
+ case 404:
78
+ reason = "not-found";
79
+ break;
80
+ case 409:
81
+ case 412:
82
+ reason = "conflict";
83
+ break;
84
+ case 429:
85
+ reason = "rate-limit";
86
+ break;
87
+ default: reason = "unknown";
88
+ }
89
+ return {
90
+ ok: false,
91
+ reason,
92
+ ...dispatched == null && { mutationDispatched: false },
93
+ ...dispatched != null && reason === "unknown" && { applied: "maybe" },
94
+ ...reason === "invalid-input" && getRuleErrors(body, dispatched?.fields ?? [])
95
+ };
96
+ }
97
+ //#endregion
98
+ export { WorkItemWriteError, isGuid, isWorkItemIdentifier, isWorkItemNumber, isWorkItemWriteScope, toWorkItemWriteFailure };
99
+
100
+ //# sourceMappingURL=azureWorkItemWriteErrors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"azureWorkItemWriteErrors.js","names":[],"sources":["../../../../../plus/integrations/src/providers/azureWorkItemWriteErrors.ts"],"sourcesContent":["import type { IssueTrackerWriteFailure } from '../models/issueTrackerWrites.js';\nimport type { WorkItemWriteField, WorkItemWriteScope } from '../models/workItemWrites.js';\nimport {\n\tAnonymousResponseError,\n\tgetProviderResponseBodyMessage,\n\tUnexpectedHtmlResponseError,\n} from './providerErrors.js';\n\nconst guidPattern = /^[\\da-f]{8}-(?:[\\da-f]{4}-){3}[\\da-f]{12}$/i;\n\nexport function isWorkItemWriteScope(options: WorkItemWriteScope): boolean {\n\treturn (\n\t\tisWorkItemIdentifier(options.connectionId) &&\n\t\tisGuid(options.organizationId) &&\n\t\ttypeof options.organizationName === 'string' &&\n\t\t/^[a-z0-9][a-z0-9-]*$/i.test(options.organizationName) &&\n\t\tisGuid(options.projectId) &&\n\t\t(options.expectedAccountId === undefined || isWorkItemIdentifier(options.expectedAccountId))\n\t);\n}\n\nexport function isGuid(value: unknown): value is string {\n\treturn typeof value === 'string' && guidPattern.test(value);\n}\n\nexport function isWorkItemIdentifier(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === 'string' &&\n\t\tvalue.length > 0 &&\n\t\tvalue.trim() === value &&\n\t\t![...value].some(character => character < ' ' || character === '\\x7f')\n\t);\n}\n\nexport function isWorkItemNumber(value: unknown): value is number {\n\treturn typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 2147483647;\n}\n\nexport class WorkItemWriteError extends Error {\n\tconstructor(\n\t\treadonly reason: IssueTrackerWriteFailure['reason'],\n\t\treadonly fieldErrors?: Readonly<Record<string, string>>,\n\t) {\n\t\tsuper(reason);\n\t}\n}\n\nfunction getRuleErrors(body: unknown, fields: readonly WorkItemWriteField[]) {\n\tconst data = body as\n\t\t| {\n\t\t\t\truleValidationErrors?: unknown;\n\t\t\t\tcustomProperties?: { ruleValidationErrors?: unknown; RuleValidationErrors?: unknown };\n\t\t }\n\t\t| undefined;\n\tconst rows =\n\t\tdata?.ruleValidationErrors ??\n\t\tdata?.customProperties?.ruleValidationErrors ??\n\t\tdata?.customProperties?.RuleValidationErrors;\n\tconst message = getProviderResponseBodyMessage(body);\n\tconst messages = new Set<string>();\n\tconst fieldErrors = new Map<string, string>();\n\tif (message) {\n\t\tmessages.add(message);\n\t}\n\n\tif (Array.isArray(rows)) {\n\t\tfor (const row of rows) {\n\t\t\tconst error = row as { fieldReferenceName?: unknown; errorMessage?: unknown } | null;\n\t\t\tif (typeof error?.errorMessage !== 'string') continue;\n\n\t\t\tmessages.add(error.errorMessage);\n\t\t\tif (typeof error.fieldReferenceName === 'string') {\n\t\t\t\tfieldErrors.set(error.fieldReferenceName, error.errorMessage);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst fieldName = /TF401320:\\s*Rule Error for field (.+?)\\.\\s+Error code:/i.exec(message ?? '')?.[1];\n\tif (fieldName != null) {\n\t\tconst matches = fields.filter(field => field.name === fieldName || field.referenceName === fieldName);\n\t\tif (matches.length === 1 && message && !fieldErrors.has(matches[0].referenceName)) {\n\t\t\tfieldErrors.set(matches[0].referenceName, message);\n\t\t}\n\t}\n\treturn {\n\t\t...(messages.size && { messages: [...messages] }),\n\t\t...(fieldErrors.size && { fieldErrors: Object.fromEntries(fieldErrors) }),\n\t};\n}\n\nexport function toWorkItemWriteFailure(\n\tex: unknown,\n\tdispatched?: { fields: readonly WorkItemWriteField[] },\n): IssueTrackerWriteFailure {\n\tif (ex instanceof WorkItemWriteError && dispatched == null) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\treason: ex.reason,\n\t\t\tmutationDispatched: false,\n\t\t\t...(ex.fieldErrors && { fieldErrors: ex.fieldErrors }),\n\t\t};\n\t}\n\n\tif (dispatched == null && (UnexpectedHtmlResponseError.is(ex) || AnonymousResponseError.is(ex))) {\n\t\treturn { ok: false, reason: 'no-connection', mutationDispatched: false };\n\t}\n\n\tconst response = (\n\t\tex as\n\t\t\t| {\n\t\t\t\t\tresponse?: { status?: number; body?: unknown; headers?: Record<string, string> };\n\t\t\t }\n\t\t\t| undefined\n\t)?.response;\n\tconst status = response?.status;\n\tconst body = response?.body;\n\tconst type = (body as { typeKey?: unknown } | undefined)?.typeKey;\n\tconst message = getProviderResponseBodyMessage(body) ?? '';\n\tlet reason: IssueTrackerWriteFailure['reason'];\n\tswitch (status) {\n\t\tcase 400:\n\t\tcase 413:\n\t\tcase 422:\n\t\t\treason = type === 'WorkItemRevisionMismatchException' ? 'conflict' : 'invalid-input';\n\t\t\tbreak;\n\t\tcase 401:\n\t\tcase 403:\n\t\t\tif (\n\t\t\t\t/\\binsufficient[_ -]scope\\b|scope does not match|\\bvso\\.work_write\\b/i.test(\n\t\t\t\t\t`${response?.headers?.['www-authenticate'] ?? ''} ${message}`,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treason = 'insufficient-scope';\n\t\t\t} else {\n\t\t\t\treason = status === 401 && dispatched == null ? 'no-connection' : 'forbidden';\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 404:\n\t\t\treason = 'not-found';\n\t\t\tbreak;\n\t\tcase 409:\n\t\tcase 412:\n\t\t\treason = 'conflict';\n\t\t\tbreak;\n\t\tcase 429:\n\t\t\treason = 'rate-limit';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treason = 'unknown';\n\t}\n\n\treturn {\n\t\tok: false,\n\t\treason: reason,\n\t\t...(dispatched == null && { mutationDispatched: false }),\n\t\t...(dispatched != null && reason === 'unknown' && { applied: 'maybe' }),\n\t\t...(reason === 'invalid-input' && getRuleErrors(body, dispatched?.fields ?? [])),\n\t};\n}\n"],"mappings":";;AAQA,MAAM,cAAc;AAEpB,SAAgB,qBAAqB,SAAsC;CAC1E,O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;EACR,GAAI,cAAc,QAAQ,EAAE,oBAAoB,MAAM;EACtD,GAAI,cAAc,QAAQ,WAAW,aAAa,EAAE,SAAS,QAAQ;EACrE,GAAI,WAAW,mBAAmB,cAAc,MAAM,YAAY,UAAU,CAAC,CAAC;CAC/E;AACD"}
@@ -0,0 +1,38 @@
1
+ import { WorkItemAddress, WorkItemCreateOptions, WorkItemCreateOptionsResult, WorkItemDeleteOptions, WorkItemDeleteResult, WorkItemWriteOptions, WorkItemWriteOptionsResult, WorkItemWriteResult, WorkItemWriteScope, WorkItemWriteTargetOptions, WorkItemWriteTargetResult } from "../models/workItemWrites.js";
2
+ import { ProviderRequestFunction } from "./models.js";
3
+ //#region ../plus/integrations/src/providers/azureWorkItemWrites.d.ts
4
+ export declare class AzureWorkItemWriter {
5
+ private readonly request;
6
+ private readonly headers;
7
+ private readonly context;
8
+ private readonly organizationUrl;
9
+ private readonly isSessionCurrent;
10
+ static connect(request: ProviderRequestFunction, credential: {
11
+ accessToken: string;
12
+ authorization: string;
13
+ }, options: WorkItemWriteScope, isSessionCurrent: () => Promise<boolean>): Promise<AzureWorkItemWriter>;
14
+ private readonly projectUrl;
15
+ private constructor();
16
+ getCreateOptions(options: WorkItemCreateOptions): Promise<WorkItemCreateOptionsResult>;
17
+ getWriteOptions(options: WorkItemAddress): Promise<WorkItemWriteOptionsResult>;
18
+ resolveTarget(options: WorkItemWriteTargetOptions): Promise<WorkItemWriteTargetResult>;
19
+ write(options: WorkItemWriteOptions): Promise<WorkItemWriteResult>;
20
+ delete(options: WorkItemDeleteOptions): Promise<WorkItemDeleteResult>;
21
+ private toDeleteOutcome;
22
+ private findProject;
23
+ private create;
24
+ private getDeleteCapability;
25
+ private getMetadata;
26
+ private getItem;
27
+ private isInProject;
28
+ private itemType;
29
+ private getReceipt;
30
+ private assertSessionCurrent;
31
+ private url;
32
+ private read;
33
+ private readOrganization;
34
+ private get;
35
+ private save;
36
+ }
37
+ //#endregion
38
+ //# sourceMappingURL=azureWorkItemWrites.d.ts.map
@@ -0,0 +1,442 @@
1
+ import { encodeAzurePathSegment } from "./azure/models.js";
2
+ import { WorkItemWriteError, isGuid, isWorkItemIdentifier, isWorkItemNumber, toWorkItemWriteFailure } from "./azureWorkItemWriteErrors.js";
3
+ import { getAzureWorkItemBodyField, getAzureWorkItemTransitionTargets, isAzureProjectPathField, isAzureTestArtifact, toAzureWorkItemWriteFields } from "./azure/workItemWriteMetadata.js";
4
+ //#region ../plus/integrations/src/providers/azureWorkItemWrites.ts
5
+ const azureProfileApi = "https://app.vssps.visualstudio.com/_apis";
6
+ const projectSecurityNamespaceId = "52d39943-cb85-4d7f-8fa8-c6baac873819";
7
+ function sameIdentifier(actual, expected) {
8
+ return typeof actual === "string" && actual.toLowerCase() === expected.toLowerCase();
9
+ }
10
+ function isSameId(actual, id) {
11
+ return actual === id || actual === String(id);
12
+ }
13
+ function isDeletedItem(item, id) {
14
+ if (item == null || !isSameId(item.id, id) || !isWorkItemIdentifier(item.project)) return false;
15
+ return item.code == null || item.code === 0 || typeof item.code === "number" && item.code >= 200 && item.code < 300;
16
+ }
17
+ function getDeletedRevision(item, id) {
18
+ const resource = item.resource;
19
+ return resource != null && isSameId(resource.id, id) && isWorkItemNumber(resource.rev) ? resource.rev : void 0;
20
+ }
21
+ const azureDeletedDate = /^(\d{1,2})\/(\d{1,2})\/([12]\d{3}) (\d{1,2}):([0-5]\d):([0-5]\d) (AM|PM)$/;
22
+ function toDeletedAt(value) {
23
+ const match = typeof value === "string" ? azureDeletedDate.exec(value) : null;
24
+ if (match == null) return void 0;
25
+ const [month, day, year, hour, minute, second] = match.slice(1, 7).map(Number);
26
+ if (hour < 1 || hour > 12) return void 0;
27
+ const date = new Date(Date.UTC(year, month - 1, day, hour % 12 + (match[7] === "PM" ? 12 : 0), minute, second));
28
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) return;
29
+ return date.toISOString();
30
+ }
31
+ function readValues(body) {
32
+ if (!Array.isArray(body?.value)) throw new WorkItemWriteError("unknown");
33
+ return body.value;
34
+ }
35
+ function assertExistingAddress(address) {
36
+ if (!isWorkItemNumber(address.workItemId)) throw new WorkItemWriteError("invalid-input");
37
+ }
38
+ function assertMutationIdentity(expectedAccountId) {
39
+ if (!isWorkItemIdentifier(expectedAccountId)) throw new WorkItemWriteError("invalid-input");
40
+ }
41
+ function assertSameRevision(item, expectedRevision) {
42
+ if (!isWorkItemNumber(expectedRevision)) throw new WorkItemWriteError("invalid-input");
43
+ if (item.rev !== expectedRevision) throw new WorkItemWriteError("conflict");
44
+ }
45
+ function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
46
+ if (value == null) return value === null;
47
+ if (typeof value === "string" || typeof value === "boolean") return true;
48
+ if (typeof value === "number") return Number.isFinite(value);
49
+ if (typeof value !== "object" || ancestors.has(value)) return false;
50
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
51
+ ancestors.add(value);
52
+ const valid = Object.values(value).every((entry) => isJsonValue(entry, ancestors));
53
+ ancestors.delete(value);
54
+ return valid;
55
+ }
56
+ function isInProjectPath(value, projectName) {
57
+ if (typeof value !== "string") return false;
58
+ return value.split("\\", 1)[0].toLowerCase() === projectName.toLowerCase();
59
+ }
60
+ function getFieldPatches(input, fieldMetadata, projectName, current) {
61
+ if (input == null || typeof input !== "object" || Array.isArray(input)) throw new WorkItemWriteError("invalid-input");
62
+ const fields = new Map(fieldMetadata.map((field) => [field.referenceName, field]));
63
+ const errors = /* @__PURE__ */ new Map();
64
+ const patch = [];
65
+ for (const [name, value] of Object.entries(input)) {
66
+ const field = fields.get(name);
67
+ if (field == null || !isJsonValue(value)) {
68
+ errors.set(name, field == null ? "Field is unavailable for writing." : "Expected a JSON field value.");
69
+ continue;
70
+ }
71
+ if (isAzureProjectPathField(name) && !isInProjectPath(value, projectName)) {
72
+ errors.set(name, "Expected a path in the selected project.");
73
+ continue;
74
+ }
75
+ const path = `/fields/${name.replaceAll("~", "~0").replaceAll("/", "~1")}`;
76
+ if (current != null && value === null) {
77
+ if (Object.hasOwn(current, name)) patch.push({
78
+ op: "remove",
79
+ path
80
+ });
81
+ } else patch.push({
82
+ op: "add",
83
+ path,
84
+ value
85
+ });
86
+ }
87
+ if (current == null) for (const field of fieldMetadata) {
88
+ const value = Object.hasOwn(input, field.referenceName) ? input[field.referenceName] : void 0;
89
+ if (field.required && (value === null || value === "" || value === void 0 && !Object.hasOwn(field, "defaultValue"))) errors.set(field.referenceName, "This field is required.");
90
+ }
91
+ if (errors.size) throw new WorkItemWriteError("invalid-input", Object.fromEntries(errors));
92
+ return patch;
93
+ }
94
+ var AzureWorkItemWriter = class AzureWorkItemWriter {
95
+ request;
96
+ headers;
97
+ context;
98
+ organizationUrl;
99
+ isSessionCurrent;
100
+ static async connect(request, credential, options, isSessionCurrent) {
101
+ const { body: profile } = await request({
102
+ url: `${azureProfileApi}/profile/profiles/me`,
103
+ headers: { Authorization: `Bearer ${credential.accessToken}` },
104
+ redirect: "error"
105
+ });
106
+ const accountId = profile?.id;
107
+ if (!isWorkItemIdentifier(accountId) || options.expectedAccountId !== void 0 && !sameIdentifier(accountId, options.expectedAccountId)) throw new WorkItemWriteError("no-connection");
108
+ const headers = { Authorization: credential.authorization };
109
+ const { body: accounts } = await request({
110
+ url: `${azureProfileApi}/accounts?memberId=${encodeURIComponent(accountId)}&api-version=7.1`,
111
+ headers,
112
+ redirect: "error"
113
+ });
114
+ const organization = readValues(accounts).find((account) => sameIdentifier(account.accountId, options.organizationId) && sameIdentifier(account.accountName, options.organizationName));
115
+ if (organization == null) throw new WorkItemWriteError("not-found");
116
+ const organizationUrl = `https://dev.azure.com/${encodeAzurePathSegment(organization.accountName)}`;
117
+ const { body: project } = await request({
118
+ url: `${organizationUrl}/_apis/projects/${options.projectId}?api-version=7.1`,
119
+ headers,
120
+ redirect: "error"
121
+ });
122
+ if (!sameIdentifier(project?.id, options.projectId) || !isWorkItemIdentifier(project?.name)) throw new WorkItemWriteError("not-found");
123
+ return new AzureWorkItemWriter(request, headers, {
124
+ providerId: options.providerId,
125
+ connectionId: options.connectionId,
126
+ accountId,
127
+ organization: {
128
+ id: organization.accountId,
129
+ name: organization.accountName
130
+ },
131
+ project: {
132
+ id: project.id,
133
+ name: project.name
134
+ }
135
+ }, organizationUrl, isSessionCurrent);
136
+ }
137
+ projectUrl;
138
+ constructor(request, headers, context, organizationUrl, isSessionCurrent) {
139
+ this.request = request;
140
+ this.headers = headers;
141
+ this.context = context;
142
+ this.organizationUrl = organizationUrl;
143
+ this.isSessionCurrent = isSessionCurrent;
144
+ this.projectUrl = `${organizationUrl}/${context.project.id}`;
145
+ }
146
+ async getCreateOptions(options) {
147
+ if (options.workItemType === void 0) {
148
+ const enabled = readValues(await this.read("/workitemtypes")).filter((type) => isWorkItemIdentifier(type.name) && !type.isDisabled);
149
+ return {
150
+ ok: true,
151
+ ...this.context,
152
+ workItemTypes: enabled.map((type) => ({ name: type.name }))
153
+ };
154
+ }
155
+ const { type, fields, states, catalog } = await this.getMetadata(options.workItemType);
156
+ if (type.isDisabled) throw new WorkItemWriteError("invalid-input");
157
+ return {
158
+ ok: true,
159
+ ...this.context,
160
+ workItemType: type.name,
161
+ fields,
162
+ states,
163
+ initialStates: getAzureWorkItemTransitionTargets(type, states, ""),
164
+ bodyField: getAzureWorkItemBodyField(fields, catalog)
165
+ };
166
+ }
167
+ async getWriteOptions(options) {
168
+ const item = await this.getItem(options);
169
+ const metadata = await this.getMetadata(this.itemType(item));
170
+ const issue = this.getReceipt(item, metadata);
171
+ return {
172
+ ok: true,
173
+ ...this.context,
174
+ issue,
175
+ fields: metadata.fields,
176
+ availableStates: getAzureWorkItemTransitionTargets(metadata.type, metadata.states, issue.state.name),
177
+ deleteCapability: await this.getDeleteCapability(metadata.type).catch(() => ({ allowed: "unknown" })),
178
+ bodyField: issue.bodyField
179
+ };
180
+ }
181
+ async resolveTarget(options) {
182
+ if (options.intent !== void 0 && options.intent !== "delete") throw new WorkItemWriteError("invalid-input");
183
+ const item = await this.getItem(options);
184
+ const metadata = await this.getMetadata(this.itemType(item));
185
+ const issue = this.getReceipt(item, metadata);
186
+ const deleteCapability = options.intent === "delete" ? await this.getDeleteCapability(metadata.type) : void 0;
187
+ if (deleteCapability?.allowed === false) throw new WorkItemWriteError(deleteCapability.reason);
188
+ return {
189
+ ok: true,
190
+ ...this.context,
191
+ issue,
192
+ ...deleteCapability && { deleteCapability }
193
+ };
194
+ }
195
+ async write(options) {
196
+ assertMutationIdentity(options.expectedAccountId);
197
+ if (options.action === "create") return this.create(options);
198
+ if (options.action !== "edit" && options.action !== "set-state") throw new WorkItemWriteError("invalid-input");
199
+ const item = await this.getItem(options);
200
+ assertSameRevision(item, options.expectedRevision);
201
+ const metadata = await this.getMetadata(this.itemType(item));
202
+ const patch = getFieldPatches(options.fields ?? {}, metadata.fields, this.context.project.name, item.fields);
203
+ if (options.action === "set-state") {
204
+ const state = this.getReceipt(item, metadata).state.name;
205
+ if (!getAzureWorkItemTransitionTargets(metadata.type, metadata.states, state).some((s) => s.name === options.state)) throw new WorkItemWriteError("transition-unavailable");
206
+ patch.push({
207
+ op: "add",
208
+ path: "/fields/System.State",
209
+ value: options.state
210
+ });
211
+ }
212
+ if (!patch.length) throw new WorkItemWriteError("invalid-input");
213
+ patch.unshift({
214
+ op: "test",
215
+ path: "/rev",
216
+ value: options.expectedRevision
217
+ });
218
+ return this.save("PATCH", `/workitems/${item.id}`, patch, metadata, {
219
+ id: item.id,
220
+ state: options.action === "set-state" ? options.state : void 0
221
+ });
222
+ }
223
+ async delete(options) {
224
+ assertMutationIdentity(options.expectedAccountId);
225
+ const item = await this.getItem(options);
226
+ assertSameRevision(item, options.expectedRevision);
227
+ const metadata = await this.getMetadata(this.itemType(item));
228
+ const capability = await this.getDeleteCapability(metadata.type);
229
+ if (capability.allowed === false) throw new WorkItemWriteError(capability.reason);
230
+ await this.assertSessionCurrent();
231
+ const current = await this.getItem(options);
232
+ assertSameRevision(current, options.expectedRevision);
233
+ if (this.itemType(current) !== metadata.type.name) throw new WorkItemWriteError("conflict");
234
+ const issue = this.getReceipt(current, metadata);
235
+ await this.assertSessionCurrent();
236
+ try {
237
+ const { body, status } = await this.request({
238
+ method: "DELETE",
239
+ url: this.url(`/workitems/${issue.id}`),
240
+ headers: this.headers,
241
+ redirect: "error"
242
+ });
243
+ let deleted = status === 200 && isDeletedItem(body, issue.id) && body.deletedDate != null ? body : void 0;
244
+ if (deleted == null || getDeletedRevision(deleted, issue.id) === void 0) {
245
+ const recycled = await this.read(`/recyclebin/${issue.id}`).catch(() => void 0);
246
+ if (isDeletedItem(recycled, issue.id)) deleted = recycled;
247
+ }
248
+ if (deleted == null) return {
249
+ ok: false,
250
+ reason: "unknown",
251
+ applied: "maybe"
252
+ };
253
+ return await this.toDeleteOutcome(deleted, issue, options.expectedRevision);
254
+ } catch (ex) {
255
+ return toWorkItemWriteFailure(ex, { fields: metadata.fields });
256
+ }
257
+ }
258
+ async toDeleteOutcome(deleted, issue, expectedRevision) {
259
+ const revision = getDeletedRevision(deleted, issue.id);
260
+ const deletedAt = toDeletedAt(deleted.deletedDate);
261
+ const deletion = {
262
+ disposition: "recycle-bin",
263
+ restorable: true,
264
+ ...revision !== void 0 && { revision },
265
+ ...deletedAt !== void 0 && { deletedAt }
266
+ };
267
+ const project = sameIdentifier(deleted.project, isGuid(deleted.project) ? this.context.project.id : this.context.project.name) ? this.context.project : await this.findProject(deleted.project);
268
+ if (sameIdentifier(project.id, this.context.project.id) && revision === expectedRevision + 1) return {
269
+ ok: true,
270
+ ...this.context,
271
+ issue,
272
+ deletion: {
273
+ ...deletion,
274
+ revision
275
+ }
276
+ };
277
+ return {
278
+ ok: false,
279
+ reason: "target-changed",
280
+ applied: true,
281
+ ...this.context,
282
+ deleted: {
283
+ id: issue.id,
284
+ ...revision !== void 0 && { revision },
285
+ project
286
+ },
287
+ deletion
288
+ };
289
+ }
290
+ async findProject(nameOrId) {
291
+ try {
292
+ const project = await this.readOrganization(`/projects/${encodeAzurePathSegment(nameOrId)}`);
293
+ if (isGuid(project?.id) && isWorkItemIdentifier(project.name) && (sameIdentifier(project.name, nameOrId) || sameIdentifier(project.id, nameOrId))) return {
294
+ id: project.id,
295
+ name: project.name
296
+ };
297
+ } catch {}
298
+ return { name: nameOrId };
299
+ }
300
+ async create(options) {
301
+ const metadata = await this.getMetadata(options.workItemType);
302
+ if (metadata.type.isDisabled) throw new WorkItemWriteError("invalid-input");
303
+ const patch = getFieldPatches(options.fields, metadata.fields, this.context.project.name);
304
+ return this.save("POST", `/workitems/$${encodeAzurePathSegment(metadata.type.name)}`, patch, metadata);
305
+ }
306
+ async getDeleteCapability(type) {
307
+ if (isAzureTestArtifact(type)) return {
308
+ allowed: false,
309
+ reason: "unsupported"
310
+ };
311
+ const categories = await this.read("/workitemtypecategories");
312
+ if (isAzureTestArtifact(type, readValues(categories))) return {
313
+ allowed: false,
314
+ reason: "unsupported"
315
+ };
316
+ try {
317
+ const bit = readValues(await this.readOrganization(`/securitynamespaces/${projectSecurityNamespaceId}`)).find((namespace) => sameIdentifier(namespace?.namespaceId, projectSecurityNamespaceId))?.actions?.find((action) => action?.name === "WORK_ITEM_DELETE")?.bit;
318
+ if (!isWorkItemNumber(bit)) return { allowed: "unknown" };
319
+ const [allowed, ...rest] = readValues(await this.readOrganization(`/permissions/${projectSecurityNamespaceId}/${bit}`, {
320
+ tokens: `$PROJECT:vstfs:///Classification/TeamProject/${this.context.project.id}`,
321
+ alwaysAllowAdministrators: "false"
322
+ }));
323
+ if (typeof allowed !== "boolean" || rest.length) return { allowed: "unknown" };
324
+ return allowed ? { allowed: true } : {
325
+ allowed: false,
326
+ reason: "forbidden"
327
+ };
328
+ } catch {
329
+ return { allowed: "unknown" };
330
+ }
331
+ }
332
+ async getMetadata(name) {
333
+ if (!isWorkItemIdentifier(name) || name === "." || name === ".." || /[/\\]/.test(name)) throw new WorkItemWriteError("invalid-input");
334
+ const path = `/workitemtypes/${encodeAzurePathSegment(name)}`;
335
+ const [type, typeFields, definitions] = await Promise.all([
336
+ this.read(path),
337
+ this.read(`${path}/fields`, { $expand: "All" }),
338
+ this.read("/fields")
339
+ ]);
340
+ if (!sameIdentifier(type?.name, name) || !isWorkItemIdentifier(type?.referenceName)) throw new WorkItemWriteError("unknown");
341
+ if (type.transitions == null || typeof type.transitions !== "object" || Array.isArray(type.transitions)) throw new WorkItemWriteError("unknown");
342
+ const states = Array.isArray(type.states) && type.states.length !== 0 ? type.states : readValues(await this.read(`${path}/states`));
343
+ if (states.some((state) => !isWorkItemIdentifier(state?.name) || !isWorkItemIdentifier(state.category))) throw new WorkItemWriteError("unknown");
344
+ const catalog = readValues(definitions);
345
+ return {
346
+ type,
347
+ states: states.map(({ name, category, color }) => ({
348
+ name,
349
+ category,
350
+ ...typeof color === "string" && { color }
351
+ })),
352
+ fields: toAzureWorkItemWriteFields(readValues(typeFields), catalog),
353
+ catalog
354
+ };
355
+ }
356
+ async getItem(options) {
357
+ assertExistingAddress(options);
358
+ const data = await this.read(`/workitems/${options.workItemId}`);
359
+ if (!this.isInProject(data) || data.id !== options.workItemId) throw new WorkItemWriteError("not-found");
360
+ return data;
361
+ }
362
+ isInProject(item) {
363
+ return sameIdentifier(item?.fields?.["System.TeamProject"], this.context.project.name);
364
+ }
365
+ itemType(item) {
366
+ const type = item.fields["System.WorkItemType"];
367
+ if (!isWorkItemIdentifier(type)) throw new WorkItemWriteError("unknown");
368
+ return type;
369
+ }
370
+ getReceipt(item, metadata) {
371
+ const title = item.fields["System.Title"];
372
+ const state = metadata.states.find((candidate) => candidate.name === item.fields["System.State"]);
373
+ if (!isWorkItemNumber(item.id) || !isWorkItemNumber(item.rev) || typeof title !== "string" || state == null || this.itemType(item) !== metadata.type.name) throw new WorkItemWriteError("unknown");
374
+ return {
375
+ id: item.id,
376
+ revision: item.rev,
377
+ url: `${this.projectUrl}/_workitems/edit/${item.id}`,
378
+ type: metadata.type.name,
379
+ title,
380
+ state: {
381
+ name: state.name,
382
+ category: state.category
383
+ },
384
+ bodyField: getAzureWorkItemBodyField(metadata.fields, metadata.catalog, item.fields)
385
+ };
386
+ }
387
+ async assertSessionCurrent() {
388
+ if (!await this.isSessionCurrent()) throw new WorkItemWriteError("no-connection");
389
+ }
390
+ url(path, params, base = `${this.projectUrl}/_apis/wit`) {
391
+ return `${base}${path}?${new URLSearchParams({
392
+ "api-version": "7.1",
393
+ ...params
394
+ }).toString()}`;
395
+ }
396
+ read(path, params) {
397
+ return this.get(this.url(path, params));
398
+ }
399
+ readOrganization(path, params) {
400
+ return this.get(this.url(path, params, `${this.organizationUrl}/_apis`));
401
+ }
402
+ async get(url) {
403
+ const { body } = await this.request({
404
+ url,
405
+ headers: this.headers,
406
+ redirect: "error"
407
+ });
408
+ return body;
409
+ }
410
+ async save(method, path, patch, metadata, expected) {
411
+ const body = JSON.stringify(patch);
412
+ await this.assertSessionCurrent();
413
+ try {
414
+ const { body: item } = await this.request({
415
+ method,
416
+ url: this.url(path),
417
+ headers: {
418
+ ...this.headers,
419
+ "Content-Type": "application/json-patch+json"
420
+ },
421
+ body,
422
+ redirect: "error"
423
+ });
424
+ if (!this.isInProject(item) || expected != null && item.id !== expected.id || expected?.state !== void 0 && item.fields["System.State"] !== expected.state) return {
425
+ ok: false,
426
+ reason: "unknown",
427
+ applied: "maybe"
428
+ };
429
+ return {
430
+ ok: true,
431
+ ...this.context,
432
+ issue: this.getReceipt(item, metadata)
433
+ };
434
+ } catch (ex) {
435
+ return toWorkItemWriteFailure(ex, { fields: metadata.fields });
436
+ }
437
+ }
438
+ };
439
+ //#endregion
440
+ export { AzureWorkItemWriter };
441
+
442
+ //# sourceMappingURL=azureWorkItemWrites.js.map