@backstage/backend-app-api 0.9.2 → 0.10.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -5
- package/alpha/package.json +1 -1
- package/config.d.ts +7 -292
- package/dist/alpha.cjs.js +8 -7
- package/dist/alpha.cjs.js.map +1 -1
- package/dist/alpha.d.ts +6 -3
- package/dist/index.cjs.js +1 -33
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -28
- package/package.json +8 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
# @backstage/backend-app-api
|
|
2
2
|
|
|
3
|
-
## 0.
|
|
3
|
+
## 0.10.0-next.0
|
|
4
4
|
|
|
5
|
-
###
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 19ff127: **BREAKING**: The deprecated `identityServiceFactory` and `tokenManagerServiceFactory` have been removed.
|
|
8
|
+
- d425fc4: **BREAKING**: The return values from `createBackendPlugin`, `createBackendModule`, and `createServiceFactory` are now simply `BackendFeature` and `ServiceFactory`, instead of the previously deprecated form of a function that returns them. For this reason, `createServiceFactory` also no longer accepts the callback form where you provide direct options to the service. This also affects all `coreServices.*` service refs.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
This may in particular affect tests; if you were effectively doing `createBackendModule({...})()` (note the parentheses), you can now remove those extra parentheses at the end. You may encounter cases of this in your `packages/backend/src/index.ts` too, where you add plugins, modules, and services. If you were using `createServiceFactory` with a function as its argument for the purpose of passing in options, this pattern has been deprecated for a while and is no longer supported. You may want to explore the new multiton patterns to achieve your goals, or moving settings to app-config.
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
As part of this change, the `IdentityFactoryOptions` type was removed, and can no longer be used to tweak that service. The identity service was also deprecated some time ago, and you will want to [migrate to the new auth system](https://backstage.io/docs/tutorials/auth-service-migration) if you still rely on it.
|
|
10
13
|
|
|
11
14
|
### Patch Changes
|
|
12
15
|
|
|
13
|
-
-
|
|
16
|
+
- cd38da8: Deprecate the `featureDiscoveryServiceFactory` in favor of using `@backstage/backend-defaults#discoveryFeatureLoader` instead.
|
|
17
|
+
- 7f779c7: `auth.externalAccess` should be optional in the config schema
|
|
18
|
+
- 51a69b5: Fix feature loaders in CJS double-default nested builds
|
|
19
|
+
- 0b2a402: Updates to the config schema to match reality
|
|
20
|
+
- Updated dependencies
|
|
21
|
+
- @backstage/backend-plugin-api@0.9.0-next.0
|
|
22
|
+
- @backstage/plugin-permission-node@0.8.3-next.0
|
|
23
|
+
- @backstage/backend-common@0.25.0-next.0
|
|
24
|
+
- @backstage/plugin-auth-node@0.5.2-next.0
|
|
25
|
+
- @backstage/cli-common@0.1.14
|
|
26
|
+
- @backstage/config@1.2.0
|
|
27
|
+
- @backstage/config-loader@1.9.0
|
|
28
|
+
- @backstage/errors@1.2.4
|
|
29
|
+
- @backstage/types@1.1.1
|
|
14
30
|
|
|
15
31
|
## 0.9.0
|
|
16
32
|
|
package/alpha/package.json
CHANGED
package/config.d.ts
CHANGED
|
@@ -16,297 +16,12 @@
|
|
|
16
16
|
|
|
17
17
|
export interface Config {
|
|
18
18
|
backend?: {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
* plugins.
|
|
27
|
-
*
|
|
28
|
-
* If permissions are enabled, unauthenticated requests will be treated
|
|
29
|
-
* exactly as such, leaving it to the permission policy to determine what
|
|
30
|
-
* permissions should be allowed for an unauthenticated identity. Note
|
|
31
|
-
* that this will also apply to service-to-service calls between plugins
|
|
32
|
-
* unless you configure credentials for service calls.
|
|
33
|
-
*/
|
|
34
|
-
dangerouslyDisableDefaultAuthPolicy?: boolean;
|
|
35
|
-
|
|
36
|
-
/** Controls how to store keys for plugin-to-plugin auth */
|
|
37
|
-
pluginKeyStore?:
|
|
38
|
-
| { type: 'database' }
|
|
39
|
-
| {
|
|
40
|
-
type: 'static';
|
|
41
|
-
static: {
|
|
42
|
-
/**
|
|
43
|
-
* Must be declared at least once and the first one will be used for signing.
|
|
44
|
-
*/
|
|
45
|
-
keys: Array<{
|
|
46
|
-
/**
|
|
47
|
-
* Path to the public key file in the SPKI format. Should be an absolute path.
|
|
48
|
-
*/
|
|
49
|
-
publicKeyFile: string;
|
|
50
|
-
/**
|
|
51
|
-
* Path to the matching private key file in the PKCS#8 format. Should be an absolute path.
|
|
52
|
-
*
|
|
53
|
-
* The first array entry must specify a private key file, the rest must not.
|
|
54
|
-
*/
|
|
55
|
-
privateKeyFile?: string;
|
|
56
|
-
/**
|
|
57
|
-
* ID to uniquely identify this key within the JWK set.
|
|
58
|
-
*/
|
|
59
|
-
keyId: string;
|
|
60
|
-
/**
|
|
61
|
-
* JWS "alg" (Algorithm) Header Parameter value. Defaults to ES256.
|
|
62
|
-
* Must match the algorithm used to generate the keys in the provided files
|
|
63
|
-
*/
|
|
64
|
-
algorithm?: string;
|
|
65
|
-
}>;
|
|
66
|
-
};
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Configures methods of external access, ie ways for callers outside of
|
|
71
|
-
* the Backstage ecosystem to get authorized for access to APIs that do
|
|
72
|
-
* not permit unauthorized access.
|
|
73
|
-
*/
|
|
74
|
-
externalAccess?: Array<
|
|
75
|
-
| {
|
|
76
|
-
/**
|
|
77
|
-
* This is the legacy service-to-service access method, where a set
|
|
78
|
-
* of static keys were shared among plugins and used for symmetric
|
|
79
|
-
* signing and verification. These correspond to the old
|
|
80
|
-
* `backend.auth.keys` set and retain their behavior for backwards
|
|
81
|
-
* compatibility. Please migrate to other access methods when
|
|
82
|
-
* possible.
|
|
83
|
-
*
|
|
84
|
-
* Callers generate JWT tokens with the following payload:
|
|
85
|
-
*
|
|
86
|
-
* ```json
|
|
87
|
-
* {
|
|
88
|
-
* "sub": "backstage-plugin",
|
|
89
|
-
* "exp": <epoch seconds one hour in the future>
|
|
90
|
-
* }
|
|
91
|
-
* ```
|
|
92
|
-
*
|
|
93
|
-
* And sign them with HS256, using the base64 decoded secret. The
|
|
94
|
-
* tokens are then passed along with requests in the Authorization
|
|
95
|
-
* header:
|
|
96
|
-
*
|
|
97
|
-
* ```
|
|
98
|
-
* Authorization: Bearer eyJhbGciOiJIUzI...
|
|
99
|
-
* ```
|
|
100
|
-
*/
|
|
101
|
-
type: 'legacy';
|
|
102
|
-
options: {
|
|
103
|
-
/**
|
|
104
|
-
* Any set of base64 encoded random bytes to be used as both the
|
|
105
|
-
* signing and verification key. Should be sufficiently long so as
|
|
106
|
-
* not to be easy to guess by brute force.
|
|
107
|
-
*
|
|
108
|
-
* Can be generated eg using
|
|
109
|
-
*
|
|
110
|
-
* ```sh
|
|
111
|
-
* node -p 'require("crypto").randomBytes(24).toString("base64")'
|
|
112
|
-
* ```
|
|
113
|
-
*
|
|
114
|
-
* @visibility secret
|
|
115
|
-
*/
|
|
116
|
-
secret: string;
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Sets the subject of the principal, when matching this token.
|
|
120
|
-
* Useful for debugging and tracking purposes.
|
|
121
|
-
*/
|
|
122
|
-
subject: string;
|
|
123
|
-
};
|
|
124
|
-
/**
|
|
125
|
-
* Restricts what types of access that are permitted for this access
|
|
126
|
-
* method. If no access restrictions are given, it'll have unlimited
|
|
127
|
-
* access. This access restriction applies for the framework level;
|
|
128
|
-
* individual plugins may have their own access control mechanisms
|
|
129
|
-
* on top of this.
|
|
130
|
-
*/
|
|
131
|
-
accessRestrictions?: Array<{
|
|
132
|
-
/**
|
|
133
|
-
* Permit access to make requests to this plugin.
|
|
134
|
-
*
|
|
135
|
-
* Can be further refined by setting additional fields below.
|
|
136
|
-
*/
|
|
137
|
-
plugin: string;
|
|
138
|
-
/**
|
|
139
|
-
* If given, this method is limited to only performing actions
|
|
140
|
-
* with these named permissions in this plugin.
|
|
141
|
-
*
|
|
142
|
-
* Note that this only applies where permissions checks are
|
|
143
|
-
* enabled in the first place. Endpoints that are not protected by
|
|
144
|
-
* the permissions system at all, are not affected by this
|
|
145
|
-
* setting.
|
|
146
|
-
*/
|
|
147
|
-
permission?: string | Array<string>;
|
|
148
|
-
/**
|
|
149
|
-
* If given, this method is limited to only performing actions
|
|
150
|
-
* whose permissions have these attributes.
|
|
151
|
-
*
|
|
152
|
-
* Note that this only applies where permissions checks are
|
|
153
|
-
* enabled in the first place. Endpoints that are not protected by
|
|
154
|
-
* the permissions system at all, are not affected by this
|
|
155
|
-
* setting.
|
|
156
|
-
*/
|
|
157
|
-
permissionAttribute?: {
|
|
158
|
-
/**
|
|
159
|
-
* One of more of 'create', 'read', 'update', or 'delete'.
|
|
160
|
-
*/
|
|
161
|
-
action?: string | Array<string>;
|
|
162
|
-
};
|
|
163
|
-
}>;
|
|
164
|
-
}
|
|
165
|
-
| {
|
|
166
|
-
/**
|
|
167
|
-
* This access method consists of random static tokens that can be
|
|
168
|
-
* handed out to callers.
|
|
169
|
-
*
|
|
170
|
-
* The tokens are then passed along verbatim with requests in the
|
|
171
|
-
* Authorization header:
|
|
172
|
-
*
|
|
173
|
-
* ```
|
|
174
|
-
* Authorization: Bearer eZv5o+fW3KnR3kVabMW4ZcDNLPl8nmMW
|
|
175
|
-
* ```
|
|
176
|
-
*/
|
|
177
|
-
type: 'static';
|
|
178
|
-
options: {
|
|
179
|
-
/**
|
|
180
|
-
* A raw token that can be any string, but for security reasons
|
|
181
|
-
* should be sufficiently long so as not to be easy to guess by
|
|
182
|
-
* brute force.
|
|
183
|
-
*
|
|
184
|
-
* Can be generated eg using
|
|
185
|
-
*
|
|
186
|
-
* ```sh
|
|
187
|
-
* node -p 'require("crypto").randomBytes(24).toString("base64")'
|
|
188
|
-
* ```
|
|
189
|
-
*
|
|
190
|
-
* Since the tokens can be any string, you are free to add
|
|
191
|
-
* additional identifying data to them if you like. For example,
|
|
192
|
-
* adding a `freben-local-dev-` prefix for debugging purposes to a
|
|
193
|
-
* token that you know will be handed out for use as a personal
|
|
194
|
-
* access token during development.
|
|
195
|
-
*
|
|
196
|
-
* @visibility secret
|
|
197
|
-
*/
|
|
198
|
-
token: string;
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* Sets the subject of the principal, when matching this token.
|
|
202
|
-
* Useful for debugging and tracking purposes.
|
|
203
|
-
*/
|
|
204
|
-
subject: string;
|
|
205
|
-
};
|
|
206
|
-
/**
|
|
207
|
-
* Restricts what types of access that are permitted for this access
|
|
208
|
-
* method. If no access restrictions are given, it'll have unlimited
|
|
209
|
-
* access. This access restriction applies for the framework level;
|
|
210
|
-
* individual plugins may have their own access control mechanisms
|
|
211
|
-
* on top of this.
|
|
212
|
-
*/
|
|
213
|
-
accessRestrictions?: Array<{
|
|
214
|
-
/**
|
|
215
|
-
* Permit access to make requests to this plugin.
|
|
216
|
-
*
|
|
217
|
-
* Can be further refined by setting additional fields below.
|
|
218
|
-
*/
|
|
219
|
-
plugin: string;
|
|
220
|
-
/**
|
|
221
|
-
* If given, this method is limited to only performing actions
|
|
222
|
-
* with these named permissions in this plugin.
|
|
223
|
-
*
|
|
224
|
-
* Note that this only applies where permissions checks are
|
|
225
|
-
* enabled in the first place. Endpoints that are not protected by
|
|
226
|
-
* the permissions system at all, are not affected by this
|
|
227
|
-
* setting.
|
|
228
|
-
*/
|
|
229
|
-
permission?: string | Array<string>;
|
|
230
|
-
/**
|
|
231
|
-
* If given, this method is limited to only performing actions
|
|
232
|
-
* whose permissions have these attributes.
|
|
233
|
-
*
|
|
234
|
-
* Note that this only applies where permissions checks are
|
|
235
|
-
* enabled in the first place. Endpoints that are not protected by
|
|
236
|
-
* the permissions system at all, are not affected by this
|
|
237
|
-
* setting.
|
|
238
|
-
*/
|
|
239
|
-
permissionAttribute?: {
|
|
240
|
-
/**
|
|
241
|
-
* One of more of 'create', 'read', 'update', or 'delete'.
|
|
242
|
-
*/
|
|
243
|
-
action?: string | Array<string>;
|
|
244
|
-
};
|
|
245
|
-
}>;
|
|
246
|
-
}
|
|
247
|
-
| {
|
|
248
|
-
/**
|
|
249
|
-
* This access method consists of a JWKS endpoint that can be used to
|
|
250
|
-
* verify JWT tokens.
|
|
251
|
-
*
|
|
252
|
-
* Callers generate JWT tokens via 3rd party tooling
|
|
253
|
-
* and pass them in the Authorization header:
|
|
254
|
-
*
|
|
255
|
-
* ```
|
|
256
|
-
* Authorization: Bearer eZv5o+fW3KnR3kVabMW4ZcDNLPl8nmMW
|
|
257
|
-
* ```
|
|
258
|
-
*/
|
|
259
|
-
type: 'jwks';
|
|
260
|
-
options: {
|
|
261
|
-
/**
|
|
262
|
-
* The full URL of the JWKS endpoint.
|
|
263
|
-
*/
|
|
264
|
-
url: string;
|
|
265
|
-
/**
|
|
266
|
-
* Sets the algorithm(s) that should be used to verify the JWT tokens.
|
|
267
|
-
* The passed JWTs must have been signed using one of the listed algorithms.
|
|
268
|
-
*/
|
|
269
|
-
algorithm?: string | string[];
|
|
270
|
-
/**
|
|
271
|
-
* Sets the issuer(s) that should be used to verify the JWT tokens.
|
|
272
|
-
* Passed JWTs must have an `iss` claim which matches one of the specified issuers.
|
|
273
|
-
*/
|
|
274
|
-
issuer?: string | string[];
|
|
275
|
-
/**
|
|
276
|
-
* Sets the audience(s) that should be used to verify the JWT tokens.
|
|
277
|
-
* The passed JWTs must have an "aud" claim that matches one of the audiences specified,
|
|
278
|
-
* or have no audience specified.
|
|
279
|
-
*/
|
|
280
|
-
audience?: string | string[];
|
|
281
|
-
/**
|
|
282
|
-
* Sets an optional subject prefix. Passes the subject to called plugins.
|
|
283
|
-
* Useful for debugging and tracking purposes.
|
|
284
|
-
*/
|
|
285
|
-
subjectPrefix?: string;
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
>;
|
|
289
|
-
};
|
|
290
|
-
packages?: 'all' | { include?: string[]; exclude?: string[] };
|
|
291
|
-
};
|
|
292
|
-
|
|
293
|
-
/** Discovery options. */
|
|
294
|
-
discovery?: {
|
|
295
|
-
/**
|
|
296
|
-
* Endpoints
|
|
297
|
-
*
|
|
298
|
-
* A list of target baseUrls and the associated plugins.
|
|
299
|
-
*/
|
|
300
|
-
endpoints: {
|
|
301
|
-
/**
|
|
302
|
-
* The target baseUrl to use for the plugin
|
|
303
|
-
*
|
|
304
|
-
* Can be either a string or an object with internal and external keys.
|
|
305
|
-
* Targets with `{{pluginId}}` or `{{ pluginId }} in the url will be replaced with the pluginId.
|
|
306
|
-
*/
|
|
307
|
-
target: string | { internal: string; external: string };
|
|
308
|
-
/** Array of plugins which use the target baseUrl. */
|
|
309
|
-
plugins: string[];
|
|
310
|
-
}[];
|
|
19
|
+
/** Used by the feature discovery service */
|
|
20
|
+
packages?:
|
|
21
|
+
| 'all'
|
|
22
|
+
| {
|
|
23
|
+
include?: string[];
|
|
24
|
+
exclude?: string[];
|
|
25
|
+
};
|
|
311
26
|
};
|
|
312
27
|
}
|
package/dist/alpha.cjs.js
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
4
4
|
var alpha = require('@backstage/backend-plugin-api/alpha');
|
|
5
|
-
var path = require('path');
|
|
6
5
|
var fs = require('fs-extra');
|
|
6
|
+
var path = require('path');
|
|
7
7
|
|
|
8
8
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
9
9
|
|
|
@@ -15,6 +15,12 @@ const DETECTED_PACKAGE_ROLES = [
|
|
|
15
15
|
"backend-plugin",
|
|
16
16
|
"backend-plugin-module"
|
|
17
17
|
];
|
|
18
|
+
function isBackendFeature(value) {
|
|
19
|
+
return !!value && ["object", "function"].includes(typeof value) && value.$$type === "@backstage/BackendFeature";
|
|
20
|
+
}
|
|
21
|
+
function isBackendFeatureFactory(value) {
|
|
22
|
+
return !!value && typeof value === "function" && value.$$type === "@backstage/BackendFeatureFactory";
|
|
23
|
+
}
|
|
18
24
|
async function findClosestPackageDir(searchDir) {
|
|
19
25
|
let path$1 = searchDir;
|
|
20
26
|
for (let i = 0; i < 1e3; i++) {
|
|
@@ -100,6 +106,7 @@ class PackageDiscoveryService {
|
|
|
100
106
|
return { features };
|
|
101
107
|
}
|
|
102
108
|
}
|
|
109
|
+
|
|
103
110
|
const featureDiscoveryServiceFactory = backendPluginApi.createServiceFactory({
|
|
104
111
|
service: alpha.featureDiscoveryServiceRef,
|
|
105
112
|
deps: {
|
|
@@ -110,12 +117,6 @@ const featureDiscoveryServiceFactory = backendPluginApi.createServiceFactory({
|
|
|
110
117
|
return new PackageDiscoveryService(config, logger);
|
|
111
118
|
}
|
|
112
119
|
});
|
|
113
|
-
function isBackendFeature(value) {
|
|
114
|
-
return !!value && ["object", "function"].includes(typeof value) && value.$$type === "@backstage/BackendFeature";
|
|
115
|
-
}
|
|
116
|
-
function isBackendFeatureFactory(value) {
|
|
117
|
-
return !!value && typeof value === "function" && value.$$type === "@backstage/BackendFeatureFactory";
|
|
118
|
-
}
|
|
119
120
|
|
|
120
121
|
exports.featureDiscoveryServiceFactory = featureDiscoveryServiceFactory;
|
|
121
122
|
//# sourceMappingURL=alpha.cjs.js.map
|
package/dist/alpha.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alpha.cjs.js","sources":["../src/alpha/featureDiscoveryServiceFactory.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 */\n\nimport {\n BackendFeature,\n RootConfigService,\n RootLoggerService,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport {\n featureDiscoveryServiceRef,\n FeatureDiscoveryService,\n} from '@backstage/backend-plugin-api/alpha';\nimport { resolve as resolvePath, dirname } from 'path';\nimport fs from 'fs-extra';\nimport { BackstagePackageJson } from '@backstage/cli-node';\n\nconst DETECTED_PACKAGE_ROLES = [\n 'node-library',\n 'backend',\n 'backend-plugin',\n 'backend-plugin-module',\n];\n\n/** @internal */\nasync function findClosestPackageDir(\n searchDir: string,\n): Promise<string | undefined> {\n let path = searchDir;\n\n // Some confidence check to avoid infinite loop\n for (let i = 0; i < 1000; i++) {\n const packagePath = resolvePath(path, 'package.json');\n const exists = await fs.pathExists(packagePath);\n if (exists) {\n return path;\n }\n\n const newPath = dirname(path);\n if (newPath === path) {\n return undefined;\n }\n path = newPath;\n }\n\n throw new Error(\n `Iteration limit reached when searching for root package.json at ${searchDir}`,\n );\n}\n\n/** @internal */\nclass PackageDiscoveryService implements FeatureDiscoveryService {\n constructor(\n private readonly config: RootConfigService,\n private readonly logger: RootLoggerService,\n ) {}\n\n getDependencyNames(path: string) {\n const { dependencies } = require(path) as BackstagePackageJson;\n const packagesConfig = this.config.getOptional('backend.packages');\n\n const dependencyNames = Object.keys(dependencies || {});\n\n if (packagesConfig === 'all') {\n return dependencyNames;\n }\n\n const includedPackagesConfig = this.config.getOptionalStringArray(\n 'backend.packages.include',\n );\n\n const includedPackages = includedPackagesConfig\n ? new Set(includedPackagesConfig)\n : dependencyNames;\n const excludedPackagesSet = new Set(\n this.config.getOptionalStringArray('backend.packages.exclude'),\n );\n\n return [...includedPackages].filter(name => !excludedPackagesSet.has(name));\n }\n\n async getBackendFeatures(): Promise<{ features: Array<BackendFeature> }> {\n const packagesConfig = this.config.getOptional('backend.packages');\n if (!packagesConfig || Object.keys(packagesConfig).length === 0) {\n return { features: [] };\n }\n\n const packageDir = await findClosestPackageDir(process.argv[1]);\n if (!packageDir) {\n throw new Error('Package discovery failed to find package.json');\n }\n const dependencyNames = this.getDependencyNames(\n resolvePath(packageDir, 'package.json'),\n );\n\n const features: BackendFeature[] = [];\n\n for (const name of dependencyNames) {\n const depPkg = require(require.resolve(`${name}/package.json`, {\n paths: [packageDir],\n })) as BackstagePackageJson;\n if (\n !depPkg?.backstage?.role ||\n !DETECTED_PACKAGE_ROLES.includes(depPkg.backstage.role)\n ) {\n continue; // Not a backstage backend package, ignore\n }\n\n const exportedModulePaths = [\n require.resolve(name, {\n paths: [packageDir],\n }),\n ];\n\n // Find modules exported as alpha\n try {\n exportedModulePaths.push(\n require.resolve(`${name}/alpha`, { paths: [packageDir] }),\n );\n } catch {\n /* ignore */\n }\n\n for (const modulePath of exportedModulePaths) {\n const mod = require(modulePath);\n\n if (isBackendFeature(mod.default)) {\n this.logger.info(`Detected: ${name}`);\n features.push(mod.default);\n }\n if (isBackendFeatureFactory(mod.default)) {\n this.logger.info(`Detected: ${name}`);\n features.push(mod.default());\n }\n }\n }\n\n return { features };\n }\n}\n\n/** @alpha */\nexport const featureDiscoveryServiceFactory = createServiceFactory({\n service: featureDiscoveryServiceRef,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.rootLogger,\n },\n factory({ config, logger }) {\n return new PackageDiscoveryService(config, logger);\n },\n});\n\nfunction isBackendFeature(value: unknown): value is BackendFeature {\n return (\n !!value &&\n ['object', 'function'].includes(typeof value) &&\n (value as BackendFeature).$$type === '@backstage/BackendFeature'\n );\n}\n\nfunction isBackendFeatureFactory(\n value: unknown,\n): value is () => BackendFeature {\n return (\n !!value &&\n typeof value === 'function' &&\n (value as any).$$type === '@backstage/BackendFeatureFactory'\n );\n}\n"],"names":["path","resolvePath","fs","dirname","createServiceFactory","featureDiscoveryServiceRef","coreServices"],"mappings":";;;;;;;;;;;AA+BA,MAAM,sBAAyB,GAAA;AAAA,EAC7B,cAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,uBAAA;AACF,CAAA,CAAA;AAGA,eAAe,sBACb,SAC6B,EAAA;AAC7B,EAAA,IAAIA,MAAO,GAAA,SAAA,CAAA;AAGX,EAAA,KAAA,IAAS,CAAI,GAAA,CAAA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AAA;AAAA,IACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,OAAQ,CAAA,EAAE,MAAQ,EAAA,MAAA,EAAU,EAAA;AAC1B,IAAO,OAAA,IAAI,uBAAwB,CAAA,MAAA,EAAQ,MAAM,CAAA,CAAA;AAAA,GACnD;AACF,CAAC,EAAA;AAED,SAAS,iBAAiB,KAAyC,EAAA;AACjE,EAAA,OACE,CAAC,CAAC,KACF,IAAA,CAAC,QAAU,EAAA,UAAU,CAAE,CAAA,QAAA,CAAS,OAAO,KAAK,CAC3C,IAAA,KAAA,CAAyB,MAAW,KAAA,2BAAA,CAAA;AAEzC,CAAA;AAEA,SAAS,wBACP,KAC+B,EAAA;AAC/B,EAAA,OACE,CAAC,CAAC,KAAA,IACF,OAAO,KAAU,KAAA,UAAA,IAChB,MAAc,MAAW,KAAA,kCAAA,CAAA;AAE9B;;;;"}
|
|
1
|
+
{"version":3,"file":"alpha.cjs.js","sources":["../../backend-defaults/src/PackageDiscoveryService.ts","../src/alpha/featureDiscoveryServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2024 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 fs from 'fs-extra';\nimport { resolve as resolvePath, dirname } from 'path';\n\nimport {\n BackendFeature,\n RootConfigService,\n RootLoggerService,\n} from '@backstage/backend-plugin-api';\nimport { FeatureDiscoveryService } from '@backstage/backend-plugin-api/alpha';\nimport { BackstagePackageJson } from '@backstage/cli-node';\n\nconst DETECTED_PACKAGE_ROLES = [\n 'node-library',\n 'backend',\n 'backend-plugin',\n 'backend-plugin-module',\n];\n\n/** @internal */\nfunction isBackendFeature(value: unknown): value is BackendFeature {\n return (\n !!value &&\n ['object', 'function'].includes(typeof value) &&\n (value as BackendFeature).$$type === '@backstage/BackendFeature'\n );\n}\n\n/** @internal */\nfunction isBackendFeatureFactory(\n value: unknown,\n): value is () => BackendFeature {\n return (\n !!value &&\n typeof value === 'function' &&\n (value as any).$$type === '@backstage/BackendFeatureFactory'\n );\n}\n\n/** @internal */\nasync function findClosestPackageDir(\n searchDir: string,\n): Promise<string | undefined> {\n let path = searchDir;\n\n // Some confidence check to avoid infinite loop\n for (let i = 0; i < 1000; i++) {\n const packagePath = resolvePath(path, 'package.json');\n const exists = await fs.pathExists(packagePath);\n if (exists) {\n return path;\n }\n\n const newPath = dirname(path);\n if (newPath === path) {\n return undefined;\n }\n path = newPath;\n }\n\n throw new Error(\n `Iteration limit reached when searching for root package.json at ${searchDir}`,\n );\n}\n\n/** @internal */\nexport class PackageDiscoveryService implements FeatureDiscoveryService {\n constructor(\n private readonly config: RootConfigService,\n private readonly logger: RootLoggerService,\n ) {}\n\n getDependencyNames(path: string) {\n const { dependencies } = require(path) as BackstagePackageJson;\n const packagesConfig = this.config.getOptional('backend.packages');\n\n const dependencyNames = Object.keys(dependencies || {});\n\n if (packagesConfig === 'all') {\n return dependencyNames;\n }\n\n const includedPackagesConfig = this.config.getOptionalStringArray(\n 'backend.packages.include',\n );\n\n const includedPackages = includedPackagesConfig\n ? new Set(includedPackagesConfig)\n : dependencyNames;\n const excludedPackagesSet = new Set(\n this.config.getOptionalStringArray('backend.packages.exclude'),\n );\n\n return [...includedPackages].filter(name => !excludedPackagesSet.has(name));\n }\n\n async getBackendFeatures(): Promise<{ features: Array<BackendFeature> }> {\n const packagesConfig = this.config.getOptional('backend.packages');\n if (!packagesConfig || Object.keys(packagesConfig).length === 0) {\n return { features: [] };\n }\n\n const packageDir = await findClosestPackageDir(process.argv[1]);\n if (!packageDir) {\n throw new Error('Package discovery failed to find package.json');\n }\n const dependencyNames = this.getDependencyNames(\n resolvePath(packageDir, 'package.json'),\n );\n\n const features: BackendFeature[] = [];\n\n for (const name of dependencyNames) {\n const depPkg = require(require.resolve(`${name}/package.json`, {\n paths: [packageDir],\n })) as BackstagePackageJson;\n if (\n !depPkg?.backstage?.role ||\n !DETECTED_PACKAGE_ROLES.includes(depPkg.backstage.role)\n ) {\n continue; // Not a backstage backend package, ignore\n }\n\n const exportedModulePaths = [\n require.resolve(name, {\n paths: [packageDir],\n }),\n ];\n\n // Find modules exported as alpha\n try {\n exportedModulePaths.push(\n require.resolve(`${name}/alpha`, { paths: [packageDir] }),\n );\n } catch {\n /* ignore */\n }\n\n for (const modulePath of exportedModulePaths) {\n const mod = require(modulePath);\n\n if (isBackendFeature(mod.default)) {\n this.logger.info(`Detected: ${name}`);\n features.push(mod.default);\n }\n if (isBackendFeatureFactory(mod.default)) {\n this.logger.info(`Detected: ${name}`);\n features.push(mod.default());\n }\n }\n }\n\n return { features };\n }\n}\n","/*\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 */\n\nimport {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { featureDiscoveryServiceRef } from '@backstage/backend-plugin-api/alpha';\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport { PackageDiscoveryService } from '../../../backend-defaults/src/PackageDiscoveryService';\n\n/**\n * @alpha\n * @deprecated The `featureDiscoveryServiceFactory` is deprecated in favor of using {@link @backstage/backend-defaults#discoveryFeatureLoader} instead.\n */\nexport const featureDiscoveryServiceFactory = createServiceFactory({\n service: featureDiscoveryServiceRef,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.rootLogger,\n },\n factory({ config, logger }) {\n return new PackageDiscoveryService(config, logger);\n },\n});\n"],"names":["path","resolvePath","fs","dirname","createServiceFactory","featureDiscoveryServiceRef","coreServices"],"mappings":";;;;;;;;;;;AA2BA,MAAM,sBAAyB,GAAA;AAAA,EAC7B,cAAA;AAAA,EACA,SAAA;AAAA,EACA,gBAAA;AAAA,EACA,uBAAA;AACF,CAAA,CAAA;AAGA,SAAS,iBAAiB,KAAyC,EAAA;AACjE,EAAA,OACE,CAAC,CAAC,KACF,IAAA,CAAC,QAAU,EAAA,UAAU,CAAE,CAAA,QAAA,CAAS,OAAO,KAAK,CAC3C,IAAA,KAAA,CAAyB,MAAW,KAAA,2BAAA,CAAA;AAEzC,CAAA;AAGA,SAAS,wBACP,KAC+B,EAAA;AAC/B,EAAA,OACE,CAAC,CAAC,KAAA,IACF,OAAO,KAAU,KAAA,UAAA,IAChB,MAAc,MAAW,KAAA,kCAAA,CAAA;AAE9B,CAAA;AAGA,eAAe,sBACb,SAC6B,EAAA;AAC7B,EAAA,IAAIA,MAAO,GAAA,SAAA,CAAA;AAGX,EAAA,KAAA,IAAS,CAAI,GAAA,CAAA,EAAG,CAAI,GAAA,GAAA,EAAM,CAAK,EAAA,EAAA;AAC7B,IAAM,MAAA,WAAA,GAAcC,YAAY,CAAAD,MAAA,EAAM,cAAc,CAAA,CAAA;AACpD,IAAA,MAAM,MAAS,GAAA,MAAME,mBAAG,CAAA,UAAA,CAAW,WAAW,CAAA,CAAA;AAC9C,IAAA,IAAI,MAAQ,EAAA;AACV,MAAO,OAAAF,MAAA,CAAA;AAAA,KACT;AAEA,IAAM,MAAA,OAAA,GAAUG,aAAQH,MAAI,CAAA,CAAA;AAC5B,IAAA,IAAI,YAAYA,MAAM,EAAA;AACpB,MAAO,OAAA,KAAA,CAAA,CAAA;AAAA,KACT;AACA,IAAOA,MAAA,GAAA,OAAA,CAAA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M,CAAA,MAAA;AAAA,OAER;AAEA,MAAA,KAAA,MAAW,cAAc,mBAAqB,EAAA;AAC5C,QAAM,MAAA,GAAA,GAAM,QAAQ,UAAU,CAAA,CAAA;AAE9B,QAAI,IAAA,gBAAA,CAAiB,GAAI,CAAA,OAAO,CAAG,EAAA;AACjC,UAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,CAAa,UAAA,EAAA,IAAI,CAAE,CAAA,CAAA,CAAA;AACpC,UAAS,QAAA,CAAA,IAAA,CAAK,IAAI,OAAO,CAAA,CAAA;AAAA,SAC3B;AACA,QAAI,IAAA,uBAAA,CAAwB,GAAI,CAAA,OAAO,CAAG,EAAA;AACxC,UAAA,IAAA,CAAK,MAAO,CAAA,IAAA,CAAK,CAAa,UAAA,EAAA,IAAI,CAAE,CAAA,CAAA,CAAA;AACpC,UAAS,QAAA,CAAA,IAAA,CAAK,GAAI,CAAA,OAAA,EAAS,CAAA,CAAA;AAAA,SAC7B;AAAA,OACF;AAAA,KACF;AAEA,IAAA,OAAO,EAAE,QAAS,EAAA,CAAA;AAAA,GACpB;AACF;;AC7IO,MAAM,iCAAiCG,qCAAqB,CAAA;AAAA,EACjE,OAAS,EAAAC,gCAAA;AAAA,EACT,IAAM,EAAA;AAAA,IACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,OAAQ,CAAA,EAAE,MAAQ,EAAA,MAAA,EAAU,EAAA;AAC1B,IAAO,OAAA,IAAI,uBAAwB,CAAA,MAAA,EAAQ,MAAM,CAAA,CAAA;AAAA,GACnD;AACF,CAAC;;;;"}
|
package/dist/alpha.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
2
|
-
import
|
|
2
|
+
import * as _backstage_backend_plugin_api_alpha from '@backstage/backend-plugin-api/alpha';
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* @alpha
|
|
6
|
+
* @deprecated The `featureDiscoveryServiceFactory` is deprecated in favor of using {@link @backstage/backend-defaults#discoveryFeatureLoader} instead.
|
|
7
|
+
*/
|
|
8
|
+
declare const featureDiscoveryServiceFactory: _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api_alpha.FeatureDiscoveryService, "root", "singleton">;
|
|
6
9
|
|
|
7
10
|
export { featureDiscoveryServiceFactory };
|
package/dist/index.cjs.js
CHANGED
|
@@ -3,8 +3,6 @@
|
|
|
3
3
|
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
4
4
|
var errors = require('@backstage/errors');
|
|
5
5
|
var alpha = require('@backstage/backend-plugin-api/alpha');
|
|
6
|
-
var pluginAuthNode = require('@backstage/plugin-auth-node');
|
|
7
|
-
var backendCommon = require('@backstage/backend-common');
|
|
8
6
|
|
|
9
7
|
class Node {
|
|
10
8
|
constructor(value, consumes, provides) {
|
|
@@ -561,6 +559,7 @@ class BackendInitializer {
|
|
|
561
559
|
this.#addFeature(await feature);
|
|
562
560
|
}
|
|
563
561
|
const featureDiscovery = await this.#serviceRegistry.get(
|
|
562
|
+
// TODO: Let's leave this in place and remove it once the deprecated service is removed. We can do that post-1.0 since it's alpha
|
|
564
563
|
alpha.featureDiscoveryServiceRef,
|
|
565
564
|
"root"
|
|
566
565
|
);
|
|
@@ -861,36 +860,5 @@ function createSpecializedBackend(options) {
|
|
|
861
860
|
return new BackstageBackend(options.defaultServiceFactories);
|
|
862
861
|
}
|
|
863
862
|
|
|
864
|
-
const identityServiceFactory = backendPluginApi.createServiceFactory(
|
|
865
|
-
(options) => ({
|
|
866
|
-
service: backendPluginApi.coreServices.identity,
|
|
867
|
-
deps: {
|
|
868
|
-
discovery: backendPluginApi.coreServices.discovery
|
|
869
|
-
},
|
|
870
|
-
async factory({ discovery }) {
|
|
871
|
-
return pluginAuthNode.DefaultIdentityClient.create({ discovery, ...options });
|
|
872
|
-
}
|
|
873
|
-
})
|
|
874
|
-
);
|
|
875
|
-
|
|
876
|
-
const tokenManagerServiceFactory = backendPluginApi.createServiceFactory({
|
|
877
|
-
service: backendPluginApi.coreServices.tokenManager,
|
|
878
|
-
deps: {
|
|
879
|
-
config: backendPluginApi.coreServices.rootConfig,
|
|
880
|
-
logger: backendPluginApi.coreServices.rootLogger
|
|
881
|
-
},
|
|
882
|
-
createRootContext({ config, logger }) {
|
|
883
|
-
return backendCommon.ServerTokenManager.fromConfig(config, {
|
|
884
|
-
logger,
|
|
885
|
-
allowDisabledTokenManager: true
|
|
886
|
-
});
|
|
887
|
-
},
|
|
888
|
-
async factory(_deps, tokenManager) {
|
|
889
|
-
return tokenManager;
|
|
890
|
-
}
|
|
891
|
-
});
|
|
892
|
-
|
|
893
863
|
exports.createSpecializedBackend = createSpecializedBackend;
|
|
894
|
-
exports.identityServiceFactory = identityServiceFactory;
|
|
895
|
-
exports.tokenManagerServiceFactory = tokenManagerServiceFactory;
|
|
896
864
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/lib/DependencyGraph.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/createInitializationLogger.ts","../src/wiring/helpers.ts","../src/wiring/BackendInitializer.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.ts","../src/services/implementations/identity/identityServiceFactory.ts","../src/services/implementations/tokenManager/tokenManagerServiceFactory.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 */\n\ninterface NodeInput<T> {\n value: T;\n consumes?: Iterable<string>;\n provides?: Iterable<string>;\n}\n\n/** @internal */\nclass Node<T> {\n static from<T>(input: NodeInput<T>) {\n return new Node<T>(\n input.value,\n input.consumes ? new Set(input.consumes) : new Set(),\n input.provides ? new Set(input.provides) : new Set(),\n );\n }\n\n private constructor(\n readonly value: T,\n readonly consumes: Set<string>,\n readonly provides: Set<string>,\n ) {}\n}\n\n/** @internal */\nclass CycleKeySet<T> {\n static from<T>(nodes: Array<Node<T>>) {\n return new CycleKeySet<T>(nodes);\n }\n\n #nodeIds: Map<T, number>;\n #cycleKeys: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodeIds = new Map(nodes.map((n, i) => [n.value, i]));\n this.#cycleKeys = new Set<string>();\n }\n\n tryAdd(path: T[]): boolean {\n const cycleKey = this.#getCycleKey(path);\n if (this.#cycleKeys.has(cycleKey)) {\n return false;\n }\n this.#cycleKeys.add(cycleKey);\n return true;\n }\n\n #getCycleKey(path: T[]): string {\n return path\n .map(n => this.#nodeIds.get(n)!)\n .sort()\n .join(',');\n }\n}\n\n/**\n * Internal helper to help validate and traverse a dependency graph.\n * @internal\n */\nexport class DependencyGraph<T> {\n static fromMap(\n nodes: Record<string, Omit<NodeInput<unknown>, 'value'>>,\n ): DependencyGraph<string> {\n return this.fromIterable(\n Object.entries(nodes).map(([key, node]) => ({\n value: String(key),\n ...node,\n })),\n );\n }\n\n static fromIterable<T>(\n nodeInputs: Iterable<NodeInput<T>>,\n ): DependencyGraph<T> {\n const nodes = new Array<Node<T>>();\n for (const nodeInput of nodeInputs) {\n nodes.push(Node.from(nodeInput));\n }\n\n return new DependencyGraph(nodes);\n }\n\n #nodes: Array<Node<T>>;\n #allProvided: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodes = nodes;\n this.#allProvided = new Set();\n\n for (const node of this.#nodes.values()) {\n for (const produced of node.provides) {\n this.#allProvided.add(produced);\n }\n }\n }\n\n /**\n * Find all nodes that consume dependencies that are not provided by any other node.\n */\n findUnsatisfiedDeps(): Array<{ value: T; unsatisfied: string[] }> {\n const unsatisfiedDependencies = [];\n for (const node of this.#nodes.values()) {\n const unsatisfied = Array.from(node.consumes).filter(\n id => !this.#allProvided.has(id),\n );\n if (unsatisfied.length > 0) {\n unsatisfiedDependencies.push({ value: node.value, unsatisfied });\n }\n }\n return unsatisfiedDependencies;\n }\n\n /**\n * Detect the first circular dependency within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n detectCircularDependency(): T[] | undefined {\n return this.detectCircularDependencies().next().value;\n }\n\n /**\n * Detect circular dependencies within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n *detectCircularDependencies(): Generator<T[], undefined> {\n const cycleKeys = CycleKeySet.from(this.#nodes);\n\n for (const startNode of this.#nodes) {\n const visited = new Set<Node<T>>();\n const stack = new Array<[node: Node<T>, path: T[]]>([\n startNode,\n [startNode.value],\n ]);\n\n while (stack.length > 0) {\n const [node, path] = stack.pop()!;\n if (visited.has(node)) {\n continue;\n }\n visited.add(node);\n for (const consumed of node.consumes) {\n const providerNodes = this.#nodes.filter(other =>\n other.provides.has(consumed),\n );\n for (const provider of providerNodes) {\n if (provider === startNode) {\n if (cycleKeys.tryAdd(path)) {\n yield [...path, startNode.value];\n }\n\n break;\n }\n if (!visited.has(provider)) {\n stack.push([provider, [...path, provider.value]]);\n }\n }\n }\n }\n }\n return undefined;\n }\n\n /**\n * Traverses the dependency graph in topological order, calling the provided\n * function for each node and waiting for it to resolve.\n *\n * The nodes are traversed in parallel, but in such a way that no node is\n * visited before all of its dependencies.\n *\n * Dependencies of nodes that are not produced by any other nodes will be ignored.\n */\n async parallelTopologicalTraversal<TResult>(\n fn: (value: T) => Promise<TResult>,\n ): Promise<TResult[]> {\n const allProvided = this.#allProvided;\n const producedSoFar = new Set<string>();\n const waiting = new Set(this.#nodes.values());\n const visited = new Set<Node<T>>();\n const results = new Array<TResult>();\n let inFlight = 0; // Keep track of how many callbacks are in flight, so that we know if we got stuck\n\n // Find all nodes that have no dependencies that have not already been produced by visited nodes\n async function processMoreNodes() {\n if (waiting.size === 0) {\n return;\n }\n const nodesToProcess = [];\n for (const node of waiting) {\n let ready = true;\n for (const consumed of node.consumes) {\n if (allProvided.has(consumed) && !producedSoFar.has(consumed)) {\n ready = false;\n continue;\n }\n }\n if (ready) {\n nodesToProcess.push(node);\n }\n }\n\n for (const node of nodesToProcess) {\n waiting.delete(node);\n }\n\n if (nodesToProcess.length === 0 && inFlight === 0) {\n // We expect the caller to check for circular dependencies before\n // traversal, so this error should never happen\n throw new Error('Circular dependency detected');\n }\n\n await Promise.all(nodesToProcess.map(processNode));\n }\n\n // Process an individual node, and then add its produced dependencies to the set of available products\n async function processNode(node: Node<T>) {\n visited.add(node);\n inFlight += 1;\n\n const result = await fn(node.value);\n results.push(result);\n\n node.provides.forEach(produced => producedSoFar.add(produced));\n inFlight -= 1;\n await processMoreNodes();\n }\n\n await processMoreNodes();\n\n return results;\n }\n}\n","/*\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 {\n ServiceFactory,\n ServiceRef,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConflictError, stringifyError } from '@backstage/errors';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';\nimport { DependencyGraph } from '../lib/DependencyGraph';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef = ServiceRef<unknown> & {\n __defaultFactory?: (\n service: ServiceRef<unknown>,\n ) => Promise<ServiceFactory | (() => ServiceFactory)>;\n};\n\nfunction toInternalServiceFactory<TService, TScope extends 'plugin' | 'root'>(\n factory: ServiceFactory<TService, TScope>,\n): InternalServiceFactory<TService, TScope> {\n const f = factory as InternalServiceFactory<TService, TScope>;\n if (f.$$type !== '@backstage/BackendFeature') {\n throw new Error(`Invalid service factory, bad type '${f.$$type}'`);\n }\n if (f.version !== 'v1') {\n throw new Error(`Invalid service factory, bad version '${f.version}'`);\n }\n return f;\n}\n\nfunction createPluginMetadataServiceFactory(pluginId: string) {\n return createServiceFactory({\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => ({ getId: () => pluginId }),\n });\n}\n\nexport class ServiceRegistry {\n static create(factories: Array<ServiceFactory>): ServiceRegistry {\n const factoryMap = new Map<string, InternalServiceFactory[]>();\n for (const factory of factories) {\n if (factory.service.multiton) {\n const existing = factoryMap.get(factory.service.id) ?? [];\n factoryMap.set(\n factory.service.id,\n existing.concat(toInternalServiceFactory(factory)),\n );\n } else {\n factoryMap.set(factory.service.id, [toInternalServiceFactory(factory)]);\n }\n }\n const registry = new ServiceRegistry(factoryMap);\n registry.checkForCircularDeps();\n return registry;\n }\n\n readonly #providedFactories: Map<string, InternalServiceFactory[]>;\n readonly #loadedDefaultFactories: Map<\n Function,\n Promise<InternalServiceFactory>\n >;\n readonly #implementations: Map<\n InternalServiceFactory,\n {\n context: Promise<unknown>;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n readonly #rootServiceImplementations = new Map<\n InternalServiceFactory,\n Promise<unknown>\n >();\n readonly #addedFactoryIds = new Set<string>();\n readonly #instantiatedFactories = new Set<string>();\n\n private constructor(factories: Map<string, InternalServiceFactory[]>) {\n this.#providedFactories = factories;\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<InternalServiceFactory[]> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve([\n toInternalServiceFactory(createPluginMetadataServiceFactory(pluginId)),\n ]);\n }\n\n let resolvedFactory:\n | Promise<InternalServiceFactory[]>\n | InternalServiceFactory[]\n | undefined = this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } = ref as InternalServiceRef;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n toInternalServiceFactory(typeof f === 'function' ? f() : f),\n );\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.then(\n factory => [factory],\n error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n },\n );\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #checkForMissingDeps(factory: InternalServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n if (ref.multiton) {\n return false;\n }\n\n return !(ref as InternalServiceRef).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n checkForCircularDeps(): void {\n const graph = DependencyGraph.fromIterable(\n Array.from(this.#providedFactories).map(([serviceId, factories]) => ({\n value: serviceId,\n provides: [serviceId],\n consumes: factories.flatMap(factory =>\n Object.values(factory.deps).map(d => d.id),\n ),\n })),\n );\n const circularDependencies = Array.from(graph.detectCircularDependencies());\n\n if (circularDependencies.length) {\n const cycles = circularDependencies\n .map(c => c.map(id => `'${id}'`).join(' -> '))\n .join('\\n ');\n\n throw new ConflictError(`Circular dependencies detected:\\n ${cycles}`);\n }\n }\n\n add(factory: ServiceFactory) {\n const factoryId = factory.service.id;\n if (factoryId === coreServices.pluginMetadata.id) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n if (this.#instantiatedFactories.has(factoryId)) {\n throw new Error(\n `Unable to set service factory with id ${factoryId}, service has already been instantiated`,\n );\n }\n\n if (factory.service.multiton) {\n const newFactories = (\n this.#providedFactories.get(factoryId) ?? []\n ).concat(toInternalServiceFactory(factory));\n this.#providedFactories.set(factoryId, newFactories);\n } else {\n if (this.#addedFactoryIds.has(factoryId)) {\n throw new Error(\n `Duplicate service implementations provided for ${factoryId}`,\n );\n }\n\n this.#addedFactoryIds.add(factoryId);\n this.#providedFactories.set(factoryId, [\n toInternalServiceFactory(factory),\n ]);\n }\n }\n\n async initializeEagerServicesWithScope(\n scope: 'root' | 'plugin',\n pluginId: string = 'root',\n ) {\n for (const [factory] of this.#providedFactories.values()) {\n if (factory.service.scope === scope) {\n // Root-scoped services are eager by default, plugin-scoped are lazy by default\n if (scope === 'root' && factory.initialization !== 'lazy') {\n await this.get(factory.service, pluginId);\n } else if (scope === 'plugin' && factory.initialization === 'always') {\n await this.get(factory.service, pluginId);\n }\n }\n }\n }\n\n get<T, TInstances extends 'singleton' | 'multiton'>(\n ref: ServiceRef<T, 'plugin' | 'root', TInstances>,\n pluginId: string,\n ): Promise<TInstances extends 'multiton' ? T[] : T> | undefined {\n this.#instantiatedFactories.add(ref.id);\n\n const resolvedFactory = this.#resolveFactory(ref, pluginId);\n\n if (!resolvedFactory) {\n return ref.multiton\n ? (Promise.resolve([]) as\n | Promise<TInstances extends 'multiton' ? T[] : T>\n | undefined)\n : undefined;\n }\n\n return resolvedFactory\n .then(factories => {\n return Promise.all(\n factories.map(factory => {\n if (factory.service.scope === 'root') {\n let existing = this.#rootServiceImplementations.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), undefined),\n );\n this.#rootServiceImplementations.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n context: Promise.all(rootDeps)\n .then(entries =>\n factory.createRootContext?.(Object.fromEntries(entries)),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.context\n .then(context =>\n Promise.all(allDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), context),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n return result;\n }),\n );\n })\n .then(results => (ref.multiton ? results : results[0]));\n }\n}\n","/*\n * Copyright 2024 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 { RootLoggerService } from '@backstage/backend-plugin-api';\n\nconst LOGGER_INTERVAL_MAX = 60_000;\n\nfunction joinIds(ids: Iterable<string>): string {\n return [...ids].map(id => `'${id}'`).join(', ');\n}\n\nexport function createInitializationLogger(\n pluginIds: string[],\n rootLogger?: RootLoggerService,\n): {\n onPluginStarted(pluginId: string): void;\n onAllStarted(): void;\n} {\n const logger = rootLogger?.child({ type: 'initialization' });\n const starting = new Set(pluginIds);\n const started = new Set<string>();\n\n logger?.info(`Plugin initialization started: ${joinIds(pluginIds)}`);\n\n const getInitStatus = () => {\n let status = '';\n if (started.size > 0) {\n status = `, newly initialized: ${joinIds(started)}`;\n started.clear();\n }\n if (starting.size > 0) {\n status += `, still initializing: ${joinIds(starting)}`;\n }\n return status;\n };\n\n // Periodically log the initialization status with a fibonacci backoff\n let interval = 1000;\n let prevInterval = 0;\n let timeout: NodeJS.Timeout | undefined;\n const onTimeout = () => {\n logger?.info(`Plugin initialization in progress${getInitStatus()}`);\n\n const nextInterval = Math.min(interval + prevInterval, LOGGER_INTERVAL_MAX);\n prevInterval = interval;\n interval = nextInterval;\n\n timeout = setTimeout(onTimeout, nextInterval);\n };\n timeout = setTimeout(onTimeout, interval);\n\n return {\n onPluginStarted(pluginId: string) {\n starting.delete(pluginId);\n started.add(pluginId);\n },\n onAllStarted() {\n logger?.info(`Plugin initialization complete${getInitStatus()}`);\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n },\n };\n}\n","/*\n * Copyright 2024 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 { BackendFeature } from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport function unwrapFeature(\n feature: BackendFeature | { default: BackendFeature },\n): BackendFeature {\n if ('$$type' in feature) {\n return feature;\n }\n\n // This is a workaround where default exports get transpiled to `exports['default'] = ...`\n // in CommonJS modules, which in turn results in a double `{ default: { default: ... } }` nesting\n // when importing using a dynamic import.\n // TODO: This is a broader issue than just this piece of code, and should move away from CommonJS.\n if ('default' in feature) {\n return feature.default;\n }\n\n return feature;\n}\n","/*\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 {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n ServiceFactory,\n LifecycleService,\n RootLifecycleService,\n} from '@backstage/backend-plugin-api';\nimport { ServiceOrExtensionPoint } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport type {\n InternalBackendFeature,\n InternalBackendFeatureLoader,\n InternalBackendRegistrations,\n} from '../../../backend-plugin-api/src/wiring/types';\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport type { InternalServiceFactory } from '../../../backend-plugin-api/src/services/system/types';\nimport { ForwardedError, ConflictError } from '@backstage/errors';\nimport { featureDiscoveryServiceRef } from '@backstage/backend-plugin-api/alpha';\nimport { DependencyGraph } from '../lib/DependencyGraph';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { createInitializationLogger } from './createInitializationLogger';\nimport { unwrapFeature } from './helpers';\n\nexport interface BackendRegisterInit {\n consumes: Set<ServiceOrExtensionPoint>;\n provides: Set<ServiceOrExtensionPoint>;\n init: {\n deps: { [name: string]: ServiceOrExtensionPoint };\n func: (deps: { [name: string]: unknown }) => Promise<void>;\n };\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #registrations = new Array<InternalBackendRegistrations>();\n #extensionPoints = new Map<string, { impl: unknown; pluginId: string }>();\n #serviceRegistry: ServiceRegistry;\n #registeredFeatures = new Array<Promise<BackendFeature>>();\n #registeredFeatureLoaders = new Array<InternalBackendFeatureLoader>();\n\n constructor(defaultApiFactories: ServiceFactory[]) {\n this.#serviceRegistry = ServiceRegistry.create([...defaultApiFactories]);\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n moduleId?: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const ep = this.#extensionPoints.get(ref.id);\n if (ep) {\n if (ep.pluginId !== pluginId) {\n throw new Error(\n `Illegal dependency: Module '${moduleId}' for plugin '${pluginId}' attempted to depend on extension point '${ref.id}' for plugin '${ep.pluginId}'. Extension points can only be used within their plugin's scope.`,\n );\n }\n result.set(name, ep.impl);\n } else {\n const impl = await this.#serviceRegistry.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add(feature: BackendFeature | Promise<BackendFeature>) {\n if (this.#startPromise) {\n throw new Error('feature can not be added after the backend has started');\n }\n this.#registeredFeatures.push(Promise.resolve(feature));\n }\n\n #addFeature(feature: BackendFeature) {\n if (isServiceFactory(feature)) {\n this.#serviceRegistry.add(feature);\n } else if (isBackendFeatureLoader(feature)) {\n this.#registeredFeatureLoaders.push(feature);\n } else if (isBackendRegistrations(feature)) {\n this.#registrations.push(feature);\n } else {\n throw new Error(\n `Failed to add feature, invalid feature ${JSON.stringify(feature)}`,\n );\n }\n }\n\n async start(): Promise<void> {\n if (this.#startPromise) {\n throw new Error('Backend has already started');\n }\n\n const exitHandler = async () => {\n process.removeListener('SIGTERM', exitHandler);\n process.removeListener('SIGINT', exitHandler);\n process.removeListener('beforeExit', exitHandler);\n\n try {\n await this.stop();\n process.exit(0);\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n\n process.addListener('SIGTERM', exitHandler);\n process.addListener('SIGINT', exitHandler);\n process.addListener('beforeExit', exitHandler);\n\n this.#startPromise = this.#doStart();\n await this.#startPromise;\n }\n\n async #doStart(): Promise<void> {\n this.#serviceRegistry.checkForCircularDeps();\n\n for (const feature of this.#registeredFeatures) {\n this.#addFeature(await feature);\n }\n\n const featureDiscovery = await this.#serviceRegistry.get(\n featureDiscoveryServiceRef,\n 'root',\n );\n\n if (featureDiscovery) {\n const { features } = await featureDiscovery.getBackendFeatures();\n for (const feature of features) {\n this.#addFeature(unwrapFeature(feature));\n }\n this.#serviceRegistry.checkForCircularDeps();\n }\n\n await this.#applyBackendFeatureLoaders(this.#registeredFeatureLoaders);\n\n // Initialize all root scoped services\n await this.#serviceRegistry.initializeEagerServicesWithScope('root');\n\n const pluginInits = new Map<string, BackendRegisterInit>();\n const moduleInits = new Map<string, Map<string, BackendRegisterInit>>();\n\n // Enumerate all registrations\n for (const feature of this.#registrations) {\n for (const r of feature.getRegistrations()) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n if (r.type === 'plugin' || r.type === 'module') {\n for (const [extRef, extImpl] of r.extensionPoints) {\n if (this.#extensionPoints.has(extRef.id)) {\n throw new Error(\n `ExtensionPoint with ID '${extRef.id}' is already registered`,\n );\n }\n this.#extensionPoints.set(extRef.id, {\n impl: extImpl,\n pluginId: r.pluginId,\n });\n provides.add(extRef);\n }\n }\n\n if (r.type === 'plugin') {\n if (pluginInits.has(r.pluginId)) {\n throw new Error(`Plugin '${r.pluginId}' is already registered`);\n }\n pluginInits.set(r.pluginId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else if (r.type === 'module') {\n let modules = moduleInits.get(r.pluginId);\n if (!modules) {\n modules = new Map();\n moduleInits.set(r.pluginId, modules);\n }\n if (modules.has(r.moduleId)) {\n throw new Error(\n `Module '${r.moduleId}' for plugin '${r.pluginId}' is already registered`,\n );\n }\n modules.set(r.moduleId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else {\n throw new Error(`Invalid registration type '${(r as any).type}'`);\n }\n }\n }\n\n const allPluginIds = [...pluginInits.keys()];\n\n const initLogger = createInitializationLogger(\n allPluginIds,\n await this.#serviceRegistry.get(coreServices.rootLogger, 'root'),\n );\n\n // All plugins are initialized in parallel\n await Promise.all(\n allPluginIds.map(async pluginId => {\n // Initialize all eager services\n await this.#serviceRegistry.initializeEagerServicesWithScope(\n 'plugin',\n pluginId,\n );\n\n // Modules are initialized before plugins, so that they can provide extension to the plugin\n const modules = moduleInits.get(pluginId);\n if (modules) {\n const tree = DependencyGraph.fromIterable(\n Array.from(modules).map(([moduleId, moduleInit]) => ({\n value: { moduleId, moduleInit },\n // Relationships are reversed at this point since we're only interested in the extension points.\n // If a modules provides extension point A we want it to be initialized AFTER all modules\n // that depend on extension point A, so that they can provide their extensions.\n consumes: Array.from(moduleInit.provides).map(p => p.id),\n provides: Array.from(moduleInit.consumes).map(c => c.id),\n })),\n );\n const circular = tree.detectCircularDependency();\n if (circular) {\n throw new ConflictError(\n `Circular dependency detected for modules of plugin '${pluginId}', ${circular\n .map(({ moduleId }) => `'${moduleId}'`)\n .join(' -> ')}`,\n );\n }\n await tree.parallelTopologicalTraversal(\n async ({ moduleId, moduleInit }) => {\n const moduleDeps = await this.#getInitDeps(\n moduleInit.init.deps,\n pluginId,\n moduleId,\n );\n await moduleInit.init.func(moduleDeps).catch(error => {\n throw new ForwardedError(\n `Module '${moduleId}' for plugin '${pluginId}' startup failed`,\n error,\n );\n });\n },\n );\n }\n\n // Once all modules have been initialized, we can initialize the plugin itself\n const pluginInit = pluginInits.get(pluginId);\n // We allow modules to be installed without the accompanying plugin, so the plugin may not exist\n if (pluginInit) {\n const pluginDeps = await this.#getInitDeps(\n pluginInit.init.deps,\n pluginId,\n );\n await pluginInit.init.func(pluginDeps).catch(error => {\n throw new ForwardedError(\n `Plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }\n\n initLogger.onPluginStarted(pluginId);\n\n // Once the plugin and all modules have been initialized, we can signal that the plugin has stared up successfully\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.startup();\n }),\n );\n\n // Once all plugins and modules have been initialized, we can signal that the backend has started up successfully\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.startup();\n\n initLogger.onAllStarted();\n\n // Once the backend is started, any uncaught errors or unhandled rejections are caught\n // and logged, in order to avoid crashing the entire backend on local failures.\n if (process.env.NODE_ENV !== 'test') {\n const rootLogger = await this.#serviceRegistry.get(\n coreServices.rootLogger,\n 'root',\n );\n process.on('unhandledRejection', (reason: Error) => {\n rootLogger\n ?.child({ type: 'unhandledRejection' })\n ?.error('Unhandled rejection', reason);\n });\n process.on('uncaughtException', error => {\n rootLogger\n ?.child({ type: 'uncaughtException' })\n ?.error('Uncaught exception', error);\n });\n }\n }\n\n async stop(): Promise<void> {\n if (!this.#startPromise) {\n return;\n }\n\n try {\n await this.#startPromise;\n } catch (error) {\n // The startup failed, but we may still want to do cleanup so we continue silently\n }\n\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.shutdown();\n }\n\n // Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this\n async #getRootLifecycleImpl(): Promise<\n RootLifecycleService & {\n startup(): Promise<void>;\n shutdown(): Promise<void>;\n }\n > {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.rootLifecycle,\n 'root',\n );\n\n const service = lifecycleService as any;\n if (\n service &&\n typeof service.startup === 'function' &&\n typeof service.shutdown === 'function'\n ) {\n return service;\n }\n\n throw new Error('Unexpected root lifecycle service implementation');\n }\n\n async #getPluginLifecycleImpl(\n pluginId: string,\n ): Promise<LifecycleService & { startup(): Promise<void> }> {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.lifecycle,\n pluginId,\n );\n\n const service = lifecycleService as any;\n if (service && typeof service.startup === 'function') {\n return service;\n }\n\n throw new Error('Unexpected plugin lifecycle service implementation');\n }\n\n async #applyBackendFeatureLoaders(loaders: InternalBackendFeatureLoader[]) {\n for (const loader of loaders) {\n const deps = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(loader.deps ?? {})) {\n if (ref.scope !== 'root') {\n throw new Error(\n `Feature loaders can only depend on root scoped services, but '${name}' is scoped to '${ref.scope}'. Offending loader is ${loader.description}`,\n );\n }\n const impl = await this.#serviceRegistry.get(\n ref as ServiceRef<unknown>,\n 'root',\n );\n if (impl) {\n deps.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No service available for the following ref(s): ${missing}, depended on by feature loader ${loader.description}`,\n );\n }\n\n const result = await loader\n .loader(Object.fromEntries(deps))\n .then(features => features.map(unwrapFeature))\n .catch(error => {\n throw new ForwardedError(\n `Feature loader ${loader.description} failed`,\n error,\n );\n });\n\n let didAddServiceFactory = false;\n const newLoaders = new Array<InternalBackendFeatureLoader>();\n\n for await (const feature of result) {\n if (isBackendFeatureLoader(feature)) {\n newLoaders.push(feature);\n } else {\n didAddServiceFactory ||= isServiceFactory(feature);\n this.#addFeature(feature);\n }\n }\n\n // Every time we add a new service factory we need to make sure that we don't have circular dependencies\n if (didAddServiceFactory) {\n this.#serviceRegistry.checkForCircularDeps();\n }\n\n // Apply loaders recursively, depth-first\n if (newLoaders.length > 0) {\n await this.#applyBackendFeatureLoaders(newLoaders);\n }\n }\n }\n}\n\nfunction toInternalBackendFeature(\n feature: BackendFeature,\n): InternalBackendFeature {\n if (feature.$$type !== '@backstage/BackendFeature') {\n throw new Error(`Invalid BackendFeature, bad type '${feature.$$type}'`);\n }\n const internal = feature as InternalBackendFeature;\n if (internal.version !== 'v1') {\n throw new Error(\n `Invalid BackendFeature, bad version '${internal.version}'`,\n );\n }\n return internal;\n}\n\nfunction isServiceFactory(\n feature: BackendFeature,\n): feature is InternalServiceFactory {\n const internal = toInternalBackendFeature(feature);\n if (internal.featureType === 'service') {\n return true;\n }\n // Backwards compatibility for v1 registrations that use duck typing\n return 'service' in internal;\n}\n\nfunction isBackendRegistrations(\n feature: BackendFeature,\n): feature is InternalBackendRegistrations {\n const internal = toInternalBackendFeature(feature);\n if (internal.featureType === 'registrations') {\n return true;\n }\n // Backwards compatibility for v1 registrations that use duck typing\n return 'getRegistrations' in internal;\n}\n\nfunction isBackendFeatureLoader(\n feature: BackendFeature,\n): feature is InternalBackendFeatureLoader {\n return toInternalBackendFeature(feature).featureType === 'loader';\n}\n","/*\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 { BackendFeature, ServiceFactory } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { unwrapFeature } from './helpers';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #initializer: BackendInitializer;\n\n constructor(defaultServiceFactories: ServiceFactory[]) {\n this.#initializer = new BackendInitializer(defaultServiceFactories);\n }\n\n add(feature: BackendFeature | Promise<{ default: BackendFeature }>): void {\n if (isPromise(feature)) {\n this.#initializer.add(feature.then(f => unwrapFeature(f.default)));\n } else {\n this.#initializer.add(unwrapFeature(feature));\n }\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n\nfunction isPromise<T>(value: unknown | Promise<T>): value is Promise<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof value.then === 'function'\n );\n}\n","/*\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 { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of options.defaultServiceFactories) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(options.defaultServiceFactories);\n}\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { DefaultIdentityClient } from '@backstage/plugin-auth-node';\n\n/**\n * An identity client options object which allows extra configurations\n *\n * @public\n * @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead\n */\nexport type IdentityFactoryOptions = {\n issuer?: string;\n\n /**\n * JWS \"alg\" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.\n * More info on supported algorithms: https://github.com/panva/jose\n */\n algorithms?: string[];\n};\n\n/**\n * @public\n * @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead\n */\nexport const identityServiceFactory = createServiceFactory(\n (options?: IdentityFactoryOptions) => ({\n service: coreServices.identity,\n deps: {\n discovery: coreServices.discovery,\n },\n async factory({ discovery }) {\n return DefaultIdentityClient.create({ discovery, ...options });\n },\n }),\n);\n","/*\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 {\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ServerTokenManager } from '@backstage/backend-common';\n\n/**\n * @public\n * @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead\n */\nexport const tokenManagerServiceFactory = createServiceFactory({\n service: coreServices.tokenManager,\n deps: {\n config: coreServices.rootConfig,\n logger: coreServices.rootLogger,\n },\n createRootContext({ config, logger }) {\n return ServerTokenManager.fromConfig(config, {\n logger,\n allowDisabledTokenManager: true,\n });\n },\n async factory(_deps, tokenManager) {\n return tokenManager;\n },\n});\n"],"names":["createServiceFactory","coreServices","stringifyError","ConflictError","featureDiscoveryServiceRef","ForwardedError","lifecycleService","DefaultIdentityClient","ServerTokenManager"],"mappings":";;;;;;;;AAuBA,MAAM,IAAQ,CAAA;AAAA,EASJ,WAAA,CACG,KACA,EAAA,QAAA,EACA,QACT,EAAA;AAHS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA,CAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AAAA,GACR;AAAA,EAZH,OAAO,KAAQ,KAAqB,EAAA;AAClC,IAAA,OAAO,IAAI,IAAA;AAAA,MACT,KAAM,CAAA,KAAA;AAAA,MACN,KAAA,CAAM,WAAW,IAAI,GAAA,CAAI,MAAM,QAAQ,CAAA,uBAAQ,GAAI,EAAA;AAAA,MACnD,KAAA,CAAM,WAAW,IAAI,GAAA,CAAI,MAAM,QAAQ,CAAA,uBAAQ,GAAI,EAAA;AAAA,KACrD,CAAA;AAAA,GACF;AAOF,CAAA;AAGA,MAAM,WAAe,CAAA;AAAA,EACnB,OAAO,KAAQ,KAAuB,EAAA;AACpC,IAAO,OAAA,IAAI,YAAe,KAAK,CAAA,CAAA;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C,6BAAa,CAAA,YAAA;AAAA,EACtB,IAAM,EAAA;AAAA,IACJ,QAAQA,6BAAa,CAAA,UAAA;AAAA,IACrB,QAAQA,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,iBAAkB,CAAA,EAAE,MAAQ,EAAA,MAAA,EAAU,EAAA;AACpC,IAAO,OAAAO,gCAAA,CAAmB,WAAW,MAAQ,EAAA;AAAA,MAC3C,MAAA;AAAA,MACA,yBAA2B,EAAA,IAAA;AAAA,KAC5B,CAAA,CAAA;AAAA,GACH;AAAA,EACA,MAAM,OAAQ,CAAA,KAAA,EAAO,YAAc,EAAA;AACjC,IAAO,OAAA,YAAA,CAAA;AAAA,GACT;AACF,CAAC;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/lib/DependencyGraph.ts","../src/wiring/ServiceRegistry.ts","../src/wiring/createInitializationLogger.ts","../src/wiring/helpers.ts","../src/wiring/BackendInitializer.ts","../src/wiring/BackstageBackend.ts","../src/wiring/createSpecializedBackend.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 */\n\ninterface NodeInput<T> {\n value: T;\n consumes?: Iterable<string>;\n provides?: Iterable<string>;\n}\n\n/** @internal */\nclass Node<T> {\n static from<T>(input: NodeInput<T>) {\n return new Node<T>(\n input.value,\n input.consumes ? new Set(input.consumes) : new Set(),\n input.provides ? new Set(input.provides) : new Set(),\n );\n }\n\n private constructor(\n readonly value: T,\n readonly consumes: Set<string>,\n readonly provides: Set<string>,\n ) {}\n}\n\n/** @internal */\nclass CycleKeySet<T> {\n static from<T>(nodes: Array<Node<T>>) {\n return new CycleKeySet<T>(nodes);\n }\n\n #nodeIds: Map<T, number>;\n #cycleKeys: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodeIds = new Map(nodes.map((n, i) => [n.value, i]));\n this.#cycleKeys = new Set<string>();\n }\n\n tryAdd(path: T[]): boolean {\n const cycleKey = this.#getCycleKey(path);\n if (this.#cycleKeys.has(cycleKey)) {\n return false;\n }\n this.#cycleKeys.add(cycleKey);\n return true;\n }\n\n #getCycleKey(path: T[]): string {\n return path\n .map(n => this.#nodeIds.get(n)!)\n .sort()\n .join(',');\n }\n}\n\n/**\n * Internal helper to help validate and traverse a dependency graph.\n * @internal\n */\nexport class DependencyGraph<T> {\n static fromMap(\n nodes: Record<string, Omit<NodeInput<unknown>, 'value'>>,\n ): DependencyGraph<string> {\n return this.fromIterable(\n Object.entries(nodes).map(([key, node]) => ({\n value: String(key),\n ...node,\n })),\n );\n }\n\n static fromIterable<T>(\n nodeInputs: Iterable<NodeInput<T>>,\n ): DependencyGraph<T> {\n const nodes = new Array<Node<T>>();\n for (const nodeInput of nodeInputs) {\n nodes.push(Node.from(nodeInput));\n }\n\n return new DependencyGraph(nodes);\n }\n\n #nodes: Array<Node<T>>;\n #allProvided: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodes = nodes;\n this.#allProvided = new Set();\n\n for (const node of this.#nodes.values()) {\n for (const produced of node.provides) {\n this.#allProvided.add(produced);\n }\n }\n }\n\n /**\n * Find all nodes that consume dependencies that are not provided by any other node.\n */\n findUnsatisfiedDeps(): Array<{ value: T; unsatisfied: string[] }> {\n const unsatisfiedDependencies = [];\n for (const node of this.#nodes.values()) {\n const unsatisfied = Array.from(node.consumes).filter(\n id => !this.#allProvided.has(id),\n );\n if (unsatisfied.length > 0) {\n unsatisfiedDependencies.push({ value: node.value, unsatisfied });\n }\n }\n return unsatisfiedDependencies;\n }\n\n /**\n * Detect the first circular dependency within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n detectCircularDependency(): T[] | undefined {\n return this.detectCircularDependencies().next().value;\n }\n\n /**\n * Detect circular dependencies within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n *detectCircularDependencies(): Generator<T[], undefined> {\n const cycleKeys = CycleKeySet.from(this.#nodes);\n\n for (const startNode of this.#nodes) {\n const visited = new Set<Node<T>>();\n const stack = new Array<[node: Node<T>, path: T[]]>([\n startNode,\n [startNode.value],\n ]);\n\n while (stack.length > 0) {\n const [node, path] = stack.pop()!;\n if (visited.has(node)) {\n continue;\n }\n visited.add(node);\n for (const consumed of node.consumes) {\n const providerNodes = this.#nodes.filter(other =>\n other.provides.has(consumed),\n );\n for (const provider of providerNodes) {\n if (provider === startNode) {\n if (cycleKeys.tryAdd(path)) {\n yield [...path, startNode.value];\n }\n\n break;\n }\n if (!visited.has(provider)) {\n stack.push([provider, [...path, provider.value]]);\n }\n }\n }\n }\n }\n return undefined;\n }\n\n /**\n * Traverses the dependency graph in topological order, calling the provided\n * function for each node and waiting for it to resolve.\n *\n * The nodes are traversed in parallel, but in such a way that no node is\n * visited before all of its dependencies.\n *\n * Dependencies of nodes that are not produced by any other nodes will be ignored.\n */\n async parallelTopologicalTraversal<TResult>(\n fn: (value: T) => Promise<TResult>,\n ): Promise<TResult[]> {\n const allProvided = this.#allProvided;\n const producedSoFar = new Set<string>();\n const waiting = new Set(this.#nodes.values());\n const visited = new Set<Node<T>>();\n const results = new Array<TResult>();\n let inFlight = 0; // Keep track of how many callbacks are in flight, so that we know if we got stuck\n\n // Find all nodes that have no dependencies that have not already been produced by visited nodes\n async function processMoreNodes() {\n if (waiting.size === 0) {\n return;\n }\n const nodesToProcess = [];\n for (const node of waiting) {\n let ready = true;\n for (const consumed of node.consumes) {\n if (allProvided.has(consumed) && !producedSoFar.has(consumed)) {\n ready = false;\n continue;\n }\n }\n if (ready) {\n nodesToProcess.push(node);\n }\n }\n\n for (const node of nodesToProcess) {\n waiting.delete(node);\n }\n\n if (nodesToProcess.length === 0 && inFlight === 0) {\n // We expect the caller to check for circular dependencies before\n // traversal, so this error should never happen\n throw new Error('Circular dependency detected');\n }\n\n await Promise.all(nodesToProcess.map(processNode));\n }\n\n // Process an individual node, and then add its produced dependencies to the set of available products\n async function processNode(node: Node<T>) {\n visited.add(node);\n inFlight += 1;\n\n const result = await fn(node.value);\n results.push(result);\n\n node.provides.forEach(produced => producedSoFar.add(produced));\n inFlight -= 1;\n await processMoreNodes();\n }\n\n await processMoreNodes();\n\n return results;\n }\n}\n","/*\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 {\n ServiceFactory,\n ServiceRef,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConflictError, stringifyError } from '@backstage/errors';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';\nimport { DependencyGraph } from '../lib/DependencyGraph';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef = ServiceRef<unknown> & {\n __defaultFactory?: (\n service: ServiceRef<unknown>,\n ) => Promise<ServiceFactory | (() => ServiceFactory)>;\n};\n\nfunction toInternalServiceFactory<TService, TScope extends 'plugin' | 'root'>(\n factory: ServiceFactory<TService, TScope>,\n): InternalServiceFactory<TService, TScope> {\n const f = factory as InternalServiceFactory<TService, TScope>;\n if (f.$$type !== '@backstage/BackendFeature') {\n throw new Error(`Invalid service factory, bad type '${f.$$type}'`);\n }\n if (f.version !== 'v1') {\n throw new Error(`Invalid service factory, bad version '${f.version}'`);\n }\n return f;\n}\n\nfunction createPluginMetadataServiceFactory(pluginId: string) {\n return createServiceFactory({\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => ({ getId: () => pluginId }),\n });\n}\n\nexport class ServiceRegistry {\n static create(factories: Array<ServiceFactory>): ServiceRegistry {\n const factoryMap = new Map<string, InternalServiceFactory[]>();\n for (const factory of factories) {\n if (factory.service.multiton) {\n const existing = factoryMap.get(factory.service.id) ?? [];\n factoryMap.set(\n factory.service.id,\n existing.concat(toInternalServiceFactory(factory)),\n );\n } else {\n factoryMap.set(factory.service.id, [toInternalServiceFactory(factory)]);\n }\n }\n const registry = new ServiceRegistry(factoryMap);\n registry.checkForCircularDeps();\n return registry;\n }\n\n readonly #providedFactories: Map<string, InternalServiceFactory[]>;\n readonly #loadedDefaultFactories: Map<\n Function,\n Promise<InternalServiceFactory>\n >;\n readonly #implementations: Map<\n InternalServiceFactory,\n {\n context: Promise<unknown>;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n readonly #rootServiceImplementations = new Map<\n InternalServiceFactory,\n Promise<unknown>\n >();\n readonly #addedFactoryIds = new Set<string>();\n readonly #instantiatedFactories = new Set<string>();\n\n private constructor(factories: Map<string, InternalServiceFactory[]>) {\n this.#providedFactories = factories;\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<InternalServiceFactory[]> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve([\n toInternalServiceFactory(createPluginMetadataServiceFactory(pluginId)),\n ]);\n }\n\n let resolvedFactory:\n | Promise<InternalServiceFactory[]>\n | InternalServiceFactory[]\n | undefined = this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } = ref as InternalServiceRef;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n toInternalServiceFactory(typeof f === 'function' ? f() : f),\n );\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.then(\n factory => [factory],\n error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n },\n );\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #checkForMissingDeps(factory: InternalServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n if (ref.multiton) {\n return false;\n }\n\n return !(ref as InternalServiceRef).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n checkForCircularDeps(): void {\n const graph = DependencyGraph.fromIterable(\n Array.from(this.#providedFactories).map(([serviceId, factories]) => ({\n value: serviceId,\n provides: [serviceId],\n consumes: factories.flatMap(factory =>\n Object.values(factory.deps).map(d => d.id),\n ),\n })),\n );\n const circularDependencies = Array.from(graph.detectCircularDependencies());\n\n if (circularDependencies.length) {\n const cycles = circularDependencies\n .map(c => c.map(id => `'${id}'`).join(' -> '))\n .join('\\n ');\n\n throw new ConflictError(`Circular dependencies detected:\\n ${cycles}`);\n }\n }\n\n add(factory: ServiceFactory) {\n const factoryId = factory.service.id;\n if (factoryId === coreServices.pluginMetadata.id) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n if (this.#instantiatedFactories.has(factoryId)) {\n throw new Error(\n `Unable to set service factory with id ${factoryId}, service has already been instantiated`,\n );\n }\n\n if (factory.service.multiton) {\n const newFactories = (\n this.#providedFactories.get(factoryId) ?? []\n ).concat(toInternalServiceFactory(factory));\n this.#providedFactories.set(factoryId, newFactories);\n } else {\n if (this.#addedFactoryIds.has(factoryId)) {\n throw new Error(\n `Duplicate service implementations provided for ${factoryId}`,\n );\n }\n\n this.#addedFactoryIds.add(factoryId);\n this.#providedFactories.set(factoryId, [\n toInternalServiceFactory(factory),\n ]);\n }\n }\n\n async initializeEagerServicesWithScope(\n scope: 'root' | 'plugin',\n pluginId: string = 'root',\n ) {\n for (const [factory] of this.#providedFactories.values()) {\n if (factory.service.scope === scope) {\n // Root-scoped services are eager by default, plugin-scoped are lazy by default\n if (scope === 'root' && factory.initialization !== 'lazy') {\n await this.get(factory.service, pluginId);\n } else if (scope === 'plugin' && factory.initialization === 'always') {\n await this.get(factory.service, pluginId);\n }\n }\n }\n }\n\n get<T, TInstances extends 'singleton' | 'multiton'>(\n ref: ServiceRef<T, 'plugin' | 'root', TInstances>,\n pluginId: string,\n ): Promise<TInstances extends 'multiton' ? T[] : T> | undefined {\n this.#instantiatedFactories.add(ref.id);\n\n const resolvedFactory = this.#resolveFactory(ref, pluginId);\n\n if (!resolvedFactory) {\n return ref.multiton\n ? (Promise.resolve([]) as\n | Promise<TInstances extends 'multiton' ? T[] : T>\n | undefined)\n : undefined;\n }\n\n return resolvedFactory\n .then(factories => {\n return Promise.all(\n factories.map(factory => {\n if (factory.service.scope === 'root') {\n let existing = this.#rootServiceImplementations.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), undefined),\n );\n this.#rootServiceImplementations.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n context: Promise.all(rootDeps)\n .then(entries =>\n factory.createRootContext?.(Object.fromEntries(entries)),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.context\n .then(context =>\n Promise.all(allDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), context),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n return result;\n }),\n );\n })\n .then(results => (ref.multiton ? results : results[0]));\n }\n}\n","/*\n * Copyright 2024 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 { RootLoggerService } from '@backstage/backend-plugin-api';\n\nconst LOGGER_INTERVAL_MAX = 60_000;\n\nfunction joinIds(ids: Iterable<string>): string {\n return [...ids].map(id => `'${id}'`).join(', ');\n}\n\nexport function createInitializationLogger(\n pluginIds: string[],\n rootLogger?: RootLoggerService,\n): {\n onPluginStarted(pluginId: string): void;\n onAllStarted(): void;\n} {\n const logger = rootLogger?.child({ type: 'initialization' });\n const starting = new Set(pluginIds);\n const started = new Set<string>();\n\n logger?.info(`Plugin initialization started: ${joinIds(pluginIds)}`);\n\n const getInitStatus = () => {\n let status = '';\n if (started.size > 0) {\n status = `, newly initialized: ${joinIds(started)}`;\n started.clear();\n }\n if (starting.size > 0) {\n status += `, still initializing: ${joinIds(starting)}`;\n }\n return status;\n };\n\n // Periodically log the initialization status with a fibonacci backoff\n let interval = 1000;\n let prevInterval = 0;\n let timeout: NodeJS.Timeout | undefined;\n const onTimeout = () => {\n logger?.info(`Plugin initialization in progress${getInitStatus()}`);\n\n const nextInterval = Math.min(interval + prevInterval, LOGGER_INTERVAL_MAX);\n prevInterval = interval;\n interval = nextInterval;\n\n timeout = setTimeout(onTimeout, nextInterval);\n };\n timeout = setTimeout(onTimeout, interval);\n\n return {\n onPluginStarted(pluginId: string) {\n starting.delete(pluginId);\n started.add(pluginId);\n },\n onAllStarted() {\n logger?.info(`Plugin initialization complete${getInitStatus()}`);\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n },\n };\n}\n","/*\n * Copyright 2024 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 { BackendFeature } from '@backstage/backend-plugin-api';\n\n/** @internal */\nexport function unwrapFeature(\n feature: BackendFeature | { default: BackendFeature },\n): BackendFeature {\n if ('$$type' in feature) {\n return feature;\n }\n\n // This is a workaround where default exports get transpiled to `exports['default'] = ...`\n // in CommonJS modules, which in turn results in a double `{ default: { default: ... } }` nesting\n // when importing using a dynamic import.\n // TODO: This is a broader issue than just this piece of code, and should move away from CommonJS.\n if ('default' in feature) {\n return feature.default;\n }\n\n return feature;\n}\n","/*\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 {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n ServiceFactory,\n LifecycleService,\n RootLifecycleService,\n} from '@backstage/backend-plugin-api';\nimport { ServiceOrExtensionPoint } from './types';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport type {\n InternalBackendFeature,\n InternalBackendFeatureLoader,\n InternalBackendRegistrations,\n} from '../../../backend-plugin-api/src/wiring/types';\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport type { InternalServiceFactory } from '../../../backend-plugin-api/src/services/system/types';\nimport { ForwardedError, ConflictError } from '@backstage/errors';\nimport { featureDiscoveryServiceRef } from '@backstage/backend-plugin-api/alpha';\nimport { DependencyGraph } from '../lib/DependencyGraph';\nimport { ServiceRegistry } from './ServiceRegistry';\nimport { createInitializationLogger } from './createInitializationLogger';\nimport { unwrapFeature } from './helpers';\n\nexport interface BackendRegisterInit {\n consumes: Set<ServiceOrExtensionPoint>;\n provides: Set<ServiceOrExtensionPoint>;\n init: {\n deps: { [name: string]: ServiceOrExtensionPoint };\n func: (deps: { [name: string]: unknown }) => Promise<void>;\n };\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #registrations = new Array<InternalBackendRegistrations>();\n #extensionPoints = new Map<string, { impl: unknown; pluginId: string }>();\n #serviceRegistry: ServiceRegistry;\n #registeredFeatures = new Array<Promise<BackendFeature>>();\n #registeredFeatureLoaders = new Array<InternalBackendFeatureLoader>();\n\n constructor(defaultApiFactories: ServiceFactory[]) {\n this.#serviceRegistry = ServiceRegistry.create([...defaultApiFactories]);\n }\n\n async #getInitDeps(\n deps: { [name: string]: ServiceOrExtensionPoint },\n pluginId: string,\n moduleId?: string,\n ) {\n const result = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(deps)) {\n const ep = this.#extensionPoints.get(ref.id);\n if (ep) {\n if (ep.pluginId !== pluginId) {\n throw new Error(\n `Illegal dependency: Module '${moduleId}' for plugin '${pluginId}' attempted to depend on extension point '${ref.id}' for plugin '${ep.pluginId}'. Extension points can only be used within their plugin's scope.`,\n );\n }\n result.set(name, ep.impl);\n } else {\n const impl = await this.#serviceRegistry.get(\n ref as ServiceRef<unknown>,\n pluginId,\n );\n if (impl) {\n result.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No extension point or service available for the following ref(s): ${missing}`,\n );\n }\n\n return Object.fromEntries(result);\n }\n\n add(feature: BackendFeature | Promise<BackendFeature>) {\n if (this.#startPromise) {\n throw new Error('feature can not be added after the backend has started');\n }\n this.#registeredFeatures.push(Promise.resolve(feature));\n }\n\n #addFeature(feature: BackendFeature) {\n if (isServiceFactory(feature)) {\n this.#serviceRegistry.add(feature);\n } else if (isBackendFeatureLoader(feature)) {\n this.#registeredFeatureLoaders.push(feature);\n } else if (isBackendRegistrations(feature)) {\n this.#registrations.push(feature);\n } else {\n throw new Error(\n `Failed to add feature, invalid feature ${JSON.stringify(feature)}`,\n );\n }\n }\n\n async start(): Promise<void> {\n if (this.#startPromise) {\n throw new Error('Backend has already started');\n }\n\n const exitHandler = async () => {\n process.removeListener('SIGTERM', exitHandler);\n process.removeListener('SIGINT', exitHandler);\n process.removeListener('beforeExit', exitHandler);\n\n try {\n await this.stop();\n process.exit(0);\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n\n process.addListener('SIGTERM', exitHandler);\n process.addListener('SIGINT', exitHandler);\n process.addListener('beforeExit', exitHandler);\n\n this.#startPromise = this.#doStart();\n await this.#startPromise;\n }\n\n async #doStart(): Promise<void> {\n this.#serviceRegistry.checkForCircularDeps();\n\n for (const feature of this.#registeredFeatures) {\n this.#addFeature(await feature);\n }\n\n const featureDiscovery = await this.#serviceRegistry.get(\n // TODO: Let's leave this in place and remove it once the deprecated service is removed. We can do that post-1.0 since it's alpha\n featureDiscoveryServiceRef,\n 'root',\n );\n\n if (featureDiscovery) {\n const { features } = await featureDiscovery.getBackendFeatures();\n for (const feature of features) {\n this.#addFeature(unwrapFeature(feature));\n }\n this.#serviceRegistry.checkForCircularDeps();\n }\n\n await this.#applyBackendFeatureLoaders(this.#registeredFeatureLoaders);\n\n // Initialize all root scoped services\n await this.#serviceRegistry.initializeEagerServicesWithScope('root');\n\n const pluginInits = new Map<string, BackendRegisterInit>();\n const moduleInits = new Map<string, Map<string, BackendRegisterInit>>();\n\n // Enumerate all registrations\n for (const feature of this.#registrations) {\n for (const r of feature.getRegistrations()) {\n const provides = new Set<ExtensionPoint<unknown>>();\n\n if (r.type === 'plugin' || r.type === 'module') {\n for (const [extRef, extImpl] of r.extensionPoints) {\n if (this.#extensionPoints.has(extRef.id)) {\n throw new Error(\n `ExtensionPoint with ID '${extRef.id}' is already registered`,\n );\n }\n this.#extensionPoints.set(extRef.id, {\n impl: extImpl,\n pluginId: r.pluginId,\n });\n provides.add(extRef);\n }\n }\n\n if (r.type === 'plugin') {\n if (pluginInits.has(r.pluginId)) {\n throw new Error(`Plugin '${r.pluginId}' is already registered`);\n }\n pluginInits.set(r.pluginId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else if (r.type === 'module') {\n let modules = moduleInits.get(r.pluginId);\n if (!modules) {\n modules = new Map();\n moduleInits.set(r.pluginId, modules);\n }\n if (modules.has(r.moduleId)) {\n throw new Error(\n `Module '${r.moduleId}' for plugin '${r.pluginId}' is already registered`,\n );\n }\n modules.set(r.moduleId, {\n provides,\n consumes: new Set(Object.values(r.init.deps)),\n init: r.init,\n });\n } else {\n throw new Error(`Invalid registration type '${(r as any).type}'`);\n }\n }\n }\n\n const allPluginIds = [...pluginInits.keys()];\n\n const initLogger = createInitializationLogger(\n allPluginIds,\n await this.#serviceRegistry.get(coreServices.rootLogger, 'root'),\n );\n\n // All plugins are initialized in parallel\n await Promise.all(\n allPluginIds.map(async pluginId => {\n // Initialize all eager services\n await this.#serviceRegistry.initializeEagerServicesWithScope(\n 'plugin',\n pluginId,\n );\n\n // Modules are initialized before plugins, so that they can provide extension to the plugin\n const modules = moduleInits.get(pluginId);\n if (modules) {\n const tree = DependencyGraph.fromIterable(\n Array.from(modules).map(([moduleId, moduleInit]) => ({\n value: { moduleId, moduleInit },\n // Relationships are reversed at this point since we're only interested in the extension points.\n // If a modules provides extension point A we want it to be initialized AFTER all modules\n // that depend on extension point A, so that they can provide their extensions.\n consumes: Array.from(moduleInit.provides).map(p => p.id),\n provides: Array.from(moduleInit.consumes).map(c => c.id),\n })),\n );\n const circular = tree.detectCircularDependency();\n if (circular) {\n throw new ConflictError(\n `Circular dependency detected for modules of plugin '${pluginId}', ${circular\n .map(({ moduleId }) => `'${moduleId}'`)\n .join(' -> ')}`,\n );\n }\n await tree.parallelTopologicalTraversal(\n async ({ moduleId, moduleInit }) => {\n const moduleDeps = await this.#getInitDeps(\n moduleInit.init.deps,\n pluginId,\n moduleId,\n );\n await moduleInit.init.func(moduleDeps).catch(error => {\n throw new ForwardedError(\n `Module '${moduleId}' for plugin '${pluginId}' startup failed`,\n error,\n );\n });\n },\n );\n }\n\n // Once all modules have been initialized, we can initialize the plugin itself\n const pluginInit = pluginInits.get(pluginId);\n // We allow modules to be installed without the accompanying plugin, so the plugin may not exist\n if (pluginInit) {\n const pluginDeps = await this.#getInitDeps(\n pluginInit.init.deps,\n pluginId,\n );\n await pluginInit.init.func(pluginDeps).catch(error => {\n throw new ForwardedError(\n `Plugin '${pluginId}' startup failed`,\n error,\n );\n });\n }\n\n initLogger.onPluginStarted(pluginId);\n\n // Once the plugin and all modules have been initialized, we can signal that the plugin has stared up successfully\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.startup();\n }),\n );\n\n // Once all plugins and modules have been initialized, we can signal that the backend has started up successfully\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.startup();\n\n initLogger.onAllStarted();\n\n // Once the backend is started, any uncaught errors or unhandled rejections are caught\n // and logged, in order to avoid crashing the entire backend on local failures.\n if (process.env.NODE_ENV !== 'test') {\n const rootLogger = await this.#serviceRegistry.get(\n coreServices.rootLogger,\n 'root',\n );\n process.on('unhandledRejection', (reason: Error) => {\n rootLogger\n ?.child({ type: 'unhandledRejection' })\n ?.error('Unhandled rejection', reason);\n });\n process.on('uncaughtException', error => {\n rootLogger\n ?.child({ type: 'uncaughtException' })\n ?.error('Uncaught exception', error);\n });\n }\n }\n\n async stop(): Promise<void> {\n if (!this.#startPromise) {\n return;\n }\n\n try {\n await this.#startPromise;\n } catch (error) {\n // The startup failed, but we may still want to do cleanup so we continue silently\n }\n\n const lifecycleService = await this.#getRootLifecycleImpl();\n await lifecycleService.shutdown();\n }\n\n // Bit of a hacky way to grab the lifecycle services, potentially find a nicer way to do this\n async #getRootLifecycleImpl(): Promise<\n RootLifecycleService & {\n startup(): Promise<void>;\n shutdown(): Promise<void>;\n }\n > {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.rootLifecycle,\n 'root',\n );\n\n const service = lifecycleService as any;\n if (\n service &&\n typeof service.startup === 'function' &&\n typeof service.shutdown === 'function'\n ) {\n return service;\n }\n\n throw new Error('Unexpected root lifecycle service implementation');\n }\n\n async #getPluginLifecycleImpl(\n pluginId: string,\n ): Promise<LifecycleService & { startup(): Promise<void> }> {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.lifecycle,\n pluginId,\n );\n\n const service = lifecycleService as any;\n if (service && typeof service.startup === 'function') {\n return service;\n }\n\n throw new Error('Unexpected plugin lifecycle service implementation');\n }\n\n async #applyBackendFeatureLoaders(loaders: InternalBackendFeatureLoader[]) {\n for (const loader of loaders) {\n const deps = new Map<string, unknown>();\n const missingRefs = new Set<ServiceOrExtensionPoint>();\n\n for (const [name, ref] of Object.entries(loader.deps ?? {})) {\n if (ref.scope !== 'root') {\n throw new Error(\n `Feature loaders can only depend on root scoped services, but '${name}' is scoped to '${ref.scope}'. Offending loader is ${loader.description}`,\n );\n }\n const impl = await this.#serviceRegistry.get(\n ref as ServiceRef<unknown>,\n 'root',\n );\n if (impl) {\n deps.set(name, impl);\n } else {\n missingRefs.add(ref);\n }\n }\n\n if (missingRefs.size > 0) {\n const missing = Array.from(missingRefs).join(', ');\n throw new Error(\n `No service available for the following ref(s): ${missing}, depended on by feature loader ${loader.description}`,\n );\n }\n\n const result = await loader\n .loader(Object.fromEntries(deps))\n .then(features => features.map(unwrapFeature))\n .catch(error => {\n throw new ForwardedError(\n `Feature loader ${loader.description} failed`,\n error,\n );\n });\n\n let didAddServiceFactory = false;\n const newLoaders = new Array<InternalBackendFeatureLoader>();\n\n for await (const feature of result) {\n if (isBackendFeatureLoader(feature)) {\n newLoaders.push(feature);\n } else {\n didAddServiceFactory ||= isServiceFactory(feature);\n this.#addFeature(feature);\n }\n }\n\n // Every time we add a new service factory we need to make sure that we don't have circular dependencies\n if (didAddServiceFactory) {\n this.#serviceRegistry.checkForCircularDeps();\n }\n\n // Apply loaders recursively, depth-first\n if (newLoaders.length > 0) {\n await this.#applyBackendFeatureLoaders(newLoaders);\n }\n }\n }\n}\n\nfunction toInternalBackendFeature(\n feature: BackendFeature,\n): InternalBackendFeature {\n if (feature.$$type !== '@backstage/BackendFeature') {\n throw new Error(`Invalid BackendFeature, bad type '${feature.$$type}'`);\n }\n const internal = feature as InternalBackendFeature;\n if (internal.version !== 'v1') {\n throw new Error(\n `Invalid BackendFeature, bad version '${internal.version}'`,\n );\n }\n return internal;\n}\n\nfunction isServiceFactory(\n feature: BackendFeature,\n): feature is InternalServiceFactory {\n const internal = toInternalBackendFeature(feature);\n if (internal.featureType === 'service') {\n return true;\n }\n // Backwards compatibility for v1 registrations that use duck typing\n return 'service' in internal;\n}\n\nfunction isBackendRegistrations(\n feature: BackendFeature,\n): feature is InternalBackendRegistrations {\n const internal = toInternalBackendFeature(feature);\n if (internal.featureType === 'registrations') {\n return true;\n }\n // Backwards compatibility for v1 registrations that use duck typing\n return 'getRegistrations' in internal;\n}\n\nfunction isBackendFeatureLoader(\n feature: BackendFeature,\n): feature is InternalBackendFeatureLoader {\n return toInternalBackendFeature(feature).featureType === 'loader';\n}\n","/*\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 { BackendFeature, ServiceFactory } from '@backstage/backend-plugin-api';\nimport { BackendInitializer } from './BackendInitializer';\nimport { unwrapFeature } from './helpers';\nimport { Backend } from './types';\n\nexport class BackstageBackend implements Backend {\n #initializer: BackendInitializer;\n\n constructor(defaultServiceFactories: ServiceFactory[]) {\n this.#initializer = new BackendInitializer(defaultServiceFactories);\n }\n\n add(feature: BackendFeature | Promise<{ default: BackendFeature }>): void {\n if (isPromise(feature)) {\n this.#initializer.add(feature.then(f => unwrapFeature(f.default)));\n } else {\n this.#initializer.add(unwrapFeature(feature));\n }\n }\n\n async start(): Promise<void> {\n await this.#initializer.start();\n }\n\n async stop(): Promise<void> {\n await this.#initializer.stop();\n }\n}\n\nfunction isPromise<T>(value: unknown | Promise<T>): value is Promise<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof value.then === 'function'\n );\n}\n","/*\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 { coreServices } from '@backstage/backend-plugin-api';\nimport { BackstageBackend } from './BackstageBackend';\nimport { Backend, CreateSpecializedBackendOptions } from './types';\n\n/**\n * @public\n */\nexport function createSpecializedBackend(\n options: CreateSpecializedBackendOptions,\n): Backend {\n const exists = new Set<string>();\n const duplicates = new Set<string>();\n for (const { service } of options.defaultServiceFactories) {\n if (exists.has(service.id)) {\n duplicates.add(service.id);\n } else {\n exists.add(service.id);\n }\n }\n if (duplicates.size > 0) {\n const ids = Array.from(duplicates).join(', ');\n throw new Error(`Duplicate service implementations provided for ${ids}`);\n }\n if (exists.has(coreServices.pluginMetadata.id)) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n return new BackstageBackend(options.defaultServiceFactories);\n}\n"],"names":["createServiceFactory","coreServices","stringifyError","ConflictError","featureDiscoveryServiceRef","ForwardedError","lifecycleService"],"mappings":";;;;;;AAuBA,MAAM,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CAAe,EAAE,CAAG,EAAA;AAC9C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,IAAA,EAAOA,6BAAa,CAAA,cAAA,CAAe,EAAE,CAAA,6BAAA,CAAA;AAAA,KACvC,CAAA;AAAA,GACF;AAEA,EAAO,OAAA,IAAI,gBAAiB,CAAA,OAAA,CAAQ,uBAAuB,CAAA,CAAA;AAC7D;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
2
1
|
import { BackendFeature, ServiceFactory } from '@backstage/backend-plugin-api';
|
|
3
2
|
|
|
4
3
|
/**
|
|
@@ -23,30 +22,4 @@ interface CreateSpecializedBackendOptions {
|
|
|
23
22
|
*/
|
|
24
23
|
declare function createSpecializedBackend(options: CreateSpecializedBackendOptions): Backend;
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
* An identity client options object which allows extra configurations
|
|
28
|
-
*
|
|
29
|
-
* @public
|
|
30
|
-
* @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead
|
|
31
|
-
*/
|
|
32
|
-
type IdentityFactoryOptions = {
|
|
33
|
-
issuer?: string;
|
|
34
|
-
/**
|
|
35
|
-
* JWS "alg" (Algorithm) Header Parameter values. Defaults to an array containing just ES256.
|
|
36
|
-
* More info on supported algorithms: https://github.com/panva/jose
|
|
37
|
-
*/
|
|
38
|
-
algorithms?: string[];
|
|
39
|
-
};
|
|
40
|
-
/**
|
|
41
|
-
* @public
|
|
42
|
-
* @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead
|
|
43
|
-
*/
|
|
44
|
-
declare const identityServiceFactory: _backstage_backend_plugin_api.ServiceFactoryCompat<_backstage_backend_plugin_api.IdentityService, "plugin", "singleton", IdentityFactoryOptions>;
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @public
|
|
48
|
-
* @deprecated Please migrate to the new `coreServices.auth`, `coreServices.httpAuth`, and `coreServices.userInfo` services as needed instead
|
|
49
|
-
*/
|
|
50
|
-
declare const tokenManagerServiceFactory: _backstage_backend_plugin_api.ServiceFactoryCompat<_backstage_backend_plugin_api.TokenManagerService, "plugin", "singleton", undefined>;
|
|
51
|
-
|
|
52
|
-
export { type Backend, type CreateSpecializedBackendOptions, type IdentityFactoryOptions, createSpecializedBackend, identityServiceFactory, tokenManagerServiceFactory };
|
|
25
|
+
export { type Backend, type CreateSpecializedBackendOptions, createSpecializedBackend };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/backend-app-api",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0-next.0",
|
|
4
4
|
"description": "Core API used by Backstage backend apps",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "node-library"
|
|
@@ -49,15 +49,14 @@
|
|
|
49
49
|
"test": "backstage-cli package test"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@backstage/backend-common": "^0.
|
|
53
|
-
"@backstage/backend-plugin-api": "^0.
|
|
52
|
+
"@backstage/backend-common": "^0.25.0-next.0",
|
|
53
|
+
"@backstage/backend-plugin-api": "^0.9.0-next.0",
|
|
54
54
|
"@backstage/cli-common": "^0.1.14",
|
|
55
|
-
"@backstage/cli-node": "^0.2.7",
|
|
56
55
|
"@backstage/config": "^1.2.0",
|
|
57
56
|
"@backstage/config-loader": "^1.9.0",
|
|
58
57
|
"@backstage/errors": "^1.2.4",
|
|
59
|
-
"@backstage/plugin-auth-node": "^0.5.0",
|
|
60
|
-
"@backstage/plugin-permission-node": "^0.8.
|
|
58
|
+
"@backstage/plugin-auth-node": "^0.5.2-next.0",
|
|
59
|
+
"@backstage/plugin-permission-node": "^0.8.3-next.0",
|
|
61
60
|
"@backstage/types": "^1.1.1",
|
|
62
61
|
"@manypkg/get-packages": "^1.1.3",
|
|
63
62
|
"compression": "^1.7.4",
|
|
@@ -65,7 +64,6 @@
|
|
|
65
64
|
"cors": "^2.8.5",
|
|
66
65
|
"express": "^4.17.1",
|
|
67
66
|
"express-promise-router": "^4.1.0",
|
|
68
|
-
"fs-extra": "^11.2.0",
|
|
69
67
|
"helmet": "^6.0.0",
|
|
70
68
|
"jose": "^5.0.0",
|
|
71
69
|
"knex": "^3.0.0",
|
|
@@ -86,11 +84,10 @@
|
|
|
86
84
|
"winston-transport": "^4.5.0"
|
|
87
85
|
},
|
|
88
86
|
"devDependencies": {
|
|
89
|
-
"@backstage/backend-defaults": "^0.
|
|
90
|
-
"@backstage/backend-test-utils": "^0.
|
|
91
|
-
"@backstage/cli": "^0.27.0",
|
|
87
|
+
"@backstage/backend-defaults": "^0.5.0-next.0",
|
|
88
|
+
"@backstage/backend-test-utils": "^0.6.0-next.0",
|
|
89
|
+
"@backstage/cli": "^0.27.1-next.0",
|
|
92
90
|
"@types/compression": "^1.7.0",
|
|
93
|
-
"@types/fs-extra": "^11.0.0",
|
|
94
91
|
"@types/http-errors": "^2.0.0",
|
|
95
92
|
"@types/minimist": "^1.2.0",
|
|
96
93
|
"@types/morgan": "^1.9.0",
|