From 0567c625e32d7ebb25f4b1c33dc176099ffa0bc6 Mon Sep 17 00:00:00 2001 From: Chris Mounce Date: Tue, 2 Sep 2025 23:19:23 -0700 Subject: [PATCH] Add vault store, random ID generation --- src/sync.ts | 26 ++++++++++++++++++++++++-- src/util.ts | 11 +++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 src/util.ts diff --git a/src/sync.ts b/src/sync.ts index c2eefff..6e35e73 100644 --- a/src/sync.ts +++ b/src/sync.ts @@ -1,17 +1,39 @@ import _ from 'lodash'; import * as Y from 'yjs'; import { openDB } from 'idb'; +import { generateId } from './util'; const DB_NAME = 'synced-docs'; const LOCAL_UPDATE_STORE = 'local-updates'; +const VAULT_STORE = 'vaults'; -const db = await openDB(DB_NAME, 2, { +const db = await openDB(DB_NAME, 3, { upgrade(db, oldVersion, newVersion) { console.log(`Running upgrade from ${oldVersion} to ${newVersion}`); - db.createObjectStore(LOCAL_UPDATE_STORE); + if (oldVersion < 2) { + db.createObjectStore(LOCAL_UPDATE_STORE); + } + if (oldVersion < 3) { + db.createObjectStore(VAULT_STORE); + } }, }); +async function getOrCreateVault() { + const records = await db.getAll(VAULT_STORE); + if (records.length > 1) { + throw new Error(`Expected 1 vault record, got ${records.length}`); + } else if (records.length === 0) { + const key = generateId(); + const value = { id: key }; + await db.add(VAULT_STORE, value, key); + records.push(value); + } + return records[0]; +} + +await getOrCreateVault(); + export class LocalDocument { readonly id: string; readonly doc: Y.Doc; diff --git a/src/util.ts b/src/util.ts new file mode 100644 index 0000000..e107314 --- /dev/null +++ b/src/util.ts @@ -0,0 +1,11 @@ +const BASE62_ALPHABET = + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + +export function generateId(): string { + const input = new Uint32Array(20); + crypto.getRandomValues(input); + return Array.from( + input, + (int32) => BASE62_ALPHABET[int32 % BASE62_ALPHABET.length] + ).join(''); +}