@baukit/preferences-core 0.7.2 → 0.7.4

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/src/store.ts ADDED
@@ -0,0 +1,97 @@
1
+ export interface PreferenceStore<TValues extends object> {
2
+ read(): Promise<TValues | undefined>;
3
+ patch(patch: Partial<TValues>): Promise<TValues>;
4
+ }
5
+
6
+ /**
7
+ * The slice of a record-keyed repository this package needs. Products usually already
8
+ * have a repository of this shape for the row that holds a subject's settings.
9
+ *
10
+ * @typeParam TSubjectId - identifier the repository is keyed by, such as a user id.
11
+ * @typeParam TRecord - the stored record.
12
+ * @typeParam TRecordPatch - the partial record the repository accepts on write.
13
+ */
14
+ export interface PreferenceRecordRepository<TSubjectId, TRecord, TRecordPatch> {
15
+ get(subjectId: TSubjectId): Promise<TRecord | null | undefined>;
16
+ upsert(subjectId: TSubjectId, patch: TRecordPatch): Promise<TRecord>;
17
+ }
18
+
19
+ export interface RepositoryPreferenceStoreOptions<
20
+ TValues extends object,
21
+ TSubjectId,
22
+ TRecord,
23
+ TRecordPatch,
24
+ > {
25
+ readonly repository: PreferenceRecordRepository<TSubjectId, TRecord, TRecordPatch>;
26
+ readonly subjectId: TSubjectId;
27
+ /** Projects a stored record onto preference values. */
28
+ readonly toValues: (record: TRecord) => TValues;
29
+ /** Projects a preference patch onto the record patch the repository accepts. */
30
+ readonly toRecordPatch: (patch: Partial<TValues>) => TRecordPatch;
31
+ }
32
+
33
+ /**
34
+ * Adapts a record-keyed repository to {@link PreferenceStore}. It owns the mapping
35
+ * between preference values and stored columns, so the controller never sees the
36
+ * record shape and the repository never sees preference keys.
37
+ */
38
+ export class RepositoryPreferenceStore<
39
+ TValues extends object,
40
+ TSubjectId,
41
+ TRecord,
42
+ TRecordPatch,
43
+ > implements PreferenceStore<TValues> {
44
+ readonly #repository: PreferenceRecordRepository<TSubjectId, TRecord, TRecordPatch>;
45
+ readonly #subjectId: TSubjectId;
46
+ readonly #toValues: (record: TRecord) => TValues;
47
+ readonly #toRecordPatch: (patch: Partial<TValues>) => TRecordPatch;
48
+
49
+ constructor(
50
+ options: RepositoryPreferenceStoreOptions<TValues, TSubjectId, TRecord, TRecordPatch>,
51
+ ) {
52
+ this.#repository = options.repository;
53
+ this.#subjectId = options.subjectId;
54
+ this.#toValues = options.toValues;
55
+ this.#toRecordPatch = options.toRecordPatch;
56
+ }
57
+
58
+ async read(): Promise<TValues | undefined> {
59
+ const record = await this.#repository.get(this.#subjectId);
60
+ return record == null ? undefined : this.#toValues(record);
61
+ }
62
+
63
+ async patch(patch: Partial<TValues>): Promise<TValues> {
64
+ const record = await this.#repository.upsert(this.#subjectId, this.#toRecordPatch(patch));
65
+ return this.#toValues(record);
66
+ }
67
+ }
68
+
69
+ export function createRepositoryPreferenceStore<
70
+ TValues extends object,
71
+ TSubjectId,
72
+ TRecord,
73
+ TRecordPatch,
74
+ >(
75
+ options: RepositoryPreferenceStoreOptions<TValues, TSubjectId, TRecord, TRecordPatch>,
76
+ ): PreferenceStore<TValues> {
77
+ return new RepositoryPreferenceStore(options);
78
+ }
79
+
80
+ export class InMemoryPreferenceStore<TValues extends object> implements PreferenceStore<TValues> {
81
+ readonly #defaults: TValues;
82
+ #values: TValues | undefined;
83
+
84
+ constructor(defaults: TValues, initialValues?: TValues) {
85
+ this.#defaults = { ...defaults };
86
+ this.#values = initialValues ? { ...initialValues } : undefined;
87
+ }
88
+
89
+ read(): Promise<TValues | undefined> {
90
+ return Promise.resolve(this.#values ? { ...this.#values } : undefined);
91
+ }
92
+
93
+ patch(patch: Partial<TValues>): Promise<TValues> {
94
+ this.#values = { ...this.#defaults, ...this.#values, ...patch };
95
+ return Promise.resolve({ ...this.#values });
96
+ }
97
+ }
package/src/vitest.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import type { PreferenceStore } from './store.js';
4
+
5
+ export type PreferenceStoreFactory<TValues extends object> = (
6
+ initialValues?: TValues,
7
+ ) => PreferenceStore<TValues> | Promise<PreferenceStore<TValues>>;
8
+
9
+ export interface PreferenceStoreContractOptions<TValues extends object> {
10
+ readonly initialValues: TValues;
11
+ readonly patch: Partial<TValues>;
12
+ readonly expectedValues: TValues;
13
+ }
14
+
15
+ export function describePreferenceStoreContract<TValues extends object>(
16
+ makeStore: PreferenceStoreFactory<TValues>,
17
+ options: PreferenceStoreContractOptions<TValues>,
18
+ ): void {
19
+ describe('PreferenceStore contract', () => {
20
+ it('returns undefined when no values have been stored', async () => {
21
+ const store = await makeStore();
22
+ await expect(store.read()).resolves.toBeUndefined();
23
+ });
24
+
25
+ it('reads its initial values', async () => {
26
+ const store = await makeStore(options.initialValues);
27
+ await expect(store.read()).resolves.toEqual(options.initialValues);
28
+ });
29
+
30
+ it('merges a patch and returns the complete stored values', async () => {
31
+ const store = await makeStore(options.initialValues);
32
+ await expect(store.patch(options.patch)).resolves.toEqual(options.expectedValues);
33
+ await expect(store.read()).resolves.toEqual(options.expectedValues);
34
+ });
35
+
36
+ it('returns complete values when patching an empty store', async () => {
37
+ const store = await makeStore();
38
+ await expect(store.patch(options.patch)).resolves.toEqual(options.expectedValues);
39
+ await expect(store.read()).resolves.toEqual(options.expectedValues);
40
+ });
41
+
42
+ it('does not mutate the initial value or patch objects', async () => {
43
+ const initialSnapshot = { ...options.initialValues };
44
+ const patchSnapshot = { ...options.patch };
45
+ const store = await makeStore(options.initialValues);
46
+ await store.patch(options.patch);
47
+ expect(options.initialValues).toEqual(initialSnapshot);
48
+ expect(options.patch).toEqual(patchSnapshot);
49
+ });
50
+ });
51
+ }
@@ -0,0 +1,76 @@
1
+ // eslint-disable-next-line @typescript-eslint/triple-slash-reference
2
+ /// <reference path="./raw.d.ts" />
3
+
4
+ import { describe, expect, it } from 'vitest';
5
+
6
+ import fixtureJson from '../../../../fixtures/product-experience/optional-wire-values.json?raw';
7
+ import { decodeOptionalWireValue, encodeOptionalWireValue } from './wire.js';
8
+
9
+ type FixtureScalar = boolean | string;
10
+
11
+ interface OptionalWireFixture {
12
+ readonly name: string;
13
+ readonly key: string;
14
+ readonly wire: 'absent' | Record<string, FixtureScalar | null>;
15
+ readonly expectedState: 'absent' | 'null' | 'value';
16
+ readonly expectedValue?: FixtureScalar;
17
+ readonly roundTrip: 'absent' | Record<string, FixtureScalar | null>;
18
+ }
19
+
20
+ const fixtures = JSON.parse(fixtureJson) as OptionalWireFixture[];
21
+
22
+ describe('optional wire value fixtures', () => {
23
+ it('contains the product-experience source cases', () => {
24
+ expect(fixtures.map(({ name }) => name)).toEqual(
25
+ expect.arrayContaining([
26
+ 'language preference from old peer',
27
+ 'theme mode value',
28
+ 'game-layer boolean value',
29
+ 'custom color from old peer',
30
+ 'custom color explicitly cleared',
31
+ 'custom color selected',
32
+ ]),
33
+ );
34
+ });
35
+
36
+ for (const fixture of fixtures) {
37
+ it(`decodes and encodes ${fixture.name}`, () => {
38
+ const payload = fixture.wire === 'absent' ? {} : fixture.wire;
39
+ const decoded = decodeOptionalWireValue(payload, fixture.key, (value) => {
40
+ if (typeof value !== 'string' && typeof value !== 'boolean') {
41
+ throw new TypeError('Fixture value must be a string or boolean');
42
+ }
43
+ return value;
44
+ });
45
+
46
+ expect(decoded.state).toBe(fixture.expectedState);
47
+ if (decoded.state === 'value') {
48
+ expect(decoded.value).toBe(fixture.expectedValue);
49
+ }
50
+
51
+ const encoded = encodeOptionalWireValue(fixture.key, decoded);
52
+ const jsonRoundTrip = JSON.parse(JSON.stringify(encoded)) as Record<
53
+ string,
54
+ FixtureScalar | null
55
+ >;
56
+ const representedRoundTrip = Object.hasOwn(jsonRoundTrip, fixture.key)
57
+ ? jsonRoundTrip
58
+ : 'absent';
59
+ expect(representedRoundTrip).toEqual(fixture.roundTrip);
60
+ });
61
+ }
62
+ });
63
+
64
+ describe('optional wire value codec', () => {
65
+ it('does not infer presence from an undefined property value', () => {
66
+ expect(decodeOptionalWireValue({ color: undefined }, 'color', (value) => value)).toEqual({
67
+ state: 'value',
68
+ value: undefined,
69
+ });
70
+ });
71
+
72
+ it('rejects payloads that cannot contain a field', () => {
73
+ expect(() => decodeOptionalWireValue(null, 'color', String)).toThrow(TypeError);
74
+ expect(() => decodeOptionalWireValue([], 'color', String)).toThrow(TypeError);
75
+ });
76
+ });
package/src/wire.ts ADDED
@@ -0,0 +1,33 @@
1
+ export type OptionalWireValue<T> =
2
+ | { readonly state: 'absent' }
3
+ | { readonly state: 'null' }
4
+ | { readonly state: 'value'; readonly value: T };
5
+
6
+ export function decodeOptionalWireValue<T>(
7
+ payload: unknown,
8
+ key: string,
9
+ decodeValue: (value: unknown) => T,
10
+ ): OptionalWireValue<T> {
11
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
12
+ throw new TypeError('Optional wire payload must be an object');
13
+ }
14
+ if (!Object.hasOwn(payload, key)) {
15
+ return { state: 'absent' };
16
+ }
17
+ const value = (payload as Record<string, unknown>)[key];
18
+ return value === null ? { state: 'null' } : { state: 'value', value: decodeValue(value) };
19
+ }
20
+
21
+ export function encodeOptionalWireValue<TKey extends string, TValue>(
22
+ key: TKey,
23
+ value: OptionalWireValue<TValue>,
24
+ ): Partial<Record<TKey, TValue | null>> {
25
+ switch (value.state) {
26
+ case 'absent':
27
+ return {};
28
+ case 'null':
29
+ return { [key]: null } as Record<TKey, null>;
30
+ case 'value':
31
+ return { [key]: value.value } as Record<TKey, TValue>;
32
+ }
33
+ }