@vielzeug/codex 26.11.12 → 26.11.14
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/data/catalog.json +188 -62
- package/data/llms-full.txt +1711 -921
- package/data/llms.txt +4 -1
- package/data/manifest.json +2 -6
- package/data/packages/archive.json +1 -1
- package/data/packages/arsenal.json +4 -2
- package/data/packages/clockwork.json +3 -3
- package/data/packages/codex.json +20 -11
- package/data/packages/coins.json +22 -24
- package/data/packages/courier.json +12 -11
- package/data/packages/flux.json +2 -2
- package/data/packages/forge.json +3 -3
- package/data/packages/herald.json +2 -2
- package/data/packages/ledger.json +1 -1
- package/data/packages/lingua.json +37 -42
- package/data/packages/patchwork.json +50 -0
- package/data/packages/postmaster.json +8 -8
- package/data/packages/refine.json +2 -2
- package/data/packages/scribe.json +57 -0
- package/data/packages/sentinel.json +1 -1
- package/data/packages/sourcerer.json +2 -2
- package/data/packages/tabula.json +39 -0
- package/data/packages/tavern.json +20 -18
- package/data/packages/tempo.json +48 -63
- package/data/packages/vault.json +29 -31
- package/data/packages/wayfinder.json +12 -7
- package/data/refine.json +76 -0
- package/dist/catalog.d.ts +13 -1
- package/dist/catalog.js +80 -53
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/consumer.d.ts +17 -0
- package/dist/consumer.js +114 -0
- package/dist/consumer.js.map +1 -0
- package/dist/errors.js +0 -1
- package/dist/errors.js.map +1 -1
- package/dist/http.d.ts +0 -1
- package/dist/http.js +0 -5
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/port.js +2 -2
- package/dist/port.js.map +1 -1
- package/dist/server.d.ts +5 -3
- package/dist/server.js +10 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +11 -8
- package/dist/snapshot.js +24 -128
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +0 -2
- package/dist/tools/index.js +0 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/packages.js +50 -0
- package/dist/tools/packages.js.map +1 -1
- package/dist/tools/refine.d.ts +2 -2
- package/dist/tools/refine.js.map +1 -1
- package/dist/types.d.ts +2 -30
- package/dist/types.js +1 -1
- package/package.json +2 -13
- package/skills/vielzeug/SKILL.md +4 -1
- package/data/search.json +0 -1688
- package/dist/refine-catalog.d.ts +0 -15
- package/dist/refine-catalog.js +0 -27
- package/dist/refine-catalog.js.map +0 -1
- package/dist/refine.d.ts +0 -7
- package/dist/refine.js +0 -9
- package/dist/refine.js.map +0 -1
package/data/packages/vault.json
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';\nexport { ttl } from './ttl';\nexport type {\n AnySchema,\n
|
|
2
|
+
"apiSource": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';\nexport { ttl } from './ttl';\nexport type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';\nexport { table } from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Vault: Typed storage'\ndescription: Typed browser storage and opt-in driver-neutral SQLite with portable keys, TTL, observation, and transactions.\npackage: vault\ncategory: Storage\nkeywords: [storage, indexeddb, localstorage, sessionstorage, sqlite, ttl, browser, node, deno]\nrelated: [courier, forge, ripple]\nexports
|
|
5
|
-
"api": "---\ntitle: 'Vault: API Reference'\ndescription: Reference for Vault schemas, adapter entry points, storage capabilities, codecs, SQLite drivers, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------- |\n| `createMemory()` | In-memory document store | Async API | Import from `/memory`; codecs optional |\n| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API | Codecs required; available only where the corresponding Web API exists |\n| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`; codecs required |\n| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`; codecs required |\n| `table()` | Typed record schema | Sync | The key field must be a string or finite number |\n| `validatorCodec()` | Create an identity-encoding codec from a parser | Sync | Spell schemas can also be passed directly |\n| `ttl` | Valid expiration durations | Sync | Durations must be positive |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --------------------------------- | ----------------------------------------------------------------------------- |\n| `@vielzeug/vault` | Adapter-free schemas, TTL, errors, codecs, derived helpers, and shared types |\n| `@vielzeug/vault/memory` | `createMemory` |\n| `@vielzeug/vault/local-storage` | `createLocalStorage` |\n| `@vielzeug/vault/session-storage` | `createSessionStorage` |\n| `@vielzeug/vault/indexeddb` | `createIndexedDB`, the `migrate` upgrade-hook types, and IndexedDB-only types |\n| `@vielzeug/vault/sqlite` | `createSQLite`, the SQLite driver protocol types, and `TransactionContext` |\n\n## Schemas, Codecs, and TTL\n\n### `table()`\n\n```ts\nfunction table<T extends object, Key extends keyof T & string = keyof T & string>(\n key: Key & (T[Key] extends VaultKey ? unknown : never),\n options?: { defaultTtl?: number; indexes?: readonly (keyof T & string)[] },\n): SchemaEntry<T, Key>;\n```\n\nDefines a typed table and its primary-key field.\n\n| Parameter | Description |\n| -------------------- | ---------------------------------------------------------------- |\n| `key` | A record field whose values are `string` or finite `number` keys |\n| `options.defaultTtl` | Per-table default TTL in milliseconds |\n| `options.indexes` | IndexedDB secondary index fields |\n\n**Returns:** A `SchemaEntry` describing the table.\n\n```ts\nimport { table, ttl } from '@vielzeug/vault';\n\nconst users = table<{ id: number; email: string }>('id', {\n indexes: ['email'],\n defaultTtl: ttl.days(7),\n});\n```\n\n---\n\n### `validatorCodec()`\n\n```ts\nfunction validatorCodec<T>(validator: { parse(value: unknown): T }): RecordCodec<T>;\n```\n\nWraps any object with a `parse(value): T` method as an identity-encoding `RecordCodec`. Parser schemas can also be passed directly in `codecs`; a Spell schema requires no adapter.\n\n**Returns:** A `RecordCodec<T>`.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst UserSchema = s.object({ id: s.number(), name: s.string() });\nconst store = createLocalStorage({\n name: 'app',\n schema: { users: table<{ id: number; name: string }>('id') },\n codecs: { users: UserSchema },\n});\n```\n\nCustom `RecordCodec` values validate writes by round-tripping `decode(encode(value))`. IndexedDB codecs must preserve declared indexed field names and values in their encoded object.\n\n---\n\n### `ttl`\n\n```ts\nconst ttl: {\n days(n: number): number;\n hours(n: number): number;\n minutes(n: number): number;\n ms(n: number): number;\n seconds(n: number): number;\n};\n```\n\nCreates a finite, positive duration in milliseconds for writes and table defaults.\n\n**Returns:** `number`.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nconst cacheLifetime = ttl.minutes(5);\n```\n\n## Factories\n\nDurable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `codecs`. Memory may omit them.\n\n### `createMemory()`\n\n```ts\nfunction createMemory<S extends AnySchema>(options: MemoryStoreOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. Codecs are optional because memory values never cross a trust boundary.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `codecs` | Optional per-table codecs |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createMemory } from '@vielzeug/vault/memory';\n\nconst store = createMemory({ schema: { users: table<{ id: number; name: string }>('id') } });\n```\n\n---\n\n### `createLocalStorage()`\n\n```ts\nfunction createLocalStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `localStorage` store. Codecs are required.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `codecs` | Required per-table codecs |\n| `name` | Required storage namespace |\n\nA write that exceeds the browser quota rejects with `VaultQuotaError`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\nconst store = createLocalStorage({\n name: 'app',\n schema: { settings: table<{ id: string }>('id') },\n codecs: { settings: SettingsSchema },\n});\n```\n\n---\n\n### `createSessionStorage()`\n\n```ts\nfunction createSessionStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `sessionStorage` store. Its options and return type match `createLocalStorage()`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createSessionStorage } from '@vielzeug/vault/session-storage';\n\nconst store = createSessionStorage({\n name: 'checkout',\n schema: { cart: table<{ id: string }>('id') },\n codecs: { cart: CartSchema },\n});\n```\n\n---\n\n### `createIndexedDB()`\n\n```ts\nfunction createIndexedDB<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n migrate?: MigrationFn;\n name: string;\n version?: number;\n },\n): IndexedDbVaultStore<S>;\n```\n\nCreates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations. Codecs are required.\n\n| Parameter | Description |\n| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `schema` | Tables and IndexedDB secondary indexes |\n| `codecs` | Required per-table codecs |\n| `name` | Required database name |\n| `version` | Positive schema version; defaults to `1` |\n| `migrate` | Synchronous `onupgradeneeded` callback. Object stores and schema-declared indexes are created automatically; use the hook only for deletes or record transforms |\n\n**Returns:** `IndexedDbVaultStore<S>`. Its `getAllByIndex(table, field, value)` method queries a declared IndexedDB index without scanning the full table.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst store = createIndexedDB({\n name: 'app',\n schema: { users: table<{ id: number; role: string }>('id', { indexes: ['role'] }) },\n codecs: { users: UserSchema },\n});\n\nconst admins = await store.getAllByIndex('users', 'role', 'admin');\n```\n\n---\n\n### `createSQLite()`\n\n```ts\nfunction createSQLite<S extends AnySchema>(options: SQLiteVaultOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates a namespaced SQLite document store with atomic batches and keyset-paginated iteration. Codecs are required. It accepts an application-provided positional-parameter driver and never opens or imports a runtime driver.\n\n| Parameter | Description |\n| ---------------- | ---------------------------------------------------------- |\n| `schema` | Tables created by `table()` |\n| `codecs` | Required per-table codecs |\n| `database` | Caller-provided `SQLiteDatabase` connection |\n| `name` | Namespace within the connection |\n| `closeOnDispose` | Closes the connection during disposal; defaults to `false` |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst store = createSQLite({\n database: new DatabaseSync(':memory:'),\n name: 'tests',\n schema: { users: table<{ id: number; name: string }>('id') },\n codecs: { users: UserSchema },\n});\n```\n\nNode `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol. Codec output may be any JSON-compatible value. During a `batch()` callback, calls on every Vault store sharing that connection reject; use `tx.*` instead.\n\n## Store Capabilities\n\n### `KeyValueVaultStore`\n\n```ts\ninterface KeyValueVaultStore<S extends AnySchema> {\n clear(table): Promise<void>;\n count(table): Promise<number>;\n delete(table, key): Promise<boolean>;\n deleteMany(table, keys): Promise<number>;\n get(table, key): Promise<Record | undefined>;\n getAll(table): Promise<Record[]>;\n getMany(table, keys): Promise<(Record | undefined)[]>;\n has(table, key): Promise<boolean>;\n isEmpty(table): Promise<boolean>;\n keys(table, filter?): Promise<VaultKey[]>;\n update(table, key, changes, ttl?): Promise<Record | undefined>;\n upsert(table, key, update, ttl?): Promise<Record>;\n observe(table, listener, options?): Unsubscribe;\n pruneExpired(): Promise<Record<string, number>>;\n put<K extends keyof S & string>(table: K, value: RecordOf<S, K>, ttl?: number): Promise<RecordOf<S, K>>;\n putAll(table, values, ttl?): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): Promise<void>;\n readonly disposed: boolean;\n [Symbol.asyncDispose](): Promise<void>;\n}\n```\n\nThe portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by codec validation. `observe()` emits the current table snapshot by default and then emits after mutations.\n\n---\n\n### `DocumentVaultStore`\n\n```ts\ninterface DocumentVaultStore<S extends AnySchema> extends KeyValueVaultStore<S> {\n batch<K extends keyof S & string, R>(\n tables: readonly K[],\n fn: (tx: TransactionContext<S, K>) => Promise<R>,\n ): Promise<R>;\n iterate<K extends keyof S & string>(table: K): AsyncIterable<RecordOf<S, K>>;\n}\n```\n\n`batch()` runs a scoped atomic callback. `iterate()` lazily yields table records: IndexedDB uses a cursor, SQLite uses keyset pagination. Both are provided by `createIndexedDB()` and `createSQLite()`.\n\n| Parameter | Description |\n| --------- | ------------------------------------------------------- |\n| `tables` | Tables the transaction may access |\n| `fn` | Async callback that uses only the supplied `tx` context |\n\n**Returns:** The callback result after commit.\n\n```ts\nawait store.batch(['users'], async (tx) => {\n await tx.put('users', { id: 1, name: 'Ada' });\n});\n\nfor await (const user of store.iterate('users')) console.log(user);\n```\n\n## Bound Helpers\n\nConvenience operations are bound to every store and transaction context. For filtering, ordering, and pagination, compose over `getAll()`: it returns a plain array, or use `iterate()` on document stores and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n| Helper | Signature | Description |\n| -------------- | -------------------------------------------------------- | ------------------------------------------------------ |\n| `has()` | `(table, key) => Promise<boolean>` | Check whether a record exists |\n| `count()` | `(table) => Promise<number>` | Count live records |\n| `isEmpty()` | `(table) => Promise<boolean>` | Check whether a table has no live records |\n| `getMany()` | `(table, keys) => Promise<(T \\| undefined)[]>` | Fetch multiple records by key |\n| `keys()` | `(table, filter?) => Promise<VaultKey[]>` | Fetch live primary keys, optionally filtered by record |\n| `deleteMany()` | `(table, keys) => Promise<number>` | Delete multiple records, return count |\n| `update()` | `(table, key, changes, ttl?) => Promise<T \\| undefined>` | Partially update an existing record |\n| `upsert()` | `(table, key, fn, ttl?) => Promise<T>` | Read-modify-write with callback |\n\n```ts\nconst exists = await store.has('users', 1);\nconst total = await store.count('users');\nconst [a, b] = await store.getMany('users', [1, 2]);\nconst updated = await store.update('users', 1, { name: 'Alice' });\nconst result = await store.upsert('users', 99, (existing) => ({ id: 99, name: existing?.name ?? 'Guest' }));\n\nconst all = await store.getAll('users');\nconst active = all\n .filter((user) => user.status === 'active')\n .sort((a, b) => a.name.localeCompare(b.name))\n .slice(0, 20);\n```\n\nBound `update()` and `upsert()` are atomic on document stores. Their key-value-store forms are non-atomic convenience operations.\n\n## Types\n\n```ts\ntype VaultKey = number | string;\ntype Unsubscribe = () => void;\ntype Observer<T> = (records: T[]) => void;\ntype AnySchema = Record<\n string,\n {\n defaultTtl?: number;\n indexes?: readonly string[];\n key: string;\n }\n>;\ntype SchemaEntry<T extends object, Key extends keyof T & string = keyof T & string> = {\n defaultTtl?: number;\n indexes?: readonly (keyof T & string)[];\n key: Key;\n};\ntype RecordOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? S[K] extends SchemaEntry<infer R, infer _Key>\n ? R\n : never\n : never;\ntype KeyOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? Extract<S[K] extends SchemaEntry<infer R, infer Key> ? R[Key] : never, VaultKey>\n : never;\n```\n\n```ts\ntype RecordCodec<T> = {\n decode(value: unknown): T;\n encode(value: T): unknown;\n};\n\ntype RecordParser<T> = { parse(value: unknown): T };\ntype CodecInput<T> = RecordCodec<T> | RecordParser<T>;\n\ntype TableCodecs<S extends AnySchema> = {\n [K in keyof S]: CodecInput<RecordOf<S, K>>;\n};\n\ntype MemoryStoreOptions<S extends AnySchema> = {\n schema: S;\n codecs?: TableCodecs<S>;\n};\n\ntype DurableStoreOptions<S extends AnySchema> = {\n schema: S;\n codecs: TableCodecs<S>;\n};\n```\n\n```ts\ntype MigrationContext = {\n db: IDBDatabase;\n newVersion: number | null;\n oldVersion: number;\n tx: IDBTransaction;\n};\n\ntype MigrationFn = (ctx: MigrationContext) => void;\n```\n\nImport `MigrationContext` and `MigrationFn` from `@vielzeug/vault/indexeddb`.\n\n```ts\ntype SQLiteParameter = null | number | string;\n\ninterface SQLiteStatement {\n all(...parameters: SQLiteParameter[]): readonly Record<string, unknown>[];\n finalize?(): void;\n get(...parameters: SQLiteParameter[]): Record<string, unknown> | null | undefined;\n run(...parameters: SQLiteParameter[]): unknown;\n}\n\ninterface SQLiteDatabase {\n close?(): void;\n exec(sql: string): void;\n prepare(sql: string): SQLiteStatement;\n}\n\ntype SQLiteVaultOptions<S extends AnySchema> = DurableStoreOptions<S> & {\n closeOnDispose?: boolean;\n database: SQLiteDatabase;\n name: string;\n};\n```\n\n```ts\ninterface TransactionContext<S extends AnySchema, K extends keyof S & string = keyof S & string> {\n clear<T extends K>(table: T): Promise<void>;\n delete<T extends K>(table: T, key: KeyOf<S, T>): Promise<boolean>;\n get<T extends K>(table: T, key: KeyOf<S, T>): Promise<RecordOf<S, T> | undefined>;\n getAll<T extends K>(table: T): Promise<RecordOf<S, T>[]>;\n iterate<T extends K>(table: T): AsyncIterable<RecordOf<S, T>>;\n put<T extends K>(table: T, value: RecordOf<S, T>, ttl?: number): Promise<RecordOf<S, T>>;\n putAll<T extends K>(table: T, values: RecordOf<S, T>[], ttl?: number): Promise<void>;\n}\n```\n\n`TransactionContext` has core CRUD, `iterate()`, and TTL methods, narrowed to the tables declared in `batch()`. Import it from `@vielzeug/vault/indexeddb` or `@vielzeug/vault/sqlite`.\n\n## Errors\n\n| Error | Trigger |\n| --------------------- | ----------------------------------------------------------------------- |\n| `VaultError` | Any Vault-originated validation, serialization, storage, or codec error |\n| `VaultDisposedError` | An operation after the store or observer hub is disposed |\n| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope |\n| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota |\n| `VaultMigrationError` | An IndexedDB migration callback throws |\n\nEvery listed error extends `VaultError`.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Vault: Usage Guide'\ndescription: Persist typed browser or SQLite data, observe table snapshots, and use atomic transactions with required durable codecs.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a key-value store with a schema and codecs, then write a typed row.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Preference {\n id: string;\n theme: 'dark' | 'light';\n}\n\nconst PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n codecs: { preferences: PreferenceSchema },\n});\n\nawait store.put('preferences', { id: 'theme', theme: 'dark' });\nconsole.log(await store.get('preferences', 'theme'));\n```\n\n## Create a Key-Value Store\n\nLocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit codecs; Web Storage requires them. Malformed storage envelopes are evicted lazily, while codec validation failures are surfaced without deleting persisted data.\n\nThe root entry is adapter-free. Import `createMemory` from `@vielzeug/vault/memory`, `createLocalStorage` from `@vielzeug/vault/local-storage`, or `createSessionStorage` from `@vielzeug/vault/session-storage`. Import each adapter from its focused subpath so unused backends stay out of the bundle.\n\nUse a new storage name when upgrading from Vault 1. Old key and envelope formats are not read by Vault 2.\n\n```ts\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n codecs: { preferences: PreferenceSchema },\n});\n```\n\n## Read and Change Records\n\nUse bound `update()` and `upsert()` methods for read-modify-write operations; no helper imports are required.\n\n```ts\nconst updated = await store.update('preferences', 'theme', { theme: 'light' });\n\nawait store.upsert('preferences', 'locale', (current) => ({\n id: 'locale',\n theme: current?.theme ?? 'dark',\n}));\n\nconsole.log(updated);\n```\n\n`update()` returns `undefined` for a missing key. `upsert()` always writes the record returned by its callback. Document-store methods run atomically; key-value-store methods are non-atomic conveniences when multiple writers race.\n\n## Iterate and Filter Records\n\nFilter the plain array returned by `getAll()` for in-memory selection, sorting, and pagination. Use `iterate()` on a `DocumentVaultStore` for lazy cursor-based traversal, and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n```ts\n// In-memory selection over getAll()\nconst themed = (await store.getAll('preferences')).filter((preference) => preference.id.startsWith('theme'));\n\n// Document store: iterate lazily\nfor await (const pref of db.iterate('preferences')) {\n if (pref.id.startsWith('theme')) console.log(pref);\n}\n```\n\nFor large tables, prefer `iterate()` on IndexedDB or SQLite instead of materializing every record with `getAll()`.\n\n## Use TTL and Pruning\n\nUse `ttl.*` helpers for expiring rows. Call `pruneExpired()` to reclaim storage from stale rows that accumulate without reads; tables with removed rows publish fresh observer snapshots.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nawait store.put('preferences', { id: 'temporary', theme: 'dark' }, ttl.hours(1));\n\n// Reclaim expired rows on a schedule owned by the application.\nconst pruneInterval = setInterval(() => store.pruneExpired(), ttl.hours(6));\nstore.disposalSignal.addEventListener('abort', () => clearInterval(pruneInterval));\n```\n\n## Observe a Table\n\nUse `observe()` for current and future snapshots. Notifications are revision-ordered, and explicit TTL pruning publishes fresh snapshots for affected tables. Tie subscription lifetime to an `AbortSignal` when a component or request owns it.\n\n```ts\nconst controller = new AbortController();\n\nstore.observe(\n 'preferences',\n (preferences) => {\n console.log(preferences);\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\n```\n\n## Use IndexedDB for Browser Transactions\n\nChoose IndexedDB when browser storage needs multiple writes to commit together or cursor iteration.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst db = createIndexedDB({\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: EventSchema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nTransaction contexts expose the same bound helpers; `tx.update()`, `tx.upsert()`, and `tx.deleteMany()` run inside the enclosing transaction. Only await `tx.*` operations inside a batch callback. Do not retain the transaction context after the callback; later use throws `VaultScopeError`. Do not await timers, fetches, or other external asynchronous work because IndexedDB can commit an inactive transaction.\n\n## Use SQLite Outside the Browser\n\nImport SQLite from the opt-in subpath so the browser root stays free of runtime drivers. Vault never opens a connection or configures its SQLite process behavior for you.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst database = new DatabaseSync('app.db', { timeout: 5_000 });\nconst store = createSQLite({\n database,\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: EventSchema },\n});\n\nawait store.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nNode's `node:sqlite` API is experimental. Bun's `bun:sqlite` `Database` satisfies the same positional `exec()` and `prepare()` contract; configure WAL from your application when the deployment needs it. Deno does not include SQLite, but `jsr:@db/sqlite`'s `Database` satisfies the same contract when its FFI, filesystem, and environment permissions are granted.\n\nSQLite stores serialize all access through the injected connection. `batch()` starts `BEGIN IMMEDIATE` and rolls back callback failures. While its callback runs, calls on any store sharing that connection reject rather than waiting behind the transaction; use `tx.*` instead. The underlying drivers are synchronous, so move large scans and writes to a worker or isolate when event-loop latency matters.\n\n## Store SQLite Values and Observe Changes\n\nSQLite accepts any JSON-compatible codec output. Circular values, `bigint`, class instances, functions, and non-finite numbers must be transformed by the codec before writing. Number and string primary keys remain distinct.\n\n`observe()` sees mutations written through Vault stores sharing the same injected connection after a commit. It cannot detect direct SQL changes, writes from another process, or writes through another connection. The connection belongs to the caller by default; use `closeOnDispose: true` only when the store owns it.\n\n## Handle IndexedDB Schema Migrations\n\nDeclare IndexedDB indexes in the schema. Codecs must preserve each indexed field name and value in their encoded object. Use `migrate` only for IndexedDB version upgrades and mirror Vault's fixed `value.<field>` index path.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB, type MigrationFn } from '@vielzeug/vault/indexeddb';\n\nconst UserSchema = s.object({ id: s.number(), name: s.string() });\nconst schema = { users: table<{ id: number; name: string }>('id', { indexes: ['name'] }) };\nconst migrate: MigrationFn = ({ db, oldVersion, tx }) => {\n if (oldVersion < 2 && db.objectStoreNames.contains('users')) {\n tx.objectStore('users').createIndex('name', 'value.name');\n }\n};\n\ncreateIndexedDB({\n name: 'app-v2',\n migrate,\n schema,\n version: 2,\n codecs: { users: UserSchema },\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```ts [React]\nimport { useEffect, useState } from 'react';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const [rows, setRows] = useState<RecordOf<S, K>[]>([]);\n\n useEffect(() => store.observe(table, setRows), [store, table]);\n return rows;\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const rows = shallowRef<RecordOf<S, K>[]>([]);\n const stop = store.observe(table, (next) => (rows.value = next));\n\n onUnmounted(stop);\n return rows;\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function tableStore<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n return readable<RecordOf<S, K>[]>([], (set) => store.observe(table, set));\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nKeep Ripple signals as application state and persist selected changes through Vault writes.\n\n## Best Practices\n\n- Define one schema per storage namespace.\n- Use string or finite-number primary keys only.\n- Provide codecs for every durable adapter; pass Spell or another parser schema directly when identity encoding is sufficient.\n- Use `observe()` for table snapshots.\n- Use IndexedDB or SQLite for atomic work.\n- Keep external asynchronous work outside `batch()` callbacks.\n- Use `ttl.*` instead of raw durations.\n- Keep SQLite scans and writes off latency-sensitive event loops.\n- Dispose stores when their owner ends.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Vault: Examples'\ndescription: Practical Vault examples for browser storage, SQLite, TTL, transactions, observation, and framework integration.\n---\n\n## Browser Key-Value Store with TTL\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table, ttl } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Session {\n id: string;\n token: string;\n}\n\nconst SessionSchema = s.object({ id: s.string(), token: s.string() });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { sessions: table<Session>('id', { defaultTtl: ttl.hours(1) }) },\n
|
|
4
|
+
"index": "---\ntitle: 'Vault: Typed storage'\ndescription: Typed browser storage and opt-in driver-neutral SQLite with portable keys, TTL, observation, and transactions.\npackage: vault\ncategory: Storage\nkeywords: [storage, indexeddb, localstorage, sessionstorage, sqlite, ttl, browser, node, deno]\nrelated: [courier, forge, ripple]\nexports: [table, ttl, createMemory, createLocalStorage, createSessionStorage, createIndexedDB, createSQLite]\nenvironments: [browser, node, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"vault\" />\n\n## Why Vault?\n\nVault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require parsers so invalid stored data never enters typed code.\n\n```ts\n// Before\nlocalStorage.setItem('theme', JSON.stringify({ value: 'dark' }));\nconst theme = JSON.parse(localStorage.getItem('theme') ?? '{}').value;\n\n// After\nawait store.put('preferences', { id: 'theme', value: 'dark' });\nconst theme = await store.get('preferences', 'theme');\n```\n\n| Feature | Vault | Raw Web Storage | Dexie |\n| ---------------------------- | -------------------------------------------- | ----------------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"vault\" type=\"size\" /> | Browser built-in | Extra dependency |\n| Runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Typed schema and keys | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Application-defined | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Portable key-value store API | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | IndexedDB only |\n| Explicit atomic transactions | IndexedDB + SQLite capability | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Required durable parsers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Driver-neutral SQLite | Opt-in subpath | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable parsers.\n\n**Consider raw Web Storage when** you only persist one or two unstructured values. **Consider Dexie when** you need a broader IndexedDB ecosystem.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/vault\n```\n\n```sh [npm]\nnpm install @vielzeug/vault\n```\n\n```sh [yarn]\nyarn add @vielzeug/vault\n```\n\n:::\n\n## Quick Start\n\nDefine a schema, create a key-value store with parsers, and dispose it with its owner.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\nconst PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<{ id: string; theme: 'dark' | 'light' }>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n\ntry {\n await store.put('preferences', { id: 'theme', theme: 'dark' });\n console.log(await store.get('preferences', 'theme'));\n} finally {\n await store.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `table()` defines typed records with portable string or number keys.\n- Spell and other parser schemas work directly as per-table parsers.\n- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`: parsers optional (in-memory, no trust boundary).\n- `/local-storage` and `/session-storage` return `KeyValueVaultStore`: parsers required.\n- `observe()` emits current and changed table snapshots.\n- `ttl` creates validated expiration durations.\n- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`: parsers required. `/memory` shares the same contract without parsers.\n- `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.\n- `pruneExpired()` removes stale TTL entries on demand.\n- Bound helpers (`has`, `count`, `update`, `upsert`, `getMany`, `keys`, `deleteMany`) are available on every store and transaction context.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Forge](../forge/index.md) saves and restores form drafts through Vault stores.\n- [Ripple](../ripple/index.md) owns application state that can persist through Vault.\n- [Courier](../courier/index.md) can populate persistent cache data.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Vault: API Reference'\ndescription: Reference for Vault schemas, adapter entry points, storage capabilities, parsers, SQLite drivers, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |\n| `createMemory()` | In-memory document store | Async API | Import from `/memory`; parsers optional |\n| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API | Parsers required; available only where the corresponding Web API exists |\n| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`; parsers required |\n| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`; parsers required |\n| `table()` | Typed record schema | Sync | The key field must be a string or finite number |\n| `ttl` | Valid expiration durations | Sync | Durations must be positive |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --------------------------------- | ----------------------------------------------------------------------------- |\n| `@vielzeug/vault` | Adapter-free schemas, TTL, errors, parsers, derived helpers, and shared types |\n| `@vielzeug/vault/memory` | `createMemory` |\n| `@vielzeug/vault/local-storage` | `createLocalStorage` |\n| `@vielzeug/vault/session-storage` | `createSessionStorage` |\n| `@vielzeug/vault/indexeddb` | `createIndexedDB`, the `migrate` upgrade-hook types, and IndexedDB-only types |\n| `@vielzeug/vault/sqlite` | `createSQLite`, the SQLite driver protocol types, and `TransactionContext` |\n\n## Schemas, Parsers, and TTL\n\n### `table()`\n\n```ts\nfunction table<T extends object, Key extends keyof T & string = keyof T & string>(\n key: Key & (T[Key] extends VaultKey ? unknown : never),\n options?: { defaultTtl?: number; indexes?: readonly (keyof T & string)[] },\n): SchemaEntry<T, Key>;\n```\n\nDefines a typed table and its primary-key field.\n\n| Parameter | Description |\n| -------------------- | ---------------------------------------------------------------- |\n| `key` | A record field whose values are `string` or finite `number` keys |\n| `options.defaultTtl` | Per-table default TTL in milliseconds |\n| `options.indexes` | IndexedDB-only secondary index fields (`getAllByIndex()`) |\n\n**Returns:** A `SchemaEntry` describing the table.\n\n```ts\nimport { table, ttl } from '@vielzeug/vault';\n\nconst users = table<{ id: number; email: string }>('id', {\n indexes: ['email'],\n defaultTtl: ttl.days(7),\n});\n```\n\n---\n\n### `ttl`\n\n```ts\nconst ttl: {\n days(n: number): number;\n hours(n: number): number;\n minutes(n: number): number;\n ms(n: number): number;\n seconds(n: number): number;\n};\n```\n\nCreates a finite, positive duration in milliseconds for writes and table defaults.\n\n**Returns:** `number`.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nconst cacheLifetime = ttl.minutes(5);\n```\n\n## Factories\n\nDurable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `parsers`. Memory may omit them.\n\n### `createMemory()`\n\n```ts\nfunction createMemory<S extends AnySchema>(options: MemoryStoreOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. Parsers are optional because memory values never cross a trust boundary.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Optional per-table parsers |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createMemory } from '@vielzeug/vault/memory';\n\nconst store = createMemory({ schema: { users: table<{ id: number; name: string }>('id') } });\n```\n\n---\n\n### `createLocalStorage()`\n\n```ts\nfunction createLocalStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `localStorage` store. Parsers are required.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Required per-table parsers |\n| `name` | Required storage namespace |\n\nA write that exceeds the browser quota rejects with `VaultQuotaError`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\nconst store = createLocalStorage({\n name: 'app',\n schema: { settings: table<{ id: string }>('id') },\n parsers: { settings: SettingsSchema },\n});\n```\n\n---\n\n### `createSessionStorage()`\n\n```ts\nfunction createSessionStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `sessionStorage` store. Its options and return type match `createLocalStorage()`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createSessionStorage } from '@vielzeug/vault/session-storage';\n\nconst store = createSessionStorage({\n name: 'checkout',\n schema: { cart: table<{ id: string }>('id') },\n parsers: { cart: CartSchema },\n});\n```\n\n---\n\n### `createIndexedDB()`\n\n```ts\nfunction createIndexedDB<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n migrate?: MigrationFn;\n name: string;\n version?: number;\n },\n): IndexedDbVaultStore<S>;\n```\n\nCreates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations. Parsers are required.\n\n| Parameter | Description |\n| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `schema` | Tables and IndexedDB secondary indexes |\n| `parsers` | Required per-table parsers |\n| `name` | Required database name |\n| `version` | Positive schema version; defaults to `1` |\n| `migrate` | Synchronous `onupgradeneeded` callback. Object stores and schema-declared indexes are created automatically; use the hook only for deletes or record transforms |\n\n**Returns:** `IndexedDbVaultStore<S>`. Its `getAllByIndex(table, field, value)` method queries a declared IndexedDB index without scanning the full table.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst store = createIndexedDB({\n name: 'app',\n schema: { users: table<{ id: number; role: string }>('id', { indexes: ['role'] }) },\n parsers: { users: UserSchema },\n});\n\nconst admins = await store.getAllByIndex('users', 'role', 'admin');\n```\n\n---\n\n### `createSQLite()`\n\n```ts\nfunction createSQLite<S extends AnySchema>(options: SQLiteVaultOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates a namespaced SQLite document store with atomic batches and keyset-paginated iteration. Parsers are required. It accepts an application-provided positional-parameter driver and never opens or imports a runtime driver.\n\n| Parameter | Description |\n| ---------------- | ---------------------------------------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Required per-table parsers |\n| `database` | Caller-provided `SQLiteDatabase` connection |\n| `name` | Namespace within the connection |\n| `closeOnDispose` | Closes the connection during disposal; defaults to `false` |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst store = createSQLite({\n database: new DatabaseSync(':memory:'),\n name: 'tests',\n schema: { users: table<{ id: number; name: string }>('id') },\n parsers: { users: UserSchema },\n});\n```\n\nNode `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol. Records must be JSON-compatible values. During a `batch()` callback, calls on every Vault store sharing that connection reject; use `tx.*` instead.\n\n## Store Capabilities\n\n### `KeyValueVaultStore`\n\n```ts\ninterface KeyValueVaultStore<S extends AnySchema> {\n clear(table): Promise<void>;\n count(table): Promise<number>;\n delete(table, key): Promise<boolean>;\n deleteMany(table, keys): Promise<number>;\n get(table, key): Promise<Record | undefined>;\n getAll(table): Promise<Record[]>;\n getMany(table, keys): Promise<(Record | undefined)[]>;\n has(table, key): Promise<boolean>;\n isEmpty(table): Promise<boolean>;\n keys(table, filter?): Promise<VaultKey[]>;\n update(table, key, changes, ttl?): Promise<Record | undefined>;\n upsert(table, key, update, ttl?): Promise<Record>;\n observe(table, listener, options?): Unsubscribe;\n pruneExpired(): Promise<Record<string, number>>;\n put<K extends keyof S & string>(table: K, value: RecordOf<S, K>, ttl?: number): Promise<RecordOf<S, K>>;\n putAll(table, values, ttl?): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): Promise<void>;\n readonly disposed: boolean;\n [Symbol.asyncDispose](): Promise<void>;\n}\n```\n\nThe portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by the table parser. `observe()` emits the current table snapshot by default and then emits after mutations. Listener errors never break the snapshot stream; pass `onObserverError` to the factory to report them.\n\n---\n\n### `DocumentVaultStore`\n\n```ts\ninterface DocumentVaultStore<S extends AnySchema> extends KeyValueVaultStore<S> {\n batch<K extends keyof S & string, R>(\n tables: readonly K[],\n fn: (tx: TransactionContext<S, K>) => Promise<R>,\n ): Promise<R>;\n iterate<K extends keyof S & string>(table: K): AsyncIterable<RecordOf<S, K>>;\n}\n```\n\n`batch()` runs a scoped atomic callback. `iterate()` lazily yields table records: IndexedDB uses a cursor, SQLite uses keyset pagination. Both are provided by `createIndexedDB()` and `createSQLite()`.\n\n| Parameter | Description |\n| --------- | ------------------------------------------------------- |\n| `tables` | Tables the transaction may access |\n| `fn` | Async callback that uses only the supplied `tx` context |\n\n**Returns:** The callback result after commit.\n\n```ts\nawait store.batch(['users'], async (tx) => {\n await tx.put('users', { id: 1, name: 'Ada' });\n});\n\nfor await (const user of store.iterate('users')) console.log(user);\n```\n\n## Bound Helpers\n\nConvenience operations are bound to every store and transaction context. For filtering, ordering, and pagination, compose over `getAll()`: it returns a plain array, or use `iterate()` on document stores and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n| Helper | Signature | Description |\n| -------------- | -------------------------------------------------------- | ------------------------------------------------------ |\n| `has()` | `(table, key) => Promise<boolean>` | Check whether a record exists |\n| `count()` | `(table) => Promise<number>` | Count live records |\n| `isEmpty()` | `(table) => Promise<boolean>` | Check whether a table has no live records |\n| `getMany()` | `(table, keys) => Promise<(T \\| undefined)[]>` | Fetch multiple records by key |\n| `keys()` | `(table, filter?) => Promise<VaultKey[]>` | Fetch live primary keys, optionally filtered by record |\n| `deleteMany()` | `(table, keys) => Promise<number>` | Delete multiple records, return count |\n| `update()` | `(table, key, changes, ttl?) => Promise<T \\| undefined>` | Partially update an existing record |\n| `upsert()` | `(table, key, fn, ttl?) => Promise<T>` | Read-modify-write with callback |\n\n```ts\nconst exists = await store.has('users', 1);\nconst total = await store.count('users');\nconst [a, b] = await store.getMany('users', [1, 2]);\nconst updated = await store.update('users', 1, { name: 'Alice' });\nconst result = await store.upsert('users', 99, (existing) => ({ id: 99, name: existing?.name ?? 'Guest' }));\n\nconst all = await store.getAll('users');\nconst active = all\n .filter((user) => user.status === 'active')\n .sort((a, b) => a.name.localeCompare(b.name))\n .slice(0, 20);\n```\n\nBound `update()` and `upsert()` are atomic on document stores. Their key-value-store forms are non-atomic convenience operations.\n\n## Types\n\n```ts\ntype VaultKey = number | string;\ntype Unsubscribe = () => void;\ntype Observer<T> = (records: T[]) => void;\ntype AnySchema = Record<\n string,\n {\n defaultTtl?: number;\n indexes?: readonly string[];\n key: string;\n }\n>;\ntype SchemaEntry<T extends object, Key extends keyof T & string = keyof T & string> = {\n defaultTtl?: number;\n indexes?: readonly (keyof T & string)[];\n key: Key;\n};\ntype RecordOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? S[K] extends SchemaEntry<infer R, infer _Key>\n ? R\n : never\n : never;\ntype KeyOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? Extract<S[K] extends SchemaEntry<infer R, infer Key> ? R[Key] : never, VaultKey>\n : never;\n```\n\n```ts\ntype RecordParser<T> = { parse(value: unknown): T };\n\ntype TableParsers<S extends AnySchema> = {\n [K in keyof S]: RecordParser<RecordOf<S, K>>;\n};\n\ntype ObserverErrorHandler = (error: unknown) => void;\n\ntype MemoryStoreOptions<S extends AnySchema> = {\n schema: S;\n parsers?: TableParsers<S>;\n onObserverError?: ObserverErrorHandler;\n};\n\ntype DurableStoreOptions<S extends AnySchema> = {\n schema: S;\n parsers: TableParsers<S>;\n onObserverError?: ObserverErrorHandler;\n};\n```\n\nParsers validate writes and decode persisted values: `put()` stores the parser's canonical output, so a record that parses can always be read back. Records must be JSON-safe (use ISO strings for dates) to survive every adapter's serialization. Spell schemas satisfy `RecordParser` directly.\n\n```ts\ntype MigrationContext = {\n db: IDBDatabase;\n newVersion: number | null;\n oldVersion: number;\n tx: IDBTransaction;\n};\n\ntype MigrationFn = (ctx: MigrationContext) => void;\n```\n\nImport `MigrationContext` and `MigrationFn` from `@vielzeug/vault/indexeddb`.\n\n```ts\ntype SQLiteParameter = null | number | string;\n\ninterface SQLiteStatement {\n all(...parameters: SQLiteParameter[]): readonly Record<string, unknown>[];\n finalize?(): void;\n get(...parameters: SQLiteParameter[]): Record<string, unknown> | null | undefined;\n run(...parameters: SQLiteParameter[]): unknown;\n}\n\ninterface SQLiteDatabase {\n close?(): void;\n exec(sql: string): void;\n prepare(sql: string): SQLiteStatement;\n}\n\ntype SQLiteVaultOptions<S extends AnySchema> = DurableStoreOptions<S> & {\n closeOnDispose?: boolean;\n database: SQLiteDatabase;\n name: string;\n};\n```\n\n```ts\ninterface TransactionContext<S extends AnySchema, K extends keyof S & string = keyof S & string> {\n clear<T extends K>(table: T): Promise<void>;\n delete<T extends K>(table: T, key: KeyOf<S, T>): Promise<boolean>;\n get<T extends K>(table: T, key: KeyOf<S, T>): Promise<RecordOf<S, T> | undefined>;\n getAll<T extends K>(table: T): Promise<RecordOf<S, T>[]>;\n iterate<T extends K>(table: T): AsyncIterable<RecordOf<S, T>>;\n put<T extends K>(table: T, value: RecordOf<S, T>, ttl?: number): Promise<RecordOf<S, T>>;\n putAll<T extends K>(table: T, values: RecordOf<S, T>[], ttl?: number): Promise<void>;\n}\n```\n\n`TransactionContext` has core CRUD, `iterate()`, and TTL methods, narrowed to the tables declared in `batch()`. Import it from `@vielzeug/vault/indexeddb` or `@vielzeug/vault/sqlite`.\n\n## Errors\n\n| Error | Trigger |\n| --------------------- | ------------------------------------------------------------------------ |\n| `VaultError` | Any Vault-originated validation, serialization, storage, or parser error |\n| `VaultDisposedError` | An operation after the store or observer hub is disposed |\n| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope |\n| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota |\n| `VaultMigrationError` | An IndexedDB migration callback throws |\n\nEvery listed error extends `VaultError`.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Vault: Usage Guide'\ndescription: Persist typed browser or SQLite data, observe table snapshots, and use atomic transactions with required durable parsers.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a key-value store with a schema and parsers, then write a typed row.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Preference {\n id: string;\n theme: 'dark' | 'light';\n}\n\nconst PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n\nawait store.put('preferences', { id: 'theme', theme: 'dark' });\nconsole.log(await store.get('preferences', 'theme'));\n```\n\n## Create a Key-Value Store\n\nLocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit parsers; Web Storage requires them. Malformed storage envelopes are evicted lazily, while parser validation failures are surfaced without deleting persisted data.\n\nThe root entry is adapter-free. Import `createMemory` from `@vielzeug/vault/memory`, `createLocalStorage` from `@vielzeug/vault/local-storage`, or `createSessionStorage` from `@vielzeug/vault/session-storage`. Import each adapter from its focused subpath so unused backends stay out of the bundle.\n\nUse a new storage name when upgrading from Vault 1. Old key and envelope formats are not read by Vault 2.\n\n```ts\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n```\n\n## Read and Change Records\n\nUse bound `update()` and `upsert()` methods for read-modify-write operations; no helper imports are required.\n\n```ts\nconst updated = await store.update('preferences', 'theme', { theme: 'light' });\n\nawait store.upsert('preferences', 'locale', (current) => ({\n id: 'locale',\n theme: current?.theme ?? 'dark',\n}));\n\nconsole.log(updated);\n```\n\n`update()` returns `undefined` for a missing key. `upsert()` always writes the record returned by its callback. Document-store methods run atomically; key-value-store methods are non-atomic conveniences when multiple writers race.\n\n## Iterate and Filter Records\n\nFilter the plain array returned by `getAll()` for in-memory selection, sorting, and pagination. Use `iterate()` on a `DocumentVaultStore` for lazy cursor-based traversal, and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n```ts\n// In-memory selection over getAll()\nconst themed = (await store.getAll('preferences')).filter((preference) => preference.id.startsWith('theme'));\n\n// Document store: iterate lazily\nfor await (const pref of db.iterate('preferences')) {\n if (pref.id.startsWith('theme')) console.log(pref);\n}\n```\n\nFor large tables, prefer `iterate()` on IndexedDB or SQLite instead of materializing every record with `getAll()`.\n\n## Use TTL and Pruning\n\nUse `ttl.*` helpers for expiring rows. Call `pruneExpired()` to reclaim storage from stale rows that accumulate without reads; tables with removed rows publish fresh observer snapshots.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nawait store.put('preferences', { id: 'temporary', theme: 'dark' }, ttl.hours(1));\n\n// Reclaim expired rows on a schedule owned by the application.\nconst pruneInterval = setInterval(() => store.pruneExpired(), ttl.hours(6));\nstore.disposalSignal.addEventListener('abort', () => clearInterval(pruneInterval));\n```\n\n## Observe a Table\n\nUse `observe()` for current and future snapshots. Notifications are revision-ordered, and explicit TTL pruning publishes fresh snapshots for affected tables. Tie subscription lifetime to an `AbortSignal` when a component or request owns it.\n\n```ts\nconst controller = new AbortController();\n\nstore.observe(\n 'preferences',\n (preferences) => {\n console.log(preferences);\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\n```\n\n## Use IndexedDB for Browser Transactions\n\nChoose IndexedDB when browser storage needs multiple writes to commit together or cursor iteration.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst db = createIndexedDB({\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n parsers: { events: EventSchema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nTransaction contexts expose the same bound helpers; `tx.update()`, `tx.upsert()`, and `tx.deleteMany()` run inside the enclosing transaction. Only await `tx.*` operations inside a batch callback. Do not retain the transaction context after the callback; later use throws `VaultScopeError`. Do not await timers, fetches, or other external asynchronous work because IndexedDB can commit an inactive transaction.\n\n## Use SQLite Outside the Browser\n\nImport SQLite from the opt-in subpath so the browser root stays free of runtime drivers. Vault never opens a connection or configures its SQLite process behavior for you.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst database = new DatabaseSync('app.db', { timeout: 5_000 });\nconst store = createSQLite({\n database,\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n parsers: { events: EventSchema },\n});\n\nawait store.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nNode's `node:sqlite` API is experimental. Bun's `bun:sqlite` `Database` satisfies the same positional `exec()` and `prepare()` contract; configure WAL from your application when the deployment needs it. Deno does not include SQLite, but `jsr:@db/sqlite`'s `Database` satisfies the same contract when its FFI, filesystem, and environment permissions are granted.\n\nSQLite stores serialize all access through the injected connection. `batch()` starts `BEGIN IMMEDIATE` and rolls back callback failures. While its callback runs, calls on any store sharing that connection reject rather than waiting behind the transaction; use `tx.*` instead. The underlying drivers are synchronous, so move large scans and writes to a worker or isolate when event-loop latency matters.\n\n## Store SQLite Values and Observe Changes\n\nSQLite stores records as JSON, so records must be JSON-compatible: circular values, `bigint`, and functions fail serialization, and parsers should reject anything a schema cannot represent (use ISO strings for dates). Number and string primary keys remain distinct.\n\n`observe()` sees mutations written through Vault stores sharing the same injected connection after a commit. It cannot detect direct SQL changes, writes from another process, or writes through another connection. The connection belongs to the caller by default; use `closeOnDispose: true` only when the store owns it.\n\n## Handle IndexedDB Schema Migrations\n\nDeclare IndexedDB indexes in the schema; other adapters ignore them and `getAllByIndex()` is IndexedDB-only. Because writes store the parser's canonical output, indexed fields always match what readers see. Use `migrate` only for IndexedDB version upgrades and mirror Vault's fixed `value.<field>` index path.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB, type MigrationFn } from '@vielzeug/vault/indexeddb';\n\nconst UserSchema = s.object({ id: s.number(), name: s.string() });\nconst schema = { users: table<{ id: number; name: string }>('id', { indexes: ['name'] }) };\nconst migrate: MigrationFn = ({ db, oldVersion, tx }) => {\n if (oldVersion < 2 && db.objectStoreNames.contains('users')) {\n tx.objectStore('users').createIndex('name', 'value.name');\n }\n};\n\ncreateIndexedDB({\n name: 'app-v2',\n migrate,\n schema,\n version: 2,\n parsers: { users: UserSchema },\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```ts [React]\nimport { useEffect, useState } from 'react';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const [rows, setRows] = useState<RecordOf<S, K>[]>([]);\n\n useEffect(() => store.observe(table, setRows), [store, table]);\n return rows;\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const rows = shallowRef<RecordOf<S, K>[]>([]);\n const stop = store.observe(table, (next) => (rows.value = next));\n\n onUnmounted(stop);\n return rows;\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function tableStore<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n return readable<RecordOf<S, K>[]>([], (set) => store.observe(table, set));\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nKeep Ripple signals as application state and persist selected changes through Vault writes.\n\n## Best Practices\n\n- Define one schema per storage namespace.\n- Use string or finite-number primary keys only.\n- Provide parsers for every durable adapter; pass a Spell schema directly for validation or a bare `{ parse }` for passthrough.\n- Use `observe()` for table snapshots.\n- Use IndexedDB or SQLite for atomic work.\n- Keep external asynchronous work outside `batch()` callbacks.\n- Use `ttl.*` instead of raw durations.\n- Keep SQLite scans and writes off latency-sensitive event loops.\n- Dispose stores when their owner ends.\n",
|
|
7
|
+
"examples": "---\ntitle: 'Vault: Examples'\ndescription: Practical Vault examples for browser storage, SQLite, TTL, transactions, observation, and framework integration.\n---\n\n## Browser Key-Value Store with TTL\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table, ttl } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Session {\n id: string;\n token: string;\n}\n\nconst SessionSchema = s.object({ id: s.string(), token: s.string() });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { sessions: table<Session>('id', { defaultTtl: ttl.hours(1) }) },\n parsers: { sessions: SessionSchema },\n});\n\nawait store.put('sessions', { id: 'current', token: 'FAKE-TOKEN-FOR-DOCS' });\nconsole.log(await store.get('sessions', 'current'));\n```\n\n## IndexedDB with Transactions and Iteration\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\ninterface Event {\n id: number;\n type: string;\n createdAt: number;\n}\n\nconst EventSchema = s.object({ createdAt: s.number(), id: s.number(), type: s.string() });\nconst db = createIndexedDB({\n name: 'events',\n schema: { events: table<Event>('id', { indexes: ['type'] }) },\n parsers: { events: EventSchema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened', createdAt: Date.now() });\n await tx.put('events', { id: 2, type: 'saved', createdAt: Date.now() });\n});\n\nfor await (const event of db.iterate('events')) {\n console.log(event.type);\n}\n```\n\n## SQLite Document Store\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\ninterface Job {\n id: string;\n status: 'queued' | 'running' | 'done';\n}\n\nconst JobSchema = s.object({ id: s.string(), status: s.enum(['queued', 'running', 'done']) });\nconst database = new DatabaseSync(':memory:');\nconst store = createSQLite({\n database,\n name: 'app',\n schema: { jobs: table<Job>('id') },\n parsers: { jobs: JobSchema },\n});\n\nawait store.batch(['jobs'], async (tx) => {\n await tx.put('jobs', { id: 'job-1', status: 'queued' });\n await tx.put('jobs', { id: 'job-2', status: 'running' });\n});\n\nfor await (const job of store.iterate('jobs')) {\n console.log(job.id, job.status);\n}\n```\n\n## Observe Table Changes\n\n```ts\nconst stop = store.observe('sessions', (sessions) => {\n console.log(`Active sessions: ${sessions.length}`);\n});\n\nstore.disposalSignal.addEventListener('abort', stop);\n```\n\n## Bound Helpers\n\n```ts\nconsole.log(await store.has('sessions', 'current'));\nconsole.log(await store.count('sessions'));\nconsole.log(await store.isEmpty('sessions'));\n\nconst [a, b] = await store.getMany('sessions', ['current', 'old']);\nconsole.log(await store.keys('sessions'));\nconsole.log(await store.deleteMany('sessions', ['old', 'expired']));\n\nawait store.update('sessions', 'current', { token: 'FAKE-UPDATED-TOKEN' });\nawait store.upsert('sessions', 'temp', (existing) => ({\n id: 'temp',\n token: existing?.token ?? 'generated',\n}));\n\nconst current = (await store.getAll('sessions')).find((session) => session.id === 'current');\nvoid a, b, current;\n```\n\n## React Hook\n\n```tsx\nimport { useEffect, useState } from 'react';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(\n store: KeyValueVaultStore<S>,\n table: K,\n): RecordOf<S, K>[] {\n const [rows, setRows] = useState<RecordOf<S, K>[]>([]);\n\n useEffect(() => store.observe(table, setRows), [store, table]);\n return rows;\n}\n```\n\n## Migration Example\n\nObject stores and schema-declared indexes are created automatically on upgrade. The `migrate` hook covers only what the schema cannot express, such as deleting a removed store or transforming old records.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst UserSchema = s.object({ email: s.string().email(), id: s.number() });\n\nconst db = createIndexedDB({\n name: 'app-v2',\n version: 2,\n migrate({ db, oldVersion, tx }) {\n // The 'users' store and its 'email' index already exist; drop a retired store.\n if (oldVersion < 2 && db.objectStoreNames.contains('legacy_sessions')) {\n tx.deleteObjectStore('legacy_sessions');\n }\n },\n schema: { users: table<{ id: number; email: string }>('id', { indexes: ['email'] }) },\n parsers: { users: UserSchema },\n});\n```\n\n## Recipe Examples\n\n- [CRUD Operations](./examples/crud.md)\n- [TTL and Pruning](./examples/ttl.md)\n- [IndexedDB Batch Transactions](./examples/batch.md)\n- [IndexedDB Lazy Iteration](./examples/iterate.md)\n- [SQLite Transactions and Iteration](./examples/sqlite.md)\n- [Reactive Tables with observe()](./examples/reactive.md)\n- [Validators and Error Handling](./examples/plugins.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
10
10
|
{
|
|
11
11
|
"id": "basic-setup",
|
|
12
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n
|
|
12
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n parsers: { users: UserSchema },\n})\n\nawait db.put('users', { id: 1, name: 'Alice', email: 'alice@example.com' })\nawait db.put('users', { id: 2, name: 'Bob', email: 'bob@example.com' })\n\nconsole.log('Get user 1:', await db.get('users', 1))\nconsole.log('All users:', await db.getAll('users'))\nconsole.log('Count:', await db.count('users'))",
|
|
13
13
|
"name": "Basic Setup - Initialize Vault"
|
|
14
14
|
},
|
|
15
15
|
{
|
|
16
16
|
"id": "bulk-operations",
|
|
17
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ItemSchema = s.object({ id: s.number(), value: s.number() })\nconst schema = {\n items: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'bulk-demo',\n schema,\n
|
|
17
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ItemSchema = s.object({ id: s.number(), value: s.number() })\nconst schema = {\n items: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'bulk-demo',\n schema,\n parsers: { items: ItemSchema },\n})\n\nconst items = Array.from({ length: 10 }, (_, index) => ({\n id: index + 1,\n value: +(Math.random() * 1000).toFixed(2),\n}))\n\nawait db.putAll('items', items)\nconsole.log('Inserted', items.length, 'items')\n\n// getMany: fetch multiple by key in one call (missing keys return undefined)\nconst [first, missing, third] = await db.getMany('items', [1, 99, 3])\nconsole.log('getMany [1, 99, 3]:', first?.id, missing, third?.id)\n\n// deleteMany: remove multiple by key, returns count deleted\nconst deleted = await db.deleteMany('items', [1, 2, 3, 99])\nconsole.log('deleteMany [1,2,3,99] deleted:', deleted) // 3 (99 did not exist)\n\n// filter-driven removal: getAll + filter + deleteMany\nconst remaining = await db.getAll('items')\nconst toDelete = remaining.filter((item) => item.id <= 6).map((item) => item.id)\nconst queryDeleted = await db.deleteMany('items', toDelete)\nconsole.log('Deleted items with id ≤ 6:', queryDeleted)\n\nconsole.log('Remaining count:', await db.count('items'))\nconsole.log('First remaining item:', (await db.getAll('items')).sort((a, b) => a.id - b.id)[0])",
|
|
18
18
|
"name": "Bulk Operations"
|
|
19
19
|
},
|
|
20
20
|
{
|
|
21
21
|
"id": "cache-first",
|
|
22
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), fetchedAt: s.number(), id: s.string() })\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema: { cache: table('id') },\n
|
|
22
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), fetchedAt: s.number(), id: s.string() })\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema: { cache: table('id') },\n parsers: { cache: CacheSchema },\n})\n\nasync function getOrComputeConfig() {\n const existing = await db.get('cache', 'config')\n if (existing) return existing\n\n const record = {\n id: 'config',\n data: 'computed value',\n fetchedAt: Date.now(),\n }\n await db.put('cache', record, ttl.minutes(5))\n return record\n}\n\nconst first = await getOrComputeConfig()\nconst second = await getOrComputeConfig()\nconsole.log('Same cached record:', first.fetchedAt === second.fetchedAt)",
|
|
23
23
|
"name": "Cache-First with get + put"
|
|
24
24
|
},
|
|
25
25
|
{
|
|
26
26
|
"id": "crud-operations",
|
|
27
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ age: s.number(), email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n
|
|
27
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ age: s.number(), email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n parsers: { users: UserSchema },\n})\n\nawait db.put('users', { id: 1, name: 'Alice', email: 'alice@example.com', age: 25 })\nawait db.put('users', { id: 2, name: 'Bob', email: 'bob@example.com', age: 30 })\nconsole.log('Created 2 users')\n\nconsole.log('Get user 1:', await db.get('users', 1))\nconsole.log('Count:', await db.count('users'))\nconsole.log('isEmpty before clear:', await db.isEmpty('users')) // false\n\nawait db.update('users', 1, { age: 26, name: 'Alice Smith' })\nconsole.log('Updated user 1:', await db.get('users', 1))\n\nconsole.log('Deleted user 2:', await db.delete('users', 2))\nconsole.log('Remaining users:', await db.getAll('users'))\n\nawait db.clear('users')\nconsole.log('isEmpty after clear:', await db.isEmpty('users')) // true",
|
|
28
28
|
"name": "CRUD Operations"
|
|
29
29
|
},
|
|
30
30
|
{
|
|
31
31
|
"id": "filtering",
|
|
32
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ProductSchema = s.object({ category: s.string(), id: s.number(), inStock: s.boolean(), name: s.string(), price: s.number() })\nconst schema = {\n products: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'shop',\n schema,\n
|
|
32
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ProductSchema = s.object({ category: s.string(), id: s.number(), inStock: s.boolean(), name: s.string(), price: s.number() })\nconst schema = {\n products: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'shop',\n schema,\n parsers: { products: ProductSchema },\n})\n\nawait db.putAll('products', [\n { id: 1, name: 'Laptop', price: 999, category: 'electronics', inStock: true },\n { id: 2, name: 'Mouse', price: 29, category: 'electronics', inStock: true },\n { id: 3, name: 'Desk', price: 299, category: 'furniture', inStock: false },\n { id: 4, name: 'Chair', price: 199, category: 'furniture', inStock: true },\n { id: 5, name: 'Monitor', price: 399, category: 'electronics', inStock: true },\n])\n\n// getAll() returns a plain array: compose with standard array operations\nconst all = await db.getAll('products')\nconst electronics = all\n .filter((product) => product.category === 'electronics' && product.inStock)\n .sort((a, b) => a.price - b.price)\n\nconst pageSize = 2\nconst pageIndex = 0\nconst page = electronics.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize)\n\nconsole.log('Page:', page.map((p) => p.name))\nconsole.log('Total matching:', electronics.length)\nconsole.log('Page 1 of', Math.ceil(electronics.length / pageSize))\n\n// prefix match\nconst mice = all.filter((product) => product.name.toLowerCase().startsWith('m'))\nconsole.log('Starts with m:', mice.map((p) => p.name))\n\n// deletion via deleteMany with the keys to remove\nconst outOfStock = all.filter((product) => !product.inStock).map((product) => product.id)\nconsole.log('Removed out-of-stock:', await db.deleteMany('products', outOfStock))\n\nconst cheapest = (await db.getAll('products')).sort((a, b) => a.price - b.price)[0]\nconsole.log('Cheapest:', cheapest?.name, cheapest?.price)\n\nconsole.log('Remaining count:', await db.count('products'))",
|
|
33
33
|
"name": "Filtering: getAll composition, pagination, and deletion"
|
|
34
34
|
},
|
|
35
35
|
{
|
|
36
36
|
"id": "indexed-db",
|
|
37
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb'\n\nconst LogSchema = s.object({ id: s.number(), level: s.string(), message: s.string(), ts: s.number() })\nconst schema = {\n logs: table('id'),\n}\n\n// createIndexedDB returns DocumentVaultStore with transactions and cursor iteration\nconst db = createIndexedDB({\n name: 'app-logs',\n schema,\n
|
|
37
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb'\n\nconst LogSchema = s.object({ id: s.number(), level: s.string(), message: s.string(), ts: s.number() })\nconst schema = {\n logs: table('id'),\n}\n\n// createIndexedDB returns DocumentVaultStore with transactions and cursor iteration\nconst db = createIndexedDB({\n name: 'app-logs',\n schema,\n parsers: { logs: LogSchema },\n version: 1,\n})\n\nawait db.putAll('logs', [\n { id: 1, level: 'info', message: 'App started', ts: Date.now() - 3000 },\n { id: 2, level: 'warn', message: 'Slow query detected', ts: Date.now() - 2000 },\n { id: 3, level: 'error', message: 'Request failed', ts: Date.now() - 1000 },\n { id: 4, level: 'info', message: 'Request succeeded', ts: Date.now() },\n], ttl.hours(1))\n\n// batch() is atomic on IndexedDB: all writes commit or none do\nawait db.batch(['logs'], async (tx) => {\n await tx.put('logs', { id: 5, level: 'info', message: 'Batch committed', ts: Date.now() })\n await tx.delete('logs', 1)\n await tx.delete('logs', 2)\n})\n\n// iterate(): cursor-based streaming, only on DocumentVaultStore\n// the full table is never loaded into memory at once\nconst messages = []\nfor await (const entry of db.iterate('logs')) {\n messages.push(entry.message)\n}\nconsole.log('Streamed via iterate():', messages)\n\nconst errors = (await db.getAll('logs')).filter((entry) => entry.level === 'error')\nconsole.log('Errors:', errors.map((e) => e.message))\nconsole.log('Total logs:', await db.count('logs'))\n\n// pruneExpired() reclaims storage from TTL-expired records that haven't been read\nconst pruned = await db.pruneExpired()\nconsole.log('Pruned:', pruned)\n\nawait db.dispose()",
|
|
38
38
|
"name": "IndexedDB: Atomic Batch & iterate()"
|
|
39
39
|
},
|
|
40
40
|
{
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
{
|
|
51
51
|
"id": "ttl-expiration",
|
|
52
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), id: s.string() })\nconst schema = {\n cache: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema,\n
|
|
52
|
+
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), id: s.string() })\nconst schema = {\n cache: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema,\n parsers: { cache: CacheSchema },\n})\n\n// ttl helpers produce finite, positive millisecond durations\nawait db.put('cache', { id: 'short', data: 'Expires in 1 second' }, ttl.seconds(1))\nawait db.put('cache', { id: 'long', data: 'Expires in 5 minutes' }, ttl.minutes(5))\nconsole.log('Stored records with TTL')\nconsole.log('Immediate read:', await db.get('cache', 'short'))\n\nawait new Promise((resolve) => setTimeout(resolve, 1500))\nconsole.log('After 1.5s:', await db.get('cache', 'short')) // expired: undefined\nconsole.log('Long-lived still here:', await db.get('cache', 'long'))\n\nconsole.log('ttl helpers:', {\n '100ms': ttl.ms(100),\n '5 minutes': ttl.minutes(5),\n '2 hours': ttl.hours(2),\n '7 days': ttl.days(7),\n})",
|
|
53
53
|
"name": "TTL & Expiration"
|
|
54
54
|
}
|
|
55
55
|
],
|
|
@@ -60,24 +60,22 @@
|
|
|
60
60
|
"VaultQuotaError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
61
61
|
"VaultScopeError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
62
62
|
"ttl": "export { ttl } from './ttl';",
|
|
63
|
-
"AnySchema": "export type {\n AnySchema,\n
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
78
|
-
"
|
|
79
|
-
"
|
|
80
|
-
"table": "export { table, validatorCodec } from './types';",
|
|
81
|
-
"validatorCodec": "export { table, validatorCodec } from './types';"
|
|
63
|
+
"AnySchema": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
64
|
+
"DocumentVaultStore": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
65
|
+
"DurableStoreOptions": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
66
|
+
"KeyOf": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
67
|
+
"KeyValueVaultStore": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
68
|
+
"MemoryStoreOptions": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
69
|
+
"Observer": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
70
|
+
"ObserverErrorHandler": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
71
|
+
"RecordOf": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
72
|
+
"RecordParser": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
73
|
+
"SchemaEntry": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
74
|
+
"TableParsers": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
75
|
+
"TransactionContext": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
76
|
+
"Unsubscribe": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
77
|
+
"VaultConveniences": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
78
|
+
"VaultKey": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
79
|
+
"table": "export { table } from './types';"
|
|
82
80
|
}
|
|
83
81
|
}
|