tauri-plugin-configurate 0.4.1

Tauri v2 plugin for type-safe application configuration management.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# TypeScript API Reference


Complete API reference for `tauri-plugin-configurate-api`.

---

## Table of Contents


- [Schema Definition]#schema-definition
- [Providers]#providers
- [Configurate Class]#configurate-class
  - [Constructor]#constructor
  - [CRUD Operations]#crud-operations
  - [Patch]#patch
  - [Reset]#reset
  - [Exists / List]#exists--list
  - [Export / Import]#export--import
  - [Validation]#validation
  - [File Watching]#file-watching
  - [Batch Operations]#batch-operations
- [Result Types]#result-types
- [Utility Functions]#utility-functions

---

## Schema Definition


### `defineConfig(schema)`


Defines and validates a config schema object. Returns the schema unchanged (used for type inference).

```ts
import { defineConfig, keyring, optional } from "tauri-plugin-configurate-api";

const schema = defineConfig({
  theme: String,
  fontSize: optional(Number),
  apiKey: keyring(String, { id: "api-key" }),
  database: {
    host: String,
    port: Number,
    password: keyring(String, { id: "db-password" }),
  },
  tags: [String],
});
```

**Schema value types:**

| Type | Description |
|------|-------------|
| `String` | String field |
| `Number` | Number field (must be finite) |
| `Boolean` | Boolean field |
| `keyring(Type, { id })` | OS keyring-protected field |
| `optional(Type)` | Optional field (may be `undefined` or `null`) |
| `{ ... }` | Nested object |
| `[Type]` | Array of a single element type |

**Type inference:**

- `InferUnlocked<S>` — Full type with keyring fields as their actual types
- `InferLocked<S>` — Type with keyring fields replaced by `null`

### `keyring(typeCtor, opts)`


Marks a schema field as keyring-protected.

```ts
keyring(String, { id: "my-secret" })
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `typeCtor` | `StringConstructor \| NumberConstructor \| BooleanConstructor` | The value type constructor |
| `opts.id` | `string` | Unique identifier. Must not be empty or contain `/` |

### `optional(schema)`


Marks a field as optional. Can wrap primitives, keyring fields, objects, or arrays.

```ts
optional(Number)
optional(keyring(String, { id: "opt-secret" }))
optional({ host: String, port: Number })
optional([String])
```

---

## Providers


All providers return a branded `ConfigurateProvider` object.

### `JsonProvider()`


Plain JSON file storage. Human-readable, pretty-printed.

### `YmlProvider()`


YAML file storage.

### `TomlProvider()`


TOML file storage.

> **Note:** TOML has no native `null` type. Fields with `null` values are silently omitted on write and will be absent on the next load.

### `BinaryProvider(opts?)`


Binary file storage with optional encryption.

```ts
BinaryProvider()                                          // Unencrypted (compact JSON bytes)
BinaryProvider({ encryptionKey: "key" })                  // XChaCha20-Poly1305 with SHA-256 KDF
BinaryProvider({ encryptionKey: "key", kdf: "argon2" })   // XChaCha20-Poly1305 with Argon2id KDF
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `encryptionKey` | `string?` | `undefined` | Encryption key. Omit for unencrypted |
| `kdf` | `"sha256" \| "argon2"` | `"sha256"` | Key derivation function |

### `SqliteProvider(opts?)`


SQLite database storage. Schema fields are materialized as typed columns.

```ts
SqliteProvider()
SqliteProvider({ dbName: "app.db", tableName: "settings" })
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `dbName` | `string?` | `"configurate.db"` | Database file name |
| `tableName` | `string?` | `"configurate_configs"` | Table name |

---

## Configurate Class


### Constructor


```ts
new Configurate<S>(opts: ConfigurateInit<S>)
```

| Option | Type | Required | Description |
|--------|------|----------|-------------|
| `schema` | `S` | Yes | Schema object from `defineConfig()` |
| `fileName` | `string` | Yes | Config file name (no path separators) |
| `baseDir` | `BaseDirectory` | Yes | Tauri base directory |
| `provider` | `ConfigurateProvider` | Yes | Storage provider |
| `options` | `ConfiguratePathOptions?` | No | Path customization |
| `options.dirName` | `string?` | No | Replaces app-identifier directory segment |
| `options.currentPath` | `string?` | No | Sub-directory within root |
| `validation` | `SchemaValidationOptions?` | No | Schema validation settings |
| `validation.validateOnWrite` | `boolean` | No | Validate on create/save (default: `false`) |
| `validation.validateOnRead` | `boolean` | No | Validate on load/unlock (default: `false`) |
| `validation.allowUnknownKeys` | `boolean` | No | Allow undeclared keys (default: `false`) |
| `defaults` | `Partial<InferUnlocked<S>>?` | No | Default values to fill on load |
| `version` | `number?` | No | Schema version for migration |
| `migrations` | `MigrationStep[]?` | No | Ordered migration steps |

---

### CRUD Operations


#### `config.create(data)`


Creates a new config file.

```ts
const entry = config.create({
  theme: "dark",
  database: { host: "localhost", password: "secret" },
});

// Without keyring
const locked = await entry.run();

// With keyring (required when schema has keyring fields)
const locked = await entry.lock(keyringOpts).run();

// Get unlocked data back
const unlocked = await entry.unlock(keyringOpts);
```

**Returns:** `LazyConfigEntry<S>`

| Method | Returns | Description |
|--------|---------|-------------|
| `.run()` | `Promise<LockedConfig<S>>` | Execute and return locked data |
| `.lock(opts).run()` | `Promise<LockedConfig<S>>` | Store secrets in keyring, return locked data |
| `.unlock(opts)` | `Promise<UnlockedConfig<S>>` | Store secrets in keyring, return unlocked data |

---

#### `config.load()`


Loads an existing config file.

```ts
// Locked — keyring fields are null
const locked = await config.load().run();
console.log(locked.data.database.password); // null

// Unlocked — keyring fields are populated
const unlocked = await config.load().unlock(keyringOpts);
console.log(unlocked.data.database.password); // "secret"

// Unlock from locked data
const unlocked2 = await locked.unlock(keyringOpts);
```

**Returns:** `LazyConfigEntry<S>`

---

#### `config.save(data)`


Overwrites an existing config file completely.

```ts
await config.save({ theme: "light", database: { host: "db.example.com", password: "new-secret" } })
  .lock(keyringOpts)
  .run();
```

**Returns:** `LazyConfigEntry<S>`

---

#### `config.delete(keyringOpts?)`


Deletes the config file and associated keyring entries.

```ts
await config.delete(keyringOpts);
// or without keyring:
await config.delete();
```

**Returns:** `Promise<void>`

---

### Patch


#### `config.patch(partial)`


Partially updates an existing config by deep-merging. Omitted keys are left unchanged.

```ts
const entry = config.patch({ theme: "dark" });

// Run without keyring
const patched = await entry.run();

// Run with keyring
const patched = await entry.lock(keyringOpts).run();

// Create the config if it doesn't exist
const patched = await entry.createIfMissing().run();

// Run and get unlocked result
const unlocked = await entry.unlock(keyringOpts);
```

**Returns:** `LazyPatchEntry<S>`

| Method | Returns | Description |
|--------|---------|-------------|
| `.run()` | `Promise<PatchedConfig<S>>` | Execute patch, return locked result |
| `.lock(opts).run()` | `Promise<PatchedConfig<S>>` | Patch with keyring, return locked result |
| `.createIfMissing()` | `this` | Create config if not found instead of throwing |
| `.unlock(opts)` | `Promise<UnlockedConfig<S>>` | Patch with keyring, return unlocked result |

---

### Reset


#### `config.reset(data)`


Deletes the existing config and re-creates it with the provided data.

```ts
const entry = config.reset({
  theme: "dark",
  language: "en",
  database: { host: "localhost", password: "secret" },
});

// With keyring
const locked = await entry.lock(keyringOpts).run();

// Get unlocked result
const unlocked = await entry.unlock(keyringOpts);
```

**Returns:** `LazyResetEntry<S>`

| Method | Returns | Description |
|--------|---------|-------------|
| `.run()` | `Promise<LockedConfig<S>>` | Reset and return locked data |
| `.lock(opts).run()` | `Promise<LockedConfig<S>>` | Reset with keyring, return locked data |
| `.unlock(opts)` | `Promise<UnlockedConfig<S>>` | Reset with keyring, return unlocked data |

---

### Exists / List


#### `config.exists()`


Checks whether the config entry exists.

```ts
const present: boolean = await config.exists();
```

#### `config.list()`


Lists config file names in the resolved root directory.

- **File-based providers:** Scans the directory for files matching the provider's extension. Backup files (`.bak*`) and temp files are excluded.
- **SQLite:** Returns all `config_key` values in the table.

```ts
const files: string[] = await config.list();
// ["app.json", "user.json", "settings.json"]
```

---

### Export / Import


#### `config.exportAs(format, keyringOpts?)`


Exports the stored config data as a formatted string.

```ts
const jsonStr = await config.exportAs("json");
const yamlStr = await config.exportAs("yml");
const tomlStr = await config.exportAs("toml");
const yamlWithSecrets = await config.exportAs("yml", keyringOpts);
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `format` | `"json" \| "yml" \| "toml"` | Target serialization format |
| `keyringOpts` | `KeyringOptions?` | When provided, keyring fields are unlocked before export |

**Returns:** `Promise<string>`

#### `config.importFrom(content, format, keyringOpts?)`


Imports config data from a string, replacing the current stored config.

```ts
await config.importFrom('{"theme": "dark"}', "json");
await config.importFrom("theme: dark\n", "yml");
await config.importFrom('theme = "dark"\n', "toml", keyringOpts);
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `content` | `string` | Serialized config string |
| `format` | `"json" \| "yml" \| "toml"` | Source format |
| `keyringOpts` | `KeyringOptions?` | Required to import decrypted values for schemas that use `keyring()` |

**Returns:** `Promise<void>`

---

### Validation


#### `config.validate(data)`


Validates full config data against the schema without writing to storage. Throws on validation failure.

```ts
try {
  config.validate({
    theme: "dark",
    database: { host: "localhost", password: "secret" },
  });
  console.log("Valid!");
} catch (e) {
  console.error(e.message);
}
```

#### `config.validatePartial(data)`


Validates partial config data against the schema. Only provided keys are checked.

```ts
config.validatePartial({ theme: "dark" }); // OK
config.validatePartial({ theme: 123 });    // throws
```

---

### File Watching


#### `config.watchExternal(callback)`


Watches the config file for changes made by external processes. File-based providers only (throws for SQLite).

```ts
const stopWatching = await config.watchExternal((event) => {
  console.log(`External change detected: ${event.operation}`);
});

// Later
await stopWatching();
```

**Returns:** `Promise<() => Promise<void>>` — async function to stop watching

#### `config.onChange(callback)`


Registers a callback for any config change (create, save, patch, delete, reset, import).

```ts
const unlisten = await config.onChange((event) => {
  console.log(`Config ${event.operation} on ${event.fileName}`);
});

// Later
unlisten();
```

**Returns:** `Promise<() => void>` — function to stop listening

#### `ConfigChangeEvent`


```ts
interface ConfigChangeEvent {
  fileName: string;   // Config file name
  operation: string;  // "create" | "save" | "patch" | "delete" | "reset" | "import" | "external_change"
  targetId: string;   // Unique identifier for this config target
}
```

---

### Batch Operations


#### `Configurate.loadAll(entries)`


Loads multiple configs in a single IPC call.

Batch loads apply the same post-load defaults and migration processing as
`config.load()`.

```ts
const result = await Configurate.loadAll([
  { id: "app", config: appConfig },
  { id: "secret", config: secretConfig },
])
  .unlock("secret", keyringOpts)    // unlock specific entry
  // .unlockAll(keyringOpts)         // or unlock all entries
  .run();

if (result.results.app.ok) {
  console.log(result.results.app.data);
}
```

#### `Configurate.saveAll(entries)`


Saves multiple configs in a single IPC call.

```ts
const result = await Configurate.saveAll([
  { id: "app", config: appConfig, data: { theme: "dark" } },
  { id: "secret", config: secretConfig, data: { token: "tok" } },
])
  .lock("secret", keyringOpts)     // lock specific entry
  // .lockAll(keyringOpts)          // or lock all entries
  .run();
```

#### `Configurate.patchAll(entries)`


Patches multiple configs in a single IPC call.

```ts
const result = await Configurate.patchAll([
  { id: "app", config: appConfig, data: { theme: "light" } },
])
  .lock("app", keyringOpts)
  .run();
```

---

## Result Types


### `LockedConfig<S>`


Wrapper for loaded config data with keyring fields as `null`.

```ts
class LockedConfig<S> {
  readonly data: InferLocked<S>;
  unlock(opts: KeyringOptions): Promise<UnlockedConfig<S>>;
}
```

### `UnlockedConfig<S>`


Wrapper for config data with keyring fields populated. Access is revoked after calling `lock()`.

```ts
class UnlockedConfig<S> {
  get data(): InferUnlocked<S>;  // throws after lock()
  lock(): void;                  // revokes access to data
}
```

### `PatchedConfig<S>`


Wrapper for the locked result of a patch operation.

```ts
class PatchedConfig<S> {
  readonly data: Partial<InferLocked<S>>;
}
```

### `BatchRunResult`


```ts
interface BatchRunResult {
  results: Record<string, BatchRunEntryResult>;
}

type BatchRunEntryResult =
  | { ok: true; data: unknown }
  | { ok: false; error: { kind: string; message: string } };
```

### `KeyringOptions`


```ts
interface KeyringOptions {
  service: string;  // Keyring service name (e.g. your app name)
  account: string;  // Keyring account name (e.g. "default")
}
```

---

## Utility Functions


### `configDiff(oldData, newData)`


Computes a structural diff between two config objects.

```ts
import { configDiff } from "tauri-plugin-configurate-api";

const changes = configDiff(
  { theme: "light", fontSize: 14 },
  { theme: "dark", fontSize: 14, lang: "en" },
);
// [
//   { path: "theme", type: "changed", oldValue: "light", newValue: "dark" },
//   { path: "lang", type: "added", newValue: "en" },
// ]
```

**Returns:** `DiffEntry[]`

```ts
interface DiffEntry {
  path: string;                           // Dot-separated path
  type: "added" | "removed" | "changed";  // Kind of change
  oldValue?: unknown;                     // Previous value (for "removed" and "changed")
  newValue?: unknown;                     // New value (for "added" and "changed")
}
```

Nested objects are compared recursively using dot-separated paths (e.g. `"database.host"`).

---

### `MigrationStep`


Used with the `version` and `migrations` options for schema versioning.

```ts
interface MigrationStep<TData> {
  version: number;          // The version this migration upgrades FROM
  up: (data: TData) => TData;  // Transform function
}
```

Example:

```ts
const config = new Configurate({
  schema,
  fileName: "app.json",
  baseDir: BaseDirectory.AppConfig,
  provider: JsonProvider(),
  version: 2,
  migrations: [
    { version: 0, up: (data) => ({ ...data, newField: "default" }) },
    { version: 1, up: (data) => { delete data.oldField; return data; } },
  ],
});
```

Migrations run automatically on `load()`. If data is migrated, it is auto-saved back to storage.