@backstage/integration 1.16.4-next.1 → 1.17.0-next.3
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 +47 -0
- package/config.d.ts +6 -0
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.cjs.js +14 -1
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.cjs.js.map +1 -1
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.esm.js +15 -2
- package/dist/azure/CachedAzureDevOpsCredentialsProvider.esm.js.map +1 -1
- package/dist/azure/ManagedIdentityClientAssertion.cjs.js +42 -0
- package/dist/azure/ManagedIdentityClientAssertion.cjs.js.map +1 -0
- package/dist/azure/ManagedIdentityClientAssertion.esm.js +40 -0
- package/dist/azure/ManagedIdentityClientAssertion.esm.js.map +1 -0
- package/dist/azure/config.cjs.js +9 -3
- package/dist/azure/config.cjs.js.map +1 -1
- package/dist/azure/config.esm.js +9 -3
- package/dist/azure/config.esm.js.map +1 -1
- package/dist/gerrit/GerritIntegration.cjs.js +10 -1
- package/dist/gerrit/GerritIntegration.cjs.js.map +1 -1
- package/dist/gerrit/GerritIntegration.esm.js +11 -2
- package/dist/gerrit/GerritIntegration.esm.js.map +1 -1
- package/dist/gerrit/config.cjs.js +3 -5
- package/dist/gerrit/config.cjs.js.map +1 -1
- package/dist/gerrit/config.esm.js +3 -5
- package/dist/gerrit/config.esm.js.map +1 -1
- package/dist/gerrit/core.cjs.js +7 -0
- package/dist/gerrit/core.cjs.js.map +1 -1
- package/dist/gerrit/core.esm.js +7 -1
- package/dist/gerrit/core.esm.js.map +1 -1
- package/dist/index.d.ts +30 -5
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# @backstage/integration
|
|
2
2
|
|
|
3
|
+
## 1.17.0-next.3
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- d945206: Added support for federated credentials using managed identities in the Azure DevOps integration. Federated credentials are only available for Azure DevOps organizations that have been configured to use Entra ID for authentication.
|
|
8
|
+
|
|
9
|
+
```diff
|
|
10
|
+
integrations:
|
|
11
|
+
azure:
|
|
12
|
+
- host: dev.azure.com
|
|
13
|
+
credentials:
|
|
14
|
+
+ - clientId: ${APP_REGISTRATION_CLIENT_ID}
|
|
15
|
+
+ managedIdentityClientId: system-assigned
|
|
16
|
+
+ tenantId: ${AZURE_TENANT_ID}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
This also adds support for automatically using the system-assigned managed identity of an Azure resource by specifying `system-assigned` as the client ID of the managed identity.
|
|
20
|
+
|
|
21
|
+
```diff
|
|
22
|
+
integrations:
|
|
23
|
+
azure:
|
|
24
|
+
- host: dev.azure.com
|
|
25
|
+
credentials:
|
|
26
|
+
- - clientId: ${AZURE_CLIENT_ID}
|
|
27
|
+
+ - clientId: system-assigned
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Patch Changes
|
|
31
|
+
|
|
32
|
+
- Updated dependencies
|
|
33
|
+
- @backstage/config@1.3.2
|
|
34
|
+
- @backstage/errors@1.2.7
|
|
35
|
+
|
|
36
|
+
## 1.17.0-next.2
|
|
37
|
+
|
|
38
|
+
### Minor Changes
|
|
39
|
+
|
|
40
|
+
- f134cea: Implement Edit URL feature for Gerrit 3.9+.
|
|
41
|
+
|
|
42
|
+
It's possible to disable the edit url by adding the `disableEditUrl: true` config in the Gerrit integration.
|
|
43
|
+
|
|
44
|
+
### Patch Changes
|
|
45
|
+
|
|
46
|
+
- Updated dependencies
|
|
47
|
+
- @backstage/config@1.3.2
|
|
48
|
+
- @backstage/errors@1.2.7
|
|
49
|
+
|
|
3
50
|
## 1.16.4-next.1
|
|
4
51
|
|
|
5
52
|
### Patch Changes
|
package/config.d.ts
CHANGED
|
@@ -62,6 +62,7 @@ export interface Config {
|
|
|
62
62
|
clientSecret?: string;
|
|
63
63
|
tenantId?: string;
|
|
64
64
|
personalAccessToken?: string;
|
|
65
|
+
managedIdentityClientId?: string;
|
|
65
66
|
}[];
|
|
66
67
|
/**
|
|
67
68
|
* PGP signing key for signing commits.
|
|
@@ -182,6 +183,11 @@ export interface Config {
|
|
|
182
183
|
* @visibility frontend
|
|
183
184
|
*/
|
|
184
185
|
cloneUrl?: string;
|
|
186
|
+
/**
|
|
187
|
+
* Disable the edit url feature.
|
|
188
|
+
* @visibility frontend
|
|
189
|
+
*/
|
|
190
|
+
disableEditUrl?: boolean;
|
|
185
191
|
/**
|
|
186
192
|
* The username to use for authenticated requests.
|
|
187
193
|
* @visibility secret
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var identity = require('@azure/identity');
|
|
4
|
+
var ManagedIdentityClientAssertion = require('./ManagedIdentityClientAssertion.cjs.js');
|
|
4
5
|
|
|
5
6
|
const tenMinutes = 1e3 * 60 * 10;
|
|
6
7
|
class CachedAzureDevOpsCredentialsProvider {
|
|
@@ -23,9 +24,21 @@ class CachedAzureDevOpsCredentialsProvider {
|
|
|
23
24
|
credential.clientSecret
|
|
24
25
|
)
|
|
25
26
|
);
|
|
27
|
+
case "ManagedIdentityClientAssertion": {
|
|
28
|
+
const clientAssertion = new ManagedIdentityClientAssertion.ManagedIdentityClientAssertion({
|
|
29
|
+
clientId: credential.managedIdentityClientId
|
|
30
|
+
});
|
|
31
|
+
return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(
|
|
32
|
+
new identity.ClientAssertionCredential(
|
|
33
|
+
credential.tenantId,
|
|
34
|
+
credential.clientId,
|
|
35
|
+
() => clientAssertion.getSignedAssertion()
|
|
36
|
+
)
|
|
37
|
+
);
|
|
38
|
+
}
|
|
26
39
|
case "ManagedIdentity":
|
|
27
40
|
return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(
|
|
28
|
-
new identity.ManagedIdentityCredential(credential.clientId)
|
|
41
|
+
credential.clientId === "system-assigned" ? new identity.ManagedIdentityCredential() : new identity.ManagedIdentityCredential(credential.clientId)
|
|
29
42
|
);
|
|
30
43
|
default:
|
|
31
44
|
throw new Error(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CachedAzureDevOpsCredentialsProvider.cjs.js","sources":["../../src/azure/CachedAzureDevOpsCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AzureDevOpsCredential, PersonalAccessTokenCredential } from './config';\nimport {\n ClientSecretCredential,\n ManagedIdentityCredential,\n TokenCredential,\n} from '@azure/identity';\nimport {\n AzureDevOpsCredentials,\n AzureDevOpsCredentialsProvider,\n} from './types';\n\ntype CachedAzureDevOpsCredentials = AzureDevOpsCredentials & {\n expiresAt?: number;\n};\n\nfunction exhaustiveCheck(_param: never) {}\n\nconst tenMinutes = 1000 * 60 * 10;\n\n/**\n * A credentials provider that caches the credentials for as long as it is valid.\n *\n * @public\n */\nexport class CachedAzureDevOpsCredentialsProvider\n implements AzureDevOpsCredentialsProvider\n{\n azureDevOpsScope = '499b84ac-1321-427f-aa17-267ca6975798/.default';\n cached: CachedAzureDevOpsCredentials | undefined;\n\n static fromAzureDevOpsCredential(\n credential: AzureDevOpsCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n switch (credential.kind) {\n case 'PersonalAccessToken':\n return CachedAzureDevOpsCredentialsProvider.fromPersonalAccessTokenCredential(\n credential,\n );\n case 'ClientSecret':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientSecretCredential(\n credential.tenantId,\n credential.clientId,\n credential.clientSecret,\n ),\n );\n case 'ManagedIdentity':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ManagedIdentityCredential(credential.clientId),\n );\n default:\n exhaustiveCheck(credential);\n\n throw new Error(\n `Credential kind '${(credential as any).kind}' not supported`,\n );\n }\n }\n\n static fromTokenCredential(\n credential: TokenCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n return new CachedAzureDevOpsCredentialsProvider(credential);\n }\n\n static fromPersonalAccessTokenCredential(\n credential: PersonalAccessTokenCredential,\n ) {\n return new CachedAzureDevOpsCredentialsProvider(\n credential.personalAccessToken,\n );\n }\n\n private constructor(private readonly credential: TokenCredential | string) {}\n\n async getCredentials(): Promise<AzureDevOpsCredentials> {\n if (\n this.cached === undefined ||\n (this.cached.expiresAt !== undefined &&\n Date.now() > this.cached.expiresAt)\n ) {\n if (typeof this.credential === 'string') {\n this.cached = {\n headers: {\n Authorization: `Basic ${btoa(`:${this.credential}`)}`,\n },\n type: 'pat',\n token: this.credential,\n };\n } else {\n const accessToken = await this.credential.getToken(\n this.azureDevOpsScope,\n );\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n this.cached = {\n expiresAt: accessToken.expiresOnTimestamp - tenMinutes,\n headers: {\n Authorization: `Bearer ${accessToken.token}`,\n },\n type: 'bearer',\n token: accessToken.token,\n };\n }\n }\n\n return this.cached;\n }\n}\n"],"names":["ClientSecretCredential","ManagedIdentityCredential"],"mappings":"
|
|
1
|
+
{"version":3,"file":"CachedAzureDevOpsCredentialsProvider.cjs.js","sources":["../../src/azure/CachedAzureDevOpsCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AzureDevOpsCredential, PersonalAccessTokenCredential } from './config';\nimport {\n ClientAssertionCredential,\n ClientSecretCredential,\n ManagedIdentityCredential,\n TokenCredential,\n} from '@azure/identity';\nimport {\n AzureDevOpsCredentials,\n AzureDevOpsCredentialsProvider,\n} from './types';\nimport { ManagedIdentityClientAssertion } from './ManagedIdentityClientAssertion';\n\ntype CachedAzureDevOpsCredentials = AzureDevOpsCredentials & {\n expiresAt?: number;\n};\n\nfunction exhaustiveCheck(_param: never) {}\n\nconst tenMinutes = 1000 * 60 * 10;\n\n/**\n * A credentials provider that caches the credentials for as long as it is valid.\n *\n * @public\n */\nexport class CachedAzureDevOpsCredentialsProvider\n implements AzureDevOpsCredentialsProvider\n{\n azureDevOpsScope = '499b84ac-1321-427f-aa17-267ca6975798/.default';\n cached: CachedAzureDevOpsCredentials | undefined;\n\n static fromAzureDevOpsCredential(\n credential: AzureDevOpsCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n switch (credential.kind) {\n case 'PersonalAccessToken':\n return CachedAzureDevOpsCredentialsProvider.fromPersonalAccessTokenCredential(\n credential,\n );\n case 'ClientSecret':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientSecretCredential(\n credential.tenantId,\n credential.clientId,\n credential.clientSecret,\n ),\n );\n\n case 'ManagedIdentityClientAssertion': {\n const clientAssertion = new ManagedIdentityClientAssertion({\n clientId: credential.managedIdentityClientId,\n });\n\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientAssertionCredential(\n credential.tenantId,\n credential.clientId,\n () => clientAssertion.getSignedAssertion(),\n ),\n );\n }\n\n case 'ManagedIdentity':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n credential.clientId === 'system-assigned'\n ? new ManagedIdentityCredential()\n : new ManagedIdentityCredential(credential.clientId),\n );\n default:\n exhaustiveCheck(credential);\n\n throw new Error(\n `Credential kind '${(credential as any).kind}' not supported`,\n );\n }\n }\n\n static fromTokenCredential(\n credential: TokenCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n return new CachedAzureDevOpsCredentialsProvider(credential);\n }\n\n static fromPersonalAccessTokenCredential(\n credential: PersonalAccessTokenCredential,\n ) {\n return new CachedAzureDevOpsCredentialsProvider(\n credential.personalAccessToken,\n );\n }\n\n private constructor(private readonly credential: TokenCredential | string) {}\n\n async getCredentials(): Promise<AzureDevOpsCredentials> {\n if (\n this.cached === undefined ||\n (this.cached.expiresAt !== undefined &&\n Date.now() > this.cached.expiresAt)\n ) {\n if (typeof this.credential === 'string') {\n this.cached = {\n headers: {\n Authorization: `Basic ${btoa(`:${this.credential}`)}`,\n },\n type: 'pat',\n token: this.credential,\n };\n } else {\n const accessToken = await this.credential.getToken(\n this.azureDevOpsScope,\n );\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n this.cached = {\n expiresAt: accessToken.expiresOnTimestamp - tenMinutes,\n headers: {\n Authorization: `Bearer ${accessToken.token}`,\n },\n type: 'bearer',\n token: accessToken.token,\n };\n }\n }\n\n return this.cached;\n }\n}\n"],"names":["ClientSecretCredential","ManagedIdentityClientAssertion","ClientAssertionCredential","ManagedIdentityCredential"],"mappings":";;;;;AAkCA,MAAM,UAAA,GAAa,MAAO,EAAK,GAAA,EAAA;AAOxB,MAAM,oCAEb,CAAA;AAAA,EAgEU,YAA6B,UAAsC,EAAA;AAAtC,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA;AAAuC,EA/D5E,gBAAmB,GAAA,+CAAA;AAAA,EACnB,MAAA;AAAA,EAEA,OAAO,0BACL,UACsC,EAAA;AACtC,IAAA,QAAQ,WAAW,IAAM;AAAA,MACvB,KAAK,qBAAA;AACH,QAAA,OAAO,oCAAqC,CAAA,iCAAA;AAAA,UAC1C;AAAA,SACF;AAAA,MACF,KAAK,cAAA;AACH,QAAA,OAAO,oCAAqC,CAAA,mBAAA;AAAA,UAC1C,IAAIA,+BAAA;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A;AAAA,YACP,eAAe,CAAS,MAAA,EAAA,IAAA,CAAK,IAAI,IAAK,CAAA,UAAU,EAAE,CAAC,CAAA;AAAA,WACrD;AAAA,UACA,IAAM,EAAA,KAAA;AAAA,UACN,OAAO,IAAK,CAAA;AAAA,SACd;AAAA,OACK,MAAA;AACL,QAAM,MAAA,WAAA,GAAc,MAAM,IAAA,CAAK,UAAW,CAAA,QAAA;AAAA,UACxC,IAAK,CAAA;AAAA,SACP;AAEA,QAAA,IAAI,CAAC,WAAa,EAAA;AAChB,UAAM,MAAA,IAAI,MAAM,iCAAiC,CAAA;AAAA;AAGnD,QAAA,IAAA,CAAK,MAAS,GAAA;AAAA,UACZ,SAAA,EAAW,YAAY,kBAAqB,GAAA,UAAA;AAAA,UAC5C,OAAS,EAAA;AAAA,YACP,aAAA,EAAe,CAAU,OAAA,EAAA,WAAA,CAAY,KAAK,CAAA;AAAA,WAC5C;AAAA,UACA,IAAM,EAAA,QAAA;AAAA,UACN,OAAO,WAAY,CAAA;AAAA,SACrB;AAAA;AACF;AAGF,IAAA,OAAO,IAAK,CAAA,MAAA;AAAA;AAEhB;;;;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ManagedIdentityCredential, ClientSecretCredential } from '@azure/identity';
|
|
1
|
+
import { ManagedIdentityCredential, ClientAssertionCredential, ClientSecretCredential } from '@azure/identity';
|
|
2
|
+
import { ManagedIdentityClientAssertion } from './ManagedIdentityClientAssertion.esm.js';
|
|
2
3
|
|
|
3
4
|
const tenMinutes = 1e3 * 60 * 10;
|
|
4
5
|
class CachedAzureDevOpsCredentialsProvider {
|
|
@@ -21,9 +22,21 @@ class CachedAzureDevOpsCredentialsProvider {
|
|
|
21
22
|
credential.clientSecret
|
|
22
23
|
)
|
|
23
24
|
);
|
|
25
|
+
case "ManagedIdentityClientAssertion": {
|
|
26
|
+
const clientAssertion = new ManagedIdentityClientAssertion({
|
|
27
|
+
clientId: credential.managedIdentityClientId
|
|
28
|
+
});
|
|
29
|
+
return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(
|
|
30
|
+
new ClientAssertionCredential(
|
|
31
|
+
credential.tenantId,
|
|
32
|
+
credential.clientId,
|
|
33
|
+
() => clientAssertion.getSignedAssertion()
|
|
34
|
+
)
|
|
35
|
+
);
|
|
36
|
+
}
|
|
24
37
|
case "ManagedIdentity":
|
|
25
38
|
return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(
|
|
26
|
-
new ManagedIdentityCredential(credential.clientId)
|
|
39
|
+
credential.clientId === "system-assigned" ? new ManagedIdentityCredential() : new ManagedIdentityCredential(credential.clientId)
|
|
27
40
|
);
|
|
28
41
|
default:
|
|
29
42
|
throw new Error(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CachedAzureDevOpsCredentialsProvider.esm.js","sources":["../../src/azure/CachedAzureDevOpsCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AzureDevOpsCredential, PersonalAccessTokenCredential } from './config';\nimport {\n ClientSecretCredential,\n ManagedIdentityCredential,\n TokenCredential,\n} from '@azure/identity';\nimport {\n AzureDevOpsCredentials,\n AzureDevOpsCredentialsProvider,\n} from './types';\n\ntype CachedAzureDevOpsCredentials = AzureDevOpsCredentials & {\n expiresAt?: number;\n};\n\nfunction exhaustiveCheck(_param: never) {}\n\nconst tenMinutes = 1000 * 60 * 10;\n\n/**\n * A credentials provider that caches the credentials for as long as it is valid.\n *\n * @public\n */\nexport class CachedAzureDevOpsCredentialsProvider\n implements AzureDevOpsCredentialsProvider\n{\n azureDevOpsScope = '499b84ac-1321-427f-aa17-267ca6975798/.default';\n cached: CachedAzureDevOpsCredentials | undefined;\n\n static fromAzureDevOpsCredential(\n credential: AzureDevOpsCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n switch (credential.kind) {\n case 'PersonalAccessToken':\n return CachedAzureDevOpsCredentialsProvider.fromPersonalAccessTokenCredential(\n credential,\n );\n case 'ClientSecret':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientSecretCredential(\n credential.tenantId,\n credential.clientId,\n credential.clientSecret,\n ),\n );\n case 'ManagedIdentity':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ManagedIdentityCredential(credential.clientId),\n );\n default:\n exhaustiveCheck(credential);\n\n throw new Error(\n `Credential kind '${(credential as any).kind}' not supported`,\n );\n }\n }\n\n static fromTokenCredential(\n credential: TokenCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n return new CachedAzureDevOpsCredentialsProvider(credential);\n }\n\n static fromPersonalAccessTokenCredential(\n credential: PersonalAccessTokenCredential,\n ) {\n return new CachedAzureDevOpsCredentialsProvider(\n credential.personalAccessToken,\n );\n }\n\n private constructor(private readonly credential: TokenCredential | string) {}\n\n async getCredentials(): Promise<AzureDevOpsCredentials> {\n if (\n this.cached === undefined ||\n (this.cached.expiresAt !== undefined &&\n Date.now() > this.cached.expiresAt)\n ) {\n if (typeof this.credential === 'string') {\n this.cached = {\n headers: {\n Authorization: `Basic ${btoa(`:${this.credential}`)}`,\n },\n type: 'pat',\n token: this.credential,\n };\n } else {\n const accessToken = await this.credential.getToken(\n this.azureDevOpsScope,\n );\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n this.cached = {\n expiresAt: accessToken.expiresOnTimestamp - tenMinutes,\n headers: {\n Authorization: `Bearer ${accessToken.token}`,\n },\n type: 'bearer',\n token: accessToken.token,\n };\n }\n }\n\n return this.cached;\n }\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"CachedAzureDevOpsCredentialsProvider.esm.js","sources":["../../src/azure/CachedAzureDevOpsCredentialsProvider.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { AzureDevOpsCredential, PersonalAccessTokenCredential } from './config';\nimport {\n ClientAssertionCredential,\n ClientSecretCredential,\n ManagedIdentityCredential,\n TokenCredential,\n} from '@azure/identity';\nimport {\n AzureDevOpsCredentials,\n AzureDevOpsCredentialsProvider,\n} from './types';\nimport { ManagedIdentityClientAssertion } from './ManagedIdentityClientAssertion';\n\ntype CachedAzureDevOpsCredentials = AzureDevOpsCredentials & {\n expiresAt?: number;\n};\n\nfunction exhaustiveCheck(_param: never) {}\n\nconst tenMinutes = 1000 * 60 * 10;\n\n/**\n * A credentials provider that caches the credentials for as long as it is valid.\n *\n * @public\n */\nexport class CachedAzureDevOpsCredentialsProvider\n implements AzureDevOpsCredentialsProvider\n{\n azureDevOpsScope = '499b84ac-1321-427f-aa17-267ca6975798/.default';\n cached: CachedAzureDevOpsCredentials | undefined;\n\n static fromAzureDevOpsCredential(\n credential: AzureDevOpsCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n switch (credential.kind) {\n case 'PersonalAccessToken':\n return CachedAzureDevOpsCredentialsProvider.fromPersonalAccessTokenCredential(\n credential,\n );\n case 'ClientSecret':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientSecretCredential(\n credential.tenantId,\n credential.clientId,\n credential.clientSecret,\n ),\n );\n\n case 'ManagedIdentityClientAssertion': {\n const clientAssertion = new ManagedIdentityClientAssertion({\n clientId: credential.managedIdentityClientId,\n });\n\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n new ClientAssertionCredential(\n credential.tenantId,\n credential.clientId,\n () => clientAssertion.getSignedAssertion(),\n ),\n );\n }\n\n case 'ManagedIdentity':\n return CachedAzureDevOpsCredentialsProvider.fromTokenCredential(\n credential.clientId === 'system-assigned'\n ? new ManagedIdentityCredential()\n : new ManagedIdentityCredential(credential.clientId),\n );\n default:\n exhaustiveCheck(credential);\n\n throw new Error(\n `Credential kind '${(credential as any).kind}' not supported`,\n );\n }\n }\n\n static fromTokenCredential(\n credential: TokenCredential,\n ): CachedAzureDevOpsCredentialsProvider {\n return new CachedAzureDevOpsCredentialsProvider(credential);\n }\n\n static fromPersonalAccessTokenCredential(\n credential: PersonalAccessTokenCredential,\n ) {\n return new CachedAzureDevOpsCredentialsProvider(\n credential.personalAccessToken,\n );\n }\n\n private constructor(private readonly credential: TokenCredential | string) {}\n\n async getCredentials(): Promise<AzureDevOpsCredentials> {\n if (\n this.cached === undefined ||\n (this.cached.expiresAt !== undefined &&\n Date.now() > this.cached.expiresAt)\n ) {\n if (typeof this.credential === 'string') {\n this.cached = {\n headers: {\n Authorization: `Basic ${btoa(`:${this.credential}`)}`,\n },\n type: 'pat',\n token: this.credential,\n };\n } else {\n const accessToken = await this.credential.getToken(\n this.azureDevOpsScope,\n );\n\n if (!accessToken) {\n throw new Error('Failed to retrieve access token');\n }\n\n this.cached = {\n expiresAt: accessToken.expiresOnTimestamp - tenMinutes,\n headers: {\n Authorization: `Bearer ${accessToken.token}`,\n },\n type: 'bearer',\n token: accessToken.token,\n };\n }\n }\n\n return this.cached;\n }\n}\n"],"names":[],"mappings":";;;AAkCA,MAAM,UAAA,GAAa,MAAO,EAAK,GAAA,EAAA;AAOxB,MAAM,oCAEb,CAAA;AAAA,EAgEU,YAA6B,UAAsC,EAAA;AAAtC,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA;AAAuC,EA/D5E,gBAAmB,GAAA,+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,KAAW,KACf,CAAA,IAAA,IAAA,CAAK,MAAO,CAAA,SAAA,KAAc,KACzB,CAAA,IAAA,IAAA,CAAK,GAAI,EAAA,GAAI,IAAK,CAAA,MAAA,CAAO,SAC3B,EAAA;AACA,MAAI,IAAA,OAAO,IAAK,CAAA,UAAA,KAAe,QAAU,EAAA;AACvC,QAAA,IAAA,CAAK,MAAS,GAAA;AAAA,UACZ,OAAS,EAAA;AAAA,YACP,eAAe,CAAS,MAAA,EAAA,IAAA,CAAK,IAAI,IAAK,CAAA,UAAU,EAAE,CAAC,CAAA;AAAA,WACrD;AAAA,UACA,IAAM,EAAA,KAAA;AAAA,UACN,OAAO,IAAK,CAAA;AAAA,SACd;AAAA,OACK,MAAA;AACL,QAAM,MAAA,WAAA,GAAc,MAAM,IAAA,CAAK,UAAW,CAAA,QAAA;AAAA,UACxC,IAAK,CAAA;AAAA,SACP;AAEA,QAAA,IAAI,CAAC,WAAa,EAAA;AAChB,UAAM,MAAA,IAAI,MAAM,iCAAiC,CAAA;AAAA;AAGnD,QAAA,IAAA,CAAK,MAAS,GAAA;AAAA,UACZ,SAAA,EAAW,YAAY,kBAAqB,GAAA,UAAA;AAAA,UAC5C,OAAS,EAAA;AAAA,YACP,aAAA,EAAe,CAAU,OAAA,EAAA,WAAA,CAAY,KAAK,CAAA;AAAA,WAC5C;AAAA,UACA,IAAM,EAAA,QAAA;AAAA,UACN,OAAO,WAAY,CAAA;AAAA,SACrB;AAAA;AACF;AAGF,IAAA,OAAO,IAAK,CAAA,MAAA;AAAA;AAEhB;;;;"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var identity = require('@azure/identity');
|
|
4
|
+
|
|
5
|
+
const fiveMinutes = 5 * 60 * 1e3;
|
|
6
|
+
const expiresWithinFiveMinutes = (clientAssertion) => clientAssertion.expiresOnTimestamp - Date.now() <= fiveMinutes;
|
|
7
|
+
class ManagedIdentityClientAssertion {
|
|
8
|
+
credential;
|
|
9
|
+
clientAssertion;
|
|
10
|
+
/**
|
|
11
|
+
* Creates an instance of ManagedIdentityClientAssertion.
|
|
12
|
+
* @param options - Optional parameters for the ManagedIdentityClientAssertion.
|
|
13
|
+
* - clientId: The client ID of the managed identity. If not provided, 'system-assigned' is used.
|
|
14
|
+
*/
|
|
15
|
+
constructor(options) {
|
|
16
|
+
let { clientId } = options || {};
|
|
17
|
+
clientId ??= "system-assigned";
|
|
18
|
+
this.credential = clientId === "system-assigned" ? new identity.ManagedIdentityCredential() : new identity.ManagedIdentityCredential(clientId);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Gets a signed client assertion.
|
|
22
|
+
* If a valid client assertion is already cached which doesn't expire soon, it returns the cached assertion.
|
|
23
|
+
* Otherwise, it obtains a new access token and creates a new client assertion.
|
|
24
|
+
* @returns A promise that resolves to the signed client assertion.
|
|
25
|
+
*/
|
|
26
|
+
async getSignedAssertion() {
|
|
27
|
+
if (this.clientAssertion !== void 0 && !expiresWithinFiveMinutes(this.clientAssertion)) {
|
|
28
|
+
return this.clientAssertion.signedAssertion;
|
|
29
|
+
}
|
|
30
|
+
const accessToken = await this.credential.getToken(
|
|
31
|
+
"api://AzureADTokenExchange"
|
|
32
|
+
);
|
|
33
|
+
this.clientAssertion = {
|
|
34
|
+
signedAssertion: accessToken.token,
|
|
35
|
+
expiresOnTimestamp: accessToken.expiresOnTimestamp
|
|
36
|
+
};
|
|
37
|
+
return accessToken.token;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
exports.ManagedIdentityClientAssertion = ManagedIdentityClientAssertion;
|
|
42
|
+
//# sourceMappingURL=ManagedIdentityClientAssertion.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ManagedIdentityClientAssertion.cjs.js","sources":["../../src/azure/ManagedIdentityClientAssertion.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ManagedIdentityCredential } from '@azure/identity';\nimport { ClientAssertion } from './ClientAssertion';\n\nexport type ManagedIdentityClientAssertionOptions = {\n clientId?: string;\n};\n\nconst fiveMinutes = 5 * 60 * 1000; // 5 minutes in milliseconds\nconst expiresWithinFiveMinutes = (clientAssertion: ClientAssertion) =>\n clientAssertion.expiresOnTimestamp - Date.now() <= fiveMinutes;\n\n/**\n * Class representing a Managed Identity Client Assertion.\n * This class is responsible for obtaining a signed client assertion using Azure Managed Identity.\n */\nexport class ManagedIdentityClientAssertion {\n private credential: ManagedIdentityCredential;\n private clientAssertion?: ClientAssertion;\n\n /**\n * Creates an instance of ManagedIdentityClientAssertion.\n * @param options - Optional parameters for the ManagedIdentityClientAssertion.\n * - clientId: The client ID of the managed identity. If not provided, 'system-assigned' is used.\n */\n constructor(options?: ManagedIdentityClientAssertionOptions) {\n let { clientId } = options || {};\n clientId ??= 'system-assigned';\n\n this.credential =\n clientId === 'system-assigned'\n ? new ManagedIdentityCredential()\n : new ManagedIdentityCredential(clientId);\n }\n\n /**\n * Gets a signed client assertion.\n * If a valid client assertion is already cached which doesn't expire soon, it returns the cached assertion.\n * Otherwise, it obtains a new access token and creates a new client assertion.\n * @returns A promise that resolves to the signed client assertion.\n */\n public async getSignedAssertion(): Promise<string> {\n if (\n this.clientAssertion !== undefined &&\n !expiresWithinFiveMinutes(this.clientAssertion)\n ) {\n return this.clientAssertion.signedAssertion;\n }\n\n const accessToken = await this.credential.getToken(\n 'api://AzureADTokenExchange',\n );\n\n this.clientAssertion = {\n signedAssertion: accessToken.token,\n expiresOnTimestamp: accessToken.expiresOnTimestamp,\n };\n\n return accessToken.token;\n }\n}\n"],"names":["ManagedIdentityCredential"],"mappings":";;;;AAsBA,MAAM,WAAA,GAAc,IAAI,EAAK,GAAA,GAAA;AAC7B,MAAM,2BAA2B,CAAC,eAAA,KAChC,gBAAgB,kBAAqB,GAAA,IAAA,CAAK,KAAS,IAAA,WAAA;AAM9C,MAAM,8BAA+B,CAAA;AAAA,EAClC,UAAA;AAAA,EACA,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,YAAY,OAAiD,EAAA;AAC3D,IAAA,IAAI,EAAE,QAAA,EAAa,GAAA,OAAA,IAAW,EAAC;AAC/B,IAAa,QAAA,KAAA,iBAAA;AAEb,IAAK,IAAA,CAAA,UAAA,GACH,aAAa,iBACT,GAAA,IAAIA,oCACJ,GAAA,IAAIA,mCAA0B,QAAQ,CAAA;AAAA;AAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,kBAAsC,GAAA;AACjD,IAAA,IACE,KAAK,eAAoB,KAAA,KAAA,CAAA,IACzB,CAAC,wBAAyB,CAAA,IAAA,CAAK,eAAe,CAC9C,EAAA;AACA,MAAA,OAAO,KAAK,eAAgB,CAAA,eAAA;AAAA;AAG9B,IAAM,MAAA,WAAA,GAAc,MAAM,IAAA,CAAK,UAAW,CAAA,QAAA;AAAA,MACxC;AAAA,KACF;AAEA,IAAA,IAAA,CAAK,eAAkB,GAAA;AAAA,MACrB,iBAAiB,WAAY,CAAA,KAAA;AAAA,MAC7B,oBAAoB,WAAY,CAAA;AAAA,KAClC;AAEA,IAAA,OAAO,WAAY,CAAA,KAAA;AAAA;AAEvB;;;;"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ManagedIdentityCredential } from '@azure/identity';
|
|
2
|
+
|
|
3
|
+
const fiveMinutes = 5 * 60 * 1e3;
|
|
4
|
+
const expiresWithinFiveMinutes = (clientAssertion) => clientAssertion.expiresOnTimestamp - Date.now() <= fiveMinutes;
|
|
5
|
+
class ManagedIdentityClientAssertion {
|
|
6
|
+
credential;
|
|
7
|
+
clientAssertion;
|
|
8
|
+
/**
|
|
9
|
+
* Creates an instance of ManagedIdentityClientAssertion.
|
|
10
|
+
* @param options - Optional parameters for the ManagedIdentityClientAssertion.
|
|
11
|
+
* - clientId: The client ID of the managed identity. If not provided, 'system-assigned' is used.
|
|
12
|
+
*/
|
|
13
|
+
constructor(options) {
|
|
14
|
+
let { clientId } = options || {};
|
|
15
|
+
clientId ??= "system-assigned";
|
|
16
|
+
this.credential = clientId === "system-assigned" ? new ManagedIdentityCredential() : new ManagedIdentityCredential(clientId);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Gets a signed client assertion.
|
|
20
|
+
* If a valid client assertion is already cached which doesn't expire soon, it returns the cached assertion.
|
|
21
|
+
* Otherwise, it obtains a new access token and creates a new client assertion.
|
|
22
|
+
* @returns A promise that resolves to the signed client assertion.
|
|
23
|
+
*/
|
|
24
|
+
async getSignedAssertion() {
|
|
25
|
+
if (this.clientAssertion !== void 0 && !expiresWithinFiveMinutes(this.clientAssertion)) {
|
|
26
|
+
return this.clientAssertion.signedAssertion;
|
|
27
|
+
}
|
|
28
|
+
const accessToken = await this.credential.getToken(
|
|
29
|
+
"api://AzureADTokenExchange"
|
|
30
|
+
);
|
|
31
|
+
this.clientAssertion = {
|
|
32
|
+
signedAssertion: accessToken.token,
|
|
33
|
+
expiresOnTimestamp: accessToken.expiresOnTimestamp
|
|
34
|
+
};
|
|
35
|
+
return accessToken.token;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export { ManagedIdentityClientAssertion };
|
|
40
|
+
//# sourceMappingURL=ManagedIdentityClientAssertion.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ManagedIdentityClientAssertion.esm.js","sources":["../../src/azure/ManagedIdentityClientAssertion.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ManagedIdentityCredential } from '@azure/identity';\nimport { ClientAssertion } from './ClientAssertion';\n\nexport type ManagedIdentityClientAssertionOptions = {\n clientId?: string;\n};\n\nconst fiveMinutes = 5 * 60 * 1000; // 5 minutes in milliseconds\nconst expiresWithinFiveMinutes = (clientAssertion: ClientAssertion) =>\n clientAssertion.expiresOnTimestamp - Date.now() <= fiveMinutes;\n\n/**\n * Class representing a Managed Identity Client Assertion.\n * This class is responsible for obtaining a signed client assertion using Azure Managed Identity.\n */\nexport class ManagedIdentityClientAssertion {\n private credential: ManagedIdentityCredential;\n private clientAssertion?: ClientAssertion;\n\n /**\n * Creates an instance of ManagedIdentityClientAssertion.\n * @param options - Optional parameters for the ManagedIdentityClientAssertion.\n * - clientId: The client ID of the managed identity. If not provided, 'system-assigned' is used.\n */\n constructor(options?: ManagedIdentityClientAssertionOptions) {\n let { clientId } = options || {};\n clientId ??= 'system-assigned';\n\n this.credential =\n clientId === 'system-assigned'\n ? new ManagedIdentityCredential()\n : new ManagedIdentityCredential(clientId);\n }\n\n /**\n * Gets a signed client assertion.\n * If a valid client assertion is already cached which doesn't expire soon, it returns the cached assertion.\n * Otherwise, it obtains a new access token and creates a new client assertion.\n * @returns A promise that resolves to the signed client assertion.\n */\n public async getSignedAssertion(): Promise<string> {\n if (\n this.clientAssertion !== undefined &&\n !expiresWithinFiveMinutes(this.clientAssertion)\n ) {\n return this.clientAssertion.signedAssertion;\n }\n\n const accessToken = await this.credential.getToken(\n 'api://AzureADTokenExchange',\n );\n\n this.clientAssertion = {\n signedAssertion: accessToken.token,\n expiresOnTimestamp: accessToken.expiresOnTimestamp,\n };\n\n return accessToken.token;\n }\n}\n"],"names":[],"mappings":";;AAsBA,MAAM,WAAA,GAAc,IAAI,EAAK,GAAA,GAAA;AAC7B,MAAM,2BAA2B,CAAC,eAAA,KAChC,gBAAgB,kBAAqB,GAAA,IAAA,CAAK,KAAS,IAAA,WAAA;AAM9C,MAAM,8BAA+B,CAAA;AAAA,EAClC,UAAA;AAAA,EACA,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,YAAY,OAAiD,EAAA;AAC3D,IAAA,IAAI,EAAE,QAAA,EAAa,GAAA,OAAA,IAAW,EAAC;AAC/B,IAAa,QAAA,KAAA,iBAAA;AAEb,IAAK,IAAA,CAAA,UAAA,GACH,aAAa,iBACT,GAAA,IAAI,2BACJ,GAAA,IAAI,0BAA0B,QAAQ,CAAA;AAAA;AAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,kBAAsC,GAAA;AACjD,IAAA,IACE,KAAK,eAAoB,KAAA,KAAA,CAAA,IACzB,CAAC,wBAAyB,CAAA,IAAA,CAAK,eAAe,CAC9C,EAAA;AACA,MAAA,OAAO,KAAK,eAAgB,CAAA,eAAA;AAAA;AAG9B,IAAM,MAAA,WAAA,GAAc,MAAM,IAAA,CAAK,UAAW,CAAA,QAAA;AAAA,MACxC;AAAA,KACF;AAEA,IAAA,IAAA,CAAK,eAAkB,GAAA;AAAA,MACrB,iBAAiB,WAAY,CAAA,KAAA;AAAA,MAC7B,oBAAoB,WAAY,CAAA;AAAA,KAClC;AAEA,IAAA,OAAO,WAAY,CAAA,KAAA;AAAA;AAEvB;;;;"}
|
package/dist/azure/config.cjs.js
CHANGED
|
@@ -6,12 +6,17 @@ const AZURE_HOST = "dev.azure.com";
|
|
|
6
6
|
const AzureDevOpsCredentialFields = [
|
|
7
7
|
"clientId",
|
|
8
8
|
"clientSecret",
|
|
9
|
+
"managedIdentityClientId",
|
|
9
10
|
"tenantId",
|
|
10
11
|
"personalAccessToken"
|
|
11
12
|
];
|
|
12
13
|
const AzureDevopsCredentialFieldMap = /* @__PURE__ */ new Map([
|
|
13
14
|
["ClientSecret", ["clientId", "clientSecret", "tenantId"]],
|
|
14
15
|
["ManagedIdentity", ["clientId"]],
|
|
16
|
+
[
|
|
17
|
+
"ManagedIdentityClientAssertion",
|
|
18
|
+
["clientId", "managedIdentityClientId", "tenantId"]
|
|
19
|
+
],
|
|
15
20
|
["PersonalAccessToken", ["personalAccessToken"]]
|
|
16
21
|
]);
|
|
17
22
|
function asAzureDevOpsCredential(credential) {
|
|
@@ -39,9 +44,10 @@ function readAzureIntegrationConfig(config) {
|
|
|
39
44
|
const result = {
|
|
40
45
|
organizations: credential.getOptionalStringArray("organizations"),
|
|
41
46
|
personalAccessToken: credential.getOptionalString("personalAccessToken")?.trim(),
|
|
42
|
-
tenantId: credential.getOptionalString("tenantId"),
|
|
43
|
-
clientId: credential.getOptionalString("clientId"),
|
|
44
|
-
clientSecret: credential.getOptionalString("clientSecret")?.trim()
|
|
47
|
+
tenantId: credential.getOptionalString("tenantId")?.trim(),
|
|
48
|
+
clientId: credential.getOptionalString("clientId")?.trim(),
|
|
49
|
+
clientSecret: credential.getOptionalString("clientSecret")?.trim(),
|
|
50
|
+
managedIdentityClientId: credential.getOptionalString("managedIdentityClientId")?.trim()
|
|
45
51
|
};
|
|
46
52
|
return result;
|
|
47
53
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs.js","sources":["../../src/azure/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { isValidHost } from '../helpers';\n\nconst AZURE_HOST = 'dev.azure.com';\n\n/**\n * The configuration parameters for a single Azure provider.\n *\n * @public\n */\nexport type AzureIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"dev.azure.com\".\n *\n * Currently only \"dev.azure.com\" is supported.\n */\n host: string;\n\n /**\n * The authorization token to use for requests.\n *\n * If no token is specified, anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n token?: string;\n\n /**\n * The credential to use for requests.\n *\n * If no credential is specified anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n credential?: AzureDevOpsCredential;\n\n /**\n * The credentials to use for requests. If multiple credentials are specified the first one that matches the organization is used.\n * If not organization matches the first credential without an organization is used.\n *\n * If no credentials are specified at all, either a default credential (for Azure DevOps) or anonymous access (for Azure DevOps Server) is used.\n */\n credentials?: AzureDevOpsCredential[];\n\n /**\n * Signing key for commits\n */\n commitSigningKey?: string;\n};\n\n/**\n * The kind of Azure DevOps credential.\n * @public\n */\nexport type AzureDevOpsCredentialKind =\n | 'PersonalAccessToken'\n | 'ClientSecret'\n | 'ManagedIdentity';\n\n/**\n * Common fields for the Azure DevOps credentials.\n * @public\n */\nexport type AzureCredentialBase = {\n /**\n * The kind of credential.\n */\n kind: AzureDevOpsCredentialKind;\n /**\n * The Azure DevOps organizations for which to use this credential.\n */\n organizations?: string[];\n};\n\n/**\n * A client secret credential that was generated for an App Registration.\n * @public\n */\nexport type AzureClientSecretCredential = AzureCredentialBase & {\n kind: 'ClientSecret';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n /**\n * The client id\n */\n clientId: string;\n\n /**\n * The client secret\n */\n clientSecret: string;\n};\n\n/**\n * A managed identity credential.\n * @public\n */\nexport type AzureManagedIdentityCredential = AzureCredentialBase & {\n kind: 'ManagedIdentity';\n /**\n * The clientId\n */\n clientId: string;\n};\n\n/**\n * A personal access token credential.\n * @public\n */\nexport type PersonalAccessTokenCredential = AzureCredentialBase & {\n kind: 'PersonalAccessToken';\n personalAccessToken: string;\n};\n\n/**\n * The general shape of a credential that can be used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredentialLike = Omit<\n Partial<AzureClientSecretCredential> &\n Partial<AzureManagedIdentityCredential> &\n Partial<PersonalAccessTokenCredential>,\n 'kind'\n>;\n\n/**\n * Credential used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredential =\n | AzureClientSecretCredential\n | AzureManagedIdentityCredential\n | PersonalAccessTokenCredential;\n\nconst AzureDevOpsCredentialFields = [\n 'clientId',\n 'clientSecret',\n 'tenantId',\n 'personalAccessToken',\n] as const;\ntype AzureDevOpsCredentialField = (typeof AzureDevOpsCredentialFields)[number];\n\nconst AzureDevopsCredentialFieldMap = new Map<\n AzureDevOpsCredentialKind,\n AzureDevOpsCredentialField[]\n>([\n ['ClientSecret', ['clientId', 'clientSecret', 'tenantId']],\n ['ManagedIdentity', ['clientId']],\n ['PersonalAccessToken', ['personalAccessToken']],\n]);\n\nfunction asAzureDevOpsCredential(\n credential: AzureDevOpsCredentialLike,\n): AzureDevOpsCredential {\n for (const entry of AzureDevopsCredentialFieldMap.entries()) {\n const [kind, requiredFields] = entry;\n\n const forbiddenFields = AzureDevOpsCredentialFields.filter(\n field => !requiredFields.includes(field as AzureDevOpsCredentialField),\n );\n\n if (\n requiredFields.every(field => credential[field] !== undefined) &&\n forbiddenFields.every(field => credential[field] === undefined)\n ) {\n return {\n kind,\n organizations: credential.organizations,\n ...requiredFields.reduce((acc, field) => {\n acc[field] = credential[field];\n return acc;\n }, {} as Record<string, any>),\n } as AzureDevOpsCredential;\n }\n }\n throw new Error('is not a valid credential');\n}\n\n/**\n * Reads a single Azure integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readAzureIntegrationConfig(\n config: Config,\n): AzureIntegrationConfig {\n const host = config.getOptionalString('host') ?? AZURE_HOST;\n\n let credentialConfigs = config\n .getOptionalConfigArray('credentials')\n ?.map(credential => {\n const result: Partial<AzureDevOpsCredentialLike> = {\n organizations: credential.getOptionalStringArray('organizations'),\n personalAccessToken: credential\n .getOptionalString('personalAccessToken')\n ?.trim(),\n tenantId: credential.getOptionalString('tenantId'),\n clientId: credential.getOptionalString('clientId'),\n clientSecret: credential.getOptionalString('clientSecret')?.trim(),\n };\n\n return result;\n });\n\n const token = config.getOptionalString('token')?.trim();\n\n if (\n config.getOptional('credential') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'credential' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (\n config.getOptional('token') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'token' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (token !== undefined) {\n const mapped = [{ personalAccessToken: token }];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (config.getOptional('credential') !== undefined) {\n const mapped = [\n {\n organizations: config.getOptionalStringArray(\n 'credential.organizations',\n ),\n token: config.getOptionalString('credential.token')?.trim(),\n tenantId: config.getOptionalString('credential.tenantId'),\n clientId: config.getOptionalString('credential.clientId'),\n clientSecret: config\n .getOptionalString('credential.clientSecret')\n ?.trim(),\n },\n ];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Azure integration config, '${host}' is not a valid host`,\n );\n }\n\n let credentials: AzureDevOpsCredential[] | undefined = undefined;\n if (credentialConfigs !== undefined) {\n const errors = credentialConfigs\n ?.reduce((acc, credentialConfig, index) => {\n let error: string | undefined = undefined;\n try {\n asAzureDevOpsCredential(credentialConfig);\n } catch (e) {\n error = e.message;\n }\n\n if (error !== undefined) {\n acc.push(`credential at position ${index + 1} ${error}`);\n }\n\n return acc;\n }, Array.of<string>())\n .concat(\n Object.entries(\n credentialConfigs\n .filter(\n credential =>\n credential.organizations !== undefined &&\n credential.organizations.length > 0,\n )\n .reduce((acc, credential, index) => {\n credential.organizations?.forEach(organization => {\n if (!acc[organization]) {\n acc[organization] = [];\n }\n\n acc[organization].push(index + 1);\n });\n\n return acc;\n }, {} as Record<string, number[]>),\n )\n .filter(([_, indexes]) => indexes.length > 1)\n .reduce((acc, [org, indexes]) => {\n acc.push(\n `organization ${org} is specified multiple times in credentials at positions ${indexes\n .slice(0, indexes.length - 1)\n .join(', ')} and ${indexes[indexes.length - 1]}`,\n );\n return acc;\n }, Array.of<string>()),\n );\n\n if (errors?.length > 0) {\n throw new Error(\n `Invalid Azure integration config for ${host}: ${errors.join('; ')}`,\n );\n }\n\n credentials = credentialConfigs.map(credentialConfig =>\n asAzureDevOpsCredential(credentialConfig),\n );\n\n if (\n credentials.some(\n credential => credential.kind !== 'PersonalAccessToken',\n ) &&\n host !== AZURE_HOST\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, only personal access tokens can be used with hosts other than ${AZURE_HOST}`,\n );\n }\n\n if (\n credentials.filter(\n credential =>\n credential.organizations === undefined ||\n credential.organizations.length === 0,\n ).length > 1\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, you cannot specify multiple credentials without organizations`,\n );\n }\n }\n\n return {\n host,\n credentials,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Azure integration configs, and inserts some defaults for\n * public Azure if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readAzureIntegrationConfigs(\n configs: Config[],\n): AzureIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readAzureIntegrationConfig);\n\n // If no explicit dev.azure.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === AZURE_HOST)) {\n result.push({ host: AZURE_HOST });\n }\n\n return result;\n}\n"],"names":["isValidHost"],"mappings":";;;;AAmBA,MAAM,UAAa,GAAA,eAAA;AAqInB,MAAM,2BAA8B,GAAA;AAAA,EAClC,UAA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CAAA,GAAA;AAAA,MAAI,CAAA,gBAAA,KAClC,wBAAwB,gBAAgB;AAAA,KAC1C;AAEA,IAAA,IACE,WAAY,CAAA,IAAA;AAAA,MACV,CAAA,UAAA,KAAc,WAAW,IAAS,KAAA;AAAA,KACpC,IACA,SAAS,UACT,EAAA;AACA,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,qCAAA,EAAwC,IAAI,CAAA,gEAAA,EAAmE,UAAU,CAAA;AAAA,OAC3H;AAAA;AAGF,IAAA,IACE,WAAY,CAAA,MAAA;AAAA,MACV,gBACE,UAAW,CAAA,aAAA,KAAkB,KAC7B,CAAA,IAAA,UAAA,CAAW,cAAc,MAAW,KAAA;AAAA,KACxC,CAAE,SAAS,CACX,EAAA;AACA,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,wCAAwC,IAAI,CAAA,+DAAA;AAAA,OAC9C;AAAA;AACF;AAGF,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,WAAA;AAAA,IACA,gBAAA,EAAkB,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,4BACd,OAC0B,EAAA;AAE1B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,0BAA0B,CAAA;AAIrD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,UAAU,CAAG,EAAA;AAC5C,IAAA,MAAA,CAAO,IAAK,CAAA,EAAE,IAAM,EAAA,UAAA,EAAY,CAAA;AAAA;AAGlC,EAAO,OAAA,MAAA;AACT;;;;;"}
|
|
1
|
+
{"version":3,"file":"config.cjs.js","sources":["../../src/azure/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { isValidHost } from '../helpers';\n\nconst AZURE_HOST = 'dev.azure.com';\n\n/**\n * The configuration parameters for a single Azure provider.\n *\n * @public\n */\nexport type AzureIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"dev.azure.com\".\n *\n * Currently only \"dev.azure.com\" is supported.\n */\n host: string;\n\n /**\n * The authorization token to use for requests.\n *\n * If no token is specified, anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n token?: string;\n\n /**\n * The credential to use for requests.\n *\n * If no credential is specified anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n credential?: AzureDevOpsCredential;\n\n /**\n * The credentials to use for requests. If multiple credentials are specified the first one that matches the organization is used.\n * If not organization matches the first credential without an organization is used.\n *\n * If no credentials are specified at all, either a default credential (for Azure DevOps) or anonymous access (for Azure DevOps Server) is used.\n */\n credentials?: AzureDevOpsCredential[];\n\n /**\n * Signing key for commits\n */\n commitSigningKey?: string;\n};\n\n/**\n * The kind of Azure DevOps credential.\n * @public\n */\nexport type AzureDevOpsCredentialKind =\n | 'PersonalAccessToken'\n | 'ClientSecret'\n | 'ManagedIdentity'\n | 'ManagedIdentityClientAssertion';\n\n/**\n * Common fields for the Azure DevOps credentials.\n * @public\n */\nexport type AzureCredentialBase = {\n /**\n * The kind of credential.\n */\n kind: AzureDevOpsCredentialKind;\n /**\n * The Azure DevOps organizations for which to use this credential.\n */\n organizations?: string[];\n};\n\n/**\n * A client secret credential that was generated for an App Registration.\n * @public\n */\nexport type AzureClientSecretCredential = AzureCredentialBase & {\n kind: 'ClientSecret';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n /**\n * The client id\n */\n clientId: string;\n\n /**\n * The client secret\n */\n clientSecret: string;\n};\n\n/**\n * A client assertion credential that uses a managed identity to generate a client assertion (JWT).\n * @public\n */\nexport type AzureManagedIdentityClientAssertionCredential =\n AzureCredentialBase & {\n kind: 'ManagedIdentityClientAssertion';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n\n /**\n * The client ID of the app registration you want to authenticate as.\n */\n clientId: string;\n\n /**\n * The client ID of the managed identity used to generate a client assertion (JWT).\n * Set to \"system-assigned\" to automatically use the system-assigned managed identity.\n * For user-assigned managed identities, specify the client ID of the managed identity you want to use.\n */\n managedIdentityClientId: 'system-assigned' | string;\n };\n\n/**\n * A managed identity credential.\n * @public\n */\nexport type AzureManagedIdentityCredential = AzureCredentialBase & {\n kind: 'ManagedIdentity';\n /**\n * The clientId\n */\n clientId: 'system-assigned' | string;\n};\n\n/**\n * A personal access token credential.\n * @public\n */\nexport type PersonalAccessTokenCredential = AzureCredentialBase & {\n kind: 'PersonalAccessToken';\n personalAccessToken: string;\n};\n\n/**\n * The general shape of a credential that can be used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredentialLike = Omit<\n Partial<AzureClientSecretCredential> &\n Partial<AzureManagedIdentityClientAssertionCredential> &\n Partial<AzureManagedIdentityCredential> &\n Partial<PersonalAccessTokenCredential>,\n 'kind'\n>;\n\n/**\n * Credential used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredential =\n | AzureClientSecretCredential\n | AzureManagedIdentityClientAssertionCredential\n | AzureManagedIdentityCredential\n | PersonalAccessTokenCredential;\n\nconst AzureDevOpsCredentialFields = [\n 'clientId',\n 'clientSecret',\n 'managedIdentityClientId',\n 'tenantId',\n 'personalAccessToken',\n] as const;\ntype AzureDevOpsCredentialField = (typeof AzureDevOpsCredentialFields)[number];\n\nconst AzureDevopsCredentialFieldMap = new Map<\n AzureDevOpsCredentialKind,\n AzureDevOpsCredentialField[]\n>([\n ['ClientSecret', ['clientId', 'clientSecret', 'tenantId']],\n ['ManagedIdentity', ['clientId']],\n [\n 'ManagedIdentityClientAssertion',\n ['clientId', 'managedIdentityClientId', 'tenantId'],\n ],\n ['PersonalAccessToken', ['personalAccessToken']],\n]);\n\nfunction asAzureDevOpsCredential(\n credential: AzureDevOpsCredentialLike,\n): AzureDevOpsCredential {\n for (const entry of AzureDevopsCredentialFieldMap.entries()) {\n const [kind, requiredFields] = entry;\n\n const forbiddenFields = AzureDevOpsCredentialFields.filter(\n field => !requiredFields.includes(field as AzureDevOpsCredentialField),\n );\n\n if (\n requiredFields.every(field => credential[field] !== undefined) &&\n forbiddenFields.every(field => credential[field] === undefined)\n ) {\n return {\n kind,\n organizations: credential.organizations,\n ...requiredFields.reduce((acc, field) => {\n acc[field] = credential[field];\n return acc;\n }, {} as Record<string, any>),\n } as AzureDevOpsCredential;\n }\n }\n throw new Error('is not a valid credential');\n}\n\n/**\n * Reads a single Azure integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readAzureIntegrationConfig(\n config: Config,\n): AzureIntegrationConfig {\n const host = config.getOptionalString('host') ?? AZURE_HOST;\n\n let credentialConfigs = config\n .getOptionalConfigArray('credentials')\n ?.map(credential => {\n const result: Partial<AzureDevOpsCredentialLike> = {\n organizations: credential.getOptionalStringArray('organizations'),\n personalAccessToken: credential\n .getOptionalString('personalAccessToken')\n ?.trim(),\n tenantId: credential.getOptionalString('tenantId')?.trim(),\n clientId: credential.getOptionalString('clientId')?.trim(),\n clientSecret: credential.getOptionalString('clientSecret')?.trim(),\n managedIdentityClientId: credential\n .getOptionalString('managedIdentityClientId')\n ?.trim(),\n };\n\n return result;\n });\n\n const token = config.getOptionalString('token')?.trim();\n\n if (\n config.getOptional('credential') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'credential' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (\n config.getOptional('token') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'token' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (token !== undefined) {\n const mapped = [{ personalAccessToken: token }];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (config.getOptional('credential') !== undefined) {\n const mapped = [\n {\n organizations: config.getOptionalStringArray(\n 'credential.organizations',\n ),\n token: config.getOptionalString('credential.token')?.trim(),\n tenantId: config.getOptionalString('credential.tenantId'),\n clientId: config.getOptionalString('credential.clientId'),\n clientSecret: config\n .getOptionalString('credential.clientSecret')\n ?.trim(),\n },\n ];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Azure integration config, '${host}' is not a valid host`,\n );\n }\n\n let credentials: AzureDevOpsCredential[] | undefined = undefined;\n if (credentialConfigs !== undefined) {\n const errors = credentialConfigs\n ?.reduce((acc, credentialConfig, index) => {\n let error: string | undefined = undefined;\n try {\n asAzureDevOpsCredential(credentialConfig);\n } catch (e) {\n error = e.message;\n }\n\n if (error !== undefined) {\n acc.push(`credential at position ${index + 1} ${error}`);\n }\n\n return acc;\n }, Array.of<string>())\n .concat(\n Object.entries(\n credentialConfigs\n .filter(\n credential =>\n credential.organizations !== undefined &&\n credential.organizations.length > 0,\n )\n .reduce((acc, credential, index) => {\n credential.organizations?.forEach(organization => {\n if (!acc[organization]) {\n acc[organization] = [];\n }\n\n acc[organization].push(index + 1);\n });\n\n return acc;\n }, {} as Record<string, number[]>),\n )\n .filter(([_, indexes]) => indexes.length > 1)\n .reduce((acc, [org, indexes]) => {\n acc.push(\n `organization ${org} is specified multiple times in credentials at positions ${indexes\n .slice(0, indexes.length - 1)\n .join(', ')} and ${indexes[indexes.length - 1]}`,\n );\n return acc;\n }, Array.of<string>()),\n );\n\n if (errors?.length > 0) {\n throw new Error(\n `Invalid Azure integration config for ${host}: ${errors.join('; ')}`,\n );\n }\n\n credentials = credentialConfigs.map(credentialConfig =>\n asAzureDevOpsCredential(credentialConfig),\n );\n\n if (\n credentials.some(\n credential => credential.kind !== 'PersonalAccessToken',\n ) &&\n host !== AZURE_HOST\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, only personal access tokens can be used with hosts other than ${AZURE_HOST}`,\n );\n }\n\n if (\n credentials.filter(\n credential =>\n credential.organizations === undefined ||\n credential.organizations.length === 0,\n ).length > 1\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, you cannot specify multiple credentials without organizations`,\n );\n }\n }\n\n return {\n host,\n credentials,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Azure integration configs, and inserts some defaults for\n * public Azure if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readAzureIntegrationConfigs(\n configs: Config[],\n): AzureIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readAzureIntegrationConfig);\n\n // If no explicit dev.azure.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === AZURE_HOST)) {\n result.push({ host: AZURE_HOST });\n }\n\n return result;\n}\n"],"names":["isValidHost"],"mappings":";;;;AAmBA,MAAM,UAAa,GAAA,eAAA;AAiKnB,MAAM,2BAA8B,GAAA;AAAA,EAClC,UAAA;AAAA,EACA,cAAA;AAAA,EACA,yBAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA;AAGA,MAAM,6BAAA,uBAAoC,GAGxC,CAAA;AAAA,EACA,CAAC,cAAgB,EAAA,CAAC,UAAY,EAAA,cAAA,EAAgB,UAAU,CAAC,CAAA;AAAA,EACzD,CAAC,iBAAA,EAAmB,CAAC,UAAU,CAAC,CAAA;AAAA,EAChC;AAAA,IACE,gCAAA;AAAA,IACA,CAAC,UAAY,EAAA,yBAAA,EAA2B,UAAU;AAAA,GACpD;AAAA,EACA,CAAC,qBAAA,EAAuB,CAAC,qBAAqB,CAAC;AACjD,CAAC,CAAA;AAED,SAAS,wBACP,UACuB,EAAA;AACvB,EAAW,KAAA,MAAA,KAAA,IAAS,6BAA8B,CAAA,OAAA,EAAW,EAAA;AAC3D,IAAM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,IAAA,IACE,WAAY,CAAA,MAAA;AAAA,MACV,gBACE,UAAW,CAAA,aAAA,KAAkB,KAC7B,CAAA,IAAA,UAAA,CAAW,cAAc,MAAW,KAAA;AAAA,KACxC,CAAE,SAAS,CACX,EAAA;AACA,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,wCAAwC,IAAI,CAAA,+DAAA;AAAA,OAC9C;AAAA;AACF;AAGF,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,WAAA;AAAA,IACA,gBAAA,EAAkB,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,4BACd,OAC0B,EAAA;AAE1B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,0BAA0B,CAAA;AAIrD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,UAAU,CAAG,EAAA;AAC5C,IAAA,MAAA,CAAO,IAAK,CAAA,EAAE,IAAM,EAAA,UAAA,EAAY,CAAA;AAAA;AAGlC,EAAO,OAAA,MAAA;AACT;;;;;"}
|
package/dist/azure/config.esm.js
CHANGED
|
@@ -4,12 +4,17 @@ const AZURE_HOST = "dev.azure.com";
|
|
|
4
4
|
const AzureDevOpsCredentialFields = [
|
|
5
5
|
"clientId",
|
|
6
6
|
"clientSecret",
|
|
7
|
+
"managedIdentityClientId",
|
|
7
8
|
"tenantId",
|
|
8
9
|
"personalAccessToken"
|
|
9
10
|
];
|
|
10
11
|
const AzureDevopsCredentialFieldMap = /* @__PURE__ */ new Map([
|
|
11
12
|
["ClientSecret", ["clientId", "clientSecret", "tenantId"]],
|
|
12
13
|
["ManagedIdentity", ["clientId"]],
|
|
14
|
+
[
|
|
15
|
+
"ManagedIdentityClientAssertion",
|
|
16
|
+
["clientId", "managedIdentityClientId", "tenantId"]
|
|
17
|
+
],
|
|
13
18
|
["PersonalAccessToken", ["personalAccessToken"]]
|
|
14
19
|
]);
|
|
15
20
|
function asAzureDevOpsCredential(credential) {
|
|
@@ -37,9 +42,10 @@ function readAzureIntegrationConfig(config) {
|
|
|
37
42
|
const result = {
|
|
38
43
|
organizations: credential.getOptionalStringArray("organizations"),
|
|
39
44
|
personalAccessToken: credential.getOptionalString("personalAccessToken")?.trim(),
|
|
40
|
-
tenantId: credential.getOptionalString("tenantId"),
|
|
41
|
-
clientId: credential.getOptionalString("clientId"),
|
|
42
|
-
clientSecret: credential.getOptionalString("clientSecret")?.trim()
|
|
45
|
+
tenantId: credential.getOptionalString("tenantId")?.trim(),
|
|
46
|
+
clientId: credential.getOptionalString("clientId")?.trim(),
|
|
47
|
+
clientSecret: credential.getOptionalString("clientSecret")?.trim(),
|
|
48
|
+
managedIdentityClientId: credential.getOptionalString("managedIdentityClientId")?.trim()
|
|
43
49
|
};
|
|
44
50
|
return result;
|
|
45
51
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.esm.js","sources":["../../src/azure/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { isValidHost } from '../helpers';\n\nconst AZURE_HOST = 'dev.azure.com';\n\n/**\n * The configuration parameters for a single Azure provider.\n *\n * @public\n */\nexport type AzureIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"dev.azure.com\".\n *\n * Currently only \"dev.azure.com\" is supported.\n */\n host: string;\n\n /**\n * The authorization token to use for requests.\n *\n * If no token is specified, anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n token?: string;\n\n /**\n * The credential to use for requests.\n *\n * If no credential is specified anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n credential?: AzureDevOpsCredential;\n\n /**\n * The credentials to use for requests. If multiple credentials are specified the first one that matches the organization is used.\n * If not organization matches the first credential without an organization is used.\n *\n * If no credentials are specified at all, either a default credential (for Azure DevOps) or anonymous access (for Azure DevOps Server) is used.\n */\n credentials?: AzureDevOpsCredential[];\n\n /**\n * Signing key for commits\n */\n commitSigningKey?: string;\n};\n\n/**\n * The kind of Azure DevOps credential.\n * @public\n */\nexport type AzureDevOpsCredentialKind =\n | 'PersonalAccessToken'\n | 'ClientSecret'\n | 'ManagedIdentity';\n\n/**\n * Common fields for the Azure DevOps credentials.\n * @public\n */\nexport type AzureCredentialBase = {\n /**\n * The kind of credential.\n */\n kind: AzureDevOpsCredentialKind;\n /**\n * The Azure DevOps organizations for which to use this credential.\n */\n organizations?: string[];\n};\n\n/**\n * A client secret credential that was generated for an App Registration.\n * @public\n */\nexport type AzureClientSecretCredential = AzureCredentialBase & {\n kind: 'ClientSecret';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n /**\n * The client id\n */\n clientId: string;\n\n /**\n * The client secret\n */\n clientSecret: string;\n};\n\n/**\n * A managed identity credential.\n * @public\n */\nexport type AzureManagedIdentityCredential = AzureCredentialBase & {\n kind: 'ManagedIdentity';\n /**\n * The clientId\n */\n clientId: string;\n};\n\n/**\n * A personal access token credential.\n * @public\n */\nexport type PersonalAccessTokenCredential = AzureCredentialBase & {\n kind: 'PersonalAccessToken';\n personalAccessToken: string;\n};\n\n/**\n * The general shape of a credential that can be used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredentialLike = Omit<\n Partial<AzureClientSecretCredential> &\n Partial<AzureManagedIdentityCredential> &\n Partial<PersonalAccessTokenCredential>,\n 'kind'\n>;\n\n/**\n * Credential used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredential =\n | AzureClientSecretCredential\n | AzureManagedIdentityCredential\n | PersonalAccessTokenCredential;\n\nconst AzureDevOpsCredentialFields = [\n 'clientId',\n 'clientSecret',\n 'tenantId',\n 'personalAccessToken',\n] as const;\ntype AzureDevOpsCredentialField = (typeof AzureDevOpsCredentialFields)[number];\n\nconst AzureDevopsCredentialFieldMap = new Map<\n AzureDevOpsCredentialKind,\n AzureDevOpsCredentialField[]\n>([\n ['ClientSecret', ['clientId', 'clientSecret', 'tenantId']],\n ['ManagedIdentity', ['clientId']],\n ['PersonalAccessToken', ['personalAccessToken']],\n]);\n\nfunction asAzureDevOpsCredential(\n credential: AzureDevOpsCredentialLike,\n): AzureDevOpsCredential {\n for (const entry of AzureDevopsCredentialFieldMap.entries()) {\n const [kind, requiredFields] = entry;\n\n const forbiddenFields = AzureDevOpsCredentialFields.filter(\n field => !requiredFields.includes(field as AzureDevOpsCredentialField),\n );\n\n if (\n requiredFields.every(field => credential[field] !== undefined) &&\n forbiddenFields.every(field => credential[field] === undefined)\n ) {\n return {\n kind,\n organizations: credential.organizations,\n ...requiredFields.reduce((acc, field) => {\n acc[field] = credential[field];\n return acc;\n }, {} as Record<string, any>),\n } as AzureDevOpsCredential;\n }\n }\n throw new Error('is not a valid credential');\n}\n\n/**\n * Reads a single Azure integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readAzureIntegrationConfig(\n config: Config,\n): AzureIntegrationConfig {\n const host = config.getOptionalString('host') ?? AZURE_HOST;\n\n let credentialConfigs = config\n .getOptionalConfigArray('credentials')\n ?.map(credential => {\n const result: Partial<AzureDevOpsCredentialLike> = {\n organizations: credential.getOptionalStringArray('organizations'),\n personalAccessToken: credential\n .getOptionalString('personalAccessToken')\n ?.trim(),\n tenantId: credential.getOptionalString('tenantId'),\n clientId: credential.getOptionalString('clientId'),\n clientSecret: credential.getOptionalString('clientSecret')?.trim(),\n };\n\n return result;\n });\n\n const token = config.getOptionalString('token')?.trim();\n\n if (\n config.getOptional('credential') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'credential' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (\n config.getOptional('token') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'token' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (token !== undefined) {\n const mapped = [{ personalAccessToken: token }];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (config.getOptional('credential') !== undefined) {\n const mapped = [\n {\n organizations: config.getOptionalStringArray(\n 'credential.organizations',\n ),\n token: config.getOptionalString('credential.token')?.trim(),\n tenantId: config.getOptionalString('credential.tenantId'),\n clientId: config.getOptionalString('credential.clientId'),\n clientSecret: config\n .getOptionalString('credential.clientSecret')\n ?.trim(),\n },\n ];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Azure integration config, '${host}' is not a valid host`,\n );\n }\n\n let credentials: AzureDevOpsCredential[] | undefined = undefined;\n if (credentialConfigs !== undefined) {\n const errors = credentialConfigs\n ?.reduce((acc, credentialConfig, index) => {\n let error: string | undefined = undefined;\n try {\n asAzureDevOpsCredential(credentialConfig);\n } catch (e) {\n error = e.message;\n }\n\n if (error !== undefined) {\n acc.push(`credential at position ${index + 1} ${error}`);\n }\n\n return acc;\n }, Array.of<string>())\n .concat(\n Object.entries(\n credentialConfigs\n .filter(\n credential =>\n credential.organizations !== undefined &&\n credential.organizations.length > 0,\n )\n .reduce((acc, credential, index) => {\n credential.organizations?.forEach(organization => {\n if (!acc[organization]) {\n acc[organization] = [];\n }\n\n acc[organization].push(index + 1);\n });\n\n return acc;\n }, {} as Record<string, number[]>),\n )\n .filter(([_, indexes]) => indexes.length > 1)\n .reduce((acc, [org, indexes]) => {\n acc.push(\n `organization ${org} is specified multiple times in credentials at positions ${indexes\n .slice(0, indexes.length - 1)\n .join(', ')} and ${indexes[indexes.length - 1]}`,\n );\n return acc;\n }, Array.of<string>()),\n );\n\n if (errors?.length > 0) {\n throw new Error(\n `Invalid Azure integration config for ${host}: ${errors.join('; ')}`,\n );\n }\n\n credentials = credentialConfigs.map(credentialConfig =>\n asAzureDevOpsCredential(credentialConfig),\n );\n\n if (\n credentials.some(\n credential => credential.kind !== 'PersonalAccessToken',\n ) &&\n host !== AZURE_HOST\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, only personal access tokens can be used with hosts other than ${AZURE_HOST}`,\n );\n }\n\n if (\n credentials.filter(\n credential =>\n credential.organizations === undefined ||\n credential.organizations.length === 0,\n ).length > 1\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, you cannot specify multiple credentials without organizations`,\n );\n }\n }\n\n return {\n host,\n credentials,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Azure integration configs, and inserts some defaults for\n * public Azure if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readAzureIntegrationConfigs(\n configs: Config[],\n): AzureIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readAzureIntegrationConfig);\n\n // If no explicit dev.azure.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === AZURE_HOST)) {\n result.push({ host: AZURE_HOST });\n }\n\n return result;\n}\n"],"names":[],"mappings":";;AAmBA,MAAM,UAAa,GAAA,eAAA;AAqInB,MAAM,2BAA8B,GAAA;AAAA,EAClC,UAAA;AAAA,EACA,cAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA;AAGA,MAAM,6BAAA,uBAAoC,GAGxC,CAAA;AAAA,EACA,CAAC,cAAgB,EAAA,CAAC,UAAY,EAAA,cAAA,EAAgB,UAAU,CAAC,CAAA;AAAA,EACzD,CAAC,iBAAA,EAAmB,CAAC,UAAU,CAAC,CAAA;AAAA,EAChC,CAAC,qBAAA,EAAuB,CAAC,qBAAqB,CAAC;AACjD,CAAC,CAAA;AAED,SAAS,wBACP,UACuB,EAAA;AACvB,E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AAA,MACV,gBACE,UAAW,CAAA,aAAA,KAAkB,KAC7B,CAAA,IAAA,UAAA,CAAW,cAAc,MAAW,KAAA;AAAA,KACxC,CAAE,SAAS,CACX,EAAA;AACA,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,wCAAwC,IAAI,CAAA,+DAAA;AAAA,OAC9C;AAAA;AACF;AAGF,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,WAAA;AAAA,IACA,gBAAA,EAAkB,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,4BACd,OAC0B,EAAA;AAE1B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,0BAA0B,CAAA;AAIrD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,UAAU,CAAG,EAAA;AAC5C,IAAA,MAAA,CAAO,IAAK,CAAA,EAAE,IAAM,EAAA,UAAA,EAAY,CAAA;AAAA;AAGlC,EAAO,OAAA,MAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"config.esm.js","sources":["../../src/azure/config.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { isValidHost } from '../helpers';\n\nconst AZURE_HOST = 'dev.azure.com';\n\n/**\n * The configuration parameters for a single Azure provider.\n *\n * @public\n */\nexport type AzureIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"dev.azure.com\".\n *\n * Currently only \"dev.azure.com\" is supported.\n */\n host: string;\n\n /**\n * The authorization token to use for requests.\n *\n * If no token is specified, anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n token?: string;\n\n /**\n * The credential to use for requests.\n *\n * If no credential is specified anonymous access is used.\n *\n * @deprecated Use `credentials` instead.\n */\n credential?: AzureDevOpsCredential;\n\n /**\n * The credentials to use for requests. If multiple credentials are specified the first one that matches the organization is used.\n * If not organization matches the first credential without an organization is used.\n *\n * If no credentials are specified at all, either a default credential (for Azure DevOps) or anonymous access (for Azure DevOps Server) is used.\n */\n credentials?: AzureDevOpsCredential[];\n\n /**\n * Signing key for commits\n */\n commitSigningKey?: string;\n};\n\n/**\n * The kind of Azure DevOps credential.\n * @public\n */\nexport type AzureDevOpsCredentialKind =\n | 'PersonalAccessToken'\n | 'ClientSecret'\n | 'ManagedIdentity'\n | 'ManagedIdentityClientAssertion';\n\n/**\n * Common fields for the Azure DevOps credentials.\n * @public\n */\nexport type AzureCredentialBase = {\n /**\n * The kind of credential.\n */\n kind: AzureDevOpsCredentialKind;\n /**\n * The Azure DevOps organizations for which to use this credential.\n */\n organizations?: string[];\n};\n\n/**\n * A client secret credential that was generated for an App Registration.\n * @public\n */\nexport type AzureClientSecretCredential = AzureCredentialBase & {\n kind: 'ClientSecret';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n /**\n * The client id\n */\n clientId: string;\n\n /**\n * The client secret\n */\n clientSecret: string;\n};\n\n/**\n * A client assertion credential that uses a managed identity to generate a client assertion (JWT).\n * @public\n */\nexport type AzureManagedIdentityClientAssertionCredential =\n AzureCredentialBase & {\n kind: 'ManagedIdentityClientAssertion';\n /**\n * The Entra ID tenant\n */\n tenantId: string;\n\n /**\n * The client ID of the app registration you want to authenticate as.\n */\n clientId: string;\n\n /**\n * The client ID of the managed identity used to generate a client assertion (JWT).\n * Set to \"system-assigned\" to automatically use the system-assigned managed identity.\n * For user-assigned managed identities, specify the client ID of the managed identity you want to use.\n */\n managedIdentityClientId: 'system-assigned' | string;\n };\n\n/**\n * A managed identity credential.\n * @public\n */\nexport type AzureManagedIdentityCredential = AzureCredentialBase & {\n kind: 'ManagedIdentity';\n /**\n * The clientId\n */\n clientId: 'system-assigned' | string;\n};\n\n/**\n * A personal access token credential.\n * @public\n */\nexport type PersonalAccessTokenCredential = AzureCredentialBase & {\n kind: 'PersonalAccessToken';\n personalAccessToken: string;\n};\n\n/**\n * The general shape of a credential that can be used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredentialLike = Omit<\n Partial<AzureClientSecretCredential> &\n Partial<AzureManagedIdentityClientAssertionCredential> &\n Partial<AzureManagedIdentityCredential> &\n Partial<PersonalAccessTokenCredential>,\n 'kind'\n>;\n\n/**\n * Credential used to authenticate to Azure DevOps.\n * @public\n */\nexport type AzureDevOpsCredential =\n | AzureClientSecretCredential\n | AzureManagedIdentityClientAssertionCredential\n | AzureManagedIdentityCredential\n | PersonalAccessTokenCredential;\n\nconst AzureDevOpsCredentialFields = [\n 'clientId',\n 'clientSecret',\n 'managedIdentityClientId',\n 'tenantId',\n 'personalAccessToken',\n] as const;\ntype AzureDevOpsCredentialField = (typeof AzureDevOpsCredentialFields)[number];\n\nconst AzureDevopsCredentialFieldMap = new Map<\n AzureDevOpsCredentialKind,\n AzureDevOpsCredentialField[]\n>([\n ['ClientSecret', ['clientId', 'clientSecret', 'tenantId']],\n ['ManagedIdentity', ['clientId']],\n [\n 'ManagedIdentityClientAssertion',\n ['clientId', 'managedIdentityClientId', 'tenantId'],\n ],\n ['PersonalAccessToken', ['personalAccessToken']],\n]);\n\nfunction asAzureDevOpsCredential(\n credential: AzureDevOpsCredentialLike,\n): AzureDevOpsCredential {\n for (const entry of AzureDevopsCredentialFieldMap.entries()) {\n const [kind, requiredFields] = entry;\n\n const forbiddenFields = AzureDevOpsCredentialFields.filter(\n field => !requiredFields.includes(field as AzureDevOpsCredentialField),\n );\n\n if (\n requiredFields.every(field => credential[field] !== undefined) &&\n forbiddenFields.every(field => credential[field] === undefined)\n ) {\n return {\n kind,\n organizations: credential.organizations,\n ...requiredFields.reduce((acc, field) => {\n acc[field] = credential[field];\n return acc;\n }, {} as Record<string, any>),\n } as AzureDevOpsCredential;\n }\n }\n throw new Error('is not a valid credential');\n}\n\n/**\n * Reads a single Azure integration config.\n *\n * @param config - The config object of a single integration\n * @public\n */\nexport function readAzureIntegrationConfig(\n config: Config,\n): AzureIntegrationConfig {\n const host = config.getOptionalString('host') ?? AZURE_HOST;\n\n let credentialConfigs = config\n .getOptionalConfigArray('credentials')\n ?.map(credential => {\n const result: Partial<AzureDevOpsCredentialLike> = {\n organizations: credential.getOptionalStringArray('organizations'),\n personalAccessToken: credential\n .getOptionalString('personalAccessToken')\n ?.trim(),\n tenantId: credential.getOptionalString('tenantId')?.trim(),\n clientId: credential.getOptionalString('clientId')?.trim(),\n clientSecret: credential.getOptionalString('clientSecret')?.trim(),\n managedIdentityClientId: credential\n .getOptionalString('managedIdentityClientId')\n ?.trim(),\n };\n\n return result;\n });\n\n const token = config.getOptionalString('token')?.trim();\n\n if (\n config.getOptional('credential') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'credential' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (\n config.getOptional('token') !== undefined &&\n config.getOptional('credentials') !== undefined\n ) {\n throw new Error(\n `Invalid Azure integration config, 'token' and 'credentials' cannot be used together. Use 'credentials' instead.`,\n );\n }\n\n if (token !== undefined) {\n const mapped = [{ personalAccessToken: token }];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (config.getOptional('credential') !== undefined) {\n const mapped = [\n {\n organizations: config.getOptionalStringArray(\n 'credential.organizations',\n ),\n token: config.getOptionalString('credential.token')?.trim(),\n tenantId: config.getOptionalString('credential.tenantId'),\n clientId: config.getOptionalString('credential.clientId'),\n clientSecret: config\n .getOptionalString('credential.clientSecret')\n ?.trim(),\n },\n ];\n credentialConfigs = credentialConfigs?.concat(mapped) ?? mapped;\n }\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Azure integration config, '${host}' is not a valid host`,\n );\n }\n\n let credentials: AzureDevOpsCredential[] | undefined = undefined;\n if (credentialConfigs !== undefined) {\n const errors = credentialConfigs\n ?.reduce((acc, credentialConfig, index) => {\n let error: string | undefined = undefined;\n try {\n asAzureDevOpsCredential(credentialConfig);\n } catch (e) {\n error = e.message;\n }\n\n if (error !== undefined) {\n acc.push(`credential at position ${index + 1} ${error}`);\n }\n\n return acc;\n }, Array.of<string>())\n .concat(\n Object.entries(\n credentialConfigs\n .filter(\n credential =>\n credential.organizations !== undefined &&\n credential.organizations.length > 0,\n )\n .reduce((acc, credential, index) => {\n credential.organizations?.forEach(organization => {\n if (!acc[organization]) {\n acc[organization] = [];\n }\n\n acc[organization].push(index + 1);\n });\n\n return acc;\n }, {} as Record<string, number[]>),\n )\n .filter(([_, indexes]) => indexes.length > 1)\n .reduce((acc, [org, indexes]) => {\n acc.push(\n `organization ${org} is specified multiple times in credentials at positions ${indexes\n .slice(0, indexes.length - 1)\n .join(', ')} and ${indexes[indexes.length - 1]}`,\n );\n return acc;\n }, Array.of<string>()),\n );\n\n if (errors?.length > 0) {\n throw new Error(\n `Invalid Azure integration config for ${host}: ${errors.join('; ')}`,\n );\n }\n\n credentials = credentialConfigs.map(credentialConfig =>\n asAzureDevOpsCredential(credentialConfig),\n );\n\n if (\n credentials.some(\n credential => credential.kind !== 'PersonalAccessToken',\n ) &&\n host !== AZURE_HOST\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, only personal access tokens can be used with hosts other than ${AZURE_HOST}`,\n );\n }\n\n if (\n credentials.filter(\n credential =>\n credential.organizations === undefined ||\n credential.organizations.length === 0,\n ).length > 1\n ) {\n throw new Error(\n `Invalid Azure integration config for ${host}, you cannot specify multiple credentials without organizations`,\n );\n }\n }\n\n return {\n host,\n credentials,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Azure integration configs, and inserts some defaults for\n * public Azure if not specified.\n *\n * @param configs - All of the integration config objects\n * @public\n */\nexport function readAzureIntegrationConfigs(\n configs: Config[],\n): AzureIntegrationConfig[] {\n // First read all the explicit integrations\n const result = configs.map(readAzureIntegrationConfig);\n\n // If no explicit dev.azure.com integration was added, put one in the list as\n // a convenience\n if (!result.some(c => c.host === AZURE_HOST)) {\n result.push({ host: AZURE_HOST });\n }\n\n return result;\n}\n"],"names":[],"mappings":";;AAmBA,MAAM,UAAa,GAAA,eAAA;AAiKnB,MAAM,2BAA8B,GAAA;AAAA,EAClC,UAAA;AAAA,EACA,cAAA;AAAA,EACA,yBAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA;AAGA,MAAM,6BAAA,uBAAoC,GAGxC,CAAA;AAAA,EACA,CAAC,cAAgB,EAAA,CAAC,UAAY,EAAA,cAAA,EAAgB,UAAU,CAAC,CAAA;AAAA,EACzD,CAAC,iBAAA,EAAmB,CAAC,UAAU,CAAC,CAAA;AAAA,EAChC;AAAA,IACE,gCAAA;AAAA,IACA,CAAC,UAAY,EAAA,yBAAA,EAA2B,UAAU;AAAA,GACpD;AAAA,EACA,CAAC,qBAAA,EAAuB,CAAC,qBAAqB,CAAC;AACjD,CAAC,CAAA;AAED,SAAS,wBACP,UACuB,EAAA;AACvB,EAAW,KAAA,MAAA,KAAA,IAAS,6BAA8B,CAAA,OAAA,EAAW,EAAA;AAC3D,IAAM,MAAA,CAAC,IAAM,EAAA,cAAc,CAAI,GAAA,KAAA;AAE/B,IAAA,MAAM,kBAAkB,2BAA4B,CAAA,MAAA;AAAA,MAClD,CAAS,KAAA,KAAA,CAAC,cAAe,CAAA,QAAA,CAAS,KAAmC;AAAA,KACvE;AAEA,IAAA,IACE,cAAe,CAAA,KAAA,CAAM,CAAS,KAAA,KAAA,UAAA,CAAW,KAAK,CAAM,KAAA,KAAA,CAAS,CAC7D,IAAA,eAAA,CAAgB,MAAM,CAAS,KAAA,KAAA,UAAA,CAAW,KAAK,CAAA,KA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kB;AAAA,GAC/D;AACF;AASO,SAAS,4BACd,OAC0B,EAAA;AAE1B,EAAM,MAAA,MAAA,GAAS,OAAQ,CAAA,GAAA,CAAI,0BAA0B,CAAA;AAIrD,EAAA,IAAI,CAAC,MAAO,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,UAAU,CAAG,EAAA;AAC5C,IAAA,MAAA,CAAO,IAAK,CAAA,EAAE,IAAM,EAAA,UAAA,EAAY,CAAA;AAAA;AAGlC,EAAO,OAAA,MAAA;AACT;;;;"}
|
|
@@ -44,7 +44,16 @@ class GerritIntegration {
|
|
|
44
44
|
return updated.toString();
|
|
45
45
|
}
|
|
46
46
|
resolveEditUrl(url) {
|
|
47
|
-
|
|
47
|
+
if (this.config.disableEditUrl) {
|
|
48
|
+
return url;
|
|
49
|
+
}
|
|
50
|
+
const parsed = core.parseGitilesUrlRef(this.config, url);
|
|
51
|
+
return core.buildGerritEditUrl(
|
|
52
|
+
this.config,
|
|
53
|
+
parsed.project,
|
|
54
|
+
parsed.ref,
|
|
55
|
+
parsed.path
|
|
56
|
+
);
|
|
48
57
|
}
|
|
49
58
|
}
|
|
50
59
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GerritIntegration.cjs.js","sources":["../../src/gerrit/GerritIntegration.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations } from '../helpers';\nimport { ScmIntegration, ScmIntegrationsFactory } from '../types';\nimport {\n GerritIntegrationConfig,\n readGerritIntegrationConfigs,\n} from './config';\nimport { parseGitilesUrlRef } from './core';\n\n/**\n * A Gerrit based integration.\n *\n * @public\n */\nexport class GerritIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GerritIntegration> = ({ config }) => {\n const configs = readGerritIntegrationConfigs(\n config.getOptionalConfigArray('integrations.gerrit') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GerritIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GerritIntegrationConfig) {}\n\n get type(): string {\n return 'gerrit';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GerritIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n const { url, base, lineNumber } = options;\n let updated;\n if (url.startsWith('/')) {\n const { basePath } = parseGitilesUrlRef(this.config, base);\n return basePath + url;\n }\n if (url) {\n updated = new URL(url, base);\n } else {\n updated = new URL(base);\n }\n if (lineNumber) {\n updated.hash = lineNumber.toString();\n }\n return updated.toString();\n }\n\n resolveEditUrl(url: string): string {\n
|
|
1
|
+
{"version":3,"file":"GerritIntegration.cjs.js","sources":["../../src/gerrit/GerritIntegration.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations } from '../helpers';\nimport { ScmIntegration, ScmIntegrationsFactory } from '../types';\nimport {\n GerritIntegrationConfig,\n readGerritIntegrationConfigs,\n} from './config';\nimport { buildGerritEditUrl, parseGitilesUrlRef } from './core';\n\n/**\n * A Gerrit based integration.\n *\n * @public\n */\nexport class GerritIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GerritIntegration> = ({ config }) => {\n const configs = readGerritIntegrationConfigs(\n config.getOptionalConfigArray('integrations.gerrit') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GerritIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GerritIntegrationConfig) {}\n\n get type(): string {\n return 'gerrit';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GerritIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n const { url, base, lineNumber } = options;\n let updated;\n if (url.startsWith('/')) {\n const { basePath } = parseGitilesUrlRef(this.config, base);\n return basePath + url;\n }\n if (url) {\n updated = new URL(url, base);\n } else {\n updated = new URL(base);\n }\n if (lineNumber) {\n updated.hash = lineNumber.toString();\n }\n return updated.toString();\n }\n\n resolveEditUrl(url: string): string {\n if (this.config.disableEditUrl) {\n return url;\n }\n\n const parsed = parseGitilesUrlRef(this.config, url);\n return buildGerritEditUrl(\n this.config,\n parsed.project,\n parsed.ref,\n parsed.path,\n );\n }\n}\n"],"names":["config","readGerritIntegrationConfigs","basicIntegrations","parseGitilesUrlRef","buildGerritEditUrl"],"mappings":";;;;;;AA6BO,MAAM,iBAA4C,CAAA;AAAA,EAWvD,YAA6B,iBAA4C,EAAA;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA;AAA6C,EAV1E,OAAO,OAAA,GAAqD,CAAC,UAAEA,UAAa,KAAA;AAC1E,IAAA,MAAM,OAAU,GAAAC,mCAAA;AAAA,MACdD,QAAO,CAAA,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAO,OAAAE,yBAAA;AAAA,MACL,QAAQ,GAAI,CAAA,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAO,CAAA;AAA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6 @@
|
|
|
1
1
|
import { basicIntegrations } from '../helpers.esm.js';
|
|
2
2
|
import { readGerritIntegrationConfigs } from './config.esm.js';
|
|
3
|
-
import { parseGitilesUrlRef } from './core.esm.js';
|
|
3
|
+
import { parseGitilesUrlRef, buildGerritEditUrl } from './core.esm.js';
|
|
4
4
|
|
|
5
5
|
class GerritIntegration {
|
|
6
6
|
constructor(integrationConfig) {
|
|
@@ -42,7 +42,16 @@ class GerritIntegration {
|
|
|
42
42
|
return updated.toString();
|
|
43
43
|
}
|
|
44
44
|
resolveEditUrl(url) {
|
|
45
|
-
|
|
45
|
+
if (this.config.disableEditUrl) {
|
|
46
|
+
return url;
|
|
47
|
+
}
|
|
48
|
+
const parsed = parseGitilesUrlRef(this.config, url);
|
|
49
|
+
return buildGerritEditUrl(
|
|
50
|
+
this.config,
|
|
51
|
+
parsed.project,
|
|
52
|
+
parsed.ref,
|
|
53
|
+
parsed.path
|
|
54
|
+
);
|
|
46
55
|
}
|
|
47
56
|
}
|
|
48
57
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GerritIntegration.esm.js","sources":["../../src/gerrit/GerritIntegration.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations } from '../helpers';\nimport { ScmIntegration, ScmIntegrationsFactory } from '../types';\nimport {\n GerritIntegrationConfig,\n readGerritIntegrationConfigs,\n} from './config';\nimport { parseGitilesUrlRef } from './core';\n\n/**\n * A Gerrit based integration.\n *\n * @public\n */\nexport class GerritIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GerritIntegration> = ({ config }) => {\n const configs = readGerritIntegrationConfigs(\n config.getOptionalConfigArray('integrations.gerrit') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GerritIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GerritIntegrationConfig) {}\n\n get type(): string {\n return 'gerrit';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GerritIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n const { url, base, lineNumber } = options;\n let updated;\n if (url.startsWith('/')) {\n const { basePath } = parseGitilesUrlRef(this.config, base);\n return basePath + url;\n }\n if (url) {\n updated = new URL(url, base);\n } else {\n updated = new URL(base);\n }\n if (lineNumber) {\n updated.hash = lineNumber.toString();\n }\n return updated.toString();\n }\n\n resolveEditUrl(url: string): string {\n
|
|
1
|
+
{"version":3,"file":"GerritIntegration.esm.js","sources":["../../src/gerrit/GerritIntegration.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { basicIntegrations } from '../helpers';\nimport { ScmIntegration, ScmIntegrationsFactory } from '../types';\nimport {\n GerritIntegrationConfig,\n readGerritIntegrationConfigs,\n} from './config';\nimport { buildGerritEditUrl, parseGitilesUrlRef } from './core';\n\n/**\n * A Gerrit based integration.\n *\n * @public\n */\nexport class GerritIntegration implements ScmIntegration {\n static factory: ScmIntegrationsFactory<GerritIntegration> = ({ config }) => {\n const configs = readGerritIntegrationConfigs(\n config.getOptionalConfigArray('integrations.gerrit') ?? [],\n );\n return basicIntegrations(\n configs.map(c => new GerritIntegration(c)),\n i => i.config.host,\n );\n };\n\n constructor(private readonly integrationConfig: GerritIntegrationConfig) {}\n\n get type(): string {\n return 'gerrit';\n }\n\n get title(): string {\n return this.integrationConfig.host;\n }\n\n get config(): GerritIntegrationConfig {\n return this.integrationConfig;\n }\n\n resolveUrl(options: {\n url: string;\n base: string;\n lineNumber?: number;\n }): string {\n const { url, base, lineNumber } = options;\n let updated;\n if (url.startsWith('/')) {\n const { basePath } = parseGitilesUrlRef(this.config, base);\n return basePath + url;\n }\n if (url) {\n updated = new URL(url, base);\n } else {\n updated = new URL(base);\n }\n if (lineNumber) {\n updated.hash = lineNumber.toString();\n }\n return updated.toString();\n }\n\n resolveEditUrl(url: string): string {\n if (this.config.disableEditUrl) {\n return url;\n }\n\n const parsed = parseGitilesUrlRef(this.config, url);\n return buildGerritEditUrl(\n this.config,\n parsed.project,\n parsed.ref,\n parsed.path,\n );\n }\n}\n"],"names":[],"mappings":";;;;AA6BO,MAAM,iBAA4C,CAAA;AAAA,EAWvD,YAA6B,iBAA4C,EAAA;AAA5C,IAAA,IAAA,CAAA,iBAAA,GAAA,iBAAA;AAAA;AAA6C,EAV1E,OAAO,OAAA,GAAqD,CAAC,EAAE,QAAa,KAAA;AAC1E,IAAA,MAAM,OAAU,GAAA,4BAAA;AAAA,MACd,MAAO,CAAA,sBAAA,CAAuB,qBAAqB,CAAA,IAAK;AAAC,KAC3D;AACA,IAAO,OAAA,iBAAA;AAAA,MACL,QAAQ,GAAI,CAAA,CAAA,CAAA,KAAK,IAAI,iBAAA,CAAkB,CAAC,CAAC,CAAA;AAAA,MACzC,CAAA,CAAA,KAAK,EAAE,MAAO,CAAA;AAAA,KAChB;AAAA,GACF;AAAA,EAIA,IAAI,IAAe,GAAA;AACjB,IAAO,OAAA,QAAA;AAAA;AACT,EAEA,IAAI,KAAgB,GAAA;AAClB,IAAA,OAAO,KAAK,iBAAkB,CAAA,IAAA;AAAA;AAChC,EAEA,IAAI,MAAkC,GAAA;AACpC,IAAA,OAAO,IAAK,CAAA,iBAAA;AAAA;AACd,EAEA,WAAW,OAIA,EAAA;AACT,IAAA,MAAM,EAAE,GAAA,EAAK,IAAM,EAAA,UAAA,EAAe,GAAA,OAAA;AAClC,IAAI,IAAA,OAAA;AACJ,IAAI,IAAA,GAAA,CAAI,UAAW,CAAA,GAAG,CAAG,EAAA;AACvB,MAAA,MAAM,EAAE,QAAS,EAAA,GAAI,kBAAmB,CAAA,IAAA,CAAK,QAAQ,IAAI,CAAA;AACzD,MAAA,OAAO,QAAW,GAAA,GAAA;AAAA;AAEpB,IAAA,IAAI,GAAK,EAAA;AACP,MAAU,OAAA,GAAA,IAAI,GAAI,CAAA,GAAA,EAAK,IAAI,CAAA;AAAA,KACtB,MAAA;AACL,MAAU,OAAA,GAAA,IAAI,IAAI,IAAI,CAAA;AAAA;AAExB,IAAA,IAAI,UAAY,EAAA;AACd,MAAQ,OAAA,CAAA,IAAA,GAAO,WAAW,QAAS,EAAA;AAAA;AAErC,IAAA,OAAO,QAAQ,QAAS,EAAA;AAAA;AAC1B,EAEA,eAAe,GAAqB,EAAA;AAClC,IAAI,IAAA,IAAA,CAAK,OAAO,cAAgB,EAAA;AAC9B,MAAO,OAAA,GAAA;AAAA;AAGT,IAAA,MAAM,MAAS,GAAA,kBAAA,CAAmB,IAAK,CAAA,MAAA,EAAQ,GAAG,CAAA;AAClD,IAAO,OAAA,kBAAA;AAAA,MACL,IAAK,CAAA,MAAA;AAAA,MACL,MAAO,CAAA,OAAA;AAAA,MACP,MAAO,CAAA,GAAA;AAAA,MACP,MAAO,CAAA;AAAA,KACT;AAAA;AAEJ;;;;"}
|
|
@@ -7,6 +7,7 @@ function readGerritIntegrationConfig(config) {
|
|
|
7
7
|
const host = config.getString("host");
|
|
8
8
|
let baseUrl = config.getOptionalString("baseUrl");
|
|
9
9
|
let cloneUrl = config.getOptionalString("cloneUrl");
|
|
10
|
+
const disableEditUrl = config.getOptionalBoolean("disableEditUrl");
|
|
10
11
|
let gitilesBaseUrl = config.getString("gitilesBaseUrl");
|
|
11
12
|
const username = config.getOptionalString("username");
|
|
12
13
|
const password = config.getOptionalString("password")?.trim();
|
|
@@ -32,20 +33,17 @@ function readGerritIntegrationConfig(config) {
|
|
|
32
33
|
} else {
|
|
33
34
|
baseUrl = `https://${host}`;
|
|
34
35
|
}
|
|
35
|
-
if (gitilesBaseUrl) {
|
|
36
|
-
gitilesBaseUrl = lodash.trimEnd(gitilesBaseUrl, "/");
|
|
37
|
-
} else {
|
|
38
|
-
gitilesBaseUrl = `https://${host}`;
|
|
39
|
-
}
|
|
40
36
|
if (cloneUrl) {
|
|
41
37
|
cloneUrl = lodash.trimEnd(cloneUrl, "/");
|
|
42
38
|
} else {
|
|
43
39
|
cloneUrl = baseUrl;
|
|
44
40
|
}
|
|
41
|
+
gitilesBaseUrl = lodash.trimEnd(gitilesBaseUrl, "/");
|
|
45
42
|
return {
|
|
46
43
|
host,
|
|
47
44
|
baseUrl,
|
|
48
45
|
cloneUrl,
|
|
46
|
+
disableEditUrl,
|
|
49
47
|
gitilesBaseUrl,
|
|
50
48
|
username,
|
|
51
49
|
password,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs.js","sources":["../../src/gerrit/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost, isValidUrl } from '../helpers';\n\n/**\n * The configuration parameters for a single Gerrit API provider.\n *\n * @public\n */\nexport type GerritIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"gerrit-review.com\"\n */\n host: string;\n\n /**\n * The optional base URL of the Gerrit instance. It is assumed that https\n * is used and that the base path is \"/\" on the host. If that is not the\n * case set the complete base url to the gerrit instance, e.g.\n * \"https://gerrit-review.com/gerrit\". This is the url that you would open\n * in a browser.\n */\n baseUrl?: string;\n\n /**\n * The optional base url to use for cloning a repository. If not set the\n * baseUrl will be used.\n */\n cloneUrl?: string;\n\n /**\n * Base url for Gitiles. This is needed for creating a valid\n * user-friendly url that can be used for browsing the content of the\n * provider.\n */\n gitilesBaseUrl: string;\n\n /**\n * The username to use for requests to gerrit.\n */\n username?: string;\n\n /**\n * The password or http token to use for authentication.\n */\n password?: string;\n\n /**\n * The signing key to use for signing commits.\n */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Gerrit integration config.\n *\n * @param config - The config object of a single integration\n *\n * @public\n */\nexport function readGerritIntegrationConfig(\n config: Config,\n): GerritIntegrationConfig {\n const host = config.getString('host');\n let baseUrl = config.getOptionalString('baseUrl');\n let cloneUrl = config.getOptionalString('cloneUrl');\n let gitilesBaseUrl = config.getString('gitilesBaseUrl');\n const username = config.getOptionalString('username');\n const password = config.getOptionalString('password')?.trim();\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Gerrit integration config, '${host}' is not a valid host`,\n );\n } else if (baseUrl && !isValidUrl(baseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${baseUrl}' is not a valid baseUrl`,\n );\n } else if (cloneUrl && !isValidUrl(cloneUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${cloneUrl}' is not a valid cloneUrl`,\n );\n } else if (!isValidUrl(gitilesBaseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${gitilesBaseUrl}' is not a valid gitilesBaseUrl`,\n );\n }\n if (baseUrl) {\n baseUrl = trimEnd(baseUrl, '/');\n } else {\n baseUrl = `https://${host}`;\n }\n if (
|
|
1
|
+
{"version":3,"file":"config.cjs.js","sources":["../../src/gerrit/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost, isValidUrl } from '../helpers';\n\n/**\n * The configuration parameters for a single Gerrit API provider.\n *\n * @public\n */\nexport type GerritIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"gerrit-review.com\"\n */\n host: string;\n\n /**\n * The optional base URL of the Gerrit instance. It is assumed that https\n * is used and that the base path is \"/\" on the host. If that is not the\n * case set the complete base url to the gerrit instance, e.g.\n * \"https://gerrit-review.com/gerrit\". This is the url that you would open\n * in a browser.\n */\n baseUrl?: string;\n\n /**\n * The optional base url to use for cloning a repository. If not set the\n * baseUrl will be used.\n */\n cloneUrl?: string;\n\n /**\n * Disable the edit url feature for Gerrit version less than 3.9.\n */\n disableEditUrl?: boolean;\n\n /**\n * Base url for Gitiles. This is needed for creating a valid\n * user-friendly url that can be used for browsing the content of the\n * provider.\n */\n gitilesBaseUrl: string;\n\n /**\n * The username to use for requests to gerrit.\n */\n username?: string;\n\n /**\n * The password or http token to use for authentication.\n */\n password?: string;\n\n /**\n * The signing key to use for signing commits.\n */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Gerrit integration config.\n *\n * @param config - The config object of a single integration\n *\n * @public\n */\nexport function readGerritIntegrationConfig(\n config: Config,\n): GerritIntegrationConfig {\n const host = config.getString('host');\n let baseUrl = config.getOptionalString('baseUrl');\n let cloneUrl = config.getOptionalString('cloneUrl');\n const disableEditUrl = config.getOptionalBoolean('disableEditUrl');\n let gitilesBaseUrl = config.getString('gitilesBaseUrl');\n const username = config.getOptionalString('username');\n const password = config.getOptionalString('password')?.trim();\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Gerrit integration config, '${host}' is not a valid host`,\n );\n } else if (baseUrl && !isValidUrl(baseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${baseUrl}' is not a valid baseUrl`,\n );\n } else if (cloneUrl && !isValidUrl(cloneUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${cloneUrl}' is not a valid cloneUrl`,\n );\n } else if (!isValidUrl(gitilesBaseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${gitilesBaseUrl}' is not a valid gitilesBaseUrl`,\n );\n }\n if (baseUrl) {\n baseUrl = trimEnd(baseUrl, '/');\n } else {\n baseUrl = `https://${host}`;\n }\n if (cloneUrl) {\n cloneUrl = trimEnd(cloneUrl, '/');\n } else {\n cloneUrl = baseUrl;\n }\n\n gitilesBaseUrl = trimEnd(gitilesBaseUrl, '/');\n\n return {\n host,\n baseUrl,\n cloneUrl,\n disableEditUrl,\n gitilesBaseUrl,\n username,\n password,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Gerrit integration configs.\n *\n * @param configs - All of the integration config objects\n *\n * @public\n */\nexport function readGerritIntegrationConfigs(\n configs: Config[],\n): GerritIntegrationConfig[] {\n return configs.map(readGerritIntegrationConfig);\n}\n"],"names":["isValidHost","isValidUrl","trimEnd"],"mappings":";;;;;AAiFO,SAAS,4BACd,MACyB,EAAA;AACzB,EAAM,MAAA,IAAA,GAAO,MAAO,CAAA,SAAA,CAAU,MAAM,CAAA;AACpC,EAAI,IAAA,OAAA,GAAU,MAAO,CAAA,iBAAA,CAAkB,SAAS,CAAA;AAChD,EAAI,IAAA,QAAA,GAAW,MAAO,CAAA,iBAAA,CAAkB,UAAU,CAAA;AAClD,EAAM,MAAA,cAAA,GAAiB,MAAO,CAAA,k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AAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,gBAAA,EAAkB,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,6BACd,OAC2B,EAAA;AAC3B,EAAO,OAAA,OAAA,CAAQ,IAAI,2BAA2B,CAAA;AAChD;;;;;"}
|
|
@@ -5,6 +5,7 @@ function readGerritIntegrationConfig(config) {
|
|
|
5
5
|
const host = config.getString("host");
|
|
6
6
|
let baseUrl = config.getOptionalString("baseUrl");
|
|
7
7
|
let cloneUrl = config.getOptionalString("cloneUrl");
|
|
8
|
+
const disableEditUrl = config.getOptionalBoolean("disableEditUrl");
|
|
8
9
|
let gitilesBaseUrl = config.getString("gitilesBaseUrl");
|
|
9
10
|
const username = config.getOptionalString("username");
|
|
10
11
|
const password = config.getOptionalString("password")?.trim();
|
|
@@ -30,20 +31,17 @@ function readGerritIntegrationConfig(config) {
|
|
|
30
31
|
} else {
|
|
31
32
|
baseUrl = `https://${host}`;
|
|
32
33
|
}
|
|
33
|
-
if (gitilesBaseUrl) {
|
|
34
|
-
gitilesBaseUrl = trimEnd(gitilesBaseUrl, "/");
|
|
35
|
-
} else {
|
|
36
|
-
gitilesBaseUrl = `https://${host}`;
|
|
37
|
-
}
|
|
38
34
|
if (cloneUrl) {
|
|
39
35
|
cloneUrl = trimEnd(cloneUrl, "/");
|
|
40
36
|
} else {
|
|
41
37
|
cloneUrl = baseUrl;
|
|
42
38
|
}
|
|
39
|
+
gitilesBaseUrl = trimEnd(gitilesBaseUrl, "/");
|
|
43
40
|
return {
|
|
44
41
|
host,
|
|
45
42
|
baseUrl,
|
|
46
43
|
cloneUrl,
|
|
44
|
+
disableEditUrl,
|
|
47
45
|
gitilesBaseUrl,
|
|
48
46
|
username,
|
|
49
47
|
password,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.esm.js","sources":["../../src/gerrit/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost, isValidUrl } from '../helpers';\n\n/**\n * The configuration parameters for a single Gerrit API provider.\n *\n * @public\n */\nexport type GerritIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"gerrit-review.com\"\n */\n host: string;\n\n /**\n * The optional base URL of the Gerrit instance. It is assumed that https\n * is used and that the base path is \"/\" on the host. If that is not the\n * case set the complete base url to the gerrit instance, e.g.\n * \"https://gerrit-review.com/gerrit\". This is the url that you would open\n * in a browser.\n */\n baseUrl?: string;\n\n /**\n * The optional base url to use for cloning a repository. If not set the\n * baseUrl will be used.\n */\n cloneUrl?: string;\n\n /**\n * Base url for Gitiles. This is needed for creating a valid\n * user-friendly url that can be used for browsing the content of the\n * provider.\n */\n gitilesBaseUrl: string;\n\n /**\n * The username to use for requests to gerrit.\n */\n username?: string;\n\n /**\n * The password or http token to use for authentication.\n */\n password?: string;\n\n /**\n * The signing key to use for signing commits.\n */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Gerrit integration config.\n *\n * @param config - The config object of a single integration\n *\n * @public\n */\nexport function readGerritIntegrationConfig(\n config: Config,\n): GerritIntegrationConfig {\n const host = config.getString('host');\n let baseUrl = config.getOptionalString('baseUrl');\n let cloneUrl = config.getOptionalString('cloneUrl');\n let gitilesBaseUrl = config.getString('gitilesBaseUrl');\n const username = config.getOptionalString('username');\n const password = config.getOptionalString('password')?.trim();\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Gerrit integration config, '${host}' is not a valid host`,\n );\n } else if (baseUrl && !isValidUrl(baseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${baseUrl}' is not a valid baseUrl`,\n );\n } else if (cloneUrl && !isValidUrl(cloneUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${cloneUrl}' is not a valid cloneUrl`,\n );\n } else if (!isValidUrl(gitilesBaseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${gitilesBaseUrl}' is not a valid gitilesBaseUrl`,\n );\n }\n if (baseUrl) {\n baseUrl = trimEnd(baseUrl, '/');\n } else {\n baseUrl = `https://${host}`;\n }\n if (
|
|
1
|
+
{"version":3,"file":"config.esm.js","sources":["../../src/gerrit/config.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { trimEnd } from 'lodash';\nimport { isValidHost, isValidUrl } from '../helpers';\n\n/**\n * The configuration parameters for a single Gerrit API provider.\n *\n * @public\n */\nexport type GerritIntegrationConfig = {\n /**\n * The host of the target that this matches on, e.g. \"gerrit-review.com\"\n */\n host: string;\n\n /**\n * The optional base URL of the Gerrit instance. It is assumed that https\n * is used and that the base path is \"/\" on the host. If that is not the\n * case set the complete base url to the gerrit instance, e.g.\n * \"https://gerrit-review.com/gerrit\". This is the url that you would open\n * in a browser.\n */\n baseUrl?: string;\n\n /**\n * The optional base url to use for cloning a repository. If not set the\n * baseUrl will be used.\n */\n cloneUrl?: string;\n\n /**\n * Disable the edit url feature for Gerrit version less than 3.9.\n */\n disableEditUrl?: boolean;\n\n /**\n * Base url for Gitiles. This is needed for creating a valid\n * user-friendly url that can be used for browsing the content of the\n * provider.\n */\n gitilesBaseUrl: string;\n\n /**\n * The username to use for requests to gerrit.\n */\n username?: string;\n\n /**\n * The password or http token to use for authentication.\n */\n password?: string;\n\n /**\n * The signing key to use for signing commits.\n */\n commitSigningKey?: string;\n};\n\n/**\n * Reads a single Gerrit integration config.\n *\n * @param config - The config object of a single integration\n *\n * @public\n */\nexport function readGerritIntegrationConfig(\n config: Config,\n): GerritIntegrationConfig {\n const host = config.getString('host');\n let baseUrl = config.getOptionalString('baseUrl');\n let cloneUrl = config.getOptionalString('cloneUrl');\n const disableEditUrl = config.getOptionalBoolean('disableEditUrl');\n let gitilesBaseUrl = config.getString('gitilesBaseUrl');\n const username = config.getOptionalString('username');\n const password = config.getOptionalString('password')?.trim();\n\n if (!isValidHost(host)) {\n throw new Error(\n `Invalid Gerrit integration config, '${host}' is not a valid host`,\n );\n } else if (baseUrl && !isValidUrl(baseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${baseUrl}' is not a valid baseUrl`,\n );\n } else if (cloneUrl && !isValidUrl(cloneUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${cloneUrl}' is not a valid cloneUrl`,\n );\n } else if (!isValidUrl(gitilesBaseUrl)) {\n throw new Error(\n `Invalid Gerrit integration config, '${gitilesBaseUrl}' is not a valid gitilesBaseUrl`,\n );\n }\n if (baseUrl) {\n baseUrl = trimEnd(baseUrl, '/');\n } else {\n baseUrl = `https://${host}`;\n }\n if (cloneUrl) {\n cloneUrl = trimEnd(cloneUrl, '/');\n } else {\n cloneUrl = baseUrl;\n }\n\n gitilesBaseUrl = trimEnd(gitilesBaseUrl, '/');\n\n return {\n host,\n baseUrl,\n cloneUrl,\n disableEditUrl,\n gitilesBaseUrl,\n username,\n password,\n commitSigningKey: config.getOptionalString('commitSigningKey'),\n };\n}\n\n/**\n * Reads a set of Gerrit integration configs.\n *\n * @param configs - All of the integration config objects\n *\n * @public\n */\nexport function readGerritIntegrationConfigs(\n configs: Config[],\n): GerritIntegrationConfig[] {\n return configs.map(readGerritIntegrationConfig);\n}\n"],"names":[],"mappings":";;;AAiFO,SAAS,4BACd,MACyB,EAAA;AACzB,EAAM,MAAA,IAAA,GAAO,MAAO,CAAA,SAAA,CAAU,MAAM,CAAA;AACpC,EAAI,IAAA,OAAA,GAAU,MAAO,CAAA,iBAAA,CAAkB,SAAS,CAAA;AAChD,EAAI,IAAA,QAAA,GAAW,MAAO,CAAA,iBAAA,CAAkB,UAAU,CAAA;AAClD,EAAM,MAAA,cAAA,GAAiB,MAAO,CAAA,kBAAA,CAAmB,gBAAgB,CAAA;AACjE,EAAI,IAAA,cAAA,GAAiB,MAAO,CAAA,SAAA,CAAU,gBAAgB,CAAA;AACtD,EAAM,MAAA,QAAA,GAAW,MAAO,CAAA,iBAAA,CAAkB,UAAU,CAAA;AACpD,EAAA,MAAM,QAAW,GAAA,MAAA,CAAO,iBAAkB,CAAA,UAAU,GAAG,IAAK,EAAA;AAE5D,EAAI,IAAA,CAAC,WAAY,CAAA,IAAI,CAAG,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,qBAAA;AAAA,KAC7C;AAAA,GACS,MAAA,IAAA,OAAA,IAAW,CAAC,UAAA,CAAW,OAAO,CAAG,EAAA;AAC1C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,OAAO,CAAA,wBAAA;AAAA,KAChD;AAAA,GACS,MAAA,IAAA,QAAA,IAAY,CAAC,UAAA,CAAW,QAAQ,CAAG,EAAA;AAC5C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,QAAQ,CAAA,yBAAA;AAAA,KACjD;AAAA,GACS,MAAA,IAAA,CAAC,UAAW,CAAA,cAAc,CAAG,EAAA;AACtC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,cAAc,CAAA,+BAAA;AAAA,KACvD;AAAA;AAEF,EAAA,IAAI,OAAS,EAAA;AACX,IAAU,OAAA,GAAA,OAAA,CAAQ,SAAS,GAAG,CAAA;AAAA,GACzB,MAAA;AACL,IAAA,OAAA,GAAU,WAAW,IAAI,CAAA,CAAA;AAAA;AAE3B,EAAA,IAAI,QAAU,EAAA;AACZ,IAAW,QAAA,GAAA,OAAA,CAAQ,UAAU,GAAG,CAAA;AAAA,GAC3B,MAAA;AACL,IAAW,QAAA,GAAA,OAAA;AAAA;AAGb,EAAiB,cAAA,GAAA,OAAA,CAAQ,gBAAgB,GAAG,CAAA;AAE5C,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,gBAAA,EAAkB,MAAO,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,GAC/D;AACF;AASO,SAAS,6BACd,OAC2B,EAAA;AAC3B,EAAO,OAAA,OAAA,CAAQ,IAAI,2BAA2B,CAAA;AAChD;;;;"}
|
package/dist/gerrit/core.cjs.js
CHANGED
|
@@ -89,6 +89,12 @@ function parseGitilesUrlRef(config, url) {
|
|
|
89
89
|
}
|
|
90
90
|
throw new Error(`Unable to parse gitiles : ${url}`);
|
|
91
91
|
}
|
|
92
|
+
function buildGerritEditUrl(config, project, branch, filePath) {
|
|
93
|
+
return `${config.baseUrl}/admin/repos/edit/repo/${project}/branch/refs/heads/${branch}/file/${lodash.trimStart(
|
|
94
|
+
filePath,
|
|
95
|
+
"/"
|
|
96
|
+
)}`;
|
|
97
|
+
}
|
|
92
98
|
function buildGerritGitilesArchiveUrl(config, project, branch, filePath) {
|
|
93
99
|
const archiveName = filePath === "/" || filePath === "" ? ".tar.gz" : `/${filePath}.tar.gz`;
|
|
94
100
|
return `${getGitilesAuthenticationUrl(
|
|
@@ -195,6 +201,7 @@ async function parseGerritJsonResponse(response) {
|
|
|
195
201
|
);
|
|
196
202
|
}
|
|
197
203
|
|
|
204
|
+
exports.buildGerritEditUrl = buildGerritEditUrl;
|
|
198
205
|
exports.buildGerritGitilesArchiveUrl = buildGerritGitilesArchiveUrl;
|
|
199
206
|
exports.buildGerritGitilesArchiveUrlFromLocation = buildGerritGitilesArchiveUrlFromLocation;
|
|
200
207
|
exports.getAuthenticationPrefix = getAuthenticationPrefix;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs.js","sources":["../../src/gerrit/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join, takeWhile, trimEnd, trimStart } from 'lodash';\nimport { GerritIntegrationConfig } from './config';\n\nconst GERRIT_BODY_PREFIX = \")]}'\";\n\n/**\n * Parse a Gitiles URL and return branch, file path and project.\n *\n * @remarks\n *\n * Gerrit only handles code reviews so it does not have a native way to browse\n * or showing the content of gits. Image if Github only had the \"pull requests\"\n * tab.\n *\n * Any source code browsing is instead handled by optional services outside\n * Gerrit. The url format chosen for the Gerrit url reader is the one used by\n * the Gitiles project. Gerrit will work perfectly with Backstage without\n * having Gitiles installed but there are some places in the Backstage GUI\n * with links to the url used by the url reader. These will not work unless\n * the urls point to an actual Gitiles installation.\n *\n * Gitiles url:\n * https://g.com/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n * https://g.com/a/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n *\n *\n * @param url - An URL pointing to a file stored in git.\n * @public\n * @deprecated `parseGerritGitilesUrl` is deprecated. Use\n * {@link parseGitilesUrlRef} instead.\n */\nexport function parseGerritGitilesUrl(\n config: GerritIntegrationConfig,\n url: string,\n): { branch: string; filePath: string; project: string } {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, '');\n\n const parts = urlPath.split('/').filter(p => !!p);\n\n const projectEndIndex = parts.indexOf('+');\n\n if (projectEndIndex <= 0) {\n throw new Error(`Unable to parse project from url: ${url}`);\n }\n const project = trimStart(parts.slice(0, projectEndIndex).join('/'), '/');\n\n const branchIndex = parts.indexOf('heads');\n if (branchIndex <= 0) {\n throw new Error(`Unable to parse branch from url: ${url}`);\n }\n const branch = parts[branchIndex + 1];\n const filePath = parts.slice(branchIndex + 2).join('/');\n\n return {\n branch,\n filePath: filePath === '' ? '/' : filePath,\n project,\n };\n}\n\n/**\n * Parses Gitiles urls and returns the following:\n *\n * - The project\n * - The type of ref. I.e: branch name, SHA, HEAD or tag.\n * - The file path from the repo root.\n * - The base path as the path that points to the repo root.\n *\n * Supported types of gitiles urls that point to:\n *\n * - Branches\n * - Tags\n * - A commit SHA\n * - HEAD\n *\n * @param config - A Gerrit provider config.\n * @param url - An url to a file or folder in Gitiles.\n * @public\n */\nexport function parseGitilesUrlRef(\n config: GerritIntegrationConfig,\n url: string,\n): {\n project: string;\n path: string;\n ref: string;\n refType: 'sha' | 'branch' | 'tag' | 'head';\n basePath: string;\n} {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = trimStart(\n urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, ''),\n '/',\n );\n\n // Find the project by taking everything up to \"/+/\".\n const parts = urlPath.split('/').filter(p => !!p);\n const projectParts = takeWhile(parts, p => p !== '+');\n if (projectParts.length === 0) {\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n // Also remove the \"+\" after the project.\n const rest = parts.slice(projectParts.length + 1);\n const project = join(projectParts, '/');\n\n // match <project>/+/HEAD/<path>\n if (rest.length > 0 && rest[0] === 'HEAD') {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'head' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n // match <project>/+/<sha>/<path>\n if (rest.length > 0 && rest[0].length === 40) {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'sha' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n const remainingPath = join(rest, '/');\n // Regexp for matching \"refs/tags/<tag>\" or \"refs/heads/<branch>/\"\n const refsRegexp = /^refs\\/(?<refsReference>heads|tags)\\/(?<ref>.*?)(\\/|$)/;\n const result = refsRegexp.exec(remainingPath);\n if (result) {\n const matchString = result[0];\n let refType;\n const { refsReference, ref } = result.groups || {};\n const path = remainingPath.replace(matchString, '');\n switch (refsReference) {\n case 'heads':\n refType = 'branch' as const;\n break;\n case 'tags':\n refType = 'tag' as const;\n break;\n default:\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n return {\n project,\n ref,\n refType,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n throw new Error(`Unable to parse gitiles : ${url}`);\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritGitilesUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.gitilesBaseUrl\n }/${project}/+/refs/heads/${branch}/${trimStart(filePath, '/')}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url that targets a specific branch and path\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n * @deprecated `buildGerritGitilesArchiveUrl` is deprecated. Use\n * {@link buildGerritGitilesArchiveUrlFromLocation} instead.\n */\nexport function buildGerritGitilesArchiveUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${branch}${archiveName}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url from a Gitiles url.\n *\n * @param config - A Gerrit provider config.\n * @param url - The gitiles url\n * @public\n */\nexport function buildGerritGitilesArchiveUrlFromLocation(\n config: GerritIntegrationConfig,\n url: string,\n): string {\n const {\n path: filePath,\n ref,\n project,\n refType,\n } = parseGitilesUrlRef(config, url);\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n if (refType === 'branch') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${ref}${archiveName}`;\n }\n if (refType === 'sha') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/${ref}${archiveName}`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the authentication prefix.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getAuthenticationPrefix(\n config: GerritIntegrationConfig,\n): string {\n return config.password ? '/a/' : '/';\n}\n\n/**\n * Return the authentication gitiles url.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGitilesAuthenticationUrl(\n config: GerritIntegrationConfig,\n): string {\n if (!config.baseUrl || !config.gitilesBaseUrl) {\n throw new Error(\n 'Unexpected Gerrit config values. baseUrl or gitilesBaseUrl not set.',\n );\n }\n if (config.gitilesBaseUrl.startsWith(config.baseUrl)) {\n return config.gitilesBaseUrl.replace(\n config.baseUrl.concat('/'),\n config.baseUrl.concat(getAuthenticationPrefix(config)),\n );\n }\n if (config.password) {\n throw new Error(\n 'Since the baseUrl (Gerrit) is not part of the gitilesBaseUrl, an authentication URL could not be constructed.',\n );\n }\n return config.gitilesBaseUrl!;\n}\n\n/**\n * Return the url to get branch info from the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritBranchApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { branch, project } = parseGerritGitilesUrl(config, url);\n\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(project)}/branches/${branch}`;\n}\n\n/**\n * Return the url to clone the repo that is referenced by the url.\n *\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritCloneRepoUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { project } = parseGerritGitilesUrl(config, url);\n\n return `${config.cloneUrl}${getAuthenticationPrefix(config)}${project}`;\n}\n\n/**\n * Return the url to fetch the contents of a file using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritFileContentsApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { ref, refType, path, project } = parseGitilesUrlRef(config, url);\n\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content\n if (refType === 'branch') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/branches/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content-from-commit\n if (refType === 'sha') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/commits/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the url to query available projects using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGerritProjectsApiUrl(config: GerritIntegrationConfig) {\n return `${config.baseUrl}${getAuthenticationPrefix(config)}projects/`;\n}\n\n/**\n * Return request headers for a Gerrit provider.\n *\n * @param config - A Gerrit provider config\n * @public\n */\nexport function getGerritRequestOptions(config: GerritIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n if (!config.password) {\n return headers;\n }\n const buffer = Buffer.from(`${config.username}:${config.password}`, 'utf8');\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n return {\n headers,\n };\n}\n\n/**\n * Parse the json response from Gerrit and strip the magic prefix.\n *\n * @remarks\n *\n * To prevent against XSSI attacks the JSON response body from Gerrit starts\n * with a magic prefix that must be stripped before it can be fed to a JSON\n * parser.\n *\n * @param response - An API response.\n * @public\n */\nexport async function parseGerritJsonResponse(\n response: Response,\n): Promise<unknown> {\n const responseBody = await response.text();\n if (responseBody.startsWith(GERRIT_BODY_PREFIX)) {\n try {\n return JSON.parse(responseBody.slice(GERRIT_BODY_PREFIX.length));\n } catch (ex) {\n throw new Error(\n `Invalid response from Gerrit: ${responseBody.slice(0, 10)} - ${ex}`,\n );\n }\n }\n throw new Error(\n `Gerrit JSON body prefix missing. Found: ${responseBody.slice(0, 10)}`,\n );\n}\n"],"names":["trimStart","takeWhile","join","trimEnd"],"mappings":";;;;A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MAAA,CAAO,QAAQ,CAAI,CAAA,EAAA,MAAA,CAAO,QAAQ,CAAA,CAAA,EAAI,MAAM,CAAA;AAC1E,EAAA,OAAA,CAAQ,aAAgB,GAAA,CAAA,MAAA,EAAS,MAAO,CAAA,QAAA,CAAS,QAAQ,CAAC,CAAA,CAAA;AAC1D,EAAO,OAAA;AAAA,IACL;AAAA,GACF;AACF;AAcA,eAAsB,wBACpB,QACkB,EAAA;AAClB,EAAM,MAAA,YAAA,GAAe,MAAM,QAAA,CAAS,IAAK,EAAA;AACzC,EAAI,IAAA,YAAA,CAAa,UAAW,CAAA,kBAAkB,CAAG,EAAA;AAC/C,IAAI,IAAA;AACF,MAAA,OAAO,KAAK,KAAM,CAAA,YAAA,CAAa,KAAM,CAAA,kBAAA,CAAmB,MAAM,CAAC,CAAA;AAAA,aACxD,EAAI,EAAA;AACX,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,iCAAiC,YAAa,CAAA,KAAA,CAAM,GAAG,EAAE,CAAC,MAAM,EAAE,CAAA;AAAA,OACpE;AAAA;AACF;AAEF,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAA2C,wCAAA,EAAA,YAAA,CAAa,KAAM,CAAA,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,GACtE;AACF;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"core.cjs.js","sources":["../../src/gerrit/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join, takeWhile, trimEnd, trimStart } from 'lodash';\nimport { GerritIntegrationConfig } from './config';\n\nconst GERRIT_BODY_PREFIX = \")]}'\";\n\n/**\n * Parse a Gitiles URL and return branch, file path and project.\n *\n * @remarks\n *\n * Gerrit only handles code reviews so it does not have a native way to browse\n * or showing the content of gits. Image if Github only had the \"pull requests\"\n * tab.\n *\n * Any source code browsing is instead handled by optional services outside\n * Gerrit. The url format chosen for the Gerrit url reader is the one used by\n * the Gitiles project. Gerrit will work perfectly with Backstage without\n * having Gitiles installed but there are some places in the Backstage GUI\n * with links to the url used by the url reader. These will not work unless\n * the urls point to an actual Gitiles installation.\n *\n * Gitiles url:\n * https://g.com/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n * https://g.com/a/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n *\n *\n * @param url - An URL pointing to a file stored in git.\n * @public\n * @deprecated `parseGerritGitilesUrl` is deprecated. Use\n * {@link parseGitilesUrlRef} instead.\n */\nexport function parseGerritGitilesUrl(\n config: GerritIntegrationConfig,\n url: string,\n): { branch: string; filePath: string; project: string } {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, '');\n\n const parts = urlPath.split('/').filter(p => !!p);\n\n const projectEndIndex = parts.indexOf('+');\n\n if (projectEndIndex <= 0) {\n throw new Error(`Unable to parse project from url: ${url}`);\n }\n const project = trimStart(parts.slice(0, projectEndIndex).join('/'), '/');\n\n const branchIndex = parts.indexOf('heads');\n if (branchIndex <= 0) {\n throw new Error(`Unable to parse branch from url: ${url}`);\n }\n const branch = parts[branchIndex + 1];\n const filePath = parts.slice(branchIndex + 2).join('/');\n\n return {\n branch,\n filePath: filePath === '' ? '/' : filePath,\n project,\n };\n}\n\n/**\n * Parses Gitiles urls and returns the following:\n *\n * - The project\n * - The type of ref. I.e: branch name, SHA, HEAD or tag.\n * - The file path from the repo root.\n * - The base path as the path that points to the repo root.\n *\n * Supported types of gitiles urls that point to:\n *\n * - Branches\n * - Tags\n * - A commit SHA\n * - HEAD\n *\n * @param config - A Gerrit provider config.\n * @param url - An url to a file or folder in Gitiles.\n * @public\n */\nexport function parseGitilesUrlRef(\n config: GerritIntegrationConfig,\n url: string,\n): {\n project: string;\n path: string;\n ref: string;\n refType: 'sha' | 'branch' | 'tag' | 'head';\n basePath: string;\n} {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = trimStart(\n urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, ''),\n '/',\n );\n\n // Find the project by taking everything up to \"/+/\".\n const parts = urlPath.split('/').filter(p => !!p);\n const projectParts = takeWhile(parts, p => p !== '+');\n if (projectParts.length === 0) {\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n // Also remove the \"+\" after the project.\n const rest = parts.slice(projectParts.length + 1);\n const project = join(projectParts, '/');\n\n // match <project>/+/HEAD/<path>\n if (rest.length > 0 && rest[0] === 'HEAD') {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'head' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n // match <project>/+/<sha>/<path>\n if (rest.length > 0 && rest[0].length === 40) {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'sha' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n const remainingPath = join(rest, '/');\n // Regexp for matching \"refs/tags/<tag>\" or \"refs/heads/<branch>/\"\n const refsRegexp = /^refs\\/(?<refsReference>heads|tags)\\/(?<ref>.*?)(\\/|$)/;\n const result = refsRegexp.exec(remainingPath);\n if (result) {\n const matchString = result[0];\n let refType;\n const { refsReference, ref } = result.groups || {};\n const path = remainingPath.replace(matchString, '');\n switch (refsReference) {\n case 'heads':\n refType = 'branch' as const;\n break;\n case 'tags':\n refType = 'tag' as const;\n break;\n default:\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n return {\n project,\n ref,\n refType,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n throw new Error(`Unable to parse gitiles : ${url}`);\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritGitilesUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.gitilesBaseUrl\n }/${project}/+/refs/heads/${branch}/${trimStart(filePath, '/')}`;\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritEditUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.baseUrl\n }/admin/repos/edit/repo/${project}/branch/refs/heads/${branch}/file/${trimStart(\n filePath,\n '/',\n )}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url that targets a specific branch and path\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n * @deprecated `buildGerritGitilesArchiveUrl` is deprecated. Use\n * {@link buildGerritGitilesArchiveUrlFromLocation} instead.\n */\nexport function buildGerritGitilesArchiveUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${branch}${archiveName}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url from a Gitiles url.\n *\n * @param config - A Gerrit provider config.\n * @param url - The gitiles url\n * @public\n */\nexport function buildGerritGitilesArchiveUrlFromLocation(\n config: GerritIntegrationConfig,\n url: string,\n): string {\n const {\n path: filePath,\n ref,\n project,\n refType,\n } = parseGitilesUrlRef(config, url);\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n if (refType === 'branch') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${ref}${archiveName}`;\n }\n if (refType === 'sha') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/${ref}${archiveName}`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the authentication prefix.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getAuthenticationPrefix(\n config: GerritIntegrationConfig,\n): string {\n return config.password ? '/a/' : '/';\n}\n\n/**\n * Return the authentication gitiles url.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGitilesAuthenticationUrl(\n config: GerritIntegrationConfig,\n): string {\n if (!config.baseUrl || !config.gitilesBaseUrl) {\n throw new Error(\n 'Unexpected Gerrit config values. baseUrl or gitilesBaseUrl not set.',\n );\n }\n if (config.gitilesBaseUrl.startsWith(config.baseUrl)) {\n return config.gitilesBaseUrl.replace(\n config.baseUrl.concat('/'),\n config.baseUrl.concat(getAuthenticationPrefix(config)),\n );\n }\n if (config.password) {\n throw new Error(\n 'Since the baseUrl (Gerrit) is not part of the gitilesBaseUrl, an authentication URL could not be constructed.',\n );\n }\n return config.gitilesBaseUrl!;\n}\n\n/**\n * Return the url to get branch info from the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritBranchApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { branch, project } = parseGerritGitilesUrl(config, url);\n\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(project)}/branches/${branch}`;\n}\n\n/**\n * Return the url to clone the repo that is referenced by the url.\n *\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritCloneRepoUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { project } = parseGerritGitilesUrl(config, url);\n\n return `${config.cloneUrl}${getAuthenticationPrefix(config)}${project}`;\n}\n\n/**\n * Return the url to fetch the contents of a file using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritFileContentsApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { ref, refType, path, project } = parseGitilesUrlRef(config, url);\n\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content\n if (refType === 'branch') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/branches/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content-from-commit\n if (refType === 'sha') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/commits/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the url to query available projects using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGerritProjectsApiUrl(config: GerritIntegrationConfig) {\n return `${config.baseUrl}${getAuthenticationPrefix(config)}projects/`;\n}\n\n/**\n * Return request headers for a Gerrit provider.\n *\n * @param config - A Gerrit provider config\n * @public\n */\nexport function getGerritRequestOptions(config: GerritIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n if (!config.password) {\n return headers;\n }\n const buffer = Buffer.from(`${config.username}:${config.password}`, 'utf8');\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n return {\n headers,\n };\n}\n\n/**\n * Parse the json response from Gerrit and strip the magic prefix.\n *\n * @remarks\n *\n * To prevent against XSSI attacks the JSON response body from Gerrit starts\n * with a magic prefix that must be stripped before it can be fed to a JSON\n * parser.\n *\n * @param response - An API response.\n * @public\n */\nexport async function parseGerritJsonResponse(\n response: Response,\n): Promise<unknown> {\n const responseBody = await response.text();\n if (responseBody.startsWith(GERRIT_BODY_PREFIX)) {\n try {\n return JSON.parse(responseBody.slice(GERRIT_BODY_PREFIX.length));\n } catch (ex) {\n throw new Error(\n `Invalid response from Gerrit: ${responseBody.slice(0, 10)} - ${ex}`,\n );\n }\n }\n throw new Error(\n `Gerrit JSON body prefix missing. Found: ${responseBody.slice(0, 10)}`,\n );\n}\n"],"names":["trimStart","takeWhile","join","trimEnd"],"mappings":";;;;AAkBA,MAAM,kBAAqB,GAAA,MAAA;AA4BX,SAAA,qBAAA,CACd,QACA,GACuD,EAAA;AACvD,EAAA,MAAM,YAAe,GAAA,IAAI,GAAI,CAAA,MAAA,CAAO,cAAe,CAAA;AACnD,EAAM,MAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA;AAM5B,EAAA,MAAM,OAAU,GAAA,QAAA,CAAS,QACtB,CAAA,SAAA,CAAU,SAAS,QAAS,CAAA,UAAA,CAAW,KAAK,CAAA,GAAI,IAAI,CAAC,CAAA,CACrD,OAAQ,CAAA,YAAA,CAAa,UAAU,EAAE,CAAA;AAEpC,EAAM,MAAA,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AC,CAAA,CAAA;AAC1D,EAAO,OAAA;AAAA,IACL;AAAA,GACF;AACF;AAcA,eAAsB,wBACpB,QACkB,EAAA;AAClB,EAAM,MAAA,YAAA,GAAe,MAAM,QAAA,CAAS,IAAK,EAAA;AACzC,EAAI,IAAA,YAAA,CAAa,UAAW,CAAA,kBAAkB,CAAG,EAAA;AAC/C,IAAI,IAAA;AACF,MAAA,OAAO,KAAK,KAAM,CAAA,YAAA,CAAa,KAAM,CAAA,kBAAA,CAAmB,MAAM,CAAC,CAAA;AAAA,aACxD,EAAI,EAAA;AACX,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,iCAAiC,YAAa,CAAA,KAAA,CAAM,GAAG,EAAE,CAAC,MAAM,EAAE,CAAA;AAAA,OACpE;AAAA;AACF;AAEF,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAA2C,wCAAA,EAAA,YAAA,CAAa,KAAM,CAAA,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,GACtE;AACF;;;;;;;;;;;;;;;;"}
|
package/dist/gerrit/core.esm.js
CHANGED
|
@@ -87,6 +87,12 @@ function parseGitilesUrlRef(config, url) {
|
|
|
87
87
|
}
|
|
88
88
|
throw new Error(`Unable to parse gitiles : ${url}`);
|
|
89
89
|
}
|
|
90
|
+
function buildGerritEditUrl(config, project, branch, filePath) {
|
|
91
|
+
return `${config.baseUrl}/admin/repos/edit/repo/${project}/branch/refs/heads/${branch}/file/${trimStart(
|
|
92
|
+
filePath,
|
|
93
|
+
"/"
|
|
94
|
+
)}`;
|
|
95
|
+
}
|
|
90
96
|
function buildGerritGitilesArchiveUrl(config, project, branch, filePath) {
|
|
91
97
|
const archiveName = filePath === "/" || filePath === "" ? ".tar.gz" : `/${filePath}.tar.gz`;
|
|
92
98
|
return `${getGitilesAuthenticationUrl(
|
|
@@ -193,5 +199,5 @@ async function parseGerritJsonResponse(response) {
|
|
|
193
199
|
);
|
|
194
200
|
}
|
|
195
201
|
|
|
196
|
-
export { buildGerritGitilesArchiveUrl, buildGerritGitilesArchiveUrlFromLocation, getAuthenticationPrefix, getGerritBranchApiUrl, getGerritCloneRepoUrl, getGerritFileContentsApiUrl, getGerritProjectsApiUrl, getGerritRequestOptions, getGitilesAuthenticationUrl, parseGerritGitilesUrl, parseGerritJsonResponse, parseGitilesUrlRef };
|
|
202
|
+
export { buildGerritEditUrl, buildGerritGitilesArchiveUrl, buildGerritGitilesArchiveUrlFromLocation, getAuthenticationPrefix, getGerritBranchApiUrl, getGerritCloneRepoUrl, getGerritFileContentsApiUrl, getGerritProjectsApiUrl, getGerritRequestOptions, getGitilesAuthenticationUrl, parseGerritGitilesUrl, parseGerritJsonResponse, parseGitilesUrlRef };
|
|
197
203
|
//# sourceMappingURL=core.esm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.esm.js","sources":["../../src/gerrit/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join, takeWhile, trimEnd, trimStart } from 'lodash';\nimport { GerritIntegrationConfig } from './config';\n\nconst GERRIT_BODY_PREFIX = \")]}'\";\n\n/**\n * Parse a Gitiles URL and return branch, file path and project.\n *\n * @remarks\n *\n * Gerrit only handles code reviews so it does not have a native way to browse\n * or showing the content of gits. Image if Github only had the \"pull requests\"\n * tab.\n *\n * Any source code browsing is instead handled by optional services outside\n * Gerrit. The url format chosen for the Gerrit url reader is the one used by\n * the Gitiles project. Gerrit will work perfectly with Backstage without\n * having Gitiles installed but there are some places in the Backstage GUI\n * with links to the url used by the url reader. These will not work unless\n * the urls point to an actual Gitiles installation.\n *\n * Gitiles url:\n * https://g.com/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n * https://g.com/a/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n *\n *\n * @param url - An URL pointing to a file stored in git.\n * @public\n * @deprecated `parseGerritGitilesUrl` is deprecated. Use\n * {@link parseGitilesUrlRef} instead.\n */\nexport function parseGerritGitilesUrl(\n config: GerritIntegrationConfig,\n url: string,\n): { branch: string; filePath: string; project: string } {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, '');\n\n const parts = urlPath.split('/').filter(p => !!p);\n\n const projectEndIndex = parts.indexOf('+');\n\n if (projectEndIndex <= 0) {\n throw new Error(`Unable to parse project from url: ${url}`);\n }\n const project = trimStart(parts.slice(0, projectEndIndex).join('/'), '/');\n\n const branchIndex = parts.indexOf('heads');\n if (branchIndex <= 0) {\n throw new Error(`Unable to parse branch from url: ${url}`);\n }\n const branch = parts[branchIndex + 1];\n const filePath = parts.slice(branchIndex + 2).join('/');\n\n return {\n branch,\n filePath: filePath === '' ? '/' : filePath,\n project,\n };\n}\n\n/**\n * Parses Gitiles urls and returns the following:\n *\n * - The project\n * - The type of ref. I.e: branch name, SHA, HEAD or tag.\n * - The file path from the repo root.\n * - The base path as the path that points to the repo root.\n *\n * Supported types of gitiles urls that point to:\n *\n * - Branches\n * - Tags\n * - A commit SHA\n * - HEAD\n *\n * @param config - A Gerrit provider config.\n * @param url - An url to a file or folder in Gitiles.\n * @public\n */\nexport function parseGitilesUrlRef(\n config: GerritIntegrationConfig,\n url: string,\n): {\n project: string;\n path: string;\n ref: string;\n refType: 'sha' | 'branch' | 'tag' | 'head';\n basePath: string;\n} {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = trimStart(\n urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, ''),\n '/',\n );\n\n // Find the project by taking everything up to \"/+/\".\n const parts = urlPath.split('/').filter(p => !!p);\n const projectParts = takeWhile(parts, p => p !== '+');\n if (projectParts.length === 0) {\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n // Also remove the \"+\" after the project.\n const rest = parts.slice(projectParts.length + 1);\n const project = join(projectParts, '/');\n\n // match <project>/+/HEAD/<path>\n if (rest.length > 0 && rest[0] === 'HEAD') {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'head' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n // match <project>/+/<sha>/<path>\n if (rest.length > 0 && rest[0].length === 40) {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'sha' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n const remainingPath = join(rest, '/');\n // Regexp for matching \"refs/tags/<tag>\" or \"refs/heads/<branch>/\"\n const refsRegexp = /^refs\\/(?<refsReference>heads|tags)\\/(?<ref>.*?)(\\/|$)/;\n const result = refsRegexp.exec(remainingPath);\n if (result) {\n const matchString = result[0];\n let refType;\n const { refsReference, ref } = result.groups || {};\n const path = remainingPath.replace(matchString, '');\n switch (refsReference) {\n case 'heads':\n refType = 'branch' as const;\n break;\n case 'tags':\n refType = 'tag' as const;\n break;\n default:\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n return {\n project,\n ref,\n refType,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n throw new Error(`Unable to parse gitiles : ${url}`);\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritGitilesUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.gitilesBaseUrl\n }/${project}/+/refs/heads/${branch}/${trimStart(filePath, '/')}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url that targets a specific branch and path\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n * @deprecated `buildGerritGitilesArchiveUrl` is deprecated. Use\n * {@link buildGerritGitilesArchiveUrlFromLocation} instead.\n */\nexport function buildGerritGitilesArchiveUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${branch}${archiveName}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url from a Gitiles url.\n *\n * @param config - A Gerrit provider config.\n * @param url - The gitiles url\n * @public\n */\nexport function buildGerritGitilesArchiveUrlFromLocation(\n config: GerritIntegrationConfig,\n url: string,\n): string {\n const {\n path: filePath,\n ref,\n project,\n refType,\n } = parseGitilesUrlRef(config, url);\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n if (refType === 'branch') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${ref}${archiveName}`;\n }\n if (refType === 'sha') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/${ref}${archiveName}`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the authentication prefix.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getAuthenticationPrefix(\n config: GerritIntegrationConfig,\n): string {\n return config.password ? '/a/' : '/';\n}\n\n/**\n * Return the authentication gitiles url.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGitilesAuthenticationUrl(\n config: GerritIntegrationConfig,\n): string {\n if (!config.baseUrl || !config.gitilesBaseUrl) {\n throw new Error(\n 'Unexpected Gerrit config values. baseUrl or gitilesBaseUrl not set.',\n );\n }\n if (config.gitilesBaseUrl.startsWith(config.baseUrl)) {\n return config.gitilesBaseUrl.replace(\n config.baseUrl.concat('/'),\n config.baseUrl.concat(getAuthenticationPrefix(config)),\n );\n }\n if (config.password) {\n throw new Error(\n 'Since the baseUrl (Gerrit) is not part of the gitilesBaseUrl, an authentication URL could not be constructed.',\n );\n }\n return config.gitilesBaseUrl!;\n}\n\n/**\n * Return the url to get branch info from the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritBranchApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { branch, project } = parseGerritGitilesUrl(config, url);\n\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(project)}/branches/${branch}`;\n}\n\n/**\n * Return the url to clone the repo that is referenced by the url.\n *\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritCloneRepoUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { project } = parseGerritGitilesUrl(config, url);\n\n return `${config.cloneUrl}${getAuthenticationPrefix(config)}${project}`;\n}\n\n/**\n * Return the url to fetch the contents of a file using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritFileContentsApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { ref, refType, path, project } = parseGitilesUrlRef(config, url);\n\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content\n if (refType === 'branch') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/branches/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content-from-commit\n if (refType === 'sha') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/commits/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the url to query available projects using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGerritProjectsApiUrl(config: GerritIntegrationConfig) {\n return `${config.baseUrl}${getAuthenticationPrefix(config)}projects/`;\n}\n\n/**\n * Return request headers for a Gerrit provider.\n *\n * @param config - A Gerrit provider config\n * @public\n */\nexport function getGerritRequestOptions(config: GerritIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n if (!config.password) {\n return headers;\n }\n const buffer = Buffer.from(`${config.username}:${config.password}`, 'utf8');\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n return {\n headers,\n };\n}\n\n/**\n * Parse the json response from Gerrit and strip the magic prefix.\n *\n * @remarks\n *\n * To prevent against XSSI attacks the JSON response body from Gerrit starts\n * with a magic prefix that must be stripped before it can be fed to a JSON\n * parser.\n *\n * @param response - An API response.\n * @public\n */\nexport async function parseGerritJsonResponse(\n response: Response,\n): Promise<unknown> {\n const responseBody = await response.text();\n if (responseBody.startsWith(GERRIT_BODY_PREFIX)) {\n try {\n return JSON.parse(responseBody.slice(GERRIT_BODY_PREFIX.length));\n } catch (ex) {\n throw new Error(\n `Invalid response from Gerrit: ${responseBody.slice(0, 10)} - ${ex}`,\n );\n }\n }\n throw new Error(\n `Gerrit JSON body prefix missing. Found: ${responseBody.slice(0, 10)}`,\n );\n}\n"],"names":[],"mappings":";;AAkBA,MAAM,kBAAqB,GAAA,MAAA;AA4BX,SAAA,qBAAA,CACd,QACA,GACuD,EAAA;AACvD,EAAA,MAAM,YAAe,GAAA,IAAI,GAAI,CAAA,MAAA,CAAO,cAAe,CAAA;AACnD,EAAM,MAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA;AAM5B,EAAA,MAAM,OAAU,GAAA,QAAA,CAAS,QACtB,CAAA,SAAA,CAAU,SAAS,QAAS,CAAA,UAAA,CAAW,KAAK,CAAA,GAAI,IAAI,CAAC,CAAA,CACrD,OAAQ,CAAA,YAAA,CAAa,UAAU,EAAE,CAAA;AAEpC,EAAM,MAAA,KAAA,GAAQ,QAAQ,KAAM,CAAA,GAAG,EAAE,MAAO,CAAA,CAAA,CAAA,KAAK,CAAC,CAAC,CAAC,CAAA;AAEhD,EAAM,MAAA,eAAA,GAAkB,KAAM,CAAA,OAAA,CAAQ,GAAG,CAAA;AAEzC,EAAA,IAAI,mBAAmB,CAAG,EAAA;AACxB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAqC,kCAAA,EAAA,GAAG,CAAE,CAAA,CAAA;AAAA;AAE5D,EAAM,MAAA,OAAA,GAAU,SAAU,CAAA,KAAA,CAAM,KAAM,CAAA,CAAA,EAAG,eAAe,CAAE,CAAA,IAAA,CAAK,GAAG,CAAA,EAAG,GAAG,CAAA;AAExE,EAAM,MAAA,WAAA,GAAc,KAAM,CAAA,OAAA,CAAQ,OAAO,CAAA;AACzC,EAAA,IAAI,eAAe,CAAG,EAAA;AACpB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAoC,iCAAA,EAAA,GAAG,CAAE,CAAA,CAAA;AAAA;AAE3D,EAAM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A;AACA,EAAA,MAAM,UAAkC,EAAC;AAEzC,EAAI,IAAA,CAAC,OAAO,QAAU,EAAA;AACpB,IAAO,OAAA,OAAA;AAAA;AAET,EAAM,MAAA,MAAA,GAAS,MAAO,CAAA,IAAA,CAAK,CAAG,EAAA,MAAA,CAAO,QAAQ,CAAI,CAAA,EAAA,MAAA,CAAO,QAAQ,CAAA,CAAA,EAAI,MAAM,CAAA;AAC1E,EAAA,OAAA,CAAQ,aAAgB,GAAA,CAAA,MAAA,EAAS,MAAO,CAAA,QAAA,CAAS,QAAQ,CAAC,CAAA,CAAA;AAC1D,EAAO,OAAA;AAAA,IACL;AAAA,GACF;AACF;AAcA,eAAsB,wBACpB,QACkB,EAAA;AAClB,EAAM,MAAA,YAAA,GAAe,MAAM,QAAA,CAAS,IAAK,EAAA;AACzC,EAAI,IAAA,YAAA,CAAa,UAAW,CAAA,kBAAkB,CAAG,EAAA;AAC/C,IAAI,IAAA;AACF,MAAA,OAAO,KAAK,KAAM,CAAA,YAAA,CAAa,KAAM,CAAA,kBAAA,CAAmB,MAAM,CAAC,CAAA;AAAA,aACxD,EAAI,EAAA;AACX,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,iCAAiC,YAAa,CAAA,KAAA,CAAM,GAAG,EAAE,CAAC,MAAM,EAAE,CAAA;AAAA,OACpE;AAAA;AACF;AAEF,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAA2C,wCAAA,EAAA,YAAA,CAAa,KAAM,CAAA,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,GACtE;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"core.esm.js","sources":["../../src/gerrit/core.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { join, takeWhile, trimEnd, trimStart } from 'lodash';\nimport { GerritIntegrationConfig } from './config';\n\nconst GERRIT_BODY_PREFIX = \")]}'\";\n\n/**\n * Parse a Gitiles URL and return branch, file path and project.\n *\n * @remarks\n *\n * Gerrit only handles code reviews so it does not have a native way to browse\n * or showing the content of gits. Image if Github only had the \"pull requests\"\n * tab.\n *\n * Any source code browsing is instead handled by optional services outside\n * Gerrit. The url format chosen for the Gerrit url reader is the one used by\n * the Gitiles project. Gerrit will work perfectly with Backstage without\n * having Gitiles installed but there are some places in the Backstage GUI\n * with links to the url used by the url reader. These will not work unless\n * the urls point to an actual Gitiles installation.\n *\n * Gitiles url:\n * https://g.com/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n * https://g.com/a/optional_path/\\{project\\}/+/refs/heads/\\{branch\\}/\\{filePath\\}\n *\n *\n * @param url - An URL pointing to a file stored in git.\n * @public\n * @deprecated `parseGerritGitilesUrl` is deprecated. Use\n * {@link parseGitilesUrlRef} instead.\n */\nexport function parseGerritGitilesUrl(\n config: GerritIntegrationConfig,\n url: string,\n): { branch: string; filePath: string; project: string } {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, '');\n\n const parts = urlPath.split('/').filter(p => !!p);\n\n const projectEndIndex = parts.indexOf('+');\n\n if (projectEndIndex <= 0) {\n throw new Error(`Unable to parse project from url: ${url}`);\n }\n const project = trimStart(parts.slice(0, projectEndIndex).join('/'), '/');\n\n const branchIndex = parts.indexOf('heads');\n if (branchIndex <= 0) {\n throw new Error(`Unable to parse branch from url: ${url}`);\n }\n const branch = parts[branchIndex + 1];\n const filePath = parts.slice(branchIndex + 2).join('/');\n\n return {\n branch,\n filePath: filePath === '' ? '/' : filePath,\n project,\n };\n}\n\n/**\n * Parses Gitiles urls and returns the following:\n *\n * - The project\n * - The type of ref. I.e: branch name, SHA, HEAD or tag.\n * - The file path from the repo root.\n * - The base path as the path that points to the repo root.\n *\n * Supported types of gitiles urls that point to:\n *\n * - Branches\n * - Tags\n * - A commit SHA\n * - HEAD\n *\n * @param config - A Gerrit provider config.\n * @param url - An url to a file or folder in Gitiles.\n * @public\n */\nexport function parseGitilesUrlRef(\n config: GerritIntegrationConfig,\n url: string,\n): {\n project: string;\n path: string;\n ref: string;\n refType: 'sha' | 'branch' | 'tag' | 'head';\n basePath: string;\n} {\n const baseUrlParse = new URL(config.gitilesBaseUrl!);\n const urlParse = new URL(url);\n // Remove the gerrit authentication prefix '/a/' from the url\n // In case of the gitilesBaseUrl is https://review.gerrit.com/plugins/gitiles\n // and the url provided is https://review.gerrit.com/a/plugins/gitiles/...\n // remove the prefix only if the pathname start with '/a/'\n const urlPath = trimStart(\n urlParse.pathname\n .substring(urlParse.pathname.startsWith('/a/') ? 2 : 0)\n .replace(baseUrlParse.pathname, ''),\n '/',\n );\n\n // Find the project by taking everything up to \"/+/\".\n const parts = urlPath.split('/').filter(p => !!p);\n const projectParts = takeWhile(parts, p => p !== '+');\n if (projectParts.length === 0) {\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n // Also remove the \"+\" after the project.\n const rest = parts.slice(projectParts.length + 1);\n const project = join(projectParts, '/');\n\n // match <project>/+/HEAD/<path>\n if (rest.length > 0 && rest[0] === 'HEAD') {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'head' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n // match <project>/+/<sha>/<path>\n if (rest.length > 0 && rest[0].length === 40) {\n const ref = rest.shift()!;\n const path = join(rest, '/');\n return {\n project,\n ref,\n refType: 'sha' as const,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n const remainingPath = join(rest, '/');\n // Regexp for matching \"refs/tags/<tag>\" or \"refs/heads/<branch>/\"\n const refsRegexp = /^refs\\/(?<refsReference>heads|tags)\\/(?<ref>.*?)(\\/|$)/;\n const result = refsRegexp.exec(remainingPath);\n if (result) {\n const matchString = result[0];\n let refType;\n const { refsReference, ref } = result.groups || {};\n const path = remainingPath.replace(matchString, '');\n switch (refsReference) {\n case 'heads':\n refType = 'branch' as const;\n break;\n case 'tags':\n refType = 'tag' as const;\n break;\n default:\n throw new Error(`Unable to parse gitiles url: ${url}`);\n }\n return {\n project,\n ref,\n refType,\n path: path || '/',\n basePath: trimEnd(url.replace(path, ''), '/'),\n };\n }\n throw new Error(`Unable to parse gitiles : ${url}`);\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritGitilesUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.gitilesBaseUrl\n }/${project}/+/refs/heads/${branch}/${trimStart(filePath, '/')}`;\n}\n\n/**\n * Build a Gerrit Gitiles url that targets a specific path.\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n */\nexport function buildGerritEditUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n return `${\n config.baseUrl\n }/admin/repos/edit/repo/${project}/branch/refs/heads/${branch}/file/${trimStart(\n filePath,\n '/',\n )}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url that targets a specific branch and path\n *\n * @param config - A Gerrit provider config.\n * @param project - The name of the git project\n * @param branch - The branch we will target.\n * @param filePath - The absolute file path.\n * @public\n * @deprecated `buildGerritGitilesArchiveUrl` is deprecated. Use\n * {@link buildGerritGitilesArchiveUrlFromLocation} instead.\n */\nexport function buildGerritGitilesArchiveUrl(\n config: GerritIntegrationConfig,\n project: string,\n branch: string,\n filePath: string,\n): string {\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${branch}${archiveName}`;\n}\n\n/**\n * Build a Gerrit Gitiles archive url from a Gitiles url.\n *\n * @param config - A Gerrit provider config.\n * @param url - The gitiles url\n * @public\n */\nexport function buildGerritGitilesArchiveUrlFromLocation(\n config: GerritIntegrationConfig,\n url: string,\n): string {\n const {\n path: filePath,\n ref,\n project,\n refType,\n } = parseGitilesUrlRef(config, url);\n const archiveName =\n filePath === '/' || filePath === '' ? '.tar.gz' : `/${filePath}.tar.gz`;\n if (refType === 'branch') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/refs/heads/${ref}${archiveName}`;\n }\n if (refType === 'sha') {\n return `${getGitilesAuthenticationUrl(\n config,\n )}/${project}/+archive/${ref}${archiveName}`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the authentication prefix.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getAuthenticationPrefix(\n config: GerritIntegrationConfig,\n): string {\n return config.password ? '/a/' : '/';\n}\n\n/**\n * Return the authentication gitiles url.\n *\n * @remarks\n *\n * To authenticate with a password the API url must be prefixed with \"/a/\".\n * If no password is set anonymous access (without the prefix) will\n * be used.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGitilesAuthenticationUrl(\n config: GerritIntegrationConfig,\n): string {\n if (!config.baseUrl || !config.gitilesBaseUrl) {\n throw new Error(\n 'Unexpected Gerrit config values. baseUrl or gitilesBaseUrl not set.',\n );\n }\n if (config.gitilesBaseUrl.startsWith(config.baseUrl)) {\n return config.gitilesBaseUrl.replace(\n config.baseUrl.concat('/'),\n config.baseUrl.concat(getAuthenticationPrefix(config)),\n );\n }\n if (config.password) {\n throw new Error(\n 'Since the baseUrl (Gerrit) is not part of the gitilesBaseUrl, an authentication URL could not be constructed.',\n );\n }\n return config.gitilesBaseUrl!;\n}\n\n/**\n * Return the url to get branch info from the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritBranchApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { branch, project } = parseGerritGitilesUrl(config, url);\n\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(project)}/branches/${branch}`;\n}\n\n/**\n * Return the url to clone the repo that is referenced by the url.\n *\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritCloneRepoUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { project } = parseGerritGitilesUrl(config, url);\n\n return `${config.cloneUrl}${getAuthenticationPrefix(config)}${project}`;\n}\n\n/**\n * Return the url to fetch the contents of a file using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @param url - An url pointing to a file in git.\n * @public\n */\nexport function getGerritFileContentsApiUrl(\n config: GerritIntegrationConfig,\n url: string,\n) {\n const { ref, refType, path, project } = parseGitilesUrlRef(config, url);\n\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content\n if (refType === 'branch') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/branches/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n // https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content-from-commit\n if (refType === 'sha') {\n return `${config.baseUrl}${getAuthenticationPrefix(\n config,\n )}projects/${encodeURIComponent(\n project,\n )}/commits/${ref}/files/${encodeURIComponent(path)}/content`;\n }\n throw new Error(`Unsupported gitiles ref type: ${refType}`);\n}\n\n/**\n * Return the url to query available projects using the Gerrit API.\n *\n * @param config - A Gerrit provider config.\n * @public\n */\nexport function getGerritProjectsApiUrl(config: GerritIntegrationConfig) {\n return `${config.baseUrl}${getAuthenticationPrefix(config)}projects/`;\n}\n\n/**\n * Return request headers for a Gerrit provider.\n *\n * @param config - A Gerrit provider config\n * @public\n */\nexport function getGerritRequestOptions(config: GerritIntegrationConfig): {\n headers?: Record<string, string>;\n} {\n const headers: Record<string, string> = {};\n\n if (!config.password) {\n return headers;\n }\n const buffer = Buffer.from(`${config.username}:${config.password}`, 'utf8');\n headers.Authorization = `Basic ${buffer.toString('base64')}`;\n return {\n headers,\n };\n}\n\n/**\n * Parse the json response from Gerrit and strip the magic prefix.\n *\n * @remarks\n *\n * To prevent against XSSI attacks the JSON response body from Gerrit starts\n * with a magic prefix that must be stripped before it can be fed to a JSON\n * parser.\n *\n * @param response - An API response.\n * @public\n */\nexport async function parseGerritJsonResponse(\n response: Response,\n): Promise<unknown> {\n const responseBody = await response.text();\n if (responseBody.startsWith(GERRIT_BODY_PREFIX)) {\n try {\n return JSON.parse(responseBody.slice(GERRIT_BODY_PREFIX.length));\n } catch (ex) {\n throw new Error(\n `Invalid response from Gerrit: ${responseBody.slice(0, 10)} - ${ex}`,\n );\n }\n }\n throw new Error(\n `Gerrit JSON body prefix missing. Found: ${responseBody.slice(0, 10)}`,\n );\n}\n"],"names":[],"mappings":";;AAkBA,MAAM,kBAAqB,GAAA,MAAA;AA4BX,SAAA,qBAAA,CACd,QACA,GACuD,EAAA;AACvD,EAAA,MAAM,YAAe,GAAA,IAAI,GAAI,CAAA,MAAA,CAAO,cAAe,CAAA;AACnD,EAAM,MAAA,QAAA,GAAW,IAAI,GAAA,CAAI,GAAG,CAAA;AAM5B,EAAA,MAAM,OAAU,GAAA,QAAA,CAAS,QACtB,CAAA,SAAA,CAAU,SAA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AA,EAAI,MAAM,CAAA;AAC1E,EAAA,OAAA,CAAQ,aAAgB,GAAA,CAAA,MAAA,EAAS,MAAO,CAAA,QAAA,CAAS,QAAQ,CAAC,CAAA,CAAA;AAC1D,EAAO,OAAA;AAAA,IACL;AAAA,GACF;AACF;AAcA,eAAsB,wBACpB,QACkB,EAAA;AAClB,EAAM,MAAA,YAAA,GAAe,MAAM,QAAA,CAAS,IAAK,EAAA;AACzC,EAAI,IAAA,YAAA,CAAa,UAAW,CAAA,kBAAkB,CAAG,EAAA;AAC/C,IAAI,IAAA;AACF,MAAA,OAAO,KAAK,KAAM,CAAA,YAAA,CAAa,KAAM,CAAA,kBAAA,CAAmB,MAAM,CAAC,CAAA;AAAA,aACxD,EAAI,EAAA;AACX,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,iCAAiC,YAAa,CAAA,KAAA,CAAM,GAAG,EAAE,CAAC,MAAM,EAAE,CAAA;AAAA,OACpE;AAAA;AACF;AAEF,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAA2C,wCAAA,EAAA,YAAA,CAAa,KAAM,CAAA,CAAA,EAAG,EAAE,CAAC,CAAA;AAAA,GACtE;AACF;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -383,7 +383,7 @@ type AzureIntegrationConfig = {
|
|
|
383
383
|
* The kind of Azure DevOps credential.
|
|
384
384
|
* @public
|
|
385
385
|
*/
|
|
386
|
-
type AzureDevOpsCredentialKind = 'PersonalAccessToken' | 'ClientSecret' | 'ManagedIdentity';
|
|
386
|
+
type AzureDevOpsCredentialKind = 'PersonalAccessToken' | 'ClientSecret' | 'ManagedIdentity' | 'ManagedIdentityClientAssertion';
|
|
387
387
|
/**
|
|
388
388
|
* Common fields for the Azure DevOps credentials.
|
|
389
389
|
* @public
|
|
@@ -417,6 +417,27 @@ type AzureClientSecretCredential = AzureCredentialBase & {
|
|
|
417
417
|
*/
|
|
418
418
|
clientSecret: string;
|
|
419
419
|
};
|
|
420
|
+
/**
|
|
421
|
+
* A client assertion credential that uses a managed identity to generate a client assertion (JWT).
|
|
422
|
+
* @public
|
|
423
|
+
*/
|
|
424
|
+
type AzureManagedIdentityClientAssertionCredential = AzureCredentialBase & {
|
|
425
|
+
kind: 'ManagedIdentityClientAssertion';
|
|
426
|
+
/**
|
|
427
|
+
* The Entra ID tenant
|
|
428
|
+
*/
|
|
429
|
+
tenantId: string;
|
|
430
|
+
/**
|
|
431
|
+
* The client ID of the app registration you want to authenticate as.
|
|
432
|
+
*/
|
|
433
|
+
clientId: string;
|
|
434
|
+
/**
|
|
435
|
+
* The client ID of the managed identity used to generate a client assertion (JWT).
|
|
436
|
+
* Set to "system-assigned" to automatically use the system-assigned managed identity.
|
|
437
|
+
* For user-assigned managed identities, specify the client ID of the managed identity you want to use.
|
|
438
|
+
*/
|
|
439
|
+
managedIdentityClientId: 'system-assigned' | string;
|
|
440
|
+
};
|
|
420
441
|
/**
|
|
421
442
|
* A managed identity credential.
|
|
422
443
|
* @public
|
|
@@ -426,7 +447,7 @@ type AzureManagedIdentityCredential = AzureCredentialBase & {
|
|
|
426
447
|
/**
|
|
427
448
|
* The clientId
|
|
428
449
|
*/
|
|
429
|
-
clientId: string;
|
|
450
|
+
clientId: 'system-assigned' | string;
|
|
430
451
|
};
|
|
431
452
|
/**
|
|
432
453
|
* A personal access token credential.
|
|
@@ -440,12 +461,12 @@ type PersonalAccessTokenCredential = AzureCredentialBase & {
|
|
|
440
461
|
* The general shape of a credential that can be used to authenticate to Azure DevOps.
|
|
441
462
|
* @public
|
|
442
463
|
*/
|
|
443
|
-
type AzureDevOpsCredentialLike = Omit<Partial<AzureClientSecretCredential> & Partial<AzureManagedIdentityCredential> & Partial<PersonalAccessTokenCredential>, 'kind'>;
|
|
464
|
+
type AzureDevOpsCredentialLike = Omit<Partial<AzureClientSecretCredential> & Partial<AzureManagedIdentityClientAssertionCredential> & Partial<AzureManagedIdentityCredential> & Partial<PersonalAccessTokenCredential>, 'kind'>;
|
|
444
465
|
/**
|
|
445
466
|
* Credential used to authenticate to Azure DevOps.
|
|
446
467
|
* @public
|
|
447
468
|
*/
|
|
448
|
-
type AzureDevOpsCredential = AzureClientSecretCredential | AzureManagedIdentityCredential | PersonalAccessTokenCredential;
|
|
469
|
+
type AzureDevOpsCredential = AzureClientSecretCredential | AzureManagedIdentityClientAssertionCredential | AzureManagedIdentityCredential | PersonalAccessTokenCredential;
|
|
449
470
|
/**
|
|
450
471
|
* Reads a single Azure integration config.
|
|
451
472
|
*
|
|
@@ -735,6 +756,10 @@ type GerritIntegrationConfig = {
|
|
|
735
756
|
* baseUrl will be used.
|
|
736
757
|
*/
|
|
737
758
|
cloneUrl?: string;
|
|
759
|
+
/**
|
|
760
|
+
* Disable the edit url feature for Gerrit version less than 3.9.
|
|
761
|
+
*/
|
|
762
|
+
disableEditUrl?: boolean;
|
|
738
763
|
/**
|
|
739
764
|
* Base url for Gitiles. This is needed for creating a valid
|
|
740
765
|
* user-friendly url that can be used for browsing the content of the
|
|
@@ -2002,4 +2027,4 @@ declare class ScmIntegrations implements ScmIntegrationRegistry {
|
|
|
2002
2027
|
resolveEditUrl(url: string): string;
|
|
2003
2028
|
}
|
|
2004
2029
|
|
|
2005
|
-
export { AwsCodeCommitIntegration, type AwsCodeCommitIntegrationConfig, AwsS3Integration, type AwsS3IntegrationConfig, type AzureBlobStorageIntegrationConfig, AzureBlobStorageIntergation, type AzureClientSecretCredential, type AzureCredentialBase, type AzureCredentialsManager, type AzureDevOpsCredential, type AzureDevOpsCredentialKind, type AzureDevOpsCredentialLike, type AzureDevOpsCredentialType, type AzureDevOpsCredentials, type AzureDevOpsCredentialsProvider, AzureIntegration, type AzureIntegrationConfig, type AzureManagedIdentityCredential, BitbucketCloudIntegration, type BitbucketCloudIntegrationConfig, BitbucketIntegration, type BitbucketIntegrationConfig, BitbucketServerIntegration, type BitbucketServerIntegrationConfig, DefaultAzureCredentialsManager, DefaultAzureDevOpsCredentialsProvider, DefaultGithubCredentialsProvider, DefaultGitlabCredentialsProvider, GerritIntegration, type GerritIntegrationConfig, GitLabIntegration, type GitLabIntegrationConfig, GiteaIntegration, type GiteaIntegrationConfig, type GithubAppConfig, GithubAppCredentialsMux, type GithubCredentialType, type GithubCredentials, type GithubCredentialsProvider, GithubIntegration, type GithubIntegrationConfig, type GitlabCredentials, type GitlabCredentialsProvider, type GoogleGcsIntegrationConfig, HarnessIntegration, type HarnessIntegrationConfig, type IntegrationsByType, type PersonalAccessTokenCredential, type RateLimitInfo, type ScmIntegration, type ScmIntegrationRegistry, ScmIntegrations, type ScmIntegrationsFactory, type ScmIntegrationsGroup, SingleInstanceGithubCredentialsProvider, buildGerritGitilesArchiveUrl, buildGerritGitilesArchiveUrlFromLocation, defaultScmResolveUrl, getAzureCommitsUrl, getAzureDownloadUrl, getAzureFileFetchUrl, getAzureRequestOptions, getBitbucketCloudDefaultBranch, getBitbucketCloudDownloadUrl, getBitbucketCloudFileFetchUrl, getBitbucketCloudRequestOptions, getBitbucketDefaultBranch, getBitbucketDownloadUrl, getBitbucketFileFetchUrl, getBitbucketRequestOptions, getBitbucketServerDefaultBranch, getBitbucketServerDownloadUrl, getBitbucketServerFileFetchUrl, getBitbucketServerRequestOptions, getGerritBranchApiUrl, getGerritCloneRepoUrl, getGerritFileContentsApiUrl, getGerritProjectsApiUrl, getGerritRequestOptions, getGitHubRequestOptions, getGitLabFileFetchUrl, getGitLabIntegrationRelativePath, getGitLabRequestOptions, getGiteaArchiveUrl, getGiteaEditContentsUrl, getGiteaFileContentsUrl, getGiteaLatestCommitUrl, getGiteaRequestOptions, getGithubFileFetchUrl, getGitilesAuthenticationUrl, getHarnessArchiveUrl, getHarnessFileContentsUrl, getHarnessLatestCommitUrl, getHarnessRequestOptions, parseGerritGitilesUrl, parseGerritJsonResponse, parseGiteaUrl, parseGitilesUrlRef, parseHarnessUrl, readAwsCodeCommitIntegrationConfig, readAwsCodeCommitIntegrationConfigs, readAwsS3IntegrationConfig, readAwsS3IntegrationConfigs, readAzureBlobStorageIntegrationConfig, readAzureBlobStorageIntegrationConfigs, readAzureIntegrationConfig, readAzureIntegrationConfigs, readBitbucketCloudIntegrationConfig, readBitbucketCloudIntegrationConfigs, readBitbucketIntegrationConfig, readBitbucketIntegrationConfigs, readBitbucketServerIntegrationConfig, readBitbucketServerIntegrationConfigs, readGerritIntegrationConfig, readGerritIntegrationConfigs, readGitLabIntegrationConfig, readGitLabIntegrationConfigs, readGiteaConfig, readGithubIntegrationConfig, readGithubIntegrationConfigs, readGoogleGcsIntegrationConfig, readHarnessConfig, replaceGitLabUrlType, replaceGithubUrlType };
|
|
2030
|
+
export { AwsCodeCommitIntegration, type AwsCodeCommitIntegrationConfig, AwsS3Integration, type AwsS3IntegrationConfig, type AzureBlobStorageIntegrationConfig, AzureBlobStorageIntergation, type AzureClientSecretCredential, type AzureCredentialBase, type AzureCredentialsManager, type AzureDevOpsCredential, type AzureDevOpsCredentialKind, type AzureDevOpsCredentialLike, type AzureDevOpsCredentialType, type AzureDevOpsCredentials, type AzureDevOpsCredentialsProvider, AzureIntegration, type AzureIntegrationConfig, type AzureManagedIdentityClientAssertionCredential, type AzureManagedIdentityCredential, BitbucketCloudIntegration, type BitbucketCloudIntegrationConfig, BitbucketIntegration, type BitbucketIntegrationConfig, BitbucketServerIntegration, type BitbucketServerIntegrationConfig, DefaultAzureCredentialsManager, DefaultAzureDevOpsCredentialsProvider, DefaultGithubCredentialsProvider, DefaultGitlabCredentialsProvider, GerritIntegration, type GerritIntegrationConfig, GitLabIntegration, type GitLabIntegrationConfig, GiteaIntegration, type GiteaIntegrationConfig, type GithubAppConfig, GithubAppCredentialsMux, type GithubCredentialType, type GithubCredentials, type GithubCredentialsProvider, GithubIntegration, type GithubIntegrationConfig, type GitlabCredentials, type GitlabCredentialsProvider, type GoogleGcsIntegrationConfig, HarnessIntegration, type HarnessIntegrationConfig, type IntegrationsByType, type PersonalAccessTokenCredential, type RateLimitInfo, type ScmIntegration, type ScmIntegrationRegistry, ScmIntegrations, type ScmIntegrationsFactory, type ScmIntegrationsGroup, SingleInstanceGithubCredentialsProvider, buildGerritGitilesArchiveUrl, buildGerritGitilesArchiveUrlFromLocation, defaultScmResolveUrl, getAzureCommitsUrl, getAzureDownloadUrl, getAzureFileFetchUrl, getAzureRequestOptions, getBitbucketCloudDefaultBranch, getBitbucketCloudDownloadUrl, getBitbucketCloudFileFetchUrl, getBitbucketCloudRequestOptions, getBitbucketDefaultBranch, getBitbucketDownloadUrl, getBitbucketFileFetchUrl, getBitbucketRequestOptions, getBitbucketServerDefaultBranch, getBitbucketServerDownloadUrl, getBitbucketServerFileFetchUrl, getBitbucketServerRequestOptions, getGerritBranchApiUrl, getGerritCloneRepoUrl, getGerritFileContentsApiUrl, getGerritProjectsApiUrl, getGerritRequestOptions, getGitHubRequestOptions, getGitLabFileFetchUrl, getGitLabIntegrationRelativePath, getGitLabRequestOptions, getGiteaArchiveUrl, getGiteaEditContentsUrl, getGiteaFileContentsUrl, getGiteaLatestCommitUrl, getGiteaRequestOptions, getGithubFileFetchUrl, getGitilesAuthenticationUrl, getHarnessArchiveUrl, getHarnessFileContentsUrl, getHarnessLatestCommitUrl, getHarnessRequestOptions, parseGerritGitilesUrl, parseGerritJsonResponse, parseGiteaUrl, parseGitilesUrlRef, parseHarnessUrl, readAwsCodeCommitIntegrationConfig, readAwsCodeCommitIntegrationConfigs, readAwsS3IntegrationConfig, readAwsS3IntegrationConfigs, readAzureBlobStorageIntegrationConfig, readAzureBlobStorageIntegrationConfigs, readAzureIntegrationConfig, readAzureIntegrationConfigs, readBitbucketCloudIntegrationConfig, readBitbucketCloudIntegrationConfigs, readBitbucketIntegrationConfig, readBitbucketIntegrationConfigs, readBitbucketServerIntegrationConfig, readBitbucketServerIntegrationConfigs, readGerritIntegrationConfig, readGerritIntegrationConfigs, readGitLabIntegrationConfig, readGitLabIntegrationConfigs, readGiteaConfig, readGithubIntegrationConfig, readGithubIntegrationConfigs, readGoogleGcsIntegrationConfig, readHarnessConfig, replaceGitLabUrlType, replaceGithubUrlType };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/integration",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.0-next.3",
|
|
4
4
|
"description": "Helpers for managing integrations towards external systems",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "common-library"
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"luxon": "^3.0.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
|
-
"@backstage/cli": "0.32.1-next.
|
|
52
|
+
"@backstage/cli": "0.32.1-next.3",
|
|
53
53
|
"@backstage/config-loader": "1.10.1-next.0",
|
|
54
54
|
"@types/luxon": "^3.0.0",
|
|
55
55
|
"msw": "^1.0.0"
|