Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/app/src/__tests__/localStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,34 @@ describe('createEntityStore', () => {

expect(store.getAll()).toHaveLength(3);
});

it('generates deterministic ids from item content', () => {
const storeA = createEntityStore<Item>('store-det-a');
const storeB = createEntityStore<Item>('store-det-b');

const a = storeA.create({ name: 'demo-source' });
const b = storeB.create({ name: 'demo-source' });

expect(a.id).toBe(b.id);
});

it('generates the same id regardless of property insertion order', () => {
type MultiProp = { id: string; name: string; kind: string };
const storeA = createEntityStore<MultiProp>('store-ord-a');
const storeB = createEntityStore<MultiProp>('store-ord-b');

const a = storeA.create({ name: 'demo', kind: 'log' });
const b = storeB.create({ kind: 'log', name: 'demo' });

expect(a.id).toBe(b.id);
});

it('generates different ids for items with different content', () => {
const store = makeStore();
const a = store.create({ name: 'alpha' });
const b = store.create({ name: 'beta' });
expect(a.id).not.toBe(b.id);
});
});

describe('update', () => {
Expand Down
19 changes: 18 additions & 1 deletion packages/app/src/localStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@ import { parseJSON } from './utils';

type EntityWithId = { id: string };

/**
* Key-order-independent JSON serialization so that objects created from
* different code-paths (or with properties in a different insertion order)
* still produce the same string — and therefore the same deterministic ID.
*/
function stableStringify(value: unknown): string {
if (value === null || value === undefined) return String(value);
if (typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value))
return '[' + value.map(stableStringify).join(',') + ']';
const obj = value as Record<string, unknown>;
const sorted = Object.keys(obj)
.sort()
.map(k => JSON.stringify(k) + ':' + stableStringify(obj[k]));
return '{' + sorted.join(',') + '}';
}

/**
* Generic localStorage CRUD store for local-mode entities.
* Uses store2 for atomic transact operations and JSON serialization.
Expand All @@ -31,7 +48,7 @@ export function createEntityStore<T extends EntityWithId>(
create(item: Omit<T, 'id'>): T {
const newItem = {
...item,
id: Math.abs(hashCode(Math.random().toString())).toString(16),
id: Math.abs(hashCode(stableStringify(item))).toString(16),
} as T;
// Seed transact from defaults when the key is absent so that
// env-var-seeded items are not silently dropped on the first write.
Expand Down
Loading