internal-opaque -> opaque-internal

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2024-09-20 10:23:58 +02:00
parent c01c7d0c7e
commit 3a62ce217b
8 changed files with 3 additions and 3 deletions
+5
View File
@@ -0,0 +1,5 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname, {
rules: {
'@backstage/no-top-level-material-ui-4-imports': 'error',
},
});
+3
View File
@@ -0,0 +1,3 @@
# @internal/opaque
This is an internal package for use by other internal packages. Instances created with `OpaqueType.create` should never be exported in any public API, instead use an `@internal/*` if they need to be used in multiple packages.
@@ -0,0 +1,9 @@
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: internal-opaque
title: "@internal/opaque"
spec:
lifecycle: experimental
type: backstage-common-library
owner: maintainers
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@internal/opaque",
"version": "0.0.1",
"backstage": {
"role": "common-library",
"inline": true
},
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/backstage/backstage",
"directory": "packages/opaque-internal"
},
"license": "Apache-2.0",
"sideEffects": false,
"main": "src/index.ts",
"types": "src/index.ts",
"files": [
"dist"
],
"scripts": {
"lint": "backstage-cli package lint",
"test": "backstage-cli package test"
},
"devDependencies": {
"@backstage/cli": "workspace:^",
"@testing-library/jest-dom": "^6.0.0",
"@testing-library/react": "^16.0.0"
}
}
@@ -0,0 +1,416 @@
/*
* 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 { OpaqueType } from './OpaqueType';
describe('OpaqueType', () => {
it('should create a basic opaque type with a single version', () => {
type MyType = {
$$type: 'my-type';
};
const OpaqueMyType = OpaqueType.create<{
public: MyType;
versions: {
version: 'v1';
foo: string;
};
}>({
type: 'my-type',
versions: ['v1'],
});
// @ts-expect-error - unsupported version
OpaqueMyType.createInstance('v2', {
foo: 'bar',
});
// @ts-expect-error - missing internal field
OpaqueMyType.createInstance('v1', {});
OpaqueMyType.createInstance('v1', {
// @ts-expect-error - invalid internal field
foo: 3,
});
const myInstance = OpaqueMyType.createInstance('v1', {
foo: 'bar',
});
expect(myInstance.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstance.version).toBe('v1');
// @ts-expect-error - internal field not accessible
expect(myInstance.foo).toBe('bar');
expect(OpaqueMyType.isType(myInstance)).toBe(true);
expect(OpaqueMyType.isType('hello')).toBe(false);
expect(OpaqueMyType.isType({ $$type: 'some-other' })).toBe(false);
expect(OpaqueMyType.isType({ $$type: 'my-type' })).toBe(true);
const myInternal = OpaqueMyType.toInternal(myInstance);
expect(myInternal).toBe(myInstance);
// All fields accessible
expect(myInternal.$$type).toBe('my-type');
expect(myInternal.version).toBe('v1');
expect(myInternal.foo).toBe('bar');
expect(() =>
OpaqueMyType.toInternal('hello'),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<string>'"`,
);
expect(() => OpaqueMyType.toInternal(3)).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<number>'"`,
);
expect(() =>
OpaqueMyType.toInternal(undefined),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<undefined>'"`,
);
expect(() =>
OpaqueMyType.toInternal(Symbol('wat')),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<symbol>'"`,
);
expect(() =>
OpaqueMyType.toInternal(null),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<null>'"`,
);
expect(() =>
OpaqueMyType.toInternal(() => {}),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '<function>'"`,
);
expect(() =>
OpaqueMyType.toInternal({ $$type: 'some-other-type' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got 'some-other-type'"`,
);
expect(() =>
OpaqueMyType.toInternal({ an: 'object' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type, expected 'my-type', but got '[object Object]'"`,
);
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version undefined, expected 'v1'"`,
);
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type', version: 'v0' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version 'v0', expected 'v1'"`,
);
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type', version: { foo: 'bar' } }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version '[object Object]', expected 'v1'"`,
);
});
it('should create a basic opaque type with multiple versions', () => {
type MyType = {
$$type: 'my-type';
};
const OpaqueMyType = OpaqueType.create<{
public: MyType;
versions:
| {
version: 'v1';
foo: string;
}
| {
version: 'v2';
bar: string;
}
| {
version: 'v3';
baz: string;
};
}>({
type: 'my-type',
versions: ['v1', 'v2', 'v3'],
});
// @ts-expect-error - unsupported version
OpaqueMyType.createInstance('v0', {
foo: 'bar',
});
// @ts-expect-error - missing internal field
OpaqueMyType.createInstance('v1', {});
OpaqueMyType.createInstance('v1', {
// @ts-expect-error - invalid internal field
foo: 3,
});
OpaqueMyType.createInstance('v2', {
// @ts-expect-error - version mismatch
foo: 'bar',
});
OpaqueMyType.createInstance('v1', {
// @ts-expect-error - version mismatch
bar: 'foo',
});
const myInstanceV1 = OpaqueMyType.createInstance('v1', {
foo: 'bar',
});
const myInstanceV2 = OpaqueMyType.createInstance('v2', {
bar: 'foo',
});
expect(myInstanceV1.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstanceV1.version).toBe('v1');
// @ts-expect-error - internal field not accessible
expect(myInstanceV1.foo).toBe('bar');
expect(myInstanceV2.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstanceV2.version).toBe('v2');
// @ts-expect-error - internal field not accessible
expect(myInstanceV2.bar).toBe('foo');
expect(OpaqueMyType.isType(myInstanceV1)).toBe(true);
expect(OpaqueMyType.isType(myInstanceV2)).toBe(true);
expect(OpaqueMyType.isType('hello')).toBe(false);
const myInternalV1 = OpaqueMyType.toInternal(myInstanceV1);
expect(myInternalV1).toBe(myInstanceV1);
// All fields accessible
expect(myInternalV1.$$type).toBe('my-type');
expect(myInternalV1.version).toBe('v1');
// @ts-expect-error - version has not been narrowed down
expect(myInternalV1.foo).toBe('bar');
const myInternalV2 = OpaqueMyType.toInternal(myInstanceV2);
expect(myInternalV2).toBe(myInstanceV2);
// All fields accessible
expect(myInternalV2.$$type).toBe('my-type');
expect(myInternalV2.version).toBe('v2');
// @ts-expect-error - version has not been narrowed down
expect(myInternalV2.bar).toBe('foo');
// Narrowing the version allows access to internal fields
expect(myInternalV1.version === 'v1' && myInternalV1.foo).toBe('bar');
expect(myInternalV2.version === 'v2' && myInternalV2.bar).toBe('foo');
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version undefined, expected 'v1', 'v2', or 'v3'"`,
);
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type', version: 'v0' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version 'v0', expected 'v1', 'v2', or 'v3'"`,
);
});
it('should support undefined version for backwards compatibility', () => {
type MyType = {
$$type: 'my-type';
};
const OpaqueMyType = OpaqueType.create<{
public: MyType;
versions: {
version: undefined;
foo: string;
};
}>({
type: 'my-type',
versions: [undefined],
});
// @ts-expect-error - unsupported version
OpaqueMyType.createInstance('v1', {
foo: 'bar',
});
// @ts-expect-error - missing internal field
OpaqueMyType.createInstance(undefined, {});
OpaqueMyType.createInstance(undefined, {
// @ts-expect-error - invalid internal field
foo: 3,
});
const myInstance = OpaqueMyType.createInstance(undefined, {
foo: 'bar',
});
expect(myInstance.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstance.version).toBe(undefined);
// @ts-expect-error - internal field not accessible
expect(myInstance.foo).toBe('bar');
expect(OpaqueMyType.isType(myInstance)).toBe(true);
expect(OpaqueMyType.isType('hello')).toBe(false);
const myInternal = OpaqueMyType.toInternal(myInstance);
expect(myInternal).toBe(myInstance);
// All fields accessible
expect(myInternal.$$type).toBe('my-type');
expect(myInternal.version).toBe(undefined);
expect(myInternal.foo).toBe('bar');
expect(OpaqueMyType.toInternal({ $$type: 'my-type' })).toBeDefined();
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type', version: 'v0' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version 'v0', expected undefined"`,
);
});
it('should support undefined version mixed with defined versions', () => {
type MyType = {
$$type: 'my-type';
};
const OpaqueMyType = OpaqueType.create<{
public: MyType;
versions:
| {
version: 'v1';
foo: string;
}
| {
version: undefined;
bar: string;
};
}>({
type: 'my-type',
versions: [undefined, 'v1'],
});
// @ts-expect-error - unsupported version
OpaqueMyType.createInstance('v0', {
foo: 'bar',
});
// @ts-expect-error - missing internal field
OpaqueMyType.createInstance('v1', {});
OpaqueMyType.createInstance('v1', {
// @ts-expect-error - invalid internal field
foo: 3,
});
OpaqueMyType.createInstance(undefined, {
// @ts-expect-error - version mismatch
foo: 'bar',
});
OpaqueMyType.createInstance('v1', {
// @ts-expect-error - version mismatch
bar: 'foo',
});
const myInstanceV1 = OpaqueMyType.createInstance('v1', {
foo: 'bar',
});
const myInstanceV2 = OpaqueMyType.createInstance(undefined, {
bar: 'foo',
});
expect(myInstanceV1.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstanceV1.version).toBe('v1');
// @ts-expect-error - internal field not accessible
expect(myInstanceV1.foo).toBe('bar');
expect(myInstanceV2.$$type).toBe('my-type');
// @ts-expect-error - version field not accessible
expect(myInstanceV2.version).toBe(undefined);
// @ts-expect-error - internal field not accessible
expect(myInstanceV2.bar).toBe('foo');
expect(OpaqueMyType.isType(myInstanceV1)).toBe(true);
expect(OpaqueMyType.isType(myInstanceV2)).toBe(true);
expect(OpaqueMyType.isType('hello')).toBe(false);
const myInternalV1 = OpaqueMyType.toInternal(myInstanceV1);
expect(myInternalV1).toBe(myInstanceV1);
// All fields accessible
expect(myInternalV1.$$type).toBe('my-type');
expect(myInternalV1.version).toBe('v1');
// @ts-expect-error - version has not been narrowed down
expect(myInternalV1.foo).toBe('bar');
const myInternalV2 = OpaqueMyType.toInternal(myInstanceV2);
expect(myInternalV2).toBe(myInstanceV2);
// All fields accessible
expect(myInternalV2.$$type).toBe('my-type');
expect(myInternalV2.version).toBe(undefined);
// @ts-expect-error - version has not been narrowed down
expect(myInternalV2.bar).toBe('foo');
// Narrowing the version allows access to internal fields
expect(myInternalV1.version === 'v1' && myInternalV1.foo).toBe('bar');
expect(myInternalV2.version === undefined && myInternalV2.bar).toBe('foo');
expect(OpaqueMyType.toInternal({ $$type: 'my-type' })).toBeDefined();
expect(() =>
OpaqueMyType.toInternal({ $$type: 'my-type', version: 'v3' }),
).toThrowErrorMatchingInlineSnapshot(
`"Invalid opaque type instance, got version 'v3', expected undefined or 'v1'"`,
);
});
it('should create an empty opaque type with no versions', () => {
type MyType = {
$$type: 'my-type';
};
const OpaqueMyType = OpaqueType.create<{
public: MyType;
versions: {
version: undefined;
};
}>({
type: 'my-type',
versions: [undefined],
});
// @ts-expect-error - unsupported version
OpaqueMyType.createInstance('v0', {
foo: 'bar',
});
const myInstance = OpaqueMyType.createInstance(undefined, {});
expect(myInstance.$$type).toBe('my-type');
expect(OpaqueMyType.isType(myInstance)).toBe(true);
expect(OpaqueMyType.isType('hello')).toBe(false);
const myInternal = OpaqueMyType.toInternal(myInstance);
expect(myInternal).toBe(myInstance);
// All fields accessible
expect(myInternal.$$type).toBe('my-type');
expect(myInternal.version).toBe(undefined);
});
});
+168
View File
@@ -0,0 +1,168 @@
/*
* 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.
*/
// TODO(Rugvip): This lives here temporarily, but should be moved to a more
// central location. It's useful for backend packages too so we'll need to have
// it in a common package, but it might also be that we want to make it
// available publicly too in which case it would make sense to have this be part
// of @backstage/version-bridge. The problem with exporting it from there is
// that it would need to be very stable at that point, so it might be a bit
// early to put it there already.
/**
* A helper for working with opaque types.
*/
export class OpaqueType<
T extends {
public: { $$type: string };
versions: { version: string | undefined };
},
> {
/**
* Creates a new opaque type.
*
* @param options.type The type identifier of the opaque type
* @param options.versions The available versions of the opaque type
* @returns A new opaque type helper
*/
static create<
T extends {
public: { $$type: string };
versions: { version: string | undefined };
},
>(options: {
type: T['public']['$$type'];
versions: Array<T['versions']['version']>;
}) {
return new OpaqueType<T>(options.type, new Set(options.versions));
}
#type: string;
#versions: Set<string | undefined>;
private constructor(type: string, versions: Set<string | undefined>) {
this.#type = type;
this.#versions = versions;
}
/**
* The internal version of the opaque type, used like this: `typeof MyOpaqueType.TPublic`
*
* @remarks
*
* This property is only useful for type checking, its runtime value is `undefined`.
*/
TPublic: T['public'] = undefined as any;
/**
* The internal version of the opaque type, used like this: `typeof MyOpaqueType.TInternal`
*
* @remarks
*
* This property is only useful for type checking, its runtime value is `undefined`.
*/
TInternal: T['public'] & T['versions'] = undefined as any;
/**
* @param value Input value expected to be an instance of this opaque type
* @returns True if the value matches this opaque type
*/
isType = (value: unknown): value is T['public'] => {
return this.#isThisInternalType(value);
};
/**
* @param value Input value expected to be an instance of this opaque type
* @throws If the value is not an instance of this opaque type or is of an unsupported version
* @returns The internal version of the opaque type
*/
toInternal = (value: unknown): T['public'] & T['versions'] => {
if (!this.#isThisInternalType(value)) {
throw new TypeError(
`Invalid opaque type, expected '${
this.#type
}', but got '${this.#stringifyUnknown(value)}'`,
);
}
if (!this.#versions.has(value.version)) {
const versions = Array.from(this.#versions).map(this.#stringifyVersion);
if (versions.length > 1) {
versions[versions.length - 1] = `or ${versions[versions.length - 1]}`;
}
const expected =
versions.length > 2 ? versions.join(', ') : versions.join(' ');
throw new TypeError(
`Invalid opaque type instance, got version ${this.#stringifyVersion(
value.version,
)}, expected ${expected}`,
);
}
return value;
};
/**
* Creates an instance of the opaque type, returning the public type.
*
* @param version The version of the instance to create
* @param value The remaining public and internal properties of the instance
* @returns An instance of the opaque type
*/
createInstance<
TVersion extends T['versions']['version'],
TPublic extends T['public'],
>(
version: TVersion,
props: Omit<T['public'], '$$type'> &
(T['versions'] extends infer UVersion
? UVersion extends { version: TVersion }
? Omit<UVersion, 'version'>
: never
: never) &
Object, // & Object to allow for object properties too, e.g. toString()
): TPublic {
return {
...(props as object),
$$type: this.#type,
...(version && { version }),
} as unknown as TPublic;
}
#isThisInternalType(value: unknown): value is T['public'] & T['versions'] {
if (value === null || typeof value !== 'object') {
return false;
}
return (value as T['public']).$$type === this.#type;
}
#stringifyUnknown(value: unknown) {
if (typeof value !== 'object') {
return `<${typeof value}>`;
}
if (value === null) {
return '<null>';
}
if ('$$type' in value) {
return String(value.$$type);
}
return String(value);
}
#stringifyVersion = (version: string | undefined) => {
return version ? `'${version}'` : 'undefined';
};
}
+17
View File
@@ -0,0 +1,17 @@
/*
* 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.
*/
export { OpaqueType } from './OpaqueType';