create-noy-db 0.1.0-pre.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +283 -0
  3. package/dist/bin/create.d.ts +1 -0
  4. package/dist/bin/create.js +815 -0
  5. package/dist/bin/create.js.map +1 -0
  6. package/dist/bin/noy-db.d.ts +1 -0
  7. package/dist/bin/noy-db.js +555 -0
  8. package/dist/bin/noy-db.js.map +1 -0
  9. package/dist/index.d.ts +697 -0
  10. package/dist/index.js +967 -0
  11. package/dist/index.js.map +1 -0
  12. package/package.json +74 -0
  13. package/templates/electron/README.md +85 -0
  14. package/templates/electron/_gitignore +31 -0
  15. package/templates/electron/electron/main.ts +51 -0
  16. package/templates/electron/index.html +12 -0
  17. package/templates/electron/package.json +32 -0
  18. package/templates/electron/src/App.vue +75 -0
  19. package/templates/electron/src/components/AddInvoiceForm.vue +39 -0
  20. package/templates/electron/src/components/InvoiceTable.vue +41 -0
  21. package/templates/electron/src/main.ts +48 -0
  22. package/templates/electron/src/stores/invoices.ts +35 -0
  23. package/templates/electron/src/style.css +119 -0
  24. package/templates/electron/tsconfig.json +19 -0
  25. package/templates/electron/vite.config.ts +21 -0
  26. package/templates/nuxt-default/README.md +38 -0
  27. package/templates/nuxt-default/_gitignore +32 -0
  28. package/templates/nuxt-default/app/app.vue +37 -0
  29. package/templates/nuxt-default/app/pages/index.vue +21 -0
  30. package/templates/nuxt-default/app/pages/invoices.vue +62 -0
  31. package/templates/nuxt-default/app/stores/invoices.ts +23 -0
  32. package/templates/nuxt-default/nuxt.config.ts +30 -0
  33. package/templates/nuxt-default/package.json +28 -0
  34. package/templates/nuxt-default/tsconfig.json +3 -0
  35. package/templates/vanilla/README.md +77 -0
  36. package/templates/vanilla/_gitignore +29 -0
  37. package/templates/vanilla/index.html +54 -0
  38. package/templates/vanilla/package.json +21 -0
  39. package/templates/vanilla/src/main.ts +153 -0
  40. package/templates/vanilla/src/style.css +127 -0
  41. package/templates/vanilla/tsconfig.json +17 -0
  42. package/templates/vanilla/vite.config.ts +10 -0
  43. package/templates/vite-vue/README.md +95 -0
  44. package/templates/vite-vue/_gitignore +29 -0
  45. package/templates/vite-vue/index.html +12 -0
  46. package/templates/vite-vue/package.json +28 -0
  47. package/templates/vite-vue/src/App.vue +75 -0
  48. package/templates/vite-vue/src/components/AddInvoiceForm.vue +39 -0
  49. package/templates/vite-vue/src/components/InvoiceTable.vue +41 -0
  50. package/templates/vite-vue/src/main.ts +55 -0
  51. package/templates/vite-vue/src/stores/invoices.ts +35 -0
  52. package/templates/vite-vue/src/style.css +119 -0
  53. package/templates/vite-vue/tsconfig.json +18 -0
  54. package/templates/vite-vue/vite.config.ts +12 -0
@@ -0,0 +1,697 @@
1
+ import { Role, createNoydb, NoydbStore } from '@noy-db/hub';
2
+
3
+ /**
4
+ * Internationalization types for the `@noy-db/create` wizard.
5
+ *
6
+ * `WizardMessages` is the full set of user-facing strings the
7
+ * wizard emits: prompt labels, note titles, note bodies, outro
8
+ * messages, confirmation questions. Every locale bundle exports
9
+ * a `WizardMessages` constant; the key-parity test ensures they
10
+ * all have the exact same set of keys so we never ship a locale
11
+ * that's missing a string.
12
+ *
13
+ * ## What's translated, what's not
14
+ *
15
+ * **Translated:** prompts, note titles, confirmation messages,
16
+ * success banners, and the short summaries shown before each
17
+ * major step. These are the load-bearing "does the user
18
+ * understand what's happening?" strings.
19
+ *
20
+ * **Not translated:** validation error messages ("Project name
21
+ * cannot be empty"), diagnostic output, stack traces, structured
22
+ * errors from `@noy-db/core`. These stay in English so bug
23
+ * reports from any locale look the same in an issue tracker.
24
+ * Thai developers filing bugs with English error messages can
25
+ * get help from English-speaking maintainers; the reverse is
26
+ * harder.
27
+ *
28
+ * ## Why a flat shape instead of nested namespaces
29
+ *
30
+ * Flat keys are the simplest thing that can work. With ~30
31
+ * strings, namespacing (e.g., `prompts.projectName`) would just
32
+ * add ceremony without helping discoverability. If the set grows
33
+ * past ~100 strings we can revisit.
34
+ */
35
+ type Locale = 'en' | 'th';
36
+ interface WizardMessages {
37
+ /** Banner shown under the intro badge in fresh-project mode. */
38
+ wizardIntro: string;
39
+ /** "Project name" prompt label. */
40
+ promptProjectName: string;
41
+ /** Placeholder shown inside the project-name input. */
42
+ promptProjectNamePlaceholder: string;
43
+ /** "Storage adapter" select prompt label. */
44
+ promptAdapter: string;
45
+ /** Label for the browser adapter option. */
46
+ adapterBrowserLabel: string;
47
+ /** Label for the file adapter option. */
48
+ adapterFileLabel: string;
49
+ /** Label for the memory adapter option. */
50
+ adapterMemoryLabel: string;
51
+ /** "Include sample invoice records?" confirm label. */
52
+ promptSampleData: string;
53
+ /** Title of the "Next steps" note block. */
54
+ freshNextStepsTitle: string;
55
+ /** Success banner shown after the fresh project is created. */
56
+ freshOutroDone: string;
57
+ /** Title of the "augment mode detected" note block. */
58
+ augmentModeTitle: string;
59
+ /** First line of the augment-mode intro body — followed by the path. */
60
+ augmentDetectedPrefix: string;
61
+ /** Second/third lines explaining what augment mode will do. */
62
+ augmentDescription: string;
63
+ /** Title of the diff preview note block. */
64
+ augmentProposedChangesTitle: string;
65
+ /** Question shown at the confirm prompt. */
66
+ augmentApplyConfirm: string;
67
+ /** Title when the config is already configured. */
68
+ augmentAlreadyConfiguredTitle: string;
69
+ /** Prefix for the "already configured" reason line. */
70
+ augmentNothingToDo: string;
71
+ /** Success banner when there's nothing to do. */
72
+ augmentAlreadyOutro: string;
73
+ /** Cancel message when the user declines the confirm prompt. */
74
+ augmentAborted: string;
75
+ /** Success banner on dry-run success. */
76
+ augmentDryRunOutro: string;
77
+ /** Title of the "install these packages next" note block. */
78
+ augmentNextStepTitle: string;
79
+ /** Prose line above the install command. */
80
+ augmentInstallIntro: string;
81
+ /** Dim hint under the install command. */
82
+ augmentInstallPmHint: string;
83
+ /** Success banner after a real augmentation write. */
84
+ augmentDoneOutro: string;
85
+ /** Prefix for the "unsupported shape" error message. */
86
+ augmentUnsupportedPrefix: string;
87
+ /** Cancellation message used by Ctrl-C handlers. */
88
+ cancelled: string;
89
+ }
90
+
91
+ /**
92
+ * Types shared between the wizard, the bins, and the test harness.
93
+ *
94
+ * `WizardOptions` is the input shape — both the prompt UI and the test
95
+ * helper accept the same object so tests can skip the interactive prompts
96
+ * by passing answers up front.
97
+ */
98
+
99
+ /**
100
+ * Which built-in adapter to wire into the generated `nuxt.config.ts`.
101
+ *
102
+ * - `browser` — localStorage / IndexedDB. The recommended default for
103
+ * because it makes the generated app a real PWA-friendly demo.
104
+ * - `file` — JSON files on disk. Useful for Electron / Tauri wraps and
105
+ * for the USB-stick workflow.
106
+ * - `memory` — no persistence. Mostly useful for tests and demos. Picked
107
+ * automatically when running in CI to avoid touching the test runner's
108
+ * localStorage.
109
+ */
110
+ type WizardAdapter = 'browser' | 'file' | 'memory';
111
+ /**
112
+ * Which starter template to scaffold in fresh-project mode.
113
+ *
114
+ * - `nuxt-default` — Nuxt 4 + Pinia + in-nuxt, SSR-friendly. Default.
115
+ * - `vanilla` — Vite + TS, no framework. Smallest footprint.
116
+ * - `vite-vue` — Vite + Vue 3 + Pinia + in-pinia. Client-side SPA.
117
+ * - `electron` — Electron + Vue 3 + to-file. USB-stick / local-disk workflow.
118
+ *
119
+ * Augment mode (detected Nuxt project) ignores this field — the
120
+ * mutation path is shared regardless of the original scaffold.
121
+ */
122
+ type WizardTemplate = 'nuxt-default' | 'vanilla' | 'vite-vue' | 'electron';
123
+ /**
124
+ * Inputs to `runWizard()`. All fields are optional — when a field is
125
+ * omitted the wizard prompts for it. Tests pass everything to skip
126
+ * prompts entirely.
127
+ */
128
+ interface WizardOptions {
129
+ /**
130
+ * Project directory name. The wizard creates `<cwd>/<projectName>/`
131
+ * and refuses to overwrite an existing non-empty directory.
132
+ */
133
+ projectName?: string;
134
+ /**
135
+ * Adapter to use in the generated `nuxt.config.ts`. See `WizardAdapter`.
136
+ */
137
+ adapter?: WizardAdapter;
138
+ /**
139
+ * Starter template to scaffold. Defaults to `'nuxt-default'` when
140
+ * omitted. Ignored in augment mode (the existing project's shape
141
+ * determines the mutation path).
142
+ */
143
+ template?: WizardTemplate;
144
+ /**
145
+ * Optional sync-target adapter. When set, the
146
+ * generated project wires a `sync: [...]` entry in
147
+ * `createNoydb()` alongside the primary store. When omitted, the
148
+ * project runs local-only.
149
+ *
150
+ * Accepts the same adapter identifiers as `adapter` but is
151
+ * semantically orthogonal — pick the primary adapter based on
152
+ * "where do I want records persisted locally?" and the sync
153
+ * adapter based on "where do I want them replicated?".
154
+ */
155
+ syncAdapter?: WizardAdapter | 'none';
156
+ /**
157
+ * Whether to include the seed-data invoices in the generated app. When
158
+ * `true`, the page renders pre-filled records on first load so the user
159
+ * sees something immediately. When `false`, the page starts empty and
160
+ * waits for the user to click "Add invoice".
161
+ */
162
+ sampleData?: boolean;
163
+ /**
164
+ * Working directory the project should be created in. Defaults to
165
+ * `process.cwd()`. Tests pass a temp directory.
166
+ */
167
+ cwd?: string;
168
+ /**
169
+ * When `true`, skip ALL interactive prompts and use only the values
170
+ * supplied above. Missing values become defaults (`browser`, `true`,
171
+ * a generated project name). This is the path tests take.
172
+ */
173
+ yes?: boolean;
174
+ /**
175
+ * Augment mode: show the proposed diff against an existing
176
+ * `nuxt.config.ts` but do not write the file. Only meaningful
177
+ * when the wizard detects an existing Nuxt project in `cwd`. A
178
+ * no-op in fresh-project mode.
179
+ */
180
+ dryRun?: boolean;
181
+ /**
182
+ * Force fresh-project mode even when cwd looks like an existing
183
+ * Nuxt project. Useful for CI tests that create a scratch
184
+ * directory inside a parent that happens to have a nuxt.config.
185
+ */
186
+ forceFresh?: boolean;
187
+ /**
188
+ * Locale for the wizard's user-facing prompts and notes. When
189
+ * omitted, the wizard auto-detects from `LC_ALL` / `LANG` env
190
+ * vars and falls back to `'en'`. Tests pin a value to make
191
+ * snapshot output deterministic.
192
+ *
193
+ * Validation/error messages are NOT translated — they stay in
194
+ * English so bug reports look the same across locales.
195
+ */
196
+ locale?: Locale;
197
+ }
198
+ /**
199
+ * Output of `runWizard()` in fresh-project mode. The augment-mode
200
+ * path uses `WizardAugmentResult` instead; the caller narrows on
201
+ * the `kind` discriminator.
202
+ */
203
+ interface WizardFreshResult {
204
+ readonly kind: 'fresh';
205
+ /** Resolved options after prompts/defaults. */
206
+ readonly options: {
207
+ readonly projectName: string;
208
+ readonly adapter: WizardAdapter;
209
+ readonly sampleData: boolean;
210
+ readonly cwd: string;
211
+ readonly template: WizardTemplate;
212
+ readonly syncAdapter: WizardAdapter | 'none';
213
+ };
214
+ /** Absolute path of the created project directory. */
215
+ readonly projectPath: string;
216
+ /** Relative paths of every file the wizard wrote, sorted alphabetically. */
217
+ readonly files: string[];
218
+ }
219
+ /**
220
+ * Output of `runWizard()` in augment mode. Carries the outcome of
221
+ * the magicast-based config mutation — either the file was
222
+ * actually written (`changed: true`), the file was already
223
+ * configured (`changed: false, reason: 'already-configured'`),
224
+ * or the user cancelled at the confirmation prompt (`changed: false,
225
+ * reason: 'cancelled'`), or we were in dry-run (`changed: false,
226
+ * reason: 'dry-run'`).
227
+ */
228
+ interface WizardAugmentResult {
229
+ readonly kind: 'augment';
230
+ readonly configPath: string;
231
+ readonly adapter: WizardAdapter;
232
+ readonly changed: boolean;
233
+ readonly reason: 'written' | 'already-configured' | 'cancelled' | 'dry-run' | 'unsupported-shape';
234
+ /** The unified diff that was shown to the user, if any. */
235
+ readonly diff?: string;
236
+ }
237
+ type WizardResult = WizardFreshResult | WizardAugmentResult;
238
+
239
+ /**
240
+ * The wizard entry point — `runWizard()`.
241
+ *
242
+ * Two modes:
243
+ *
244
+ * 1. **Interactive (default).** Uses `@clack/prompts` to ask the user
245
+ * for project name, adapter, and sample-data inclusion. Cancellation
246
+ * at any prompt aborts cleanly with a non-zero exit code.
247
+ *
248
+ * 2. **Non-interactive (`yes: true`).** Skips every prompt and uses the
249
+ * values supplied in `WizardOptions`. Missing values become defaults.
250
+ * This is the path tests take — no terminal needed, fully scriptable.
251
+ *
252
+ * The function never spawns child processes (no `npm install` etc.). It
253
+ * only writes files and returns. The shell wrapper around `npm create` is
254
+ * responsible for installing — we keep this layer pure so it's trivially
255
+ * testable and so adding a `--no-install` flag later is a no-op.
256
+ */
257
+
258
+ /**
259
+ * Main entry point. Detects whether `cwd` is an existing Nuxt 4
260
+ * project and routes to one of two modes:
261
+ *
262
+ * - **Fresh mode** (the original behavior): prompts for
263
+ * project name, creates a new directory, renders the Nuxt 4
264
+ * starter template. Returns a `WizardFreshResult`.
265
+ *
266
+ * - **Augment mode** (new in, ): patches the existing
267
+ * `nuxt.config.ts` via magicast to add `@noy-db/in-nuxt` to the
268
+ * modules array and a `noydb:` config key. Shows a unified
269
+ * diff and asks for confirmation before writing. Supports
270
+ * `--dry-run`. Returns a `WizardAugmentResult`.
271
+ *
272
+ * The auto-detection rule: if cwd has both a `nuxt.config.ts`
273
+ * (or `.js`/`.mjs`) AND a `package.json` that lists `nuxt` in any
274
+ * dependency section, augment mode fires. Otherwise fresh mode.
275
+ * Users can force fresh mode via `forceFresh: true` (CLI:
276
+ * `--force-fresh`) when they want to create a sub-project inside
277
+ * an existing Nuxt workspace.
278
+ *
279
+ * Both modes refuse to clobber existing work: fresh mode rejects
280
+ * non-empty target dirs; augment mode rejects unsupported config
281
+ * shapes (opaque exports, non-array modules, etc.).
282
+ */
283
+ declare function runWizard(options?: WizardOptions): Promise<WizardResult>;
284
+
285
+ /**
286
+ * i18n entrypoint for the `@noy-db/create` wizard.
287
+ *
288
+ * Three responsibilities:
289
+ *
290
+ * 1. Re-export `Locale` and `WizardMessages` so callers don't
291
+ * need to know about the bundle layout.
292
+ * 2. `detectLocale(env)` — pure function that maps Unix-style
293
+ * `LC_ALL` / `LANG` / `LANGUAGE` env vars to a supported
294
+ * `Locale`. Returns `'en'` for anything we don't recognise.
295
+ * 3. `loadMessages(locale)` — synchronous lookup that returns
296
+ * the message bundle for a locale. Synchronous (not dynamic
297
+ * `import()`) on purpose: bundles are tiny (< 2 KB each), the
298
+ * wizard reads them on every prompt, and async would force
299
+ * every caller to be async. tsup tree-shakes unused locales
300
+ * out of the bin only if we use top-level `import`s.
301
+ *
302
+ * ## Why env-var detection instead of `Intl.DateTimeFormat().resolvedOptions().locale`
303
+ *
304
+ * The Intl approach reads the JS engine's *display* locale, which
305
+ * on most CI runners and Docker images is `en-US` regardless of
306
+ * the user's actual setup. The Unix env vars (`LC_ALL`, `LANG`)
307
+ * are how shells, terminals, and CLI tools have negotiated locale
308
+ * for 30+ years — that's what a Thai-speaking dev's terminal will
309
+ * actually have set. Following that convention also means power
310
+ * users can override per-invocation with `LANG=th_TH.UTF-8 npm
311
+ * create @noy-db`, no flag required.
312
+ */
313
+
314
+ /** Every locale we ship a bundle for. Used by tests and `--lang` validation. */
315
+ declare const SUPPORTED_LOCALES: readonly Locale[];
316
+ /**
317
+ * Resolve a locale code to its message bundle. Falls back to `en`
318
+ * if the requested locale isn't shipped — defensive, since
319
+ * `Locale` is a union type and TS already prevents this at compile
320
+ * time, but `--lang` parsing comes from user input at runtime.
321
+ */
322
+ declare function loadMessages(locale: Locale): WizardMessages;
323
+ /**
324
+ * Auto-detect a locale from POSIX env vars. Returns `'en'` when
325
+ * nothing is set or when the value doesn't match a supported
326
+ * locale — never throws.
327
+ *
328
+ * Inspection order matches the POSIX spec:
329
+ * 1. `LC_ALL` (overrides everything)
330
+ * 2. `LC_MESSAGES` (the category we actually care about)
331
+ * 3. `LANG` (system default)
332
+ * 4. `LANGUAGE` (GNU extension, comma-separated preference list)
333
+ *
334
+ * The first non-empty value wins. We then strip the encoding
335
+ * suffix (`th_TH.UTF-8` → `th_TH`) and the region (`th_TH` → `th`)
336
+ * before matching against `SUPPORTED_LOCALES`.
337
+ */
338
+ declare function detectLocale(env?: NodeJS.ProcessEnv): Locale;
339
+ /**
340
+ * Parse a `--lang` CLI argument into a `Locale`. Throws a clear
341
+ * error for unsupported values — the caller (parse-args) catches
342
+ * and reformats into a usage message.
343
+ */
344
+ declare function parseLocaleFlag(value: string): Locale;
345
+
346
+ /**
347
+ * `noy-db add <collection>` — scaffold a new collection inside an existing
348
+ * Nuxt 4 project that already has `@noy-db/in-nuxt` configured.
349
+ *
350
+ * The command writes two files:
351
+ *
352
+ * 1. `app/stores/<collection>.ts` — a `defineNoydbStore<T>()` call with
353
+ * a placeholder `T` interface and one example field. The user fills
354
+ * in the real shape after the file is created.
355
+ *
356
+ * 2. `app/pages/<collection>.vue` — a minimal CRUD page that lists,
357
+ * adds, and deletes records. The store ID and collection name are
358
+ * derived from the argument; everything else is boilerplate.
359
+ *
360
+ * The command refuses to overwrite existing files. If either target
361
+ * already exists it logs which one and exits non-zero — the user has to
362
+ * delete or move the file first. There's no `--force` because forcing an
363
+ * overwrite of generated UI code is almost always a footgun in disguise.
364
+ */
365
+ interface AddCollectionOptions {
366
+ /** The collection name. Must be a lowercase identifier. */
367
+ name: string;
368
+ /** Project root. Defaults to `process.cwd()`. */
369
+ cwd?: string;
370
+ /** Compartment id to embed in the generated store. Defaults to `default`. */
371
+ vault?: string;
372
+ }
373
+ /**
374
+ * Result returned to callers (the bin entry uses this to format output;
375
+ * tests assert on the file paths).
376
+ */
377
+ interface AddCollectionResult {
378
+ /** Files written, in the order they were created. */
379
+ files: string[];
380
+ }
381
+ declare function addCollection(options: AddCollectionOptions): Promise<AddCollectionResult>;
382
+
383
+ /**
384
+ * `noy-db verify` — end-to-end integrity check.
385
+ *
386
+ * Opens an in-memory NOYDB instance, writes a record, reads it back,
387
+ * decrypts it, and asserts the round-trip is byte-identical. The check
388
+ * exercises the full crypto path (PBKDF2 → KEK → DEK → AES-GCM) without
389
+ * touching any user data on disk.
390
+ *
391
+ * Why an in-memory check is the right scope:
392
+ * - It validates that @noy-db/core, @noy-db/memory, and the user's
393
+ * installed Node version all agree on Web Crypto. That's the most
394
+ * common silent failure for first-time installers.
395
+ * - It cannot accidentally corrupt user data because there isn't any.
396
+ * - It runs in well under one second, so users actually run it.
397
+ *
398
+ * What this command does NOT do (intentionally):
399
+ * - Open the user's actual vault file/dynamo/s3/browser store.
400
+ * That requires the user's passphrase — not something we want a CLI
401
+ * `verify` command to prompt for. The full passphrase-driven verify
402
+ * belongs in `nuxi noydb verify` once the auth story for CLIs lands
403
+ * in. For now `noy-db verify` is the dependency-graph smoke test.
404
+ */
405
+ interface VerifyResult {
406
+ /** `true` if the round-trip succeeded; `false` if anything diverged. */
407
+ ok: boolean;
408
+ /** Human-readable status. Always set, even on success. */
409
+ message: string;
410
+ /** Wall-clock time the integrity check took, in ms. */
411
+ durationMs: number;
412
+ }
413
+ /**
414
+ * Runs the end-to-end check. Pure function — no console output, no
415
+ * `process.exit`. The bin wrapper handles formatting and exit codes so
416
+ * the function is trivial to call from tests.
417
+ */
418
+ declare function verifyIntegrity(): Promise<VerifyResult>;
419
+
420
+ /**
421
+ * Shared primitives for the interactive `noy-db` subcommands that
422
+ * need to unlock a real vault.
423
+ *
424
+ * Three things live here:
425
+ *
426
+ * 1. `ReadPassphrase` — a tiny interface for "prompt the user for
427
+ * a passphrase", with a test-friendly default. Subcommands take
428
+ * this as an injected dependency so tests can short-circuit
429
+ * the prompt without spawning a pty.
430
+ *
431
+ * 2. `defaultReadPassphrase` — the production implementation,
432
+ * built on `@clack/prompts` `password()`. Never echoes the
433
+ * value to the terminal, never logs it, clears it from the
434
+ * returned promise after the caller consumes it.
435
+ *
436
+ * 3. `assertRole` — narrow unknown string input to the Role type
437
+ * with a consistent error message.
438
+ *
439
+ * ## Why pull this out
440
+ *
441
+ * `rotate`, `addUser`, and `backup` all need the same "prompt for
442
+ * a passphrase" shape and the same "open a file adapter and get
443
+ * back a Noydb instance" shape. Duplicating it in three files would
444
+ * drift over time; centralizing means one place to audit the
445
+ * passphrase-handling contract (never log, never persist, clear
446
+ * local variables after use).
447
+ */
448
+
449
+ /**
450
+ * Asynchronous passphrase reader. Production code passes
451
+ * `defaultReadPassphrase`; tests pass a stub that returns a fixed
452
+ * string without touching stdin.
453
+ *
454
+ * The `label` is shown to the user as the prompt message. It
455
+ * should never contain the expected passphrase or any secret.
456
+ */
457
+ type ReadPassphrase = (label: string) => Promise<string>;
458
+ /**
459
+ * Narrow an unknown string to the `Role` type from @noy-db/core.
460
+ * Used by the `add user` subcommand to validate the role argument
461
+ * before passing it to `noydb.grant()`.
462
+ */
463
+ declare function assertRole(input: string): Role;
464
+ /**
465
+ * Split a comma-separated collection list into an array of names,
466
+ * trimming whitespace and dropping empties. Returns null if the
467
+ * input itself is empty or undefined — the caller decides whether
468
+ * that means "all collections" or "error".
469
+ */
470
+ declare function parseCollectionList(input: string | undefined): string[] | null;
471
+
472
+ /**
473
+ * `noy-db rotate` — rotate the DEKs for one or more collections in
474
+ * a vault.
475
+ *
476
+ * What it does
477
+ * ------------
478
+ * For each target collection:
479
+ *
480
+ * 1. Generate a fresh DEK
481
+ * 2. Decrypt every record with the old DEK
482
+ * 3. Re-encrypt every record with the new DEK
483
+ * 4. Re-wrap the new DEK into every remaining user's keyring
484
+ *
485
+ * The old DEKs become unreachable as soon as the keyring files are
486
+ * updated. This is the "just rotate" path — nobody is revoked,
487
+ * everybody keeps their current permissions, but the key material
488
+ * is replaced.
489
+ *
490
+ * Why expose this as a CLI command
491
+ * --------------------------------
492
+ * Two real-world scenarios:
493
+ *
494
+ * 1. **Suspected key leak.** An operator lost a laptop, a
495
+ * developer accidentally pasted a passphrase into a Slack
496
+ * channel, a USB stick went missing. Even if you think the
497
+ * passphrase is safe, rotating is cheap insurance.
498
+ *
499
+ * 2. **Scheduled rotation.** Some compliance regimes require
500
+ * periodic key rotation regardless of exposure. A CLI makes
501
+ * this scriptable from cron or a CI job.
502
+ *
503
+ * This module is test-first: all inputs are plain options, the
504
+ * passphrase reader is injected, and the Noydb factory is
505
+ * injectable. The production bin is a thin wrapper that defaults
506
+ * those injections to their real implementations.
507
+ */
508
+
509
+ interface RotateOptions {
510
+ /** Directory containing the vault data (file adapter only). */
511
+ dir: string;
512
+ /** Vault (tenant) name to rotate keys in. */
513
+ vault: string;
514
+ /** The user id of the operator running the rotate. */
515
+ user: string;
516
+ /**
517
+ * Explicit list of collections to rotate. When undefined, the
518
+ * rotation targets every collection the user has a DEK for —
519
+ * resolved at run time by reading the vault snapshot.
520
+ */
521
+ collections?: string[];
522
+ /** Injected passphrase reader. Defaults to the clack implementation. */
523
+ readPassphrase?: ReadPassphrase;
524
+ /**
525
+ * Injected Noydb factory. Production code leaves this undefined
526
+ * and gets `createNoydb`; tests pass a constructor that builds
527
+ * against an in-memory adapter.
528
+ */
529
+ createDb?: typeof createNoydb;
530
+ /**
531
+ * Injected adapter factory. Production code leaves this undefined
532
+ * and gets `jsonFile`; tests pass one that returns the shared
533
+ * in-memory adapter their fixture used.
534
+ */
535
+ buildAdapter?: (dir: string) => NoydbStore;
536
+ }
537
+ interface RotateResult {
538
+ /** The collections that were actually rotated. */
539
+ rotated: string[];
540
+ }
541
+ /**
542
+ * Run the rotate flow against a file-adapter vault. Returns
543
+ * the list of collections that were rotated so callers can display
544
+ * it to the user.
545
+ *
546
+ * Throws `Error` on any auth/adapter/rotate failure. The bin
547
+ * catches these and prints a friendly message; direct callers
548
+ * (tests) can inspect the error message to assert specific
549
+ * failure modes.
550
+ */
551
+ declare function rotate(options: RotateOptions): Promise<RotateResult>;
552
+
553
+ /**
554
+ * `noy-db add user <id> <role>` — grant a new user access to a
555
+ * vault.
556
+ *
557
+ * What it does
558
+ * ------------
559
+ * Wraps `noydb.grant()` in the CLI's auth-prompt ritual:
560
+ *
561
+ * 1. Prompt the caller for their own passphrase (to unlock the
562
+ * caller's keyring and derive the wrapping key).
563
+ * 2. Prompt for the new user's passphrase.
564
+ * 3. Prompt for confirmation of the new passphrase.
565
+ * 4. Reject on mismatch.
566
+ * 5. Call `noydb.grant(vault, { userId, role, passphrase, permissions })`.
567
+ *
568
+ * For owner/admin/viewer roles, every collection is granted
569
+ * automatically (the core keyring.ts grant logic handles that via
570
+ * the `permissions` field). For operator/client, the caller must
571
+ * pass a `--collections` list because those roles need explicit
572
+ * per-collection permissions.
573
+ *
574
+ * ## What this does NOT do
575
+ *
576
+ * - No email/invite flow — is about local-CLI key management,
577
+ * not out-of-band user enrollment.
578
+ * - No rollback on partial failure — `grant()` is atomic at the
579
+ * core level (keyring file writes last, after DEK wrapping), so
580
+ * partial-state-on-crash is already handled.
581
+ */
582
+
583
+ interface AddUserOptions {
584
+ /** Directory containing the vault data (file adapter only). */
585
+ dir: string;
586
+ /** Vault (tenant) name to grant access to. */
587
+ vault: string;
588
+ /** The user id of the caller running the grant. */
589
+ callerUser: string;
590
+ /** The new user's id (must not already exist in the vault keyring). */
591
+ newUserId: string;
592
+ /** The new user's display name — shown in UI and audit logs. Defaults to `newUserId`. */
593
+ newUserDisplayName?: string;
594
+ /** The new user's role. */
595
+ role: Role;
596
+ /**
597
+ * Per-collection permissions. Required when `role` is operator or
598
+ * client; ignored for owner/admin/viewer (they get everything
599
+ * via the core's resolvePermissions logic).
600
+ *
601
+ * Shape: `{ invoices: 'rw', clients: 'ro' }`. CLI callers pass
602
+ * `--collections invoices:rw,clients:ro` and the argv parser
603
+ * converts it to this shape.
604
+ */
605
+ permissions?: Record<string, 'rw' | 'ro'>;
606
+ /** Injected passphrase reader. Defaults to the clack implementation. */
607
+ readPassphrase?: ReadPassphrase;
608
+ /** Injected Noydb factory. */
609
+ createDb?: typeof createNoydb;
610
+ /** Injected adapter factory. */
611
+ buildAdapter?: (dir: string) => NoydbStore;
612
+ }
613
+ interface AddUserResult {
614
+ /** The userId that was granted access. */
615
+ userId: string;
616
+ /** The role they were granted. */
617
+ role: Role;
618
+ }
619
+ /**
620
+ * Run the grant flow. Two passphrase prompts: caller's, then new
621
+ * user's (twice for confirmation). Calls `noydb.grant()` with the
622
+ * collected values.
623
+ */
624
+ declare function addUser(options: AddUserOptions): Promise<AddUserResult>;
625
+
626
+ /**
627
+ * `noy-db backup <target>` — dump a vault to a local file.
628
+ *
629
+ * What it does
630
+ * ------------
631
+ * Wraps `vault.dump()` in the CLI's auth-prompt ritual, then
632
+ * writes the serialized backup to the requested path. As of,
633
+ * `dump()` already produces a verifiable backup (embedded
634
+ * ledgerHead, full `_ledger` / `_ledger_deltas` snapshots) — the
635
+ * CLI just moves bytes; the integrity guarantees come from core.
636
+ *
637
+ * ## Target URI support
638
+ *
639
+ * ships **`file://` only** (or a plain filesystem path).
640
+ * The issue spec originally called for `s3://` as well, but
641
+ * wiring @aws-sdk into @noy-db/create would defeat the
642
+ * zero-runtime-deps story for the CLI package. S3 backup is
643
+ * deferred to a follow-up that can live in @noy-db/s3-cli or a
644
+ * similar optional companion package.
645
+ *
646
+ * Accepted forms:
647
+ * - `file:///absolute/path.json`
648
+ * - `file://./relative/path.json`
649
+ * - `/absolute/path.json` (treated as `file://`)
650
+ * - `./relative/path.json` (treated as `file://`)
651
+ *
652
+ * ## What this does NOT do
653
+ *
654
+ * - No encryption of the backup BEYOND what noy-db already does.
655
+ * The dumped file is a valid noy-db backup, which means
656
+ * individual records are still encrypted but the keyring is
657
+ * included (wrapped with each user's KEK). Anyone who loads
658
+ * the backup still needs the correct passphrase to read.
659
+ * - No restore — that's a separate subcommand tracked as a
660
+ * follow-up. For now users can restore via
661
+ * `vault.load(backupString)` from their own app code.
662
+ */
663
+
664
+ interface BackupOptions {
665
+ /** Directory containing the vault data (file adapter only). */
666
+ dir: string;
667
+ /** Vault (tenant) name to back up. */
668
+ vault: string;
669
+ /** The user id of the operator running the backup. */
670
+ user: string;
671
+ /**
672
+ * Where to write the backup. Accepts a `file://` URI or a plain
673
+ * filesystem path. Relative paths resolve against `process.cwd()`.
674
+ */
675
+ target: string;
676
+ /** Injected passphrase reader. */
677
+ readPassphrase?: ReadPassphrase;
678
+ /** Injected Noydb factory. */
679
+ createDb?: typeof createNoydb;
680
+ /** Injected adapter factory. */
681
+ buildAdapter?: (dir: string) => NoydbStore;
682
+ }
683
+ interface BackupResult {
684
+ /** Absolute filesystem path the backup was written to. */
685
+ path: string;
686
+ /** Size of the serialized backup in bytes. */
687
+ bytes: number;
688
+ }
689
+ /**
690
+ * Parse a backup target into an absolute filesystem path. Rejects
691
+ * unsupported URI schemes (s3://, https://, etc.) early so the
692
+ * caller doesn't silently write to the wrong place.
693
+ */
694
+ declare function resolveBackupTarget(target: string, cwd?: string): string;
695
+ declare function backup(options: BackupOptions): Promise<BackupResult>;
696
+
697
+ export { type AddCollectionOptions, type AddUserOptions, type AddUserResult, type BackupOptions, type BackupResult, type Locale, type ReadPassphrase, type RotateOptions, type RotateResult, SUPPORTED_LOCALES, type VerifyResult, type WizardMessages, type WizardOptions, type WizardResult, addCollection, addUser, assertRole, backup, detectLocale, loadMessages, parseCollectionList, parseLocaleFlag, resolveBackupTarget, rotate, runWizard, verifyIntegrity };