@backstage/backend-app-api 1.2.6-next.0 → 1.2.6

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 CHANGED
@@ -1,5 +1,12 @@
1
1
  # @backstage/backend-app-api
2
2
 
3
+ ## 1.2.6
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @backstage/backend-plugin-api@1.4.2
9
+
3
10
  ## 1.2.6-next.0
4
11
 
5
12
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"DependencyGraph.cjs.js","sources":["../../src/lib/DependencyGraph.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 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 // This keeps track of a counter of how many providers there are still left\n // to be visited for each dependency. This needs to be a counter instead of\n // a flag for the special case where there are several providers of a given\n // value, even though there may be only one consumer of it.\n const producedRemaining = new Map<string, number>();\n for (const node of this.#nodes) {\n for (const provided of node.provides) {\n producedRemaining.set(\n provided,\n (producedRemaining.get(provided) ?? 0) + 1,\n );\n }\n }\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 (\n allProvided.has(consumed) &&\n producedRemaining.get(consumed) !== 0\n ) {\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 => {\n const remaining = producedRemaining.get(produced);\n if (!remaining) {\n // This should be impossible, if the code that generates the map is correct\n throw new Error(\n `Internal error: Node provided superfluous dependency '${produced}'`,\n );\n }\n producedRemaining.set(produced, remaining - 1);\n });\n\n inFlight -= 1;\n await processMoreNodes();\n }\n\n await processMoreNodes();\n\n return results;\n }\n}\n"],"names":[],"mappings":";;AAuBA,MAAM,IAAQ,CAAA;AAAA,EASJ,WAAA,CACG,KACA,EAAA,QAAA,EACA,QACT,EAAA;AAHS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA;AACR,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;AAAA,KACrD;AAAA;AAQJ;AAGA,MAAM,WAAe,CAAA;AAAA,EACnB,OAAO,KAAQ,KAAuB,EAAA;AACpC,IAAO,OAAA,IAAI,YAAe,KAAK,CAAA;AAAA;AACjC,EAEA,QAAA;AAAA,EACA,UAAA;AAAA,EAEQ,YAAY,KAAuB,EAAA;AACzC,IAAA,IAAA,CAAK,QAAW,GAAA,IAAI,GAAI,CAAA,KAAA,CAAM,GAAI,CAAA,CAAC,C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IAAA,eAAe,YAAY,IAAe,EAAA;AACxC,MAAA,OAAA,CAAQ,IAAI,IAAI,CAAA;AAChB,MAAY,QAAA,IAAA,CAAA;AAEZ,MAAA,MAAM,MAAS,GAAA,MAAM,EAAG,CAAA,IAAA,CAAK,KAAK,CAAA;AAClC,MAAA,OAAA,CAAQ,KAAK,MAAM,CAAA;AAEnB,MAAK,IAAA,CAAA,QAAA,CAAS,QAAQ,CAAY,QAAA,KAAA;AAChC,QAAM,MAAA,SAAA,GAAY,iBAAkB,CAAA,GAAA,CAAI,QAAQ,CAAA;AAChD,QAAA,IAAI,CAAC,SAAW,EAAA;AAEd,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,yDAAyD,QAAQ,CAAA,CAAA;AAAA,WACnE;AAAA;AAEF,QAAkB,iBAAA,CAAA,GAAA,CAAI,QAAU,EAAA,SAAA,GAAY,CAAC,CAAA;AAAA,OAC9C,CAAA;AAED,MAAY,QAAA,IAAA,CAAA;AACZ,MAAA,MAAM,gBAAiB,EAAA;AAAA;AAGzB,IAAA,MAAM,gBAAiB,EAAA;AAEvB,IAAO,OAAA,OAAA;AAAA;AAEX;;;;"}
1
+ {"version":3,"file":"DependencyGraph.cjs.js","sources":["../../src/lib/DependencyGraph.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 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 // This keeps track of a counter of how many providers there are still left\n // to be visited for each dependency. This needs to be a counter instead of\n // a flag for the special case where there are several providers of a given\n // value, even though there may be only one consumer of it.\n const producedRemaining = new Map<string, number>();\n for (const node of this.#nodes) {\n for (const provided of node.provides) {\n producedRemaining.set(\n provided,\n (producedRemaining.get(provided) ?? 0) + 1,\n );\n }\n }\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 (\n allProvided.has(consumed) &&\n producedRemaining.get(consumed) !== 0\n ) {\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 => {\n const remaining = producedRemaining.get(produced);\n if (!remaining) {\n // This should be impossible, if the code that generates the map is correct\n throw new Error(\n `Internal error: Node provided superfluous dependency '${produced}'`,\n );\n }\n producedRemaining.set(produced, remaining - 1);\n });\n\n inFlight -= 1;\n await processMoreNodes();\n }\n\n await processMoreNodes();\n\n return results;\n }\n}\n"],"names":[],"mappings":";;AAuBA,MAAM,IAAA,CAAQ;AAAA,EASJ,WAAA,CACG,KAAA,EACA,QAAA,EACA,QAAA,EACT;AAHS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAAA,EACR;AAAA,EAZH,OAAO,KAAQ,KAAA,EAAqB;AAClC,IAAA,OAAO,IAAI,IAAA;AAAA,MACT,KAAA,CAAM,KAAA;AAAA,MACN,KAAA,CAAM,WAAW,IAAI,GAAA,CAAI,MAAM,QAAQ,CAAA,uBAAQ,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AAA,EAAiB;AAEvB,IAAA,OAAO,OAAA;AAAA,EACT;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"BackendInitializer.cjs.js","sources":["../../src/wiring/BackendInitializer.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n ServiceFactory,\n LifecycleService,\n RootLifecycleService,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\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, assertError } from '@backstage/errors';\nimport {\n instanceMetadataServiceRef,\n BackendFeatureMeta,\n} 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\n/**\n * A registry of backend instances, used to manage process shutdown hooks across all instances.\n */\nconst instanceRegistry = new (class InstanceRegistry {\n #registered = false;\n #instances = new Set<BackendInitializer>();\n\n register(instance: BackendInitializer) {\n if (!this.#registered) {\n this.#registered = true;\n\n process.addListener('SIGTERM', this.#exitHandler);\n process.addListener('SIGINT', this.#exitHandler);\n process.addListener('beforeExit', this.#exitHandler);\n }\n\n this.#instances.add(instance);\n }\n\n unregister(instance: BackendInitializer) {\n this.#instances.delete(instance);\n }\n\n #exitHandler = async () => {\n try {\n const results = await Promise.allSettled(\n Array.from(this.#instances).map(b => b.stop()),\n );\n const errors = results.flatMap(r =>\n r.status === 'rejected' ? [r.reason] : [],\n );\n\n if (errors.length > 0) {\n for (const error of errors) {\n console.error(error);\n }\n process.exit(1);\n } else {\n process.exit(0);\n }\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n})();\n\nfunction createInstanceMetadataServiceFactory(\n registrations: InternalBackendRegistrations[],\n) {\n const installedFeatures = registrations\n .map(registration => {\n if (registration.featureType === 'registrations') {\n return registration\n .getRegistrations()\n .map(feature => {\n if (feature.type === 'plugin') {\n return Object.defineProperty(\n {\n type: 'plugin',\n pluginId: feature.pluginId,\n },\n 'toString',\n {\n enumerable: false,\n configurable: true,\n value: () => `plugin{pluginId=${feature.pluginId}}`,\n },\n );\n } else if (feature.type === 'module') {\n return Object.defineProperty(\n {\n type: 'module',\n pluginId: feature.pluginId,\n moduleId: feature.moduleId,\n },\n 'toString',\n {\n enumerable: false,\n configurable: true,\n value: () =>\n `module{moduleId=${feature.moduleId},pluginId=${feature.pluginId}}`,\n },\n );\n }\n // Ignore unknown feature types.\n return undefined;\n })\n .filter(Boolean) as BackendFeatureMeta[];\n }\n return [];\n })\n .flat();\n return createServiceFactory({\n service: instanceMetadataServiceRef,\n deps: {},\n factory: async () => ({ getInstalledFeatures: () => installedFeatures }),\n });\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #stopPromise?: 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 const target = moduleId\n ? `module '${moduleId}' for plugin '${pluginId}'`\n : `plugin '${pluginId}'`;\n throw new Error(\n `Service or extension point dependencies of ${target} are missing 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 if (this.#stopPromise) {\n throw new Error('Backend has already stopped');\n }\n\n instanceRegistry.register(this);\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 await this.#applyBackendFeatureLoaders(this.#registeredFeatureLoaders);\n\n this.#serviceRegistry.add(\n createInstanceMetadataServiceFactory(this.#registrations),\n );\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 const rootConfig = await this.#serviceRegistry.get(\n coreServices.rootConfig,\n 'root',\n );\n\n // All plugins are initialized in parallel\n const results = await Promise.allSettled(\n allPluginIds.map(async pluginId => {\n const isBootFailurePermitted = this.#getPluginBootFailurePredicate(\n pluginId,\n rootConfig,\n );\n\n try {\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 isModuleBootFailurePermitted =\n this.#getPluginModuleBootFailurePredicate(\n pluginId,\n moduleId,\n rootConfig,\n );\n\n try {\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 } catch (error: unknown) {\n assertError(error);\n if (isModuleBootFailurePermitted) {\n initLogger.onPermittedPluginModuleFailure(\n pluginId,\n moduleId,\n error,\n );\n } else {\n initLogger.onPluginModuleFailed(pluginId, moduleId, error);\n throw 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 } catch (error: unknown) {\n assertError(error);\n if (isBootFailurePermitted) {\n initLogger.onPermittedPluginFailure(pluginId, error);\n } else {\n initLogger.onPluginFailed(pluginId, error);\n throw error;\n }\n }\n }),\n );\n\n const initErrors = results.flatMap(r =>\n r.status === 'rejected' ? [r.reason] : [],\n );\n if (initErrors.length === 1) {\n throw initErrors[0];\n } else if (initErrors.length > 1) {\n // TODO(Rugvip): Seems like there aren't proper types for AggregateError yet\n throw new (AggregateError as any)(initErrors, 'Backend startup failed');\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 // It's fine to call .stop() multiple times, which for example can happen with manual stop + process exit\n async stop(): Promise<void> {\n instanceRegistry.unregister(this);\n\n if (!this.#stopPromise) {\n this.#stopPromise = this.#doStop();\n }\n await this.#stopPromise;\n }\n\n async #doStop(): 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 rootLifecycleService = await this.#getRootLifecycleImpl();\n\n // Root services like the health one need to immediately be notified of the shutdown\n await rootLifecycleService.beforeShutdown();\n\n // Get all plugins.\n const allPlugins = new Set<string>();\n for (const feature of this.#registrations) {\n for (const r of feature.getRegistrations()) {\n if (r.type === 'plugin') {\n allPlugins.add(r.pluginId);\n }\n }\n }\n\n // Iterate through all plugins and run their shutdown hooks.\n await Promise.allSettled(\n [...allPlugins].map(async pluginId => {\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.shutdown();\n }),\n );\n\n // Once all plugin shutdown hooks are done, run root shutdown hooks.\n await rootLifecycleService.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 beforeShutdown(): 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<\n LifecycleService & { startup(): Promise<void>; shutdown(): Promise<void> }\n > {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.lifecycle,\n pluginId,\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 plugin lifecycle service implementation');\n }\n\n async #applyBackendFeatureLoaders(loaders: InternalBackendFeatureLoader[]) {\n const servicesAddedByLoaders = new Map<\n string,\n InternalBackendFeatureLoader\n >();\n\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 // This block makes sure that feature loaders do not provide duplicate\n // implementations for the same service, but at the same time allows\n // service factories provided by feature loaders to be overridden by\n // ones that are explicitly installed with backend.add(serviceFactory).\n //\n // If a factory has already been explicitly installed, the service\n // factory provided by the loader will simply be ignored.\n if (isServiceFactory(feature) && !feature.service.multiton) {\n const conflictingLoader = servicesAddedByLoaders.get(\n feature.service.id,\n );\n if (conflictingLoader) {\n throw new Error(\n `Duplicate service implementations provided for ${feature.service.id} by both feature loader ${loader.description} and feature loader ${conflictingLoader.description}`,\n );\n }\n\n // Check that this service wasn't already explicitly added by backend.add(serviceFactory)\n if (!this.#serviceRegistry.hasBeenAdded(feature.service)) {\n didAddServiceFactory = true;\n servicesAddedByLoaders.set(feature.service.id, loader);\n this.#addFeature(feature);\n }\n } else {\n this.#addFeature(feature);\n }\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 #getPluginBootFailurePredicate(pluginId: string, config?: Config): boolean {\n const defaultStartupBootFailureValue =\n config?.getOptionalString(\n 'backend.startup.default.onPluginBootFailure',\n ) ?? 'abort';\n\n const pluginStartupBootFailureValue =\n config?.getOptionalString(\n `backend.startup.plugins.${pluginId}.onPluginBootFailure`,\n ) ?? defaultStartupBootFailureValue;\n\n return pluginStartupBootFailureValue === 'continue';\n }\n\n #getPluginModuleBootFailurePredicate(\n pluginId: string,\n moduleId: string,\n config?: Config,\n ): boolean {\n const defaultStartupBootFailureValue =\n config?.getOptionalString(\n 'backend.startup.default.onPluginModuleBootFailure',\n ) ?? 'abort';\n\n const pluginModuleStartupBootFailureValue =\n config?.getOptionalString(\n `backend.startup.plugins.${pluginId}.modules.${moduleId}.onPluginModuleBootFailure`,\n ) ?? defaultStartupBootFailureValue;\n\n return pluginModuleStartupBootFailureValue === 'continue';\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"],"names":["createServiceFactory","instanceMetadataServiceRef","ServiceRegistry","createInitializationLogger","coreServices","DependencyGraph","ConflictError","ForwardedError","assertError","lifecycleService","unwrapFeature"],"mappings":";;;;;;;;;;AA2DA,MAAM,gBAAA,GAAmB,IAAK,MAAM,gBAAiB,CAAA;AAAA,EACnD,WAAc,GAAA,KAAA;AAAA,EACd,UAAA,uBAAiB,GAAwB,EAAA;AAAA,EAEzC,SAAS,QAA8B,EAAA;AACrC,IAAI,IAAA,CAAC,KAAK,WAAa,EAAA;AACrB,MAAA,IAAA,CAAK,WAAc,GAAA,IAAA;AAEnB,MAAQ,OAAA,CAAA,WAAA,CAAY,SAAW,EAAA,IAAA,CAAK,YAAY,CAAA;AAChD,MAAQ,OAAA,CAAA,WAAA,CAAY,QAAU,EAAA,IAAA,CAAK,YAAY,CAAA;AAC/C,MAAQ,OAAA,CAAA,WAAA,CAAY,YAAc,EAAA,IAAA,CAAK,YAAY,CAAA;AAAA;AAGrD,IAAK,IAAA,CAAA,UAAA,CAAW,IAAI,QAAQ,CAAA;AAAA;AAC9B,EAEA,WAAW,QAA8B,EAAA;AACvC,IAAK,IAAA,CAAA,UAAA,CAAW,OAAO,QAAQ,CAAA;AAAA;AACjC,EAEA,eAAe,YAAY;AACzB,IAAI,IAAA;AACF,MAAM,MAAA,OAAA,GAAU,MAAM,OAAQ,CAAA,UAAA;AAAA,QAC5B,KAAA,CAAM,KAAK,IAAK,CAAA,UAAU,EAAE,GAAI,CAAA,CAAA,CAAA,KAAK,CAAE,CAAA,IAAA,EAAM;AAAA,OAC/C;AACA,MAAA,MAAM,SAAS,OAAQ,CAAA,OAAA;AAAA,QAAQ,CAAA,CAAA,KAC7B,EAAE,MAAW,KAAA,UAAA,GAAa,CAAC,CAAE,CAAA,MAAM,IAAI;AAAC,O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A;AAAA;AAGT,EAAA,OAAO,SAAa,IAAA,QAAA;AACtB;AAEA,SAAS,uBACP,OACyC,EAAA;AACzC,EAAM,MAAA,QAAA,GAAW,yBAAyB,OAAO,CAAA;AACjD,EAAI,IAAA,QAAA,CAAS,gBAAgB,eAAiB,EAAA;AAC5C,IAAO,OAAA,IAAA;AAAA;AAGT,EAAA,OAAO,kBAAsB,IAAA,QAAA;AAC/B;AAEA,SAAS,uBACP,OACyC,EAAA;AACzC,EAAO,OAAA,wBAAA,CAAyB,OAAO,CAAA,CAAE,WAAgB,KAAA,QAAA;AAC3D;;;;"}
1
+ {"version":3,"file":"BackendInitializer.cjs.js","sources":["../../src/wiring/BackendInitializer.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BackendFeature,\n ExtensionPoint,\n coreServices,\n ServiceRef,\n ServiceFactory,\n LifecycleService,\n RootLifecycleService,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\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, assertError } from '@backstage/errors';\nimport {\n instanceMetadataServiceRef,\n BackendFeatureMeta,\n} 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\n/**\n * A registry of backend instances, used to manage process shutdown hooks across all instances.\n */\nconst instanceRegistry = new (class InstanceRegistry {\n #registered = false;\n #instances = new Set<BackendInitializer>();\n\n register(instance: BackendInitializer) {\n if (!this.#registered) {\n this.#registered = true;\n\n process.addListener('SIGTERM', this.#exitHandler);\n process.addListener('SIGINT', this.#exitHandler);\n process.addListener('beforeExit', this.#exitHandler);\n }\n\n this.#instances.add(instance);\n }\n\n unregister(instance: BackendInitializer) {\n this.#instances.delete(instance);\n }\n\n #exitHandler = async () => {\n try {\n const results = await Promise.allSettled(\n Array.from(this.#instances).map(b => b.stop()),\n );\n const errors = results.flatMap(r =>\n r.status === 'rejected' ? [r.reason] : [],\n );\n\n if (errors.length > 0) {\n for (const error of errors) {\n console.error(error);\n }\n process.exit(1);\n } else {\n process.exit(0);\n }\n } catch (error) {\n console.error(error);\n process.exit(1);\n }\n };\n})();\n\nfunction createInstanceMetadataServiceFactory(\n registrations: InternalBackendRegistrations[],\n) {\n const installedFeatures = registrations\n .map(registration => {\n if (registration.featureType === 'registrations') {\n return registration\n .getRegistrations()\n .map(feature => {\n if (feature.type === 'plugin') {\n return Object.defineProperty(\n {\n type: 'plugin',\n pluginId: feature.pluginId,\n },\n 'toString',\n {\n enumerable: false,\n configurable: true,\n value: () => `plugin{pluginId=${feature.pluginId}}`,\n },\n );\n } else if (feature.type === 'module') {\n return Object.defineProperty(\n {\n type: 'module',\n pluginId: feature.pluginId,\n moduleId: feature.moduleId,\n },\n 'toString',\n {\n enumerable: false,\n configurable: true,\n value: () =>\n `module{moduleId=${feature.moduleId},pluginId=${feature.pluginId}}`,\n },\n );\n }\n // Ignore unknown feature types.\n return undefined;\n })\n .filter(Boolean) as BackendFeatureMeta[];\n }\n return [];\n })\n .flat();\n return createServiceFactory({\n service: instanceMetadataServiceRef,\n deps: {},\n factory: async () => ({ getInstalledFeatures: () => installedFeatures }),\n });\n}\n\nexport class BackendInitializer {\n #startPromise?: Promise<void>;\n #stopPromise?: 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 const target = moduleId\n ? `module '${moduleId}' for plugin '${pluginId}'`\n : `plugin '${pluginId}'`;\n throw new Error(\n `Service or extension point dependencies of ${target} are missing 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 if (this.#stopPromise) {\n throw new Error('Backend has already stopped');\n }\n\n instanceRegistry.register(this);\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 await this.#applyBackendFeatureLoaders(this.#registeredFeatureLoaders);\n\n this.#serviceRegistry.add(\n createInstanceMetadataServiceFactory(this.#registrations),\n );\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 const rootConfig = await this.#serviceRegistry.get(\n coreServices.rootConfig,\n 'root',\n );\n\n // All plugins are initialized in parallel\n const results = await Promise.allSettled(\n allPluginIds.map(async pluginId => {\n const isBootFailurePermitted = this.#getPluginBootFailurePredicate(\n pluginId,\n rootConfig,\n );\n\n try {\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 isModuleBootFailurePermitted =\n this.#getPluginModuleBootFailurePredicate(\n pluginId,\n moduleId,\n rootConfig,\n );\n\n try {\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 } catch (error: unknown) {\n assertError(error);\n if (isModuleBootFailurePermitted) {\n initLogger.onPermittedPluginModuleFailure(\n pluginId,\n moduleId,\n error,\n );\n } else {\n initLogger.onPluginModuleFailed(pluginId, moduleId, error);\n throw 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 } catch (error: unknown) {\n assertError(error);\n if (isBootFailurePermitted) {\n initLogger.onPermittedPluginFailure(pluginId, error);\n } else {\n initLogger.onPluginFailed(pluginId, error);\n throw error;\n }\n }\n }),\n );\n\n const initErrors = results.flatMap(r =>\n r.status === 'rejected' ? [r.reason] : [],\n );\n if (initErrors.length === 1) {\n throw initErrors[0];\n } else if (initErrors.length > 1) {\n // TODO(Rugvip): Seems like there aren't proper types for AggregateError yet\n throw new (AggregateError as any)(initErrors, 'Backend startup failed');\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 // It's fine to call .stop() multiple times, which for example can happen with manual stop + process exit\n async stop(): Promise<void> {\n instanceRegistry.unregister(this);\n\n if (!this.#stopPromise) {\n this.#stopPromise = this.#doStop();\n }\n await this.#stopPromise;\n }\n\n async #doStop(): 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 rootLifecycleService = await this.#getRootLifecycleImpl();\n\n // Root services like the health one need to immediately be notified of the shutdown\n await rootLifecycleService.beforeShutdown();\n\n // Get all plugins.\n const allPlugins = new Set<string>();\n for (const feature of this.#registrations) {\n for (const r of feature.getRegistrations()) {\n if (r.type === 'plugin') {\n allPlugins.add(r.pluginId);\n }\n }\n }\n\n // Iterate through all plugins and run their shutdown hooks.\n await Promise.allSettled(\n [...allPlugins].map(async pluginId => {\n const lifecycleService = await this.#getPluginLifecycleImpl(pluginId);\n await lifecycleService.shutdown();\n }),\n );\n\n // Once all plugin shutdown hooks are done, run root shutdown hooks.\n await rootLifecycleService.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 beforeShutdown(): 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<\n LifecycleService & { startup(): Promise<void>; shutdown(): Promise<void> }\n > {\n const lifecycleService = await this.#serviceRegistry.get(\n coreServices.lifecycle,\n pluginId,\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 plugin lifecycle service implementation');\n }\n\n async #applyBackendFeatureLoaders(loaders: InternalBackendFeatureLoader[]) {\n const servicesAddedByLoaders = new Map<\n string,\n InternalBackendFeatureLoader\n >();\n\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 // This block makes sure that feature loaders do not provide duplicate\n // implementations for the same service, but at the same time allows\n // service factories provided by feature loaders to be overridden by\n // ones that are explicitly installed with backend.add(serviceFactory).\n //\n // If a factory has already been explicitly installed, the service\n // factory provided by the loader will simply be ignored.\n if (isServiceFactory(feature) && !feature.service.multiton) {\n const conflictingLoader = servicesAddedByLoaders.get(\n feature.service.id,\n );\n if (conflictingLoader) {\n throw new Error(\n `Duplicate service implementations provided for ${feature.service.id} by both feature loader ${loader.description} and feature loader ${conflictingLoader.description}`,\n );\n }\n\n // Check that this service wasn't already explicitly added by backend.add(serviceFactory)\n if (!this.#serviceRegistry.hasBeenAdded(feature.service)) {\n didAddServiceFactory = true;\n servicesAddedByLoaders.set(feature.service.id, loader);\n this.#addFeature(feature);\n }\n } else {\n this.#addFeature(feature);\n }\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 #getPluginBootFailurePredicate(pluginId: string, config?: Config): boolean {\n const defaultStartupBootFailureValue =\n config?.getOptionalString(\n 'backend.startup.default.onPluginBootFailure',\n ) ?? 'abort';\n\n const pluginStartupBootFailureValue =\n config?.getOptionalString(\n `backend.startup.plugins.${pluginId}.onPluginBootFailure`,\n ) ?? defaultStartupBootFailureValue;\n\n return pluginStartupBootFailureValue === 'continue';\n }\n\n #getPluginModuleBootFailurePredicate(\n pluginId: string,\n moduleId: string,\n config?: Config,\n ): boolean {\n const defaultStartupBootFailureValue =\n config?.getOptionalString(\n 'backend.startup.default.onPluginModuleBootFailure',\n ) ?? 'abort';\n\n const pluginModuleStartupBootFailureValue =\n config?.getOptionalString(\n `backend.startup.plugins.${pluginId}.modules.${moduleId}.onPluginModuleBootFailure`,\n ) ?? defaultStartupBootFailureValue;\n\n return pluginModuleStartupBootFailureValue === 'continue';\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"],"names":["createServiceFactory","instanceMetadataServiceRef","ServiceRegistry","createInitializationLogger","coreServices","DependencyGraph","ConflictError","ForwardedError","assertError","lifecycleService","unwrapFeature"],"mappings":";;;;;;;;;;AA2DA,MAAM,gBAAA,GAAmB,IAAK,MAAM,gBAAA,CAAiB;AAAA,EACnD,WAAA,GAAc,KAAA;AAAA,EACd,UAAA,uBAAiB,GAAA,EAAwB;AAAA,EAEzC,SAAS,QAAA,EAA8B;AACrC,IAAA,IAAI,CAAC,KAAK,WAAA,EAAa;AACrB,MAAA,IAAA,CAAK,WAAA,GAAc,IAAA;AAEnB,MAAA,OAAA,CAAQ,WAAA,CAAY,SAAA,EAAW,IAAA,CAAK,YAAY,CAAA;AAChD,MAAA,OAAA,CAAQ,WAAA,CAAY,QAAA,EAAU,IAAA,CAAK,YAAY,CAAA;AAC/C,MAAA,OAAA,CAAQ,WAAA,CAAY,YAAA,EAAc,IAAA,CAAK,YAAY,CAAA;AAAA,IACrD;AAEA,IAAA,IAAA,CAAK,UAAA,CAAW,IAAI,QAAQ,CAAA;AAAA,EAC9B;AAAA,EAEA,WAAW,QAAA,EAA8B;AACvC,IAAA,IAAA,CAAK,UAAA,CAAW,OAAO,QAAQ,CAAA;AAAA,EACjC;AAAA,EAEA,eAAe,YAAY;AACzB,IAAA,IAAI;A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;"}
@@ -1 +1 @@
1
- {"version":3,"file":"BackstageBackend.cjs.js","sources":["../../src/wiring/BackstageBackend.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"],"names":["BackendInitializer","unwrapFeature"],"mappings":";;;;;AAqBO,MAAM,gBAAoC,CAAA;AAAA,EAC/C,YAAA;AAAA,EAEA,YAAY,uBAA2C,EAAA;AACrD,IAAK,IAAA,CAAA,YAAA,GAAe,IAAIA,qCAAA,CAAmB,uBAAuB,CAAA;AAAA;AACpE,EAEA,IAAI,OAAsE,EAAA;AACxE,IAAI,IAAA,SAAA,CAAU,OAAO,CAAG,EAAA;AACtB,MAAK,IAAA,CAAA,YAAA,CAAa,IAAI,OAAQ,CAAA,IAAA,CAAK,OAAKC,qBAAc,CAAA,CAAA,CAAE,OAAO,CAAC,CAAC,CAAA;AAAA,KAC5D,MAAA;AACL,MAAA,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIA,qBAAc,CAAA,OAAO,CAAC,CAAA;AAAA;AAC9C;AACF,EAEA,MAAM,KAAuB,GAAA;AAC3B,IAAM,MAAA,IAAA,CAAK,aAAa,KAAM,EAAA;AAAA;AAChC,EAEA,MAAM,IAAsB,GAAA;AAC1B,IAAM,MAAA,IAAA,CAAK,aAAa,IAAK,EAAA;AAAA;AAEjC;AAEA,SAAS,UAAa,KAAkD,EAAA;AACtE,EACE,OAAA,OAAO,UAAU,QACjB,IAAA,KAAA,KAAU,QACV,MAAU,IAAA,KAAA,IACV,OAAO,KAAA,CAAM,IAAS,KAAA,UAAA;AAE1B;;;;"}
1
+ {"version":3,"file":"BackstageBackend.cjs.js","sources":["../../src/wiring/BackstageBackend.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"],"names":["BackendInitializer","unwrapFeature"],"mappings":";;;;;AAqBO,MAAM,gBAAA,CAAoC;AAAA,EAC/C,YAAA;AAAA,EAEA,YAAY,uBAAA,EAA2C;AACrD,IAAA,IAAA,CAAK,YAAA,GAAe,IAAIA,qCAAA,CAAmB,uBAAuB,CAAA;AAAA,EACpE;AAAA,EAEA,IAAI,OAAA,EAAsE;AACxE,IAAA,IAAI,SAAA,CAAU,OAAO,CAAA,EAAG;AACtB,MAAA,IAAA,CAAK,YAAA,CAAa,IAAI,OAAA,CAAQ,IAAA,CAAK,OAAKC,qBAAA,CAAc,CAAA,CAAE,OAAO,CAAC,CAAC,CAAA;AAAA,IACnE,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,YAAA,CAAa,GAAA,CAAIA,qBAAA,CAAc,OAAO,CAAC,CAAA;AAAA,IAC9C;AAAA,EACF;AAAA,EAEA,MAAM,KAAA,GAAuB;AAC3B,IAAA,MAAM,IAAA,CAAK,aAAa,KAAA,EAAM;AAAA,EAChC;AAAA,EAEA,MAAM,IAAA,GAAsB;AAC1B,IAAA,MAAM,IAAA,CAAK,aAAa,IAAA,EAAK;AAAA,EAC/B;AACF;AAEA,SAAS,UAAa,KAAA,EAAkD;AACtE,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,MAAA,IAAU,KAAA,IACV,OAAO,KAAA,CAAM,IAAA,KAAS,UAAA;AAE1B;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceRegistry.cjs.js","sources":["../../src/wiring/ServiceRegistry.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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-relative-monorepo-imports\nimport { InternalServiceFactory } from '../../../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 hasBeenAdded(ref: ServiceRef<any>) {\n if (ref.id === coreServices.pluginMetadata.id) {\n return true;\n }\n return this.#addedFactoryIds.has(ref.id);\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"],"names":["createServiceFactory","coreServices","stringifyError","DependencyGraph","ConflictError"],"mappings":";;;;;;AAqCA,SAAS,yBACP,OAC0C,EAAA;AAC1C,EAAA,MAAM,CAAI,GAAA,OAAA;AACV,EAAI,IAAA,CAAA,CAAE,WAAW,2BAA6B,EAAA;AAC5C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,CAAA,CAAE,MAAM,CAAG,CAAA,CAAA,CAAA;AAAA;AAEnE,EAAI,IAAA,CAAA,CAAE,YAAY,IAAM,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAyC,sCAAA,EAAA,CAAA,CAAE,OAAO,CAAG,CAAA,CAAA,CAAA;AAAA;AAEvE,EAAO,OAAA,CAAA;AACT;AAEA,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U,MAAM,CAAA;AAAA;AAE9C,UAAO,OAAA,MAAA;AAAA,SACR;AAAA,OACH;AAAA,KACD,EACA,IAAK,CAAA,CAAA,OAAA,KAAY,IAAI,QAAW,GAAA,OAAA,GAAU,OAAQ,CAAA,CAAC,CAAE,CAAA;AAAA;AAE5D;;;;"}
1
+ {"version":3,"file":"ServiceRegistry.cjs.js","sources":["../../src/wiring/ServiceRegistry.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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-relative-monorepo-imports\nimport { InternalServiceFactory } from '../../../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 hasBeenAdded(ref: ServiceRef<any>) {\n if (ref.id === coreServices.pluginMetadata.id) {\n return true;\n }\n return this.#addedFactoryIds.has(ref.id);\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"],"names":["createServiceFactory","coreServices","stringifyError","DependencyGraph","ConflictError"],"mappings":";;;;;;AAqCA,SAAS,yBACP,OAAA,EAC0C;AAC1C,EAAA,MAAM,CAAA,GAAI,OAAA;AACV,EAAA,IAAI,CAAA,CAAE,WAAW,2BAAA,EAA6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AA,YAChD;AAEA,YAAA,MAAA,GAAS,eAAe,OAAA,CACrB,IAAA;AAAA,cAAK,CAAA,OAAA,KACJ,OAAA,CAAQ,GAAA,CAAI,OAAO,CAAA,CAAE,IAAA;AAAA,gBAAK,aACxB,OAAA,CAAQ,OAAA,CAAQ,OAAO,WAAA,CAAY,OAAO,GAAG,OAAO;AAAA;AACtD,aACF,CACC,MAAM,CAAA,KAAA,KAAS;AACd,cAAA,MAAM,KAAA,GAAQA,sBAAe,KAAK,CAAA;AAClC,cAAA,MAAM,IAAI,KAAA;AAAA,gBACR,kCAAkC,GAAA,CAAI,EAAE,CAAA,OAAA,EAAU,QAAQ,kDAAkD,KAAK,CAAA;AAAA,eACnH;AAAA,YACF,CAAC,CAAA;AACH,YAAA,cAAA,CAAe,QAAA,CAAS,GAAA,CAAI,QAAA,EAAU,MAAM,CAAA;AAAA,UAC9C;AACA,UAAA,OAAO,MAAA;AAAA,QACT,CAAC;AAAA,OACH;AAAA,IACF,CAAC,EACA,IAAA,CAAK,CAAA,OAAA,KAAY,IAAI,QAAA,GAAW,OAAA,GAAU,OAAA,CAAQ,CAAC,CAAE,CAAA;AAAA,EAC1D;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"createInitializationLogger.cjs.js","sources":["../../src/wiring/createInitializationLogger.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 { 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 onPluginFailed(pluginId: string, error: Error): void;\n onPermittedPluginFailure(pluginId: string, error: Error): void;\n onPluginModuleFailed(pluginId: string, moduleId: string, error: Error): void;\n onPermittedPluginModuleFailure(\n pluginId: string,\n moduleId: string,\n error: Error,\n ): 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 onPluginFailed(pluginId: string, error: Error) {\n starting.delete(pluginId);\n const status =\n starting.size > 0\n ? `, waiting for ${starting.size} other plugins to finish before shutting down the process`\n : '';\n logger?.error(\n `Plugin '${pluginId}' threw an error during startup${status}.`,\n error,\n );\n },\n onPermittedPluginFailure(pluginId: string, error: Error) {\n starting.delete(pluginId);\n logger?.error(\n `Plugin '${pluginId}' threw an error during startup, but boot failure is permitted for this plugin so startup will continue.`,\n error,\n );\n },\n onPluginModuleFailed(pluginId: string, moduleId: string, error: Error) {\n const status =\n starting.size > 0\n ? `, waiting for ${starting.size} other plugins to finish before shutting down the process`\n : '';\n logger?.error(\n `Module ${moduleId} in Plugin '${pluginId}' threw an error during startup${status}.`,\n error,\n );\n },\n onPermittedPluginModuleFailure(\n pluginId: string,\n moduleId: string,\n error: Error,\n ) {\n logger?.error(\n `Module ${moduleId} in Plugin '${pluginId}' threw an error during startup, but boot failure is permitted for this plugin module so startup will continue.`,\n error,\n );\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"],"names":[],"mappings":";;AAkBA,MAAM,mBAAsB,GAAA,GAAA;AAE5B,SAAS,QAAQ,GAA+B,EAAA;AAC9C,EAAO,OAAA,CAAC,GAAG,GAAG,CAAE,CAAA,GAAA,CAAI,CAAM,EAAA,KAAA,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA,CAAG,CAAE,CAAA,IAAA,CAAK,IAAI,CAAA;AAChD;AAEgB,SAAA,0BAAA,CACd,WACA,UAYA,EAAA;AACA,EAAA,MAAM,SAAS,UAAY,EAAA,KAAA,CAAM,EAAE,IAAA,EAAM,kBAAkB,CAAA;AAC3D,EAAM,MAAA,QAAA,GAAW,IAAI,GAAA,CAAI,SAAS,CAAA;AAClC,EAAM,MAAA,OAAA,uBAAc,GAAY,EAAA;AAEhC,EAAA,MAAA,EAAQ,IAAK,CAAA,CAAA,+BAAA,EAAkC,OAAQ,CAAA,SAAS,CAAC,CAAE,CAAA,CAAA;AAEnE,EAAA,MAAM,gBAAgB,MAAM;AAC1B,IAAA,IAAI,MAAS,GAAA,EAAA;AACb,IAAI,IAAA,OAAA,CAAQ,OAAO,CAAG,EAAA;AACpB,MAAS,MAAA,GAAA,CAAA,qBAAA,EAAwB,OAAQ,CAAA,OAAO,CAAC,CAAA,CAAA;AACjD,MAAA,OAAA,CAAQ,KAAM,EAAA;AAAA;AAEhB,IAAI,IAAA,QAAA,CAAS,OAAO,CAAG,EAAA;AACrB,MAAU,MAAA,IAAA,CAAA,sBAAA,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CAAA;AAAA,QACnB;AAAA,OACF;AAAA,KACF;AAAA,IACA,oBAAA,CAAqB,QAAkB,EAAA,QAAA,EAAkB,KAAc,EAAA;AACrE,MAAA,MAAM,SACJ,QAAS,CAAA,IAAA,GAAO,IACZ,CAAiB,cAAA,EAAA,QAAA,CAAS,IAAI,CAC9B,yDAAA,CAAA,GAAA,EAAA;AACN,MAAQ,MAAA,EAAA,KAAA;AAAA,QACN,CAAU,OAAA,EAAA,QAAQ,CAAe,YAAA,EAAA,QAAQ,kCAAkC,MAAM,CAAA,CAAA,CAAA;AAAA,QACjF;AAAA,OACF;AAAA,KACF;AAAA,IACA,8BAAA,CACE,QACA,EAAA,QAAA,EACA,KACA,EAAA;AACA,MAAQ,MAAA,EAAA,KAAA;AAAA,QACN,CAAA,OAAA,EAAU,QAAQ,CAAA,YAAA,EAAe,QAAQ,CAAA,+GAAA,CAAA;AAAA,QACzC;AAAA,OACF;AAAA,KACF;AAAA,IACA,YAAe,GAAA;AACb,MAAA,MAAA,EAAQ,IAAK,CAAA,CAAA,8BAAA,EAAiC,aAAc,EAAC,CAAE,CAAA,CAAA;AAE/D,MAAA,IAAI,OAAS,EAAA;AACX,QAAA,YAAA,CAAa,OAAO,CAAA;AACpB,QAAU,OAAA,GAAA,KAAA,CAAA;AAAA;AACZ;AACF,GACF;AACF;;;;"}
1
+ {"version":3,"file":"createInitializationLogger.cjs.js","sources":["../../src/wiring/createInitializationLogger.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 { 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 onPluginFailed(pluginId: string, error: Error): void;\n onPermittedPluginFailure(pluginId: string, error: Error): void;\n onPluginModuleFailed(pluginId: string, moduleId: string, error: Error): void;\n onPermittedPluginModuleFailure(\n pluginId: string,\n moduleId: string,\n error: Error,\n ): 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 onPluginFailed(pluginId: string, error: Error) {\n starting.delete(pluginId);\n const status =\n starting.size > 0\n ? `, waiting for ${starting.size} other plugins to finish before shutting down the process`\n : '';\n logger?.error(\n `Plugin '${pluginId}' threw an error during startup${status}.`,\n error,\n );\n },\n onPermittedPluginFailure(pluginId: string, error: Error) {\n starting.delete(pluginId);\n logger?.error(\n `Plugin '${pluginId}' threw an error during startup, but boot failure is permitted for this plugin so startup will continue.`,\n error,\n );\n },\n onPluginModuleFailed(pluginId: string, moduleId: string, error: Error) {\n const status =\n starting.size > 0\n ? `, waiting for ${starting.size} other plugins to finish before shutting down the process`\n : '';\n logger?.error(\n `Module ${moduleId} in Plugin '${pluginId}' threw an error during startup${status}.`,\n error,\n );\n },\n onPermittedPluginModuleFailure(\n pluginId: string,\n moduleId: string,\n error: Error,\n ) {\n logger?.error(\n `Module ${moduleId} in Plugin '${pluginId}' threw an error during startup, but boot failure is permitted for this plugin module so startup will continue.`,\n error,\n );\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"],"names":[],"mappings":";;AAkBA,MAAM,mBAAA,GAAsB,GAAA;AAE5B,SAAS,QAAQ,GAAA,EAA+B;AAC9C,EAAA,OAAO,CAAC,GAAG,GAAG,CAAA,CAAE,GAAA,CAAI,CAAA,EAAA,KAAM,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA;AAChD;AAEO,SAAS,0BAAA,CACd,WACA,UAAA,EAYA;AACA,EAAA,MAAM,SAAS,UAAA,EAAY,KAAA,CAAM,EAAE,IAAA,EAAM,kBAAkB,CAAA;AAC3D,EAAA,MAAM,QAAA,GAAW,IAAI,GAAA,CAAI,SAAS,CAAA;AAClC,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAY;AAEhC,EAAA,MAAA,EAAQ,IAAA,CAAK,CAAA,+BAAA,EAAkC,OAAA,CAAQ,SAAS,CAAC,CAAA,CAAE,CAAA;AAEnE,EAAA,MAAM,gBAAgB,MAAM;AAC1B,IAAA,IAAI,MAAA,GAAS,EAAA;AACb,IAAA,IAAI,OAAA,CAAQ,OAAO,CAAA,EAAG;AACpB,MAAA,MAAA,GAAS,CAAA,qBAAA,EAAwB,OAAA,CAAQ,OAAO,CAAC,CAAA,CAAA;AACjD,MAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,IAChB;A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ACvD,MAAA,QAAA,CAAS,OAAO,QAAQ,CAAA;AACxB,MAAA,MAAA,EAAQ,KAAA;AAAA,QACN,WAAW,QAAQ,CAAA,wGAAA,CAAA;AAAA,QACnB;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,oBAAA,CAAqB,QAAA,EAAkB,QAAA,EAAkB,KAAA,EAAc;AACrE,MAAA,MAAM,SACJ,QAAA,CAAS,IAAA,GAAO,IACZ,CAAA,cAAA,EAAiB,QAAA,CAAS,IAAI,CAAA,yDAAA,CAAA,GAC9B,EAAA;AACN,MAAA,MAAA,EAAQ,KAAA;AAAA,QACN,CAAA,OAAA,EAAU,QAAQ,CAAA,YAAA,EAAe,QAAQ,kCAAkC,MAAM,CAAA,CAAA,CAAA;AAAA,QACjF;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,8BAAA,CACE,QAAA,EACA,QAAA,EACA,KAAA,EACA;AACA,MAAA,MAAA,EAAQ,KAAA;AAAA,QACN,CAAA,OAAA,EAAU,QAAQ,CAAA,YAAA,EAAe,QAAQ,CAAA,+GAAA,CAAA;AAAA,QACzC;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,YAAA,GAAe;AACb,MAAA,MAAA,EAAQ,IAAA,CAAK,CAAA,8BAAA,EAAiC,aAAA,EAAe,CAAA,CAAE,CAAA;AAE/D,MAAA,IAAI,OAAA,EAAS;AACX,QAAA,YAAA,CAAa,OAAO,CAAA;AACpB,QAAA,OAAA,GAAU,MAAA;AAAA,MACZ;AAAA,IACF;AAAA,GACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"createSpecializedBackend.cjs.js","sources":["../../src/wiring/createSpecializedBackend.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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":["coreServices","BackstageBackend"],"mappings":";;;;;AAuBO,SAAS,yBACd,OACS,EAAA;AACT,EAAM,MAAA,MAAA,uBAAa,GAAY,EAAA;AAC/B,EAAM,MAAA,UAAA,uBAAiB,GAAY,EAAA;AACnC,EAAA,KAAA,MAAW,EAAE,OAAA,EAAa,IAAA,OAAA,CAAQ,uBAAyB,EAAA;AACzD,IAAA,IAAI,MAAO,CAAA,GAAA,CAAI,OAAQ,CAAA,EAAE,CAAG,EAAA;AAC1B,MAAW,UAAA,CAAA,GAAA,CAAI,QAAQ,EAAE,CAAA;AAAA,KACpB,MAAA;AACL,MAAO,MAAA,CAAA,GAAA,CAAI,QAAQ,EAAE,CAAA;AAAA;AACvB;AAEF,EAAI,IAAA,UAAA,CAAW,OAAO,CAAG,EAAA;AACvB,IAAA,MAAM,MAAM,KAAM,CAAA,IAAA,CAAK,UAAU,CAAA,CAAE,KAAK,IAAI,CAAA;AAC5C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAkD,+CAAA,EAAA,GAAG,CAAE,CAAA,CAAA;AAAA;AAEzE,EAAA,IAAI,MAAO,CAAA,GAAA,CAAIA,6BAAa,CAAA,cAAA,CAAe,EAAE,CAAG,EAAA;AAC9C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,IAAA,EAAOA,6BAAa,CAAA,cAAA,CAAe,EAAE,CAAA,6BAAA;AAAA,KACvC;AAAA;AAGF,EAAO,OAAA,IAAIC,iCAAiB,CAAA,OAAA,CAAQ,uBAAuB,CAAA;AAC7D;;;;"}
1
+ {"version":3,"file":"createSpecializedBackend.cjs.js","sources":["../../src/wiring/createSpecializedBackend.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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":["coreServices","BackstageBackend"],"mappings":";;;;;AAuBO,SAAS,yBACd,OAAA,EACS;AACT,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAC/B,EAAA,MAAM,UAAA,uBAAiB,GAAA,EAAY;AACnC,EAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,OAAA,CAAQ,uBAAA,EAAyB;AACzD,IAAA,IAAI,MAAA,CAAO,GAAA,CAAI,OAAA,CAAQ,EAAE,CAAA,EAAG;AAC1B,MAAA,UAAA,CAAW,GAAA,CAAI,QAAQ,EAAE,CAAA;AAAA,IAC3B,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,GAAA,CAAI,QAAQ,EAAE,CAAA;AAAA,IACvB;AAAA,EACF;AACA,EAAA,IAAI,UAAA,CAAW,OAAO,CAAA,EAAG;AACvB,IAAA,MAAM,MAAM,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA,CAAE,KAAK,IAAI,CAAA;AAC5C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,+CAAA,EAAkD,GAAG,CAAA,CAAE,CAAA;AAAA,EACzE;AACA,EAAA,IAAI,MAAA,CAAO,GAAA,CAAIA,6BAAA,CAAa,cAAA,CAAe,EAAE,CAAA,EAAG;AAC9C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,IAAA,EAAOA,6BAAA,CAAa,cAAA,CAAe,EAAE,CAAA,6BAAA;AAAA,KACvC;AAAA,EACF;AAEA,EAAA,OAAO,IAAIC,iCAAA,CAAiB,OAAA,CAAQ,uBAAuB,CAAA;AAC7D;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.cjs.js","sources":["../../src/wiring/helpers.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 { 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"],"names":[],"mappings":";;AAmBO,SAAS,cACd,OACgB,EAAA;AAChB,EAAA,IAAI,YAAY,OAAS,EAAA;AACvB,IAAO,OAAA,OAAA;AAAA;AAOT,EAAA,IAAI,aAAa,OAAS,EAAA;AACxB,IAAA,OAAO,OAAQ,CAAA,OAAA;AAAA;AAGjB,EAAO,OAAA,OAAA;AACT;;;;"}
1
+ {"version":3,"file":"helpers.cjs.js","sources":["../../src/wiring/helpers.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 { 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"],"names":[],"mappings":";;AAmBO,SAAS,cACd,OAAA,EACgB;AAChB,EAAA,IAAI,YAAY,OAAA,EAAS;AACvB,IAAA,OAAO,OAAA;AAAA,EACT;AAMA,EAAA,IAAI,aAAa,OAAA,EAAS;AACxB,IAAA,OAAO,OAAA,CAAQ,OAAA;AAAA,EACjB;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/backend-app-api",
3
- "version": "1.2.6-next.0",
3
+ "version": "1.2.6",
4
4
  "description": "Core API used by Backstage backend apps",
5
5
  "backstage": {
6
6
  "role": "node-library"
@@ -50,14 +50,14 @@
50
50
  "test": "backstage-cli package test"
51
51
  },
52
52
  "dependencies": {
53
- "@backstage/backend-plugin-api": "1.4.2-next.0",
54
- "@backstage/config": "1.3.3",
55
- "@backstage/errors": "1.2.7"
53
+ "@backstage/backend-plugin-api": "^1.4.2",
54
+ "@backstage/config": "^1.3.3",
55
+ "@backstage/errors": "^1.2.7"
56
56
  },
57
57
  "devDependencies": {
58
- "@backstage/backend-defaults": "0.11.2-next.0",
59
- "@backstage/backend-test-utils": "1.7.1-next.0",
60
- "@backstage/cli": "0.33.2-next.0"
58
+ "@backstage/backend-defaults": "^0.12.0",
59
+ "@backstage/backend-test-utils": "^1.8.0",
60
+ "@backstage/cli": "^0.34.0"
61
61
  },
62
62
  "configSchema": "config.d.ts"
63
63
  }