Merge pull request #25903 from backstage/rugvip/presets

backend-*-api: add support for feature loaders
This commit is contained in:
Patrik Oldsberg
2024-08-06 14:00:12 +02:00
committed by GitHub
32 changed files with 1207 additions and 405 deletions
@@ -14,7 +14,11 @@
* limitations under the License.
*/
import { createServiceFactory, createServiceRef } from './types';
import {
InternalServiceFactory,
createServiceFactory,
createServiceRef,
} from './types';
const ref = createServiceRef<string>({ id: 'x' });
const rootDep = createServiceRef<number>({ id: 'y', scope: 'root' });
@@ -36,6 +40,10 @@ describe('createServiceFactory', () => {
},
});
expect(metaFactory).toEqual(expect.any(Function));
expect(metaFactory().$$type).toBe('@backstage/BackendFeature');
expect((metaFactory() as InternalServiceFactory).featureType).toBe(
'service',
);
expect(metaFactory().service).toBe(ref);
// @ts-expect-error
@@ -78,6 +78,7 @@ export interface InternalServiceFactory<
TScope extends 'plugin' | 'root' = 'plugin' | 'root',
> extends ServiceFactory<TService, TScope> {
version: 'v1';
featureType: 'service';
initialization?: 'always' | 'lazy';
deps: { [key in string]: ServiceRef<unknown> };
createRootContext?(deps: { [key in string]: unknown }): Promise<unknown>;
@@ -307,6 +308,7 @@ export function createServiceFactory<
return {
$$type: '@backstage/BackendFeature',
version: 'v1',
featureType: 'service',
service: c.service,
initialization: c.initialization,
deps: c.deps,
@@ -322,6 +324,7 @@ export function createServiceFactory<
return {
$$type: '@backstage/BackendFeature',
version: 'v1',
featureType: 'service',
service: c.service,
initialization: c.initialization,
...('createRootContext' in c
@@ -0,0 +1,195 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { coreServices, createServiceFactory } from '../services';
import { InternalServiceFactory } from '../services/system/types';
import { BackendFeature } from '../types';
import { createBackendFeatureLoader } from './createBackendFeatureLoader';
import { createBackendPlugin } from './createBackendPlugin';
import { InternalBackendFeatureLoader } from './types';
describe('createBackendFeatureLoader', () => {
it('should create an empty feature loader', () => {
const result = createBackendFeatureLoader({
deps: {},
loader: () => [],
}) as InternalBackendFeatureLoader;
expect(result.$$type).toEqual('@backstage/BackendFeature');
expect(result.version).toEqual('v1');
expect(result.featureType).toEqual('loader');
expect(result.deps).toEqual({});
expect(result.loader).toEqual(expect.any(Function));
expect(result.description).toMatch(/^created at '.*'$/);
});
it('should create a feature loader that loads a few features', async () => {
const result = createBackendFeatureLoader({
deps: {
config: coreServices.rootConfig,
},
loader({ config: _unused }) {
return [
createBackendPlugin({
pluginId: 'x',
register() {},
})(),
createServiceFactory({
service: coreServices.pluginMetadata,
deps: {},
factory: () => ({ getId: () => 'fake-id' }),
})(),
// Dynamic import format
Promise.resolve({
default: createBackendPlugin({
pluginId: 'y',
register() {},
})(),
}),
];
},
}) as InternalBackendFeatureLoader;
expect(result.$$type).toEqual('@backstage/BackendFeature');
expect(result.version).toEqual('v1');
expect(result.featureType).toEqual('loader');
const results = await result.loader({ config: {} });
expect(results.length).toBe(3);
const [pluginX, serviceFactory, pluginY] = results;
expect(pluginX.$$type).toBe('@backstage/BackendFeature');
expect(serviceFactory.$$type).toBe('@backstage/BackendFeature');
expect(pluginY.$$type).toBe('@backstage/BackendFeature');
expect((serviceFactory as InternalServiceFactory).service.id).toBe(
coreServices.pluginMetadata.id,
);
});
it('should support multiple output formats', async () => {
const feature = createBackendPlugin({ pluginId: 'x', register() {} })();
const dynamicFeature = Promise.resolve({ default: feature });
async function extractResult(f: BackendFeature) {
const internal = f as InternalBackendFeatureLoader;
return internal.loader({});
}
await expect(
extractResult(
createBackendFeatureLoader({
loader() {
return [feature];
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
async loader() {
return [feature];
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
*loader() {
yield feature;
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
async *loader() {
yield feature;
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
loader() {
return [dynamicFeature];
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
async loader() {
return [dynamicFeature];
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
*loader() {
yield dynamicFeature;
},
}),
),
).resolves.toEqual([feature]);
await expect(
extractResult(
createBackendFeatureLoader({
async *loader() {
yield dynamicFeature;
},
}),
),
).resolves.toEqual([feature]);
});
it('should only allow dependencies on root scoped services', () => {
createBackendFeatureLoader({
deps: {
rootLogger: coreServices.rootLogger,
},
loader: () => [],
});
createBackendFeatureLoader({
deps: {
// @ts-expect-error
logger: coreServices.logger,
},
loader: () => [],
});
createBackendFeatureLoader({
deps: {
rootLogger: coreServices.rootLogger,
// @ts-expect-error
logger: coreServices.logger,
},
loader: () => [],
});
expect('test').toBe('test');
});
});
@@ -0,0 +1,68 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ServiceRef } from '../services';
import { BackendFeature } from '../types';
import { describeParentCallSite } from './describeParentCallSite';
import { InternalBackendFeatureLoader } from './types';
/**
* @public
* Options for creating a new backend feature loader.
*/
export interface CreateBackendFeatureLoaderOptions<
TDeps extends { [name in string]: unknown },
> {
deps?: {
[name in keyof TDeps]: ServiceRef<TDeps[name], 'root'>;
};
loader(
deps: TDeps,
):
| Iterable<BackendFeature | Promise<{ default: BackendFeature }>>
| Promise<Iterable<BackendFeature | Promise<{ default: BackendFeature }>>>
| AsyncIterable<BackendFeature | { default: BackendFeature }>;
}
/**
* @public
* Creates a new backend feature loader.
*/
export function createBackendFeatureLoader<
TDeps extends { [name in string]: unknown },
>(options: CreateBackendFeatureLoaderOptions<TDeps>): BackendFeature {
return {
$$type: '@backstage/BackendFeature',
version: 'v1',
featureType: 'loader',
description: `created at '${describeParentCallSite()}'`,
deps: options.deps,
async loader(deps: TDeps) {
const it = await options.loader(deps);
const result = new Array<BackendFeature>();
for await (const item of it) {
if ('$$type' in item && item.$$type === '@backstage/BackendFeature') {
result.push(item);
} else if ('default' in item) {
result.push(item.default);
} else {
throw new Error(`Invalid item "${item}"`);
}
}
return result;
},
} as InternalBackendFeatureLoader;
}
@@ -0,0 +1,57 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createBackendModule } from './createBackendModule';
import { InternalBackendRegistrations } from './types';
describe('createBackendModule', () => {
it('should create a BackendModule', () => {
const result = createBackendModule({
pluginId: 'x',
moduleId: 'y',
register(r) {
r.registerInit({ deps: {}, async init() {} });
},
});
// legacy form
const legacy = result() as unknown as InternalBackendRegistrations;
expect(legacy.$$type).toEqual('@backstage/BackendFeature');
expect(legacy.version).toEqual('v1');
expect(legacy.getRegistrations).toEqual(expect.any(Function));
// new form
const module = result as unknown as InternalBackendRegistrations;
expect(module.$$type).toEqual('@backstage/BackendFeature');
expect(module.version).toEqual('v1');
expect(module.getRegistrations).toEqual(expect.any(Function));
expect(module.getRegistrations()).toEqual([
{
type: 'module',
pluginId: 'x',
moduleId: 'y',
extensionPoints: [],
init: {
deps: expect.any(Object),
func: expect.any(Function),
},
},
]);
// @ts-expect-error
expect(module({ a: 'a' })).toBeDefined();
});
});
@@ -0,0 +1,107 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BackendFeatureCompat } from '../types';
import {
BackendModuleRegistrationPoints,
InternalBackendModuleRegistration,
InternalBackendPluginRegistration,
} from './types';
/**
* The configuration options passed to {@link createBackendModule}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/modules | The architecture of modules}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateBackendModuleOptions {
/**
* Should exactly match the `id` of the plugin that the module extends.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
pluginId: string;
/**
* The ID of this module, used to identify the module and ensure that it is not installed twice.
*/
moduleId: string;
register(reg: BackendModuleRegistrationPoints): void;
}
/**
* Creates a new backend module for a given plugin.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/modules | The architecture of modules}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export function createBackendModule(
options: CreateBackendModuleOptions,
): BackendFeatureCompat {
function getRegistrations() {
const extensionPoints: InternalBackendPluginRegistration['extensionPoints'] =
[];
let init: InternalBackendModuleRegistration['init'] | undefined = undefined;
options.register({
registerExtensionPoint(ext, impl) {
if (init) {
throw new Error('registerExtensionPoint called after registerInit');
}
extensionPoints.push([ext, impl]);
},
registerInit(regInit) {
if (init) {
throw new Error('registerInit must only be called once');
}
init = {
deps: regInit.deps,
func: regInit.init,
};
},
});
if (!init) {
throw new Error(
`registerInit was not called by register in ${options.moduleId} module for ${options.pluginId}`,
);
}
return [
{
type: 'module',
pluginId: options.pluginId,
moduleId: options.moduleId,
extensionPoints,
init,
},
];
}
function backendFeatureCompatWrapper() {
return backendFeatureCompatWrapper;
}
Object.assign(backendFeatureCompatWrapper, {
$$type: '@backstage/BackendFeature' as const,
version: 'v1',
getRegistrations,
});
return backendFeatureCompatWrapper as BackendFeatureCompat;
}
@@ -0,0 +1,55 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createBackendPlugin } from './createBackendPlugin';
import { InternalBackendRegistrations } from './types';
describe('createBackendPlugin', () => {
it('should create a BackendPlugin', () => {
const result = createBackendPlugin({
pluginId: 'x',
register(r) {
r.registerInit({ deps: {}, async init() {} });
},
});
// legacy form
const legacy = result() as unknown as InternalBackendRegistrations;
expect(legacy.$$type).toEqual('@backstage/BackendFeature');
expect(legacy.version).toEqual('v1');
expect(legacy.getRegistrations).toEqual(expect.any(Function));
// new form
const plugin = result as unknown as InternalBackendRegistrations;
expect(plugin.$$type).toEqual('@backstage/BackendFeature');
expect(plugin.version).toEqual('v1');
expect(plugin.getRegistrations).toEqual(expect.any(Function));
expect(plugin.getRegistrations()).toEqual([
{
type: 'plugin',
pluginId: 'x',
extensionPoints: [],
init: {
deps: expect.any(Object),
func: expect.any(Function),
},
},
]);
// @ts-expect-error
expect(plugin({ a: 'a' })).toBeDefined();
});
});
@@ -0,0 +1,100 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BackendFeatureCompat } from '../types';
import {
BackendPluginRegistrationPoints,
InternalBackendPluginRegistration,
} from './types';
/**
* The configuration options passed to {@link createBackendPlugin}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/plugins | The architecture of plugins}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateBackendPluginOptions {
/**
* The ID of this plugin.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
pluginId: string;
register(reg: BackendPluginRegistrationPoints): void;
}
/**
* Creates a new backend plugin.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/plugins | The architecture of plugins}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export function createBackendPlugin(
options: CreateBackendPluginOptions,
): BackendFeatureCompat {
function getRegistrations() {
const extensionPoints: InternalBackendPluginRegistration['extensionPoints'] =
[];
let init: InternalBackendPluginRegistration['init'] | undefined = undefined;
options.register({
registerExtensionPoint(ext, impl) {
if (init) {
throw new Error('registerExtensionPoint called after registerInit');
}
extensionPoints.push([ext, impl]);
},
registerInit(regInit) {
if (init) {
throw new Error('registerInit must only be called once');
}
init = {
deps: regInit.deps,
func: regInit.init,
};
},
});
if (!init) {
throw new Error(
`registerInit was not called by register in ${options.pluginId}`,
);
}
return [
{
type: 'plugin',
pluginId: options.pluginId,
extensionPoints,
init,
},
];
}
function backendFeatureCompatWrapper() {
return backendFeatureCompatWrapper;
}
Object.assign(backendFeatureCompatWrapper, {
$$type: '@backstage/BackendFeature' as const,
version: 'v1',
getRegistrations,
});
return backendFeatureCompatWrapper as BackendFeatureCompat;
}
@@ -0,0 +1,27 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createExtensionPoint } from './createExtensionPoint';
describe('createExtensionPoint', () => {
it('should create an ExtensionPoint', () => {
const extensionPoint = createExtensionPoint({ id: 'x' });
expect(extensionPoint).toBeDefined();
expect(extensionPoint.id).toBe('x');
expect(() => extensionPoint.T).not.toThrow();
expect(String(extensionPoint)).toBe('extensionPoint{x}');
});
});
@@ -0,0 +1,58 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ExtensionPoint } from './types';
/**
* The configuration options passed to {@link createExtensionPoint}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/extension-points | The architecture of extension points}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateExtensionPointOptions {
/**
* The ID of this extension point.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
id: string;
}
/**
* Creates a new backend extension point.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/extension-points | The architecture of extension points}
*/
export function createExtensionPoint<T>(
options: CreateExtensionPointOptions,
): ExtensionPoint<T> {
return {
id: options.id,
get T(): T {
if (process.env.NODE_ENV === 'test') {
// Avoid throwing errors so tests asserting extensions' properties cannot be easily broken
return null as T;
}
throw new Error(`tried to read ExtensionPoint.T of ${this}`);
},
toString() {
return `extensionPoint{${options.id}}`;
},
$$type: '@backstage/ExtensionPoint',
};
}
@@ -0,0 +1,20 @@
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Single re-export to avoid doing this import in multiple places, but still
// avoid duplicate declarations because this one is a bit tricky.
// eslint-disable-next-line @backstage/no-relative-monorepo-imports
export { describeParentCallSite } from '../../../frontend-plugin-api/src/routing/describeParentCallSite';
@@ -1,108 +0,0 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
createBackendModule,
createBackendPlugin,
createExtensionPoint,
} from './factories';
import { InternalBackendFeature } from './types';
describe('createExtensionPoint', () => {
it('should create an ExtensionPoint', () => {
const extensionPoint = createExtensionPoint({ id: 'x' });
expect(extensionPoint).toBeDefined();
expect(extensionPoint.id).toBe('x');
expect(() => extensionPoint.T).not.toThrow();
expect(String(extensionPoint)).toBe('extensionPoint{x}');
});
});
describe('createBackendPlugin', () => {
it('should create a BackendPlugin', () => {
const result = createBackendPlugin({
pluginId: 'x',
register(r) {
r.registerInit({ deps: {}, async init() {} });
},
});
// legacy form
const legacy = result() as unknown as InternalBackendFeature;
expect(legacy.$$type).toEqual('@backstage/BackendFeature');
expect(legacy.version).toEqual('v1');
expect(legacy.getRegistrations).toEqual(expect.any(Function));
// new form
const plugin = result as unknown as InternalBackendFeature;
expect(plugin.$$type).toEqual('@backstage/BackendFeature');
expect(plugin.version).toEqual('v1');
expect(plugin.getRegistrations).toEqual(expect.any(Function));
expect(plugin.getRegistrations()).toEqual([
{
type: 'plugin',
pluginId: 'x',
extensionPoints: [],
init: {
deps: expect.any(Object),
func: expect.any(Function),
},
},
]);
// @ts-expect-error
expect(plugin({ a: 'a' })).toBeDefined();
});
});
describe('createBackendModule', () => {
it('should create a BackendModule', () => {
const result = createBackendModule({
pluginId: 'x',
moduleId: 'y',
register(r) {
r.registerInit({ deps: {}, async init() {} });
},
});
// legacy form
const legacy = result() as unknown as InternalBackendFeature;
expect(legacy.$$type).toEqual('@backstage/BackendFeature');
expect(legacy.version).toEqual('v1');
expect(legacy.getRegistrations).toEqual(expect.any(Function));
// new form
const module = result as unknown as InternalBackendFeature;
expect(module.$$type).toEqual('@backstage/BackendFeature');
expect(module.version).toEqual('v1');
expect(module.getRegistrations).toEqual(expect.any(Function));
expect(module.getRegistrations()).toEqual([
{
type: 'module',
pluginId: 'x',
moduleId: 'y',
extensionPoints: [],
init: {
deps: expect.any(Object),
func: expect.any(Function),
},
},
]);
// @ts-expect-error
expect(module({ a: 'a' })).toBeDefined();
});
});
@@ -1,229 +0,0 @@
/*
* Copyright 2022 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BackendFeatureCompat } from '../types';
import {
BackendModuleRegistrationPoints,
BackendPluginRegistrationPoints,
ExtensionPoint,
InternalBackendModuleRegistration,
InternalBackendPluginRegistration,
} from './types';
/**
* The configuration options passed to {@link createExtensionPoint}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/extension-points | The architecture of extension points}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateExtensionPointOptions {
/**
* The ID of this extension point.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
id: string;
}
/**
* Creates a new backend extension point.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/extension-points | The architecture of extension points}
*/
export function createExtensionPoint<T>(
options: CreateExtensionPointOptions,
): ExtensionPoint<T> {
return {
id: options.id,
get T(): T {
if (process.env.NODE_ENV === 'test') {
// Avoid throwing errors so tests asserting extensions' properties cannot be easily broken
return null as T;
}
throw new Error(`tried to read ExtensionPoint.T of ${this}`);
},
toString() {
return `extensionPoint{${options.id}}`;
},
$$type: '@backstage/ExtensionPoint',
};
}
/**
* The configuration options passed to {@link createBackendPlugin}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/plugins | The architecture of plugins}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateBackendPluginOptions {
/**
* The ID of this plugin.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
pluginId: string;
register(reg: BackendPluginRegistrationPoints): void;
}
/**
* Creates a new backend plugin.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/plugins | The architecture of plugins}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export function createBackendPlugin(
options: CreateBackendPluginOptions,
): BackendFeatureCompat {
function getRegistrations() {
const extensionPoints: InternalBackendPluginRegistration['extensionPoints'] =
[];
let init: InternalBackendPluginRegistration['init'] | undefined = undefined;
options.register({
registerExtensionPoint(ext, impl) {
if (init) {
throw new Error('registerExtensionPoint called after registerInit');
}
extensionPoints.push([ext, impl]);
},
registerInit(regInit) {
if (init) {
throw new Error('registerInit must only be called once');
}
init = {
deps: regInit.deps,
func: regInit.init,
};
},
});
if (!init) {
throw new Error(
`registerInit was not called by register in ${options.pluginId}`,
);
}
return [
{
type: 'plugin',
pluginId: options.pluginId,
extensionPoints,
init,
},
];
}
function backendFeatureCompatWrapper() {
return backendFeatureCompatWrapper;
}
Object.assign(backendFeatureCompatWrapper, {
$$type: '@backstage/BackendFeature' as const,
version: 'v1',
getRegistrations,
});
return backendFeatureCompatWrapper as BackendFeatureCompat;
}
/**
* The configuration options passed to {@link createBackendModule}.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/modules | The architecture of modules}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export interface CreateBackendModuleOptions {
/**
* Should exactly match the `id` of the plugin that the module extends.
*
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
pluginId: string;
/**
* The ID of this module, used to identify the module and ensure that it is not installed twice.
*/
moduleId: string;
register(reg: BackendModuleRegistrationPoints): void;
}
/**
* Creates a new backend module for a given plugin.
*
* @public
* @see {@link https://backstage.io/docs/backend-system/architecture/modules | The architecture of modules}
* @see {@link https://backstage.io/docs/backend-system/architecture/naming-patterns | Recommended naming patterns}
*/
export function createBackendModule(
options: CreateBackendModuleOptions,
): BackendFeatureCompat {
function getRegistrations() {
const extensionPoints: InternalBackendPluginRegistration['extensionPoints'] =
[];
let init: InternalBackendModuleRegistration['init'] | undefined = undefined;
options.register({
registerExtensionPoint(ext, impl) {
if (init) {
throw new Error('registerExtensionPoint called after registerInit');
}
extensionPoints.push([ext, impl]);
},
registerInit(regInit) {
if (init) {
throw new Error('registerInit must only be called once');
}
init = {
deps: regInit.deps,
func: regInit.init,
};
},
});
if (!init) {
throw new Error(
`registerInit was not called by register in ${options.moduleId} module for ${options.pluginId}`,
);
}
return [
{
type: 'module',
pluginId: options.pluginId,
moduleId: options.moduleId,
extensionPoints,
init,
},
];
}
function backendFeatureCompatWrapper() {
return backendFeatureCompatWrapper;
}
Object.assign(backendFeatureCompatWrapper, {
$$type: '@backstage/BackendFeature' as const,
version: 'v1',
getRegistrations,
});
return backendFeatureCompatWrapper as BackendFeatureCompat;
}
@@ -14,17 +14,17 @@
* limitations under the License.
*/
import type {
CreateBackendPluginOptions,
CreateBackendModuleOptions,
CreateExtensionPointOptions,
} from './factories';
import { type CreateBackendModuleOptions } from './createBackendModule';
import { type CreateBackendPluginOptions } from './createBackendPlugin';
import { type CreateExtensionPointOptions } from './createExtensionPoint';
export { createBackendModule } from './createBackendModule';
export { createBackendPlugin } from './createBackendPlugin';
export { createExtensionPoint } from './createExtensionPoint';
export {
createBackendModule,
createBackendPlugin,
createExtensionPoint,
} from './factories';
createBackendFeatureLoader,
type CreateBackendFeatureLoaderOptions,
} from './createBackendFeatureLoader';
export type {
BackendModuleRegistrationPoints,
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { ServiceRef } from '../services/system/types';
import { InternalServiceFactory, ServiceRef } from '../services/system/types';
import { BackendFeature } from '../types';
/**
@@ -73,8 +73,9 @@ export interface BackendModuleRegistrationPoints {
}
/** @internal */
export interface InternalBackendFeature extends BackendFeature {
export interface InternalBackendRegistrations extends BackendFeature {
version: 'v1';
featureType: 'registrations';
getRegistrations(): Array<
InternalBackendPluginRegistration | InternalBackendModuleRegistration
>;
@@ -102,3 +103,20 @@ export interface InternalBackendModuleRegistration {
func(deps: Record<string, unknown>): Promise<void>;
};
}
/**
* @public
*/
export interface InternalBackendFeatureLoader extends BackendFeature {
version: 'v1';
featureType: 'loader';
description: string;
deps: Record<string, ServiceRef<unknown>>;
loader(deps: Record<string, unknown>): Promise<BackendFeature[]>;
}
/** @internal */
export type InternalBackendFeature =
| InternalBackendRegistrations
| InternalBackendFeatureLoader
| InternalServiceFactory;