@backstage/backend-test-utils 1.10.4 → 1.11.0-next.1
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 +29 -6
- package/dist/alpha/services/ActionsRegistryServiceMock.cjs.js +4 -7
- package/dist/alpha/services/ActionsRegistryServiceMock.cjs.js.map +1 -1
- package/dist/alpha/services/ActionsServiceMock.cjs.js +2 -2
- package/dist/alpha/services/ActionsServiceMock.cjs.js.map +1 -1
- package/dist/alpha/services/MockActionsRegistry.cjs.js +1 -0
- package/dist/alpha/services/MockActionsRegistry.cjs.js.map +1 -1
- package/dist/alpha.d.ts +9 -15
- package/dist/database/mysql.cjs.js +2 -2
- package/dist/database/mysql.cjs.js.map +1 -1
- package/dist/database/postgres.cjs.js +2 -2
- package/dist/database/postgres.cjs.js.map +1 -1
- package/dist/filesystem/MockDirectory.cjs.js +14 -14
- package/dist/filesystem/MockDirectory.cjs.js.map +1 -1
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +5 -10
- package/dist/{alpha/services/simpleMock.cjs.js → services/createServiceMock.cjs.js} +3 -3
- package/dist/services/createServiceMock.cjs.js.map +1 -0
- package/dist/services/mockServices.cjs.js +35 -29
- package/dist/services/mockServices.cjs.js.map +1 -1
- package/dist/types/createServiceMock.d-CeKvILsY.d.ts +48 -0
- package/dist/util/errorHandler.cjs.js +1 -0
- package/dist/util/errorHandler.cjs.js.map +1 -1
- package/dist/wiring/TestBackend.cjs.js +3 -3
- package/dist/wiring/TestBackend.cjs.js.map +1 -1
- package/package.json +19 -11
- package/dist/alpha/services/simpleMock.cjs.js.map +0 -1
- package/dist/services/simpleMock.cjs.js +0 -28
- package/dist/services/simpleMock.cjs.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,15 +1,38 @@
|
|
|
1
1
|
# @backstage/backend-test-utils
|
|
2
2
|
|
|
3
|
-
## 1.
|
|
3
|
+
## 1.11.0-next.1
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 42abfb1: Added `createServiceMock`, a public utility for creating `ServiceMock` instances for custom service refs. This allows plugin authors to define mock creators for their own services following the same pattern as the built-in `mockServices` mocks.
|
|
4
8
|
|
|
5
9
|
### Patch Changes
|
|
6
10
|
|
|
7
|
-
-
|
|
11
|
+
- 68eb322: Added `@types/jest` as an optional peer dependency, since jest types are exposed in the public API surface.
|
|
8
12
|
- Updated dependencies
|
|
9
|
-
- @backstage/backend-
|
|
10
|
-
- @backstage/backend-defaults@0.15.1
|
|
11
|
-
- @backstage/plugin-
|
|
12
|
-
- @backstage/plugin-auth-node@0.6.
|
|
13
|
+
- @backstage/backend-app-api@1.5.0-next.1
|
|
14
|
+
- @backstage/backend-defaults@0.15.2-next.1
|
|
15
|
+
- @backstage/backend-plugin-api@1.7.0-next.1
|
|
16
|
+
- @backstage/plugin-auth-node@0.6.13-next.1
|
|
17
|
+
- @backstage/plugin-events-node@0.4.19-next.0
|
|
18
|
+
|
|
19
|
+
## 1.10.4-next.0
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- f1d29b4: Updated `startTestBackend` to support factory-based extension points (v1.1 format) in addition to the existing direct implementation format.
|
|
24
|
+
- 7455dae: Use node prefix on native imports
|
|
25
|
+
- 69d880e: Bump to latest zod to ensure it has the latest features
|
|
26
|
+
- Updated dependencies
|
|
27
|
+
- @backstage/backend-plugin-api@1.7.0-next.0
|
|
28
|
+
- @backstage/backend-defaults@0.15.1-next.0
|
|
29
|
+
- @backstage/plugin-auth-node@0.6.12-next.0
|
|
30
|
+
- @backstage/backend-app-api@1.5.0-next.0
|
|
31
|
+
- @backstage/plugin-permission-common@0.9.5-next.0
|
|
32
|
+
- @backstage/plugin-events-node@0.4.19-next.0
|
|
33
|
+
- @backstage/config@1.3.6
|
|
34
|
+
- @backstage/errors@1.2.7
|
|
35
|
+
- @backstage/types@1.2.2
|
|
13
36
|
|
|
14
37
|
## 1.10.3
|
|
15
38
|
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
var mockServices = require('../../services/mockServices.cjs.js');
|
|
4
4
|
require('../../services/mockCredentials.cjs.js');
|
|
5
|
+
var createServiceMock = require('../../services/createServiceMock.cjs.js');
|
|
5
6
|
var MockActionsRegistry = require('./MockActionsRegistry.cjs.js');
|
|
6
|
-
var simpleMock = require('./simpleMock.cjs.js');
|
|
7
7
|
var alpha$1 = require('@backstage/backend-plugin-api/alpha');
|
|
8
8
|
var alpha = require('@backstage/backend-defaults/alpha');
|
|
9
9
|
|
|
@@ -14,12 +14,9 @@ function actionsRegistryServiceMock(options) {
|
|
|
14
14
|
}
|
|
15
15
|
((actionsRegistryServiceMock2) => {
|
|
16
16
|
actionsRegistryServiceMock2.factory = () => alpha.actionsRegistryServiceFactory;
|
|
17
|
-
actionsRegistryServiceMock2.mock =
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
register: jest.fn()
|
|
21
|
-
})
|
|
22
|
-
);
|
|
17
|
+
actionsRegistryServiceMock2.mock = createServiceMock.createServiceMock(alpha$1.actionsRegistryServiceRef, () => ({
|
|
18
|
+
register: jest.fn()
|
|
19
|
+
}));
|
|
23
20
|
})(actionsRegistryServiceMock || (actionsRegistryServiceMock = {}));
|
|
24
21
|
|
|
25
22
|
exports.actionsRegistryServiceMock = actionsRegistryServiceMock;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ActionsRegistryServiceMock.cjs.js","sources":["../../../src/alpha/services/ActionsRegistryServiceMock.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { mockServices } from '../../services';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { MockActionsRegistry } from './MockActionsRegistry';\nimport {
|
|
1
|
+
{"version":3,"file":"ActionsRegistryServiceMock.cjs.js","sources":["../../../src/alpha/services/ActionsRegistryServiceMock.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { mockServices } from '../../services';\nimport { LoggerService } from '@backstage/backend-plugin-api';\nimport { MockActionsRegistry } from './MockActionsRegistry';\nimport { createServiceMock } from './alphaCreateServiceMock';\nimport { actionsRegistryServiceRef } from '@backstage/backend-plugin-api/alpha';\nimport { actionsRegistryServiceFactory } from '@backstage/backend-defaults/alpha';\n\n/**\n * @alpha\n */\nexport function actionsRegistryServiceMock(options?: {\n logger: LoggerService;\n}): MockActionsRegistry {\n return MockActionsRegistry.create({\n logger: options?.logger ?? mockServices.logger.mock(),\n });\n}\n\n/**\n * @alpha\n */\nexport namespace actionsRegistryServiceMock {\n export const factory = () => actionsRegistryServiceFactory;\n\n export const mock = createServiceMock(actionsRegistryServiceRef, () => ({\n register: jest.fn(),\n }));\n}\n"],"names":["MockActionsRegistry","mockServices","actionsRegistryServiceMock","actionsRegistryServiceFactory","createServiceMock","actionsRegistryServiceRef"],"mappings":";;;;;;;;;AAyBO,SAAS,2BAA2B,OAAA,EAEnB;AACtB,EAAA,OAAOA,wCAAoB,MAAA,CAAO;AAAA,IAChC,MAAA,EAAQ,OAAA,EAAS,MAAA,IAAUC,yBAAA,CAAa,OAAO,IAAA;AAAK,GACrD,CAAA;AACH;AAAA,CAKO,CAAUC,2BAAAA,KAAV;AACE,EAAMA,2BAAAA,CAAA,UAAU,MAAMC,mCAAA;AAEtB,EAAMD,2BAAAA,CAAA,IAAA,GAAOE,mCAAA,CAAkBC,iCAAA,EAA2B,OAAO;AAAA,IACtE,QAAA,EAAU,KAAK,EAAA;AAAG,GACpB,CAAE,CAAA;AAAA,CAAA,EALa,0BAAA,KAAA,0BAAA,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var createServiceMock = require('../../services/createServiceMock.cjs.js');
|
|
4
4
|
var alpha$1 = require('@backstage/backend-plugin-api/alpha');
|
|
5
5
|
var alpha = require('@backstage/backend-defaults/alpha');
|
|
6
6
|
|
|
7
7
|
exports.actionsServiceMock = void 0;
|
|
8
8
|
((actionsServiceMock2) => {
|
|
9
9
|
actionsServiceMock2.factory = () => alpha.actionsServiceFactory;
|
|
10
|
-
actionsServiceMock2.mock =
|
|
10
|
+
actionsServiceMock2.mock = createServiceMock.createServiceMock(alpha$1.actionsServiceRef, () => ({
|
|
11
11
|
invoke: jest.fn(),
|
|
12
12
|
list: jest.fn()
|
|
13
13
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ActionsServiceMock.cjs.js","sources":["../../../src/alpha/services/ActionsServiceMock.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {
|
|
1
|
+
{"version":3,"file":"ActionsServiceMock.cjs.js","sources":["../../../src/alpha/services/ActionsServiceMock.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createServiceMock } from './alphaCreateServiceMock';\nimport { actionsServiceRef } from '@backstage/backend-plugin-api/alpha';\nimport { actionsServiceFactory } from '@backstage/backend-defaults/alpha';\n\n/**\n * @alpha\n */\nexport namespace actionsServiceMock {\n export const factory = () => actionsServiceFactory;\n\n export const mock = createServiceMock(actionsServiceRef, () => ({\n invoke: jest.fn(),\n list: jest.fn(),\n }));\n}\n"],"names":["actionsServiceMock","actionsServiceFactory","createServiceMock","actionsServiceRef"],"mappings":";;;;;;AAuBiBA;AAAA,CAAV,CAAUA,mBAAAA,KAAV;AACE,EAAMA,mBAAAA,CAAA,UAAU,MAAMC,2BAAA;AAEtB,EAAMD,mBAAAA,CAAA,IAAA,GAAOE,mCAAA,CAAkBC,yBAAA,EAAmB,OAAO;AAAA,IAC9D,MAAA,EAAQ,KAAK,EAAA,EAAG;AAAA,IAChB,IAAA,EAAM,KAAK,EAAA;AAAG,GAChB,CAAE,CAAA;AAAA,CAAA,EANaH,0BAAA,KAAAA,0BAAA,GAAA,EAAA,CAAA,CAAA;;"}
|
|
@@ -5,6 +5,7 @@ var zod = require('zod');
|
|
|
5
5
|
var zodToJsonSchema = require('zod-to-json-schema');
|
|
6
6
|
require('../../services/mockServices.cjs.js');
|
|
7
7
|
var mockCredentials = require('../../services/mockCredentials.cjs.js');
|
|
8
|
+
require('@backstage/backend-plugin-api');
|
|
8
9
|
|
|
9
10
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
10
11
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockActionsRegistry.cjs.js","sources":["../../../src/alpha/services/MockActionsRegistry.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n BackstageCredentials,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { ForwardedError, InputError, NotFoundError } from '@backstage/errors';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { z, AnyZodObject } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport { mockCredentials } from '../../services';\nimport {\n ActionsRegistryActionOptions,\n ActionsRegistryService,\n ActionsService,\n ActionsServiceAction,\n} from '@backstage/backend-plugin-api/alpha';\n\n/**\n * A mock implementation of the ActionsRegistryService and ActionsService that can be used in tests.\n *\n * This is useful for testing actions that are registered with the ActionsRegistryService and ActionsService.\n *\n * The plugin ID is hardcoded to `testing` in the mock implementation.\n *\n * @example\n * ```ts\n * const actionsRegistry = mockServices.actionsRegistry();\n *\n * actionsRegistry.register({\n * name: 'test',\n * title: 'Test',\n * description: 'Test',\n * schema: {\n * input: z.object({ name: z.string() }),\n * output: z.object({ name: z.string() }),\n * },\n * action: async ({ input }) => ({ output: { name: input.name } }),\n * });\n *\n *\n * const result = await actionsRegistry.invoke({\n * id: 'testing:test',\n * input: { name: 'test' },\n * });\n *\n * expect(result).toEqual({ output: { name: 'test' } });\n * ```\n *\n * @alpha\n */\nexport class MockActionsRegistry\n implements ActionsRegistryService, ActionsService\n{\n private readonly logger: LoggerService;\n\n private constructor(logger: LoggerService) {\n this.logger = logger;\n }\n\n static create(opts: { logger: LoggerService }) {\n return new MockActionsRegistry(opts.logger);\n }\n\n readonly actions: Map<string, ActionsRegistryActionOptions<any, any>> =\n new Map();\n\n async list(): Promise<{ actions: ActionsServiceAction[] }> {\n return {\n actions: Array.from(this.actions.entries()).map(([id, action]) => ({\n id,\n name: action.name,\n title: action.title,\n description: action.description,\n attributes: {\n destructive: action.attributes?.destructive ?? true,\n idempotent: action.attributes?.idempotent ?? false,\n readOnly: action.attributes?.readOnly ?? false,\n },\n schema: {\n input: action.schema?.input\n ? zodToJsonSchema(action.schema.input(z))\n : zodToJsonSchema(z.object({})),\n output: action.schema?.output\n ? zodToJsonSchema(action.schema.output(z))\n : zodToJsonSchema(z.object({})),\n } as ActionsServiceAction['schema'],\n })),\n };\n }\n\n async invoke(opts: {\n id: string;\n input?: JsonObject;\n credentials?: BackstageCredentials;\n }): Promise<{ output: JsonValue }> {\n const action = this.actions.get(opts.id);\n\n if (!action) {\n const availableActionIds = Array.from(this.actions.keys()).join(', ');\n throw new NotFoundError(\n `Action \"${opts.id}\" not found, available actions: ${\n availableActionIds ? `\"${availableActionIds}\"` : 'none'\n }`,\n );\n }\n\n const input = action.schema?.input\n ? action.schema.input(z).safeParse(opts.input)\n : ({ success: true, data: undefined } as const);\n\n if (!input.success) {\n throw new InputError(`Invalid input to action \"${opts.id}\"`, input.error);\n }\n\n try {\n const result = await action.action({\n input: input.data,\n credentials: opts.credentials ?? mockCredentials.none(),\n logger: this.logger,\n });\n\n const output = action.schema?.output\n ? action.schema.output(z).safeParse(result?.output)\n : ({ success: true, data: result?.output } as const);\n\n if (!output.success) {\n throw new InputError(\n `Invalid output from action \"${opts.id}\"`,\n output.error,\n );\n }\n\n return { output: output.data };\n } catch (error) {\n throw new ForwardedError(\n `Failed execution of action \"${opts.id}\"`,\n error,\n );\n }\n }\n\n register<\n TInputSchema extends AnyZodObject,\n TOutputSchema extends AnyZodObject,\n >(options: ActionsRegistryActionOptions<TInputSchema, TOutputSchema>): void {\n // hardcode test: prefix similar to how the default actions registry does it\n // and other places around the testing ecosystem:\n // https://github.com/backstage/backstage/blob/a9219496d5c073aaa0b8caf32ece10455cf65e61/packages/backend-test-utils/src/next/services/mockServices.ts#L321\n // https://github.com/backstage/backstage/blob/861f162b4a39117b824669d67a951ed1db142e3d/packages/backend-test-utils/src/next/wiring/ServiceFactoryTester.ts#L99\n const id = `test:${options.name}`;\n\n if (this.actions.has(id)) {\n throw new Error(`Action with id \"${id}\" is already registered`);\n }\n\n this.actions.set(id, options);\n }\n}\n"],"names":["zodToJsonSchema","z","NotFoundError","InputError","mockCredentials","ForwardedError"],"mappings":"
|
|
1
|
+
{"version":3,"file":"MockActionsRegistry.cjs.js","sources":["../../../src/alpha/services/MockActionsRegistry.ts"],"sourcesContent":["/*\n * Copyright 2025 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n BackstageCredentials,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { ForwardedError, InputError, NotFoundError } from '@backstage/errors';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { z, AnyZodObject } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport { mockCredentials } from '../../services';\nimport {\n ActionsRegistryActionOptions,\n ActionsRegistryService,\n ActionsService,\n ActionsServiceAction,\n} from '@backstage/backend-plugin-api/alpha';\n\n/**\n * A mock implementation of the ActionsRegistryService and ActionsService that can be used in tests.\n *\n * This is useful for testing actions that are registered with the ActionsRegistryService and ActionsService.\n *\n * The plugin ID is hardcoded to `testing` in the mock implementation.\n *\n * @example\n * ```ts\n * const actionsRegistry = mockServices.actionsRegistry();\n *\n * actionsRegistry.register({\n * name: 'test',\n * title: 'Test',\n * description: 'Test',\n * schema: {\n * input: z.object({ name: z.string() }),\n * output: z.object({ name: z.string() }),\n * },\n * action: async ({ input }) => ({ output: { name: input.name } }),\n * });\n *\n *\n * const result = await actionsRegistry.invoke({\n * id: 'testing:test',\n * input: { name: 'test' },\n * });\n *\n * expect(result).toEqual({ output: { name: 'test' } });\n * ```\n *\n * @alpha\n */\nexport class MockActionsRegistry\n implements ActionsRegistryService, ActionsService\n{\n private readonly logger: LoggerService;\n\n private constructor(logger: LoggerService) {\n this.logger = logger;\n }\n\n static create(opts: { logger: LoggerService }) {\n return new MockActionsRegistry(opts.logger);\n }\n\n readonly actions: Map<string, ActionsRegistryActionOptions<any, any>> =\n new Map();\n\n async list(): Promise<{ actions: ActionsServiceAction[] }> {\n return {\n actions: Array.from(this.actions.entries()).map(([id, action]) => ({\n id,\n name: action.name,\n title: action.title,\n description: action.description,\n attributes: {\n destructive: action.attributes?.destructive ?? true,\n idempotent: action.attributes?.idempotent ?? false,\n readOnly: action.attributes?.readOnly ?? false,\n },\n schema: {\n input: action.schema?.input\n ? zodToJsonSchema(action.schema.input(z))\n : zodToJsonSchema(z.object({})),\n output: action.schema?.output\n ? zodToJsonSchema(action.schema.output(z))\n : zodToJsonSchema(z.object({})),\n } as ActionsServiceAction['schema'],\n })),\n };\n }\n\n async invoke(opts: {\n id: string;\n input?: JsonObject;\n credentials?: BackstageCredentials;\n }): Promise<{ output: JsonValue }> {\n const action = this.actions.get(opts.id);\n\n if (!action) {\n const availableActionIds = Array.from(this.actions.keys()).join(', ');\n throw new NotFoundError(\n `Action \"${opts.id}\" not found, available actions: ${\n availableActionIds ? `\"${availableActionIds}\"` : 'none'\n }`,\n );\n }\n\n const input = action.schema?.input\n ? action.schema.input(z).safeParse(opts.input)\n : ({ success: true, data: undefined } as const);\n\n if (!input.success) {\n throw new InputError(`Invalid input to action \"${opts.id}\"`, input.error);\n }\n\n try {\n const result = await action.action({\n input: input.data,\n credentials: opts.credentials ?? mockCredentials.none(),\n logger: this.logger,\n });\n\n const output = action.schema?.output\n ? action.schema.output(z).safeParse(result?.output)\n : ({ success: true, data: result?.output } as const);\n\n if (!output.success) {\n throw new InputError(\n `Invalid output from action \"${opts.id}\"`,\n output.error,\n );\n }\n\n return { output: output.data };\n } catch (error) {\n throw new ForwardedError(\n `Failed execution of action \"${opts.id}\"`,\n error,\n );\n }\n }\n\n register<\n TInputSchema extends AnyZodObject,\n TOutputSchema extends AnyZodObject,\n >(options: ActionsRegistryActionOptions<TInputSchema, TOutputSchema>): void {\n // hardcode test: prefix similar to how the default actions registry does it\n // and other places around the testing ecosystem:\n // https://github.com/backstage/backstage/blob/a9219496d5c073aaa0b8caf32ece10455cf65e61/packages/backend-test-utils/src/next/services/mockServices.ts#L321\n // https://github.com/backstage/backstage/blob/861f162b4a39117b824669d67a951ed1db142e3d/packages/backend-test-utils/src/next/wiring/ServiceFactoryTester.ts#L99\n const id = `test:${options.name}`;\n\n if (this.actions.has(id)) {\n throw new Error(`Action with id \"${id}\" is already registered`);\n }\n\n this.actions.set(id, options);\n }\n}\n"],"names":["zodToJsonSchema","z","NotFoundError","InputError","mockCredentials","ForwardedError"],"mappings":";;;;;;;;;;;;;AAgEO,MAAM,mBAAA,CAEb;AAAA,EACmB,MAAA;AAAA,EAET,YAAY,MAAA,EAAuB;AACzC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,OAAO,OAAO,IAAA,EAAiC;AAC7C,IAAA,OAAO,IAAI,mBAAA,CAAoB,IAAA,CAAK,MAAM,CAAA;AAAA,EAC5C;AAAA,EAES,OAAA,uBACH,GAAA,EAAI;AAAA,EAEV,MAAM,IAAA,GAAqD;AACzD,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,KAAA,CAAM,IAAA,CAAK,IAAA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,KAAK,EAAE,CAAA,CAAA,CAAA;AAAA,QACtC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,SAGE,OAAA,EAA0E;AAK1E,IAAA,MAAM,EAAA,GAAK,CAAA,KAAA,EAAQ,OAAA,CAAQ,IAAI,CAAA,CAAA;AAE/B,IAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,EAAG;AACxB,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,gBAAA,EAAmB,EAAE,CAAA,uBAAA,CAAyB,CAAA;AAAA,IAChE;AAEA,IAAA,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,EAAA,EAAI,OAAO,CAAA;AAAA,EAC9B;AACF;;;;"}
|
package/dist/alpha.d.ts
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
1
|
+
import { S as ServiceMock } from './types/createServiceMock.d-CeKvILsY.js';
|
|
1
2
|
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
2
|
-
import {
|
|
3
|
+
import { LoggerService, BackstageCredentials } from '@backstage/backend-plugin-api';
|
|
4
|
+
import * as _backstage_backend_plugin_api_alpha from '@backstage/backend-plugin-api/alpha';
|
|
5
|
+
import { ActionsRegistryService, ActionsService, ActionsRegistryActionOptions, ActionsServiceAction } from '@backstage/backend-plugin-api/alpha';
|
|
3
6
|
import { JsonObject, JsonValue } from '@backstage/types';
|
|
4
7
|
import { AnyZodObject } from 'zod';
|
|
5
|
-
import { ActionsRegistryService, ActionsService, ActionsRegistryActionOptions, ActionsServiceAction } from '@backstage/backend-plugin-api/alpha';
|
|
6
|
-
|
|
7
|
-
/** @alpha */
|
|
8
|
-
type ServiceMock<TService> = {
|
|
9
|
-
factory: ServiceFactory<TService>;
|
|
10
|
-
} & {
|
|
11
|
-
[Key in keyof TService]: TService[Key] extends (...args: infer Args) => infer Return ? TService[Key] & jest.MockInstance<Return, Args> : TService[Key];
|
|
12
|
-
};
|
|
13
8
|
|
|
14
9
|
/**
|
|
15
10
|
* A mock implementation of the ActionsRegistryService and ActionsService that can be used in tests.
|
|
@@ -74,17 +69,16 @@ declare function actionsRegistryServiceMock(options?: {
|
|
|
74
69
|
* @alpha
|
|
75
70
|
*/
|
|
76
71
|
declare namespace actionsRegistryServiceMock {
|
|
77
|
-
const factory: () => _backstage_backend_plugin_api.ServiceFactory<ActionsRegistryService, "plugin", "singleton">;
|
|
78
|
-
const mock: (partialImpl?: Partial<ActionsRegistryService> | undefined) => ServiceMock<ActionsRegistryService>;
|
|
72
|
+
const factory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api_alpha.ActionsRegistryService, "plugin", "singleton">;
|
|
73
|
+
const mock: (partialImpl?: Partial<_backstage_backend_plugin_api_alpha.ActionsRegistryService> | undefined) => ServiceMock<_backstage_backend_plugin_api_alpha.ActionsRegistryService>;
|
|
79
74
|
}
|
|
80
75
|
|
|
81
76
|
/**
|
|
82
77
|
* @alpha
|
|
83
78
|
*/
|
|
84
79
|
declare namespace actionsServiceMock {
|
|
85
|
-
const factory: () => _backstage_backend_plugin_api.ServiceFactory<ActionsService, "plugin", "singleton">;
|
|
86
|
-
const mock: (partialImpl?: Partial<ActionsService> | undefined) => ServiceMock<ActionsService>;
|
|
80
|
+
const factory: () => _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api_alpha.ActionsService, "plugin", "singleton">;
|
|
81
|
+
const mock: (partialImpl?: Partial<_backstage_backend_plugin_api_alpha.ActionsService> | undefined) => ServiceMock<_backstage_backend_plugin_api_alpha.ActionsService>;
|
|
87
82
|
}
|
|
88
83
|
|
|
89
|
-
export { MockActionsRegistry, actionsRegistryServiceMock, actionsServiceMock };
|
|
90
|
-
export type { ServiceMock };
|
|
84
|
+
export { MockActionsRegistry, ServiceMock, actionsRegistryServiceMock, actionsServiceMock };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var errors = require('@backstage/errors');
|
|
4
|
-
var
|
|
4
|
+
var node_crypto = require('node:crypto');
|
|
5
5
|
var knexFactory = require('knex');
|
|
6
6
|
var uuid = require('uuid');
|
|
7
7
|
var yn = require('yn');
|
|
@@ -132,7 +132,7 @@ class MysqlEngine {
|
|
|
132
132
|
async createDatabaseInstance() {
|
|
133
133
|
const adminConnection = this.#connectAdmin();
|
|
134
134
|
try {
|
|
135
|
-
const databaseName = `db${
|
|
135
|
+
const databaseName = `db${node_crypto.randomBytes(16).toString("hex")}`;
|
|
136
136
|
await adminConnection.raw("CREATE DATABASE ??", [databaseName]);
|
|
137
137
|
this.#databaseNames.push(databaseName);
|
|
138
138
|
const knexInstance = knexFactory__default.default({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql.cjs.js","sources":["../../src/database/mysql.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { stringifyError } from '@backstage/errors';\nimport { randomBytes } from 'crypto';\nimport knexFactory, { Knex } from 'knex';\nimport { v4 as uuid } from 'uuid';\nimport yn from 'yn';\nimport { Engine, LARGER_POOL_CONFIG, TestDatabaseProperties } from './types';\n\nasync function waitForMysqlReady(\n connection: Knex.MySqlConnectionConfig,\n): Promise<void> {\n const startTime = Date.now();\n\n let lastError: Error | undefined;\n let attempts = 0;\n for (;;) {\n attempts += 1;\n\n let knex: Knex | undefined;\n try {\n knex = knexFactory({\n client: 'mysql2',\n connection: {\n // make a copy because the driver mutates this\n ...connection,\n },\n });\n const result = await knex.select(knex.raw('version() AS version'));\n if (Array.isArray(result) && result[0]?.version) {\n return;\n }\n } catch (e) {\n lastError = e;\n } finally {\n await knex?.destroy();\n }\n\n if (Date.now() - startTime > 30_000) {\n throw new Error(\n `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${\n lastError\n ? `last error was ${stringifyError(lastError)}`\n : '(no errors thrown)'\n }`,\n );\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n}\n\nexport async function startMysqlContainer(image: string): Promise<{\n connection: Knex.MySqlConnectionConfig;\n stopContainer: () => Promise<void>;\n}> {\n const user = 'root';\n const password = uuid();\n\n // Lazy-load to avoid side-effect of importing testcontainers\n const { GenericContainer } =\n require('testcontainers') as typeof import('testcontainers');\n\n const container = await new GenericContainer(image)\n .withExposedPorts(3306)\n .withEnvironment({ MYSQL_ROOT_PASSWORD: password })\n .withTmpFs({ '/var/lib/mysql': 'rw' })\n .start();\n\n const host = container.getHost();\n const port = container.getMappedPort(3306);\n const connection = { host, port, user, password };\n const stopContainer = async () => {\n await container.stop({ timeout: 10_000 });\n };\n\n await waitForMysqlReady(connection);\n\n return { connection, stopContainer };\n}\n\nexport function parseMysqlConnectionString(\n connectionString: string,\n): Knex.MySqlConnectionConfig {\n try {\n const {\n protocol,\n username,\n password,\n port,\n hostname,\n pathname,\n searchParams,\n } = new URL(connectionString);\n\n if (protocol !== 'mysql:') {\n throw new Error(`Unknown protocol ${protocol}`);\n } else if (!username || !password) {\n throw new Error(`Missing username/password`);\n } else if (!pathname.match(/^\\/[^/]+$/)) {\n throw new Error(`Expected single path segment`);\n }\n\n const result: Knex.MySqlConnectionConfig = {\n user: username,\n password,\n host: hostname,\n port: Number(port || 3306),\n database: decodeURIComponent(pathname.substring(1)),\n };\n\n const ssl = searchParams.get('ssl');\n if (ssl) {\n result.ssl = ssl;\n }\n\n const debug = searchParams.get('debug');\n if (debug) {\n result.debug = yn(debug);\n }\n\n return result;\n } catch (e) {\n throw new Error(`Error while parsing MySQL connection string, ${e}`, e);\n }\n}\n\nexport class MysqlEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<MysqlEngine> {\n const { connectionStringEnvironmentVariableName, dockerImageName } =\n properties;\n\n if (connectionStringEnvironmentVariableName) {\n const connectionString =\n process.env[connectionStringEnvironmentVariableName];\n if (connectionString) {\n const connection = parseMysqlConnectionString(connectionString);\n return new MysqlEngine(\n properties,\n connection as Knex.MySqlConnectionConfig,\n );\n }\n }\n\n if (dockerImageName) {\n const { connection, stopContainer } = await startMysqlContainer(\n dockerImageName,\n );\n return new MysqlEngine(properties, connection, stopContainer);\n }\n\n throw new Error(`Test databasee for ${properties.name} not configured`);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #connection: Knex.MySqlConnectionConfig;\n readonly #knexInstances: Knex[];\n readonly #databaseNames: string[];\n readonly #stopContainer?: () => Promise<void>;\n\n constructor(\n properties: TestDatabaseProperties,\n connection: Knex.MySqlConnectionConfig,\n stopContainer?: () => Promise<void>,\n ) {\n this.#properties = properties;\n this.#connection = connection;\n this.#knexInstances = [];\n this.#databaseNames = [];\n this.#stopContainer = stopContainer;\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const adminConnection = this.#connectAdmin();\n try {\n const databaseName = `db${randomBytes(16).toString('hex')}`;\n\n await adminConnection.raw('CREATE DATABASE ??', [databaseName]);\n this.#databaseNames.push(databaseName);\n\n const knexInstance = knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: databaseName,\n },\n ...LARGER_POOL_CONFIG,\n });\n this.#knexInstances.push(knexInstance);\n\n return knexInstance;\n } finally {\n await adminConnection.destroy();\n }\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#knexInstances) {\n await instance.destroy();\n }\n\n const adminConnection = this.#connectAdmin();\n try {\n for (const databaseName of this.#databaseNames) {\n await adminConnection.raw('DROP DATABASE ??', [databaseName]);\n }\n } finally {\n await adminConnection.destroy();\n }\n\n await this.#stopContainer?.();\n }\n\n #connectAdmin(): Knex {\n const connection = {\n ...this.#connection,\n database: null as unknown as string,\n };\n return knexFactory({\n client: this.#properties.driver,\n connection,\n pool: {\n min: 0,\n max: 1,\n acquireTimeoutMillis: 20_000,\n createTimeoutMillis: 20_000,\n createRetryIntervalMillis: 1_000,\n },\n });\n }\n}\n"],"names":["knexFactory","stringifyError","uuid","yn","randomBytes","LARGER_POOL_CONFIG"],"mappings":";;;;;;;;;;;;;;AAuBA,eAAe,kBACb,UAAA,EACe;AACf,EAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAE3B,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI,QAAA,GAAW,CAAA;AACf,EAAA,WAAS;AACP,IAAA,QAAA,IAAY,CAAA;AAEZ,IAAA,IAAI,IAAA;AACJ,IAAA,IAAI;AACF,MAAA,IAAA,GAAOA,4BAAA,CAAY;AAAA,QACjB,MAAA,EAAQ,QAAA;AAAA,QACR,UAAA,EAAY;AAAA;AAAA,UAEV,GAAG;AAAA;AACL,OACD,CAAA;AACD,MAAA,MAAM,SAAS,MAAM,IAAA,CAAK,OAAO,IAAA,CAAK,GAAA,CAAI,sBAAsB,CAAC,CAAA;AACjE,MAAA,IAAI,MAAM,OAAA,CAAQ,MAAM,KAAK,MAAA,CAAO,CAAC,GAAG,OAAA,EAAS;AAC/C,QAAA;AAAA,MACF;AAAA,IACF,SAAS,CAAA,EAAG;AACV,MAAA,SAAA,GAAY,CAAA;AAAA,IACd,CAAA,SAAE;AACA,MAAA,MAAM,MAAM,OAAA,EAAQ;AAAA,IACtB;AAEA,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,GAAI,SAAA,GAAY,GAAA,EAAQ;AACnC,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,gEAAA,EAAmE,QAAQ,CAAA,WAAA,EACzE,SAAA,GACI,kBAAkBC,qBAAA,CAAe,SAAS,CAAC,CAAA,CAAA,GAC3C,oBACN,CAAA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAA,OAAA,KAAW,UAA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AAA,EACH;AACF;;;;;;"}
|
|
1
|
+
{"version":3,"file":"mysql.cjs.js","sources":["../../src/database/mysql.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { stringifyError } from '@backstage/errors';\nimport { randomBytes } from 'node:crypto';\nimport knexFactory, { Knex } from 'knex';\nimport { v4 as uuid } from 'uuid';\nimport yn from 'yn';\nimport { Engine, LARGER_POOL_CONFIG, TestDatabaseProperties } from './types';\n\nasync function waitForMysqlReady(\n connection: Knex.MySqlConnectionConfig,\n): Promise<void> {\n const startTime = Date.now();\n\n let lastError: Error | undefined;\n let attempts = 0;\n for (;;) {\n attempts += 1;\n\n let knex: Knex | undefined;\n try {\n knex = knexFactory({\n client: 'mysql2',\n connection: {\n // make a copy because the driver mutates this\n ...connection,\n },\n });\n const result = await knex.select(knex.raw('version() AS version'));\n if (Array.isArray(result) && result[0]?.version) {\n return;\n }\n } catch (e) {\n lastError = e;\n } finally {\n await knex?.destroy();\n }\n\n if (Date.now() - startTime > 30_000) {\n throw new Error(\n `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${\n lastError\n ? `last error was ${stringifyError(lastError)}`\n : '(no errors thrown)'\n }`,\n );\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n}\n\nexport async function startMysqlContainer(image: string): Promise<{\n connection: Knex.MySqlConnectionConfig;\n stopContainer: () => Promise<void>;\n}> {\n const user = 'root';\n const password = uuid();\n\n // Lazy-load to avoid side-effect of importing testcontainers\n const { GenericContainer } =\n require('testcontainers') as typeof import('testcontainers');\n\n const container = await new GenericContainer(image)\n .withExposedPorts(3306)\n .withEnvironment({ MYSQL_ROOT_PASSWORD: password })\n .withTmpFs({ '/var/lib/mysql': 'rw' })\n .start();\n\n const host = container.getHost();\n const port = container.getMappedPort(3306);\n const connection = { host, port, user, password };\n const stopContainer = async () => {\n await container.stop({ timeout: 10_000 });\n };\n\n await waitForMysqlReady(connection);\n\n return { connection, stopContainer };\n}\n\nexport function parseMysqlConnectionString(\n connectionString: string,\n): Knex.MySqlConnectionConfig {\n try {\n const {\n protocol,\n username,\n password,\n port,\n hostname,\n pathname,\n searchParams,\n } = new URL(connectionString);\n\n if (protocol !== 'mysql:') {\n throw new Error(`Unknown protocol ${protocol}`);\n } else if (!username || !password) {\n throw new Error(`Missing username/password`);\n } else if (!pathname.match(/^\\/[^/]+$/)) {\n throw new Error(`Expected single path segment`);\n }\n\n const result: Knex.MySqlConnectionConfig = {\n user: username,\n password,\n host: hostname,\n port: Number(port || 3306),\n database: decodeURIComponent(pathname.substring(1)),\n };\n\n const ssl = searchParams.get('ssl');\n if (ssl) {\n result.ssl = ssl;\n }\n\n const debug = searchParams.get('debug');\n if (debug) {\n result.debug = yn(debug);\n }\n\n return result;\n } catch (e) {\n throw new Error(`Error while parsing MySQL connection string, ${e}`, e);\n }\n}\n\nexport class MysqlEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<MysqlEngine> {\n const { connectionStringEnvironmentVariableName, dockerImageName } =\n properties;\n\n if (connectionStringEnvironmentVariableName) {\n const connectionString =\n process.env[connectionStringEnvironmentVariableName];\n if (connectionString) {\n const connection = parseMysqlConnectionString(connectionString);\n return new MysqlEngine(\n properties,\n connection as Knex.MySqlConnectionConfig,\n );\n }\n }\n\n if (dockerImageName) {\n const { connection, stopContainer } = await startMysqlContainer(\n dockerImageName,\n );\n return new MysqlEngine(properties, connection, stopContainer);\n }\n\n throw new Error(`Test databasee for ${properties.name} not configured`);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #connection: Knex.MySqlConnectionConfig;\n readonly #knexInstances: Knex[];\n readonly #databaseNames: string[];\n readonly #stopContainer?: () => Promise<void>;\n\n constructor(\n properties: TestDatabaseProperties,\n connection: Knex.MySqlConnectionConfig,\n stopContainer?: () => Promise<void>,\n ) {\n this.#properties = properties;\n this.#connection = connection;\n this.#knexInstances = [];\n this.#databaseNames = [];\n this.#stopContainer = stopContainer;\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const adminConnection = this.#connectAdmin();\n try {\n const databaseName = `db${randomBytes(16).toString('hex')}`;\n\n await adminConnection.raw('CREATE DATABASE ??', [databaseName]);\n this.#databaseNames.push(databaseName);\n\n const knexInstance = knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: databaseName,\n },\n ...LARGER_POOL_CONFIG,\n });\n this.#knexInstances.push(knexInstance);\n\n return knexInstance;\n } finally {\n await adminConnection.destroy();\n }\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#knexInstances) {\n await instance.destroy();\n }\n\n const adminConnection = this.#connectAdmin();\n try {\n for (const databaseName of this.#databaseNames) {\n await adminConnection.raw('DROP DATABASE ??', [databaseName]);\n }\n } finally {\n await adminConnection.destroy();\n }\n\n await this.#stopContainer?.();\n }\n\n #connectAdmin(): Knex {\n const connection = {\n ...this.#connection,\n database: null as unknown as string,\n };\n return knexFactory({\n client: this.#properties.driver,\n connection,\n pool: {\n min: 0,\n max: 1,\n acquireTimeoutMillis: 20_000,\n createTimeoutMillis: 20_000,\n createRetryIntervalMillis: 1_000,\n },\n });\n }\n}\n"],"names":["knexFactory","stringifyError","uuid","yn","randomBytes","LARGER_POOL_CONFIG"],"mappings":";;;;;;;;;;;;;;AAuBA,eAAe,kBACb,UAAA,EACe;AACf,EAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAE3B,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI,QAAA,GAAW,CAAA;AACf,EAAA,WAAS;AACP,IAAA,QAAA,IAAY,CAAA;AAEZ,IAAA,IAAI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MAAA,MAAM,SAAS,OAAA,EAAQ;AAAA,IACzB;AAEA,IAAA,MAAM,eAAA,GAAkB,KAAK,aAAA,EAAc;AAC3C,IAAA,IAAI;AACF,MAAA,KAAA,MAAW,YAAA,IAAgB,KAAK,cAAA,EAAgB;AAC9C,QAAA,MAAM,eAAA,CAAgB,GAAA,CAAI,kBAAA,EAAoB,CAAC,YAAY,CAAC,CAAA;AAAA,MAC9D;AAAA,IACF,CAAA,SAAE;AACA,MAAA,MAAM,gBAAgB,OAAA,EAAQ;AAAA,IAChC;AAEA,IAAA,MAAM,KAAK,cAAA,IAAiB;AAAA,EAC9B;AAAA,EAEA,aAAA,GAAsB;AACpB,IAAA,MAAM,UAAA,GAAa;AAAA,MACjB,GAAG,IAAA,CAAK,WAAA;AAAA,MACR,QAAA,EAAU;AAAA,KACZ;AACA,IAAA,OAAOL,4BAAA,CAAY;AAAA,MACjB,MAAA,EAAQ,KAAK,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA;AAAA,MACA,IAAA,EAAM;AAAA,QACJ,GAAA,EAAK,CAAA;AAAA,QACL,GAAA,EAAK,CAAA;AAAA,QACL,oBAAA,EAAsB,GAAA;AAAA,QACtB,mBAAA,EAAqB,GAAA;AAAA,QACrB,yBAAA,EAA2B;AAAA;AAC7B,KACD,CAAA;AAAA,EACH;AACF;;;;;;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var errors = require('@backstage/errors');
|
|
4
|
-
var
|
|
4
|
+
var node_crypto = require('node:crypto');
|
|
5
5
|
var knexFactory = require('knex');
|
|
6
6
|
var pgConnectionString = require('pg-connection-string');
|
|
7
7
|
var uuid = require('uuid');
|
|
@@ -97,7 +97,7 @@ class PostgresEngine {
|
|
|
97
97
|
async createDatabaseInstance() {
|
|
98
98
|
const adminConnection = this.#connectAdmin();
|
|
99
99
|
try {
|
|
100
|
-
const databaseName = `db${
|
|
100
|
+
const databaseName = `db${node_crypto.randomBytes(16).toString("hex")}`;
|
|
101
101
|
await adminConnection.raw("CREATE DATABASE ??", [databaseName]);
|
|
102
102
|
this.#databaseNames.push(databaseName);
|
|
103
103
|
const knexInstance = knexFactory__default.default({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.cjs.js","sources":["../../src/database/postgres.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { stringifyError } from '@backstage/errors';\nimport { randomBytes } from 'crypto';\nimport knexFactory, { Knex } from 'knex';\nimport { parse as parsePgConnectionString } from 'pg-connection-string';\nimport { v4 as uuid } from 'uuid';\nimport { Engine, LARGER_POOL_CONFIG, TestDatabaseProperties } from './types';\n\nasync function waitForPostgresReady(\n connection: Knex.PgConnectionConfig,\n): Promise<void> {\n const startTime = Date.now();\n\n let lastError: Error | undefined;\n let attempts = 0;\n for (;;) {\n attempts += 1;\n\n let knex: Knex | undefined;\n try {\n knex = knexFactory({\n client: 'pg',\n connection: {\n // make a copy because the driver mutates this\n ...connection,\n },\n });\n const result = await knex.select(knex.raw('version()'));\n if (Array.isArray(result) && result[0]?.version) {\n return;\n }\n } catch (e) {\n lastError = e;\n } finally {\n await knex?.destroy();\n }\n\n if (Date.now() - startTime > 30_000) {\n throw new Error(\n `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${\n lastError\n ? `last error was ${stringifyError(lastError)}`\n : '(no errors thrown)'\n }`,\n );\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n}\n\nexport async function startPostgresContainer(image: string): Promise<{\n connection: Knex.PgConnectionConfig;\n stopContainer: () => Promise<void>;\n}> {\n const user = 'postgres';\n const password = uuid();\n\n // Lazy-load to avoid side-effect of importing testcontainers\n const { GenericContainer } =\n require('testcontainers') as typeof import('testcontainers');\n\n const container = await new GenericContainer(image)\n .withExposedPorts(5432)\n .withEnvironment({\n // Since postgres 18, the default directory changed - so we pin it here\n PGDATA: '/var/lib/postgresql/data',\n POSTGRES_PASSWORD: password,\n })\n .withTmpFs({ '/var/lib/postgresql/data': 'rw' })\n .start();\n\n const host = container.getHost();\n const port = container.getMappedPort(5432);\n const connection = { host, port, user, password };\n const stopContainer = async () => {\n await container.stop({ timeout: 10_000 });\n };\n\n await waitForPostgresReady(connection);\n\n return { connection, stopContainer };\n}\n\nexport class PostgresEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<PostgresEngine> {\n const { connectionStringEnvironmentVariableName, dockerImageName } =\n properties;\n\n if (connectionStringEnvironmentVariableName) {\n const connectionString =\n process.env[connectionStringEnvironmentVariableName];\n if (connectionString) {\n const connection = parsePgConnectionString(connectionString);\n return new PostgresEngine(\n properties,\n connection as Knex.PgConnectionConfig,\n );\n }\n }\n\n if (dockerImageName) {\n const { connection, stopContainer } = await startPostgresContainer(\n dockerImageName,\n );\n return new PostgresEngine(properties, connection, stopContainer);\n }\n\n throw new Error(`Test databasee for ${properties.name} not configured`);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #connection: Knex.PgConnectionConfig;\n readonly #knexInstances: Knex[];\n readonly #databaseNames: string[];\n readonly #stopContainer?: () => Promise<void>;\n\n constructor(\n properties: TestDatabaseProperties,\n connection: Knex.PgConnectionConfig,\n stopContainer?: () => Promise<void>,\n ) {\n this.#properties = properties;\n this.#connection = connection;\n this.#knexInstances = [];\n this.#databaseNames = [];\n this.#stopContainer = stopContainer;\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const adminConnection = this.#connectAdmin();\n try {\n const databaseName = `db${randomBytes(16).toString('hex')}`;\n\n await adminConnection.raw('CREATE DATABASE ??', [databaseName]);\n this.#databaseNames.push(databaseName);\n\n const knexInstance = knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: databaseName,\n },\n ...LARGER_POOL_CONFIG,\n });\n this.#knexInstances.push(knexInstance);\n\n return knexInstance;\n } finally {\n await adminConnection.destroy();\n }\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#knexInstances) {\n await instance.destroy();\n }\n\n const adminConnection = this.#connectAdmin();\n try {\n for (const databaseName of this.#databaseNames) {\n await adminConnection.raw('DROP DATABASE ??', [databaseName]);\n }\n } finally {\n await adminConnection.destroy();\n }\n\n await this.#stopContainer?.();\n }\n\n #connectAdmin(): Knex {\n return knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: 'postgres',\n },\n pool: {\n acquireTimeoutMillis: 10000,\n },\n });\n }\n}\n"],"names":["knexFactory","stringifyError","uuid","parsePgConnectionString","randomBytes","LARGER_POOL_CONFIG"],"mappings":";;;;;;;;;;;;;AAuBA,eAAe,qBACb,UAAA,EACe;AACf,EAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAE3B,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI,QAAA,GAAW,CAAA;AACf,EAAA,WAAS;AACP,IAAA,QAAA,IAAY,CAAA;AAEZ,IAAA,IAAI,IAAA;AACJ,IAAA,IAAI;AACF,MAAA,IAAA,GAAOA,4BAAA,CAAY;AAAA,QACjB,MAAA,EAAQ,IAAA;AAAA,QACR,UAAA,EAAY;AAAA;AAAA,UAEV,GAAG;AAAA;AACL,OACD,CAAA;AACD,MAAA,MAAM,SAAS,MAAM,IAAA,CAAK,OAAO,IAAA,CAAK,GAAA,CAAI,WAAW,CAAC,CAAA;AACtD,MAAA,IAAI,MAAM,OAAA,CAAQ,MAAM,KAAK,MAAA,CAAO,CAAC,GAAG,OAAA,EAAS;AAC/C,QAAA;AAAA,MACF;AAAA,IACF,SAAS,CAAA,EAAG;AACV,MAAA,SAAA,GAAY,C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AAAA,MACzB,UAAA,EAAY;AAAA,QACV,GAAG,IAAA,CAAK,WAAA;AAAA,QACR,QAAA,EAAU;AAAA,OACZ;AAAA,MACA,IAAA,EAAM;AAAA,QACJ,oBAAA,EAAsB;AAAA;AACxB,KACD,CAAA;AAAA,EACH;AACF;;;;;"}
|
|
1
|
+
{"version":3,"file":"postgres.cjs.js","sources":["../../src/database/postgres.ts"],"sourcesContent":["/*\n * Copyright 2021 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 { stringifyError } from '@backstage/errors';\nimport { randomBytes } from 'node:crypto';\nimport knexFactory, { Knex } from 'knex';\nimport { parse as parsePgConnectionString } from 'pg-connection-string';\nimport { v4 as uuid } from 'uuid';\nimport { Engine, LARGER_POOL_CONFIG, TestDatabaseProperties } from './types';\n\nasync function waitForPostgresReady(\n connection: Knex.PgConnectionConfig,\n): Promise<void> {\n const startTime = Date.now();\n\n let lastError: Error | undefined;\n let attempts = 0;\n for (;;) {\n attempts += 1;\n\n let knex: Knex | undefined;\n try {\n knex = knexFactory({\n client: 'pg',\n connection: {\n // make a copy because the driver mutates this\n ...connection,\n },\n });\n const result = await knex.select(knex.raw('version()'));\n if (Array.isArray(result) && result[0]?.version) {\n return;\n }\n } catch (e) {\n lastError = e;\n } finally {\n await knex?.destroy();\n }\n\n if (Date.now() - startTime > 30_000) {\n throw new Error(\n `Timed out waiting for the database to be ready for connections, ${attempts} attempts, ${\n lastError\n ? `last error was ${stringifyError(lastError)}`\n : '(no errors thrown)'\n }`,\n );\n }\n\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n}\n\nexport async function startPostgresContainer(image: string): Promise<{\n connection: Knex.PgConnectionConfig;\n stopContainer: () => Promise<void>;\n}> {\n const user = 'postgres';\n const password = uuid();\n\n // Lazy-load to avoid side-effect of importing testcontainers\n const { GenericContainer } =\n require('testcontainers') as typeof import('testcontainers');\n\n const container = await new GenericContainer(image)\n .withExposedPorts(5432)\n .withEnvironment({\n // Since postgres 18, the default directory changed - so we pin it here\n PGDATA: '/var/lib/postgresql/data',\n POSTGRES_PASSWORD: password,\n })\n .withTmpFs({ '/var/lib/postgresql/data': 'rw' })\n .start();\n\n const host = container.getHost();\n const port = container.getMappedPort(5432);\n const connection = { host, port, user, password };\n const stopContainer = async () => {\n await container.stop({ timeout: 10_000 });\n };\n\n await waitForPostgresReady(connection);\n\n return { connection, stopContainer };\n}\n\nexport class PostgresEngine implements Engine {\n static async create(\n properties: TestDatabaseProperties,\n ): Promise<PostgresEngine> {\n const { connectionStringEnvironmentVariableName, dockerImageName } =\n properties;\n\n if (connectionStringEnvironmentVariableName) {\n const connectionString =\n process.env[connectionStringEnvironmentVariableName];\n if (connectionString) {\n const connection = parsePgConnectionString(connectionString);\n return new PostgresEngine(\n properties,\n connection as Knex.PgConnectionConfig,\n );\n }\n }\n\n if (dockerImageName) {\n const { connection, stopContainer } = await startPostgresContainer(\n dockerImageName,\n );\n return new PostgresEngine(properties, connection, stopContainer);\n }\n\n throw new Error(`Test databasee for ${properties.name} not configured`);\n }\n\n readonly #properties: TestDatabaseProperties;\n readonly #connection: Knex.PgConnectionConfig;\n readonly #knexInstances: Knex[];\n readonly #databaseNames: string[];\n readonly #stopContainer?: () => Promise<void>;\n\n constructor(\n properties: TestDatabaseProperties,\n connection: Knex.PgConnectionConfig,\n stopContainer?: () => Promise<void>,\n ) {\n this.#properties = properties;\n this.#connection = connection;\n this.#knexInstances = [];\n this.#databaseNames = [];\n this.#stopContainer = stopContainer;\n }\n\n async createDatabaseInstance(): Promise<Knex> {\n const adminConnection = this.#connectAdmin();\n try {\n const databaseName = `db${randomBytes(16).toString('hex')}`;\n\n await adminConnection.raw('CREATE DATABASE ??', [databaseName]);\n this.#databaseNames.push(databaseName);\n\n const knexInstance = knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: databaseName,\n },\n ...LARGER_POOL_CONFIG,\n });\n this.#knexInstances.push(knexInstance);\n\n return knexInstance;\n } finally {\n await adminConnection.destroy();\n }\n }\n\n async shutdown(): Promise<void> {\n for (const instance of this.#knexInstances) {\n await instance.destroy();\n }\n\n const adminConnection = this.#connectAdmin();\n try {\n for (const databaseName of this.#databaseNames) {\n await adminConnection.raw('DROP DATABASE ??', [databaseName]);\n }\n } finally {\n await adminConnection.destroy();\n }\n\n await this.#stopContainer?.();\n }\n\n #connectAdmin(): Knex {\n return knexFactory({\n client: this.#properties.driver,\n connection: {\n ...this.#connection,\n database: 'postgres',\n },\n pool: {\n acquireTimeoutMillis: 10000,\n },\n });\n }\n}\n"],"names":["knexFactory","stringifyError","uuid","parsePgConnectionString","randomBytes","LARGER_POOL_CONFIG"],"mappings":";;;;;;;;;;;;;AAuBA,eAAe,qBACb,UAAA,EACe;AACf,EAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAE3B,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI,QAAA,GAAW,CAAA;AACf,EAAA,WAAS;AACP,IAAA,QAAA,IAAY,CAAA;AAEZ,IAAA,IAAI,IAAA;AACJ,IAAA,IAAI;AACF,MAAA,IAAA,GAAOA,4BAAA,CAAY;AAAA,QACjB,MAAA,EAAQ,IAAA;AAAA,QACR,UAAA,EAAY;AAAA;AAAA,UAEV,GAAG;AAAA;AACL,OACD,CAAA;AACD,MAAA,MAAM,SAAS,MAAM,IAAA,CAAK,OAAO,IAAA,CAAK,GAAA,CAAI,WAAW,CAAC,CAAA;AACtD,MAAA,IAAI,MAAM,OAAA,CAAQ,MAAM,KAAK,MAAA,CAAO,CAAC,GAAG,OAAA,EAAS;AAC/C,QAAA;AAAA,MACF;AAAA,IACF,SA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B,MAAA,EAAQ,KAAK,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY;AAAA,QACV,GAAG,IAAA,CAAK,WAAA;AAAA,QACR,QAAA,EAAU;AAAA,OACZ;AAAA,MACA,IAAA,EAAM;AAAA,QACJ,oBAAA,EAAsB;AAAA;AACxB,KACD,CAAA;AAAA,EACH;AACF;;;;;"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var os = require('os');
|
|
3
|
+
var os = require('node:os');
|
|
4
4
|
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
5
5
|
var fs = require('fs-extra');
|
|
6
6
|
var textextensions = require('text-extensions');
|
|
7
|
-
var
|
|
7
|
+
var node_path = require('node:path');
|
|
8
8
|
|
|
9
9
|
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
10
10
|
|
|
@@ -22,7 +22,7 @@ class MockDirectoryImpl {
|
|
|
22
22
|
return this.#root;
|
|
23
23
|
}
|
|
24
24
|
resolve(...paths) {
|
|
25
|
-
return
|
|
25
|
+
return node_path.resolve(this.#root, ...paths);
|
|
26
26
|
}
|
|
27
27
|
setContent(root) {
|
|
28
28
|
this.remove();
|
|
@@ -31,7 +31,7 @@ class MockDirectoryImpl {
|
|
|
31
31
|
addContent(root) {
|
|
32
32
|
const entries = this.#transformInput(root);
|
|
33
33
|
for (const entry of entries) {
|
|
34
|
-
const fullPath =
|
|
34
|
+
const fullPath = node_path.resolve(this.#root, entry.path);
|
|
35
35
|
if (!backendPluginApi.isChildPath(this.#root, fullPath)) {
|
|
36
36
|
throw new Error(
|
|
37
37
|
`Provided path must resolve to a child path of the mock directory, got '${fullPath}'`
|
|
@@ -40,10 +40,10 @@ class MockDirectoryImpl {
|
|
|
40
40
|
if (entry.type === "dir") {
|
|
41
41
|
fs__default.default.ensureDirSync(fullPath);
|
|
42
42
|
} else if (entry.type === "file") {
|
|
43
|
-
fs__default.default.ensureDirSync(
|
|
43
|
+
fs__default.default.ensureDirSync(node_path.dirname(fullPath));
|
|
44
44
|
fs__default.default.writeFileSync(fullPath, entry.content);
|
|
45
45
|
} else if (entry.type === "callback") {
|
|
46
|
-
fs__default.default.ensureDirSync(
|
|
46
|
+
fs__default.default.ensureDirSync(node_path.dirname(fullPath));
|
|
47
47
|
entry.callback({
|
|
48
48
|
path: fullPath,
|
|
49
49
|
symlink(target) {
|
|
@@ -54,26 +54,26 @@ class MockDirectoryImpl {
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
content(options) {
|
|
57
|
-
const shouldReadAsText = (typeof options?.shouldReadAsText === "boolean" ? () => options?.shouldReadAsText : options?.shouldReadAsText) ?? ((path
|
|
58
|
-
const root =
|
|
57
|
+
const shouldReadAsText = (typeof options?.shouldReadAsText === "boolean" ? () => options?.shouldReadAsText : options?.shouldReadAsText) ?? ((path) => textextensions__default.default.includes(node_path.extname(path).slice(1)));
|
|
58
|
+
const root = node_path.resolve(this.#root, options?.path ?? "");
|
|
59
59
|
if (!backendPluginApi.isChildPath(this.#root, root)) {
|
|
60
60
|
throw new Error(
|
|
61
61
|
`Provided path must resolve to a child path of the mock directory, got '${root}'`
|
|
62
62
|
);
|
|
63
63
|
}
|
|
64
|
-
function read(path
|
|
65
|
-
if (!fs__default.default.pathExistsSync(path
|
|
64
|
+
function read(path) {
|
|
65
|
+
if (!fs__default.default.pathExistsSync(path)) {
|
|
66
66
|
return void 0;
|
|
67
67
|
}
|
|
68
|
-
const entries = fs__default.default.readdirSync(path
|
|
68
|
+
const entries = fs__default.default.readdirSync(path, { withFileTypes: true });
|
|
69
69
|
return Object.fromEntries(
|
|
70
70
|
entries.map((entry) => {
|
|
71
|
-
const fullPath =
|
|
71
|
+
const fullPath = node_path.resolve(path, entry.name);
|
|
72
72
|
if (entry.isDirectory()) {
|
|
73
73
|
return [entry.name, read(fullPath)];
|
|
74
74
|
}
|
|
75
75
|
const content = fs__default.default.readFileSync(fullPath);
|
|
76
|
-
const relativePosixPath =
|
|
76
|
+
const relativePosixPath = node_path.relative(root, fullPath).split(node_path.win32.sep).join(node_path.posix.sep);
|
|
77
77
|
if (shouldReadAsText(relativePosixPath, content)) {
|
|
78
78
|
return [entry.name, content.toString("utf8")];
|
|
79
79
|
}
|
|
@@ -139,7 +139,7 @@ function registerTestHooks() {
|
|
|
139
139
|
registerTestHooks();
|
|
140
140
|
function createMockDirectory(options) {
|
|
141
141
|
const tmpDir = process.env.RUNNER_TEMP || os__default.default.tmpdir();
|
|
142
|
-
const root = fs__default.default.mkdtempSync(
|
|
142
|
+
const root = fs__default.default.mkdtempSync(node_path.join(tmpDir, "backstage-tmp-test-dir-"));
|
|
143
143
|
const mocker = new MockDirectoryImpl(root);
|
|
144
144
|
const origTmpdir = options?.mockOsTmpDir ? os__default.default.tmpdir : void 0;
|
|
145
145
|
if (origTmpdir) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockDirectory.cjs.js","sources":["../../src/filesystem/MockDirectory.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport os from 'os';\nimport { isChildPath } from '@backstage/backend-plugin-api';\nimport fs from 'fs-extra';\nimport textextensions from 'text-extensions';\nimport {\n dirname,\n extname,\n join as joinPath,\n resolve as resolvePath,\n relative as relativePath,\n win32,\n posix,\n} from 'path';\n\nconst tmpdirMarker = Symbol('os-tmpdir-mock');\n\n/**\n * A context that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport interface MockDirectoryContentCallbackContext {\n /** Absolute path to the location of this piece of content on the filesystem */\n path: string;\n\n /** Creates a symbolic link at the current location */\n symlink(target: string): void;\n}\n\n/**\n * A callback that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport type MockDirectoryContentCallback = (\n ctx: MockDirectoryContentCallbackContext,\n) => void;\n\n/**\n * The content of a mock directory represented by a nested object structure.\n *\n * @remarks\n *\n * When used as input, the keys may contain forward slashes to indicate nested directories.\n * Then returned as output, each directory will always be represented as a separate object.\n *\n * @example\n * ```ts\n * {\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * }\n * ```\n *\n * @public\n */\nexport type MockDirectoryContent = {\n [name in string]:\n | MockDirectoryContent\n | string\n | Buffer\n | MockDirectoryContentCallback;\n};\n\n/**\n * Options for {@link MockDirectory.content}.\n *\n * @public\n */\nexport interface MockDirectoryContentOptions {\n /**\n * The path to read content from. Defaults to the root of the mock directory.\n *\n * An absolute path can also be provided, as long as it is a child path of the mock directory.\n */\n path?: string;\n\n /**\n * Whether or not to return files as text rather than buffers.\n *\n * Defaults to checking the file extension against a list of known text extensions.\n */\n shouldReadAsText?: boolean | ((path: string, buffer: Buffer) => boolean);\n}\n\n/**\n * A utility for creating a mock directory that is automatically cleaned up.\n *\n * @public\n */\nexport interface MockDirectory {\n /**\n * The path to the root of the mock directory\n */\n readonly path: string;\n\n /**\n * Resolves a path relative to the root of the mock directory.\n */\n resolve(...paths: string[]): string;\n\n /**\n * Sets the content of the mock directory. This will remove any existing content.\n *\n * @example\n * ```ts\n * mockDir.setContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n setContent(root: MockDirectoryContent): void;\n\n /**\n * Adds content of the mock directory. This will overwrite existing files.\n *\n * @example\n * ```ts\n * mockDir.addContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n addContent(root: MockDirectoryContent): void;\n\n /**\n * Reads the content of the mock directory.\n *\n * @remarks\n *\n * Text files will be returned as strings, while binary files will be returned as buffers.\n * By default the file extension is used to determine whether a file should be read as text.\n *\n * @example\n * ```ts\n * expect(mockDir.content()).toEqual({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir': {\n * 'file.txt': 'content',\n * },\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined;\n\n /**\n * Clears the content of the mock directory, ensuring that the directory itself exists.\n */\n clear(): void;\n\n /**\n * Removes the mock directory and all its contents.\n */\n remove(): void;\n}\n\n/** @internal */\ntype MockEntry =\n | {\n type: 'file';\n path: string;\n content: Buffer;\n }\n | {\n type: 'dir';\n path: string;\n }\n | {\n type: 'callback';\n path: string;\n callback: MockDirectoryContentCallback;\n };\n\n/** @internal */\nclass MockDirectoryImpl {\n readonly #root: string;\n\n constructor(root: string) {\n this.#root = root;\n }\n\n get path(): string {\n return this.#root;\n }\n\n resolve(...paths: string[]): string {\n return resolvePath(this.#root, ...paths);\n }\n\n setContent(root: MockDirectoryContent): void {\n this.remove();\n\n return this.addContent(root);\n }\n\n addContent(root: MockDirectoryContent): void {\n const entries = this.#transformInput(root);\n\n for (const entry of entries) {\n const fullPath = resolvePath(this.#root, entry.path);\n if (!isChildPath(this.#root, fullPath)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${fullPath}'`,\n );\n }\n\n if (entry.type === 'dir') {\n fs.ensureDirSync(fullPath);\n } else if (entry.type === 'file') {\n fs.ensureDirSync(dirname(fullPath));\n fs.writeFileSync(fullPath, entry.content);\n } else if (entry.type === 'callback') {\n fs.ensureDirSync(dirname(fullPath));\n entry.callback({\n path: fullPath,\n symlink(target: string) {\n fs.symlinkSync(target, fullPath);\n },\n });\n }\n }\n }\n\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined {\n const shouldReadAsText =\n (typeof options?.shouldReadAsText === 'boolean'\n ? () => options?.shouldReadAsText\n : options?.shouldReadAsText) ??\n ((path: string) => textextensions.includes(extname(path).slice(1)));\n\n const root = resolvePath(this.#root, options?.path ?? '');\n if (!isChildPath(this.#root, root)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${root}'`,\n );\n }\n\n function read(path: string): MockDirectoryContent | undefined {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n\n const entries = fs.readdirSync(path, { withFileTypes: true });\n return Object.fromEntries(\n entries.map(entry => {\n const fullPath = resolvePath(path, entry.name);\n\n if (entry.isDirectory()) {\n return [entry.name, read(fullPath)];\n }\n const content = fs.readFileSync(fullPath);\n const relativePosixPath = relativePath(root, fullPath)\n .split(win32.sep)\n .join(posix.sep);\n\n if (shouldReadAsText(relativePosixPath, content)) {\n return [entry.name, content.toString('utf8')];\n }\n return [entry.name, content];\n }),\n );\n }\n\n return read(root);\n }\n\n clear = (): void => {\n this.setContent({});\n };\n\n remove = (): void => {\n fs.rmSync(this.#root, { recursive: true, force: true, maxRetries: 10 });\n };\n\n #transformInput(input: MockDirectoryContent[string]): MockEntry[] {\n const entries: MockEntry[] = [];\n\n function traverse(node: MockDirectoryContent[string], path: string) {\n if (typeof node === 'string') {\n entries.push({\n type: 'file',\n path,\n content: Buffer.from(node, 'utf8'),\n });\n } else if (node instanceof Buffer) {\n entries.push({ type: 'file', path, content: node });\n } else if (typeof node === 'function') {\n entries.push({ type: 'callback', path, callback: node });\n } else {\n entries.push({ type: 'dir', path });\n for (const [name, child] of Object.entries(node)) {\n traverse(child, path ? `${path}/${name}` : name);\n }\n }\n }\n\n traverse(input, '');\n\n return entries;\n }\n}\n\n/**\n * Options for {@link createMockDirectory}.\n *\n * @public\n */\nexport interface CreateMockDirectoryOptions {\n /**\n * In addition to creating a temporary directory, also mock `os.tmpdir()` to\n * return the mock directory path until the end of the test suite.\n *\n * When this option is provided the `createMockDirectory` call must happen in\n * a scope where calling `afterAll` from Jest is allowed\n *\n * @returns\n */\n mockOsTmpDir?: boolean;\n\n /**\n * Initializes the directory with the given content, see {@link MockDirectory.setContent}.\n */\n content?: MockDirectoryContent;\n}\n\nconst cleanupCallbacks = new Array<() => void>();\n\nlet registered = false;\nfunction registerTestHooks() {\n if (typeof afterAll !== 'function') {\n return;\n }\n if (registered) {\n return;\n }\n registered = true;\n\n afterAll(async () => {\n for (const callback of cleanupCallbacks) {\n try {\n callback();\n } catch (error) {\n console.error(\n `Failed to clean up mock directory after tests, ${error}`,\n );\n }\n }\n cleanupCallbacks.length = 0;\n });\n}\n\nregisterTestHooks();\n\n/**\n * Creates a new temporary mock directory that will be removed after the tests have completed.\n *\n * @public\n * @remarks\n *\n * This method is intended to be called outside of any test, either at top-level or\n * within a `describe` block. It will call `afterAll` to make sure that the mock directory\n * is removed after the tests have run.\n *\n * @example\n * ```ts\n * describe('MySubject', () => {\n * const mockDir = createMockDirectory();\n *\n * beforeEach(mockDir.clear);\n *\n * it('should work', () => {\n * // ... use mockDir\n * })\n * })\n * ```\n */\nexport function createMockDirectory(\n options?: CreateMockDirectoryOptions,\n): MockDirectory {\n const tmpDir = process.env.RUNNER_TEMP || os.tmpdir(); // GitHub Actions\n const root = fs.mkdtempSync(joinPath(tmpDir, 'backstage-tmp-test-dir-'));\n\n const mocker = new MockDirectoryImpl(root);\n\n const origTmpdir = options?.mockOsTmpDir ? os.tmpdir : undefined;\n if (origTmpdir) {\n if (Object.hasOwn(origTmpdir, tmpdirMarker)) {\n throw new Error(\n 'Cannot mock os.tmpdir() when it has already been mocked',\n );\n }\n const mock = Object.assign(() => mocker.path, { [tmpdirMarker]: true });\n os.tmpdir = mock;\n }\n\n // In CI we expect there to be no need to clean up temporary directories\n const needsCleanup = !process.env.CI;\n if (needsCleanup) {\n process.on('beforeExit', mocker.remove);\n }\n\n if (needsCleanup) {\n cleanupCallbacks.push(() => mocker.remove());\n }\n\n if (origTmpdir) {\n afterAll(() => {\n os.tmpdir = origTmpdir;\n });\n }\n\n if (options?.content) {\n mocker.setContent(options.content);\n }\n\n return mocker;\n}\n"],"names":["resolvePath","isChildPath","fs","dirname","path","textextensions","extname","relativePath","win32","posix","os","joinPath"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,YAAA,0BAAsB,gBAAgB,CAAA;AAwL5C,MAAM,iBAAA,CAAkB;AAAA,EACb,KAAA;AAAA,EAET,YAAY,IAAA,EAAc;AACxB,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AAAA,EACf;AAAA,EAEA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA,EAEA,WAAW,KAAA,EAAyB;AAClC,IAAA,OAAOA,YAAA,CAAY,IAAA,CAAK,KAAA,EAAO,GAAG,KAAK,CAAA;AAAA,EACzC;AAAA,EAEA,WAAW,IAAA,EAAkC;AAC3C,IAAA,IAAA,CAAK,MAAA,EAAO;AAEZ,IAAA,OAAO,IAAA,CAAK,WAAW,IAAI,CAAA;AAAA,EAC7B;AAAA,EAEA,WAAW,IAAA,EAAkC;AAC3C,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,eAAA,CAAgB,IAAI,CAAA;AAEzC,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,MAAM,QAAA,GAAWA,YAAA,CAAY,IAAA,CAAK,KAAA,EAAO,MAAM,IAAI,CAAA;AACnD,MAAA,IAAI,CAACC,4BAAA,CAAY,IAAA,CAAK,KAAA,EAAO,QAAQ,CAAA,EAAG;AACtC,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,0EAA0E,QAAQ,CAAA,CAAA;AAAA,SACpF;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I,EAAA;AAClC,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,OAAA,CAAQ,EAAA,CAAG,YAAA,EAAc,MAAA,CAAO,MAAM,CAAA;AAAA,EACxC;AAEA,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,gBAAA,CAAiB,IAAA,CAAK,MAAM,MAAA,CAAO,MAAA,EAAQ,CAAA;AAAA,EAC7C;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,QAAA,CAAS,MAAM;AACb,MAAAA,mBAAA,CAAG,MAAA,GAAS,UAAA;AAAA,IACd,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,IAAI,SAAS,OAAA,EAAS;AACpB,IAAA,MAAA,CAAO,UAAA,CAAW,QAAQ,OAAO,CAAA;AAAA,EACnC;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"MockDirectory.cjs.js","sources":["../../src/filesystem/MockDirectory.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport os from 'node:os';\nimport { isChildPath } from '@backstage/backend-plugin-api';\nimport fs from 'fs-extra';\nimport textextensions from 'text-extensions';\nimport {\n dirname,\n extname,\n join as joinPath,\n resolve as resolvePath,\n relative as relativePath,\n win32,\n posix,\n} from 'node:path';\n\nconst tmpdirMarker = Symbol('os-tmpdir-mock');\n\n/**\n * A context that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport interface MockDirectoryContentCallbackContext {\n /** Absolute path to the location of this piece of content on the filesystem */\n path: string;\n\n /** Creates a symbolic link at the current location */\n symlink(target: string): void;\n}\n\n/**\n * A callback that allows for more advanced file system operations when writing mock directory content.\n *\n * @public\n */\nexport type MockDirectoryContentCallback = (\n ctx: MockDirectoryContentCallbackContext,\n) => void;\n\n/**\n * The content of a mock directory represented by a nested object structure.\n *\n * @remarks\n *\n * When used as input, the keys may contain forward slashes to indicate nested directories.\n * Then returned as output, each directory will always be represented as a separate object.\n *\n * @example\n * ```ts\n * {\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * }\n * ```\n *\n * @public\n */\nexport type MockDirectoryContent = {\n [name in string]:\n | MockDirectoryContent\n | string\n | Buffer\n | MockDirectoryContentCallback;\n};\n\n/**\n * Options for {@link MockDirectory.content}.\n *\n * @public\n */\nexport interface MockDirectoryContentOptions {\n /**\n * The path to read content from. Defaults to the root of the mock directory.\n *\n * An absolute path can also be provided, as long as it is a child path of the mock directory.\n */\n path?: string;\n\n /**\n * Whether or not to return files as text rather than buffers.\n *\n * Defaults to checking the file extension against a list of known text extensions.\n */\n shouldReadAsText?: boolean | ((path: string, buffer: Buffer) => boolean);\n}\n\n/**\n * A utility for creating a mock directory that is automatically cleaned up.\n *\n * @public\n */\nexport interface MockDirectory {\n /**\n * The path to the root of the mock directory\n */\n readonly path: string;\n\n /**\n * Resolves a path relative to the root of the mock directory.\n */\n resolve(...paths: string[]): string;\n\n /**\n * Sets the content of the mock directory. This will remove any existing content.\n *\n * @example\n * ```ts\n * mockDir.setContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n setContent(root: MockDirectoryContent): void;\n\n /**\n * Adds content of the mock directory. This will overwrite existing files.\n *\n * @example\n * ```ts\n * mockDir.addContent({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir/file.txt': 'content',\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n addContent(root: MockDirectoryContent): void;\n\n /**\n * Reads the content of the mock directory.\n *\n * @remarks\n *\n * Text files will be returned as strings, while binary files will be returned as buffers.\n * By default the file extension is used to determine whether a file should be read as text.\n *\n * @example\n * ```ts\n * expect(mockDir.content()).toEqual({\n * 'test.txt': 'content',\n * 'sub-dir': {\n * 'file.txt': 'content',\n * 'nested-dir': {\n * 'file.txt': 'content',\n * },\n * },\n * 'empty-dir': {},\n * 'binary-file': Buffer.from([0, 1, 2]),\n * });\n * ```\n */\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined;\n\n /**\n * Clears the content of the mock directory, ensuring that the directory itself exists.\n */\n clear(): void;\n\n /**\n * Removes the mock directory and all its contents.\n */\n remove(): void;\n}\n\n/** @internal */\ntype MockEntry =\n | {\n type: 'file';\n path: string;\n content: Buffer;\n }\n | {\n type: 'dir';\n path: string;\n }\n | {\n type: 'callback';\n path: string;\n callback: MockDirectoryContentCallback;\n };\n\n/** @internal */\nclass MockDirectoryImpl {\n readonly #root: string;\n\n constructor(root: string) {\n this.#root = root;\n }\n\n get path(): string {\n return this.#root;\n }\n\n resolve(...paths: string[]): string {\n return resolvePath(this.#root, ...paths);\n }\n\n setContent(root: MockDirectoryContent): void {\n this.remove();\n\n return this.addContent(root);\n }\n\n addContent(root: MockDirectoryContent): void {\n const entries = this.#transformInput(root);\n\n for (const entry of entries) {\n const fullPath = resolvePath(this.#root, entry.path);\n if (!isChildPath(this.#root, fullPath)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${fullPath}'`,\n );\n }\n\n if (entry.type === 'dir') {\n fs.ensureDirSync(fullPath);\n } else if (entry.type === 'file') {\n fs.ensureDirSync(dirname(fullPath));\n fs.writeFileSync(fullPath, entry.content);\n } else if (entry.type === 'callback') {\n fs.ensureDirSync(dirname(fullPath));\n entry.callback({\n path: fullPath,\n symlink(target: string) {\n fs.symlinkSync(target, fullPath);\n },\n });\n }\n }\n }\n\n content(\n options?: MockDirectoryContentOptions,\n ): MockDirectoryContent | undefined {\n const shouldReadAsText =\n (typeof options?.shouldReadAsText === 'boolean'\n ? () => options?.shouldReadAsText\n : options?.shouldReadAsText) ??\n ((path: string) => textextensions.includes(extname(path).slice(1)));\n\n const root = resolvePath(this.#root, options?.path ?? '');\n if (!isChildPath(this.#root, root)) {\n throw new Error(\n `Provided path must resolve to a child path of the mock directory, got '${root}'`,\n );\n }\n\n function read(path: string): MockDirectoryContent | undefined {\n if (!fs.pathExistsSync(path)) {\n return undefined;\n }\n\n const entries = fs.readdirSync(path, { withFileTypes: true });\n return Object.fromEntries(\n entries.map(entry => {\n const fullPath = resolvePath(path, entry.name);\n\n if (entry.isDirectory()) {\n return [entry.name, read(fullPath)];\n }\n const content = fs.readFileSync(fullPath);\n const relativePosixPath = relativePath(root, fullPath)\n .split(win32.sep)\n .join(posix.sep);\n\n if (shouldReadAsText(relativePosixPath, content)) {\n return [entry.name, content.toString('utf8')];\n }\n return [entry.name, content];\n }),\n );\n }\n\n return read(root);\n }\n\n clear = (): void => {\n this.setContent({});\n };\n\n remove = (): void => {\n fs.rmSync(this.#root, { recursive: true, force: true, maxRetries: 10 });\n };\n\n #transformInput(input: MockDirectoryContent[string]): MockEntry[] {\n const entries: MockEntry[] = [];\n\n function traverse(node: MockDirectoryContent[string], path: string) {\n if (typeof node === 'string') {\n entries.push({\n type: 'file',\n path,\n content: Buffer.from(node, 'utf8'),\n });\n } else if (node instanceof Buffer) {\n entries.push({ type: 'file', path, content: node });\n } else if (typeof node === 'function') {\n entries.push({ type: 'callback', path, callback: node });\n } else {\n entries.push({ type: 'dir', path });\n for (const [name, child] of Object.entries(node)) {\n traverse(child, path ? `${path}/${name}` : name);\n }\n }\n }\n\n traverse(input, '');\n\n return entries;\n }\n}\n\n/**\n * Options for {@link createMockDirectory}.\n *\n * @public\n */\nexport interface CreateMockDirectoryOptions {\n /**\n * In addition to creating a temporary directory, also mock `os.tmpdir()` to\n * return the mock directory path until the end of the test suite.\n *\n * When this option is provided the `createMockDirectory` call must happen in\n * a scope where calling `afterAll` from Jest is allowed\n *\n * @returns\n */\n mockOsTmpDir?: boolean;\n\n /**\n * Initializes the directory with the given content, see {@link MockDirectory.setContent}.\n */\n content?: MockDirectoryContent;\n}\n\nconst cleanupCallbacks = new Array<() => void>();\n\nlet registered = false;\nfunction registerTestHooks() {\n if (typeof afterAll !== 'function') {\n return;\n }\n if (registered) {\n return;\n }\n registered = true;\n\n afterAll(async () => {\n for (const callback of cleanupCallbacks) {\n try {\n callback();\n } catch (error) {\n console.error(\n `Failed to clean up mock directory after tests, ${error}`,\n );\n }\n }\n cleanupCallbacks.length = 0;\n });\n}\n\nregisterTestHooks();\n\n/**\n * Creates a new temporary mock directory that will be removed after the tests have completed.\n *\n * @public\n * @remarks\n *\n * This method is intended to be called outside of any test, either at top-level or\n * within a `describe` block. It will call `afterAll` to make sure that the mock directory\n * is removed after the tests have run.\n *\n * @example\n * ```ts\n * describe('MySubject', () => {\n * const mockDir = createMockDirectory();\n *\n * beforeEach(mockDir.clear);\n *\n * it('should work', () => {\n * // ... use mockDir\n * })\n * })\n * ```\n */\nexport function createMockDirectory(\n options?: CreateMockDirectoryOptions,\n): MockDirectory {\n const tmpDir = process.env.RUNNER_TEMP || os.tmpdir(); // GitHub Actions\n const root = fs.mkdtempSync(joinPath(tmpDir, 'backstage-tmp-test-dir-'));\n\n const mocker = new MockDirectoryImpl(root);\n\n const origTmpdir = options?.mockOsTmpDir ? os.tmpdir : undefined;\n if (origTmpdir) {\n if (Object.hasOwn(origTmpdir, tmpdirMarker)) {\n throw new Error(\n 'Cannot mock os.tmpdir() when it has already been mocked',\n );\n }\n const mock = Object.assign(() => mocker.path, { [tmpdirMarker]: true });\n os.tmpdir = mock;\n }\n\n // In CI we expect there to be no need to clean up temporary directories\n const needsCleanup = !process.env.CI;\n if (needsCleanup) {\n process.on('beforeExit', mocker.remove);\n }\n\n if (needsCleanup) {\n cleanupCallbacks.push(() => mocker.remove());\n }\n\n if (origTmpdir) {\n afterAll(() => {\n os.tmpdir = origTmpdir;\n });\n }\n\n if (options?.content) {\n mocker.setContent(options.content);\n }\n\n return mocker;\n}\n"],"names":["resolvePath","isChildPath","fs","dirname","textextensions","extname","relativePath","win32","posix","os","joinPath"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,YAAA,0BAAsB,gBAAgB,CAAA;AAwL5C,MAAM,iBAAA,CAAkB;AAAA,EACb,KAAA;AAAA,EAET,YAAY,IAAA,EAAc;AACxB,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA;AAAA,EACf;AAAA,EAEA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AAAA,EAEA,WAAW,KAAA,EAAyB;AAClC,IAAA,OAAOA,iBAAA,CAAY,IAAA,CAAK,KAAA,EAAO,GAAG,KAAK,CAAA;AAAA,EACzC;AAAA,EAEA,WAAW,IAAA,EAAkC;AAC3C,IAAA,IAAA,CAAK,MAAA,EAAO;AAEZ,IAAA,OAAO,IAAA,CAAK,WAAW,IAAI,CAAA;AAAA,EAC7B;AAAA,EAEA,WAAW,IAAA,EAAkC;AAC3C,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,eAAA,CAAgB,IAAI,CAAA;AAEzC,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,MAAM,QAAA,GAAWA,iBAAA,CAAY,IAAA,CAAK,KAAA,EAAO,MAAM,IAAI,CAAA;AACnD,MAAA,IAAI,CAACC,4BAAA,CAAY,IAAA,CAAK,KAAA,EAAO,QAAQ,CAAA,EAAG;AACtC,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,0EAA0E,QAAQ,CAAA,CAAA;AAAA,SACpF;AAAA,MACF;AAEA,MAAA,IAAI,KAAA,CAAM,SAAS,K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A,OAAA,CAAQ,EAAA,CAAG,YAAA,EAAc,MAAA,CAAO,MAAM,CAAA;AAAA,EACxC;AAEA,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,gBAAA,CAAiB,IAAA,CAAK,MAAM,MAAA,CAAO,MAAA,EAAQ,CAAA;AAAA,EAC7C;AAEA,EAAA,IAAI,UAAA,EAAY;AACd,IAAA,QAAA,CAAS,MAAM;AACb,MAAAA,mBAAA,CAAG,MAAA,GAAS,UAAA;AAAA,IACd,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,IAAI,SAAS,OAAA,EAAS;AACpB,IAAA,MAAA,CAAO,UAAA,CAAW,QAAQ,OAAO,CAAA;AAAA,EACnC;AAEA,EAAA,OAAO,MAAA;AACT;;;;"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -6,6 +6,7 @@ var registerMswTestHooks = require('./msw/registerMswTestHooks.cjs.js');
|
|
|
6
6
|
var MockDirectory = require('./filesystem/MockDirectory.cjs.js');
|
|
7
7
|
var mockServices = require('./services/mockServices.cjs.js');
|
|
8
8
|
var mockCredentials = require('./services/mockCredentials.cjs.js');
|
|
9
|
+
var createServiceMock = require('./services/createServiceMock.cjs.js');
|
|
9
10
|
var ServiceFactoryTester = require('./wiring/ServiceFactoryTester.cjs.js');
|
|
10
11
|
var TestBackend = require('./wiring/TestBackend.cjs.js');
|
|
11
12
|
var errorHandler = require('./util/errorHandler.cjs.js');
|
|
@@ -24,6 +25,7 @@ Object.defineProperty(exports, "mockCredentials", {
|
|
|
24
25
|
enumerable: true,
|
|
25
26
|
get: function () { return mockCredentials.mockCredentials; }
|
|
26
27
|
});
|
|
28
|
+
exports.createServiceMock = createServiceMock.createServiceMock;
|
|
27
29
|
exports.ServiceFactoryTester = ServiceFactoryTester.ServiceFactoryTester;
|
|
28
30
|
exports.startTestBackend = TestBackend.startTestBackend;
|
|
29
31
|
exports.mockErrorHandler = errorHandler.mockErrorHandler;
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import Keyv from 'keyv';
|
|
2
2
|
import { Knex } from 'knex';
|
|
3
3
|
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
4
|
-
import {
|
|
4
|
+
import { RootConfigService, ServiceFactory, RootLoggerService, AuthService, DiscoveryService, BackstageCredentials, HttpAuthService, BackstageUserInfo, UserInfoService, DatabaseService, PermissionsService, SchedulerService, RootInstanceMetadataService, BackstageNonePrincipal, BackstageUserPrincipal, BackstagePrincipalAccessRestrictions, BackstageServicePrincipal, ServiceRef, ExtensionPoint, BackendFeature } from '@backstage/backend-plugin-api';
|
|
5
|
+
import { S as ServiceMock } from './types/createServiceMock.d-CeKvILsY.js';
|
|
6
|
+
export { c as createServiceMock } from './types/createServiceMock.d-CeKvILsY.js';
|
|
5
7
|
import { EventsService } from '@backstage/plugin-events-node';
|
|
6
8
|
import { AuthorizeResult } from '@backstage/plugin-permission-common';
|
|
7
9
|
import { JsonObject } from '@backstage/types';
|
|
@@ -316,13 +318,6 @@ interface CreateMockDirectoryOptions {
|
|
|
316
318
|
*/
|
|
317
319
|
declare function createMockDirectory(options?: CreateMockDirectoryOptions): MockDirectory;
|
|
318
320
|
|
|
319
|
-
/** @public */
|
|
320
|
-
type ServiceMock<TService> = {
|
|
321
|
-
factory: ServiceFactory<TService>;
|
|
322
|
-
} & {
|
|
323
|
-
[Key in keyof TService]: TService[Key] extends (...args: infer Args) => infer Return ? TService[Key] & jest.MockInstance<Return, Args> : TService[Key];
|
|
324
|
-
};
|
|
325
|
-
|
|
326
321
|
/**
|
|
327
322
|
* Mock implementations of the core services, to be used in tests.
|
|
328
323
|
*
|
|
@@ -785,5 +780,5 @@ declare function startTestBackend<TExtensionPoints extends any[]>(options: TestB
|
|
|
785
780
|
*/
|
|
786
781
|
declare function mockErrorHandler(_options?: {}, ..._args: never[]): express.ErrorRequestHandler<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>>;
|
|
787
782
|
|
|
788
|
-
export { ServiceFactoryTester, TestCaches, TestDatabases, createMockDirectory, mockCredentials, mockErrorHandler, mockServices, registerMswTestHooks, startTestBackend };
|
|
789
|
-
export type { CreateMockDirectoryOptions, MockDirectory, MockDirectoryContent, MockDirectoryContentCallback, MockDirectoryContentCallbackContext, MockDirectoryContentOptions, ServiceFactoryTesterOptions,
|
|
783
|
+
export { ServiceFactoryTester, ServiceMock, TestCaches, TestDatabases, createMockDirectory, mockCredentials, mockErrorHandler, mockServices, registerMswTestHooks, startTestBackend };
|
|
784
|
+
export type { CreateMockDirectoryOptions, MockDirectory, MockDirectoryContent, MockDirectoryContentCallback, MockDirectoryContentCallbackContext, MockDirectoryContentOptions, ServiceFactoryTesterOptions, TestBackend, TestBackendOptions, TestCacheId, TestDatabaseId };
|