@noy-db/in-pinia 0.1.0-pre.3
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/LICENSE +21 -0
- package/README.md +146 -0
- package/dist/index.cjs +443 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +411 -0
- package/dist/index.d.ts +411 -0
- package/dist/index.js +423 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vLannaAi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# @noy-db/in-pinia
|
|
2
|
+
|
|
3
|
+
> Pinia integration for [noy-db](https://github.com/vLannaAi/noy-db) — drop-in encrypted Pinia stores for Vue 3 / Nuxt 4.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @noy-db/in-pinia @noy-db/hub pinia vue
|
|
7
|
+
# pick an adapter for your environment:
|
|
8
|
+
pnpm add @noy-db/to-file # local disk / USB
|
|
9
|
+
pnpm add @noy-db/to-browser-idb # localStorage / IndexedDB
|
|
10
|
+
pnpm add @noy-db/to-aws-dynamo # AWS DynamoDB
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// stores/invoices.ts
|
|
17
|
+
import { defineNoydbStore } from '@noy-db/in-pinia';
|
|
18
|
+
|
|
19
|
+
interface Invoice {
|
|
20
|
+
id: string;
|
|
21
|
+
amount: number;
|
|
22
|
+
status: 'draft' | 'open' | 'paid';
|
|
23
|
+
client: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const useInvoices = defineNoydbStore<Invoice>('invoices', {
|
|
27
|
+
compartment: 'C101',
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// main.ts
|
|
33
|
+
import { createApp } from 'vue';
|
|
34
|
+
import { createPinia } from 'pinia';
|
|
35
|
+
import { createNoydb } from '@noy-db/hub';
|
|
36
|
+
import { jsonFile } from '@noy-db/to-file';
|
|
37
|
+
import { setActiveNoydb } from '@noy-db/in-pinia';
|
|
38
|
+
import App from './App.vue';
|
|
39
|
+
|
|
40
|
+
const db = await createNoydb({
|
|
41
|
+
adapter: jsonFile({ dir: './data' }),
|
|
42
|
+
user: 'owner',
|
|
43
|
+
secret: () => prompt('Passphrase')!,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
setActiveNoydb(db);
|
|
47
|
+
|
|
48
|
+
createApp(App).use(createPinia()).mount('#app');
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```vue
|
|
52
|
+
<!-- App.vue -->
|
|
53
|
+
<script setup lang="ts">
|
|
54
|
+
import { useInvoices } from './stores/invoices';
|
|
55
|
+
|
|
56
|
+
const invoices = useInvoices();
|
|
57
|
+
await invoices.$ready;
|
|
58
|
+
|
|
59
|
+
async function addOne() {
|
|
60
|
+
const id = `inv-${Date.now()}`;
|
|
61
|
+
await invoices.add(id, { id, amount: 100, status: 'draft', client: 'Acme' });
|
|
62
|
+
}
|
|
63
|
+
</script>
|
|
64
|
+
|
|
65
|
+
<template>
|
|
66
|
+
<div>
|
|
67
|
+
<button @click="addOne">Add invoice</button>
|
|
68
|
+
<p>{{ invoices.count }} invoices</p>
|
|
69
|
+
<ul>
|
|
70
|
+
<li v-for="inv in invoices.items" :key="inv.id">
|
|
71
|
+
{{ inv.client }} — {{ inv.amount }} — {{ inv.status }}
|
|
72
|
+
</li>
|
|
73
|
+
</ul>
|
|
74
|
+
</div>
|
|
75
|
+
</template>
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Store API
|
|
79
|
+
|
|
80
|
+
Every store returned by `defineNoydbStore` exposes:
|
|
81
|
+
|
|
82
|
+
| Member | Type | Purpose |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `items` | `Ref<T[]>` | Reactive array of all decrypted records |
|
|
85
|
+
| `count` | `ComputedRef<number>` | Reactive count |
|
|
86
|
+
| `$ready` | `Promise<void>` | Resolves once the collection has hydrated on first use |
|
|
87
|
+
| `byId(id)` | `(id) => T \| undefined` | O(N) cache lookup |
|
|
88
|
+
| `add(id, record)` | `async (id, T) => void` | Encrypt + persist + update reactive state |
|
|
89
|
+
| `update(id, record)` | `async (id, T) => void` | Alias for `add` (NOYDB `put` is upsert) |
|
|
90
|
+
| `remove(id)` | `async (id) => void` | Delete + update reactive state |
|
|
91
|
+
| `refresh()` | `async () => void` | Re-hydrate from the adapter (use after sync pulls) |
|
|
92
|
+
| `query()` | `() => Query<T>` | Chainable query DSL — see `@noy-db/hub` |
|
|
93
|
+
|
|
94
|
+
## Composition
|
|
95
|
+
|
|
96
|
+
The store is a real Pinia store. All these work unmodified:
|
|
97
|
+
|
|
98
|
+
- `storeToRefs(store)` — destructure with reactivity intact
|
|
99
|
+
- Vue Devtools — appears in the devtools tab like any other store
|
|
100
|
+
- SSR — `items` is empty during server render, hydrates on the client
|
|
101
|
+
- `pinia-plugin-persistedstate` — works as a fallback layer below NOYDB encryption
|
|
102
|
+
|
|
103
|
+
## Schema validation
|
|
104
|
+
|
|
105
|
+
Pass any object exposing `parse(input): T` (Zod, Valibot, ArkType, Effect Schema, etc.):
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { z } from 'zod';
|
|
109
|
+
|
|
110
|
+
const InvoiceSchema = z.object({
|
|
111
|
+
id: z.string(),
|
|
112
|
+
amount: z.number().positive(),
|
|
113
|
+
status: z.enum(['draft', 'open', 'paid']),
|
|
114
|
+
client: z.string(),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
export const useInvoices = defineNoydbStore<z.infer<typeof InvoiceSchema>>('invoices', {
|
|
118
|
+
compartment: 'C101',
|
|
119
|
+
schema: InvoiceSchema,
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`add()` and `update()` will throw if the record fails validation, before any encryption or write happens.
|
|
124
|
+
|
|
125
|
+
## Query DSL
|
|
126
|
+
|
|
127
|
+
The store's `query()` method returns the same chainable builder as `Collection.query()`:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
const overdue = invoices.query()
|
|
131
|
+
.where('status', '==', 'open')
|
|
132
|
+
.where('dueDate', '<', new Date())
|
|
133
|
+
.orderBy('dueDate', 'asc')
|
|
134
|
+
.limit(50)
|
|
135
|
+
.toArray();
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
See [`@noy-db/hub` query DSL docs](../core/README.md#query-dsl) for the full operator list.
|
|
139
|
+
|
|
140
|
+
## Status
|
|
141
|
+
|
|
142
|
+
See [ROADMAP.md](../../ROADMAP.md) for the forward plan.
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
MIT © vLannaAi
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
CAPABILITY_REQUESTS_COLLECTION: () => CAPABILITY_REQUESTS_COLLECTION,
|
|
24
|
+
createNoydbPiniaPlugin: () => createNoydbPiniaPlugin,
|
|
25
|
+
defineNoydbStore: () => defineNoydbStore,
|
|
26
|
+
getActiveNoydb: () => getActiveNoydb,
|
|
27
|
+
resolveNoydb: () => resolveNoydb,
|
|
28
|
+
setActiveNoydb: () => setActiveNoydb,
|
|
29
|
+
useCapabilityGrant: () => useCapabilityGrant
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
|
|
33
|
+
// src/defineNoydbStore.ts
|
|
34
|
+
var import_pinia = require("pinia");
|
|
35
|
+
var import_vue = require("vue");
|
|
36
|
+
|
|
37
|
+
// src/context.ts
|
|
38
|
+
var activeInstance = null;
|
|
39
|
+
function setActiveNoydb(instance) {
|
|
40
|
+
activeInstance = instance;
|
|
41
|
+
}
|
|
42
|
+
function getActiveNoydb() {
|
|
43
|
+
return activeInstance;
|
|
44
|
+
}
|
|
45
|
+
function resolveNoydb(explicit) {
|
|
46
|
+
if (explicit) return explicit;
|
|
47
|
+
if (activeInstance) return activeInstance;
|
|
48
|
+
throw new Error(
|
|
49
|
+
"@noy-db/pinia: no Noydb instance bound.\n Option A \u2014 pass `noydb:` directly to defineNoydbStore({...})\n Option B \u2014 call setActiveNoydb(instance) once at app startup\n Option C \u2014 install the @noy-db/nuxt module (Nuxt 4+)"
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/defineNoydbStore.ts
|
|
54
|
+
function defineNoydbStore(id, options) {
|
|
55
|
+
const collectionName = options.collection ?? id;
|
|
56
|
+
const prefetch = options.prefetch ?? true;
|
|
57
|
+
return (0, import_pinia.defineStore)(id, () => {
|
|
58
|
+
const items = (0, import_vue.shallowRef)([]);
|
|
59
|
+
const count = (0, import_vue.computed)(() => items.value.length);
|
|
60
|
+
let cachedCompartment = null;
|
|
61
|
+
let cachedCollection = null;
|
|
62
|
+
async function getCollection() {
|
|
63
|
+
if (cachedCollection) return cachedCollection;
|
|
64
|
+
const noydb = resolveNoydb(options.noydb ?? null);
|
|
65
|
+
cachedCompartment = await noydb.openVault(options.vault);
|
|
66
|
+
const collOpts = {};
|
|
67
|
+
if (options.schema !== void 0) collOpts.schema = options.schema;
|
|
68
|
+
cachedCollection = cachedCompartment.collection(collectionName, collOpts);
|
|
69
|
+
return cachedCollection;
|
|
70
|
+
}
|
|
71
|
+
async function refresh() {
|
|
72
|
+
const c = await getCollection();
|
|
73
|
+
const list = await c.list();
|
|
74
|
+
items.value = list;
|
|
75
|
+
}
|
|
76
|
+
function byId(id2) {
|
|
77
|
+
for (const item of items.value) {
|
|
78
|
+
if (item.id === id2) return item;
|
|
79
|
+
}
|
|
80
|
+
return void 0;
|
|
81
|
+
}
|
|
82
|
+
async function add(id2, record) {
|
|
83
|
+
const c = await getCollection();
|
|
84
|
+
await c.put(id2, record);
|
|
85
|
+
items.value = await c.list();
|
|
86
|
+
}
|
|
87
|
+
async function update(id2, record) {
|
|
88
|
+
await add(id2, record);
|
|
89
|
+
}
|
|
90
|
+
async function remove(id2) {
|
|
91
|
+
const c = await getCollection();
|
|
92
|
+
await c.delete(id2);
|
|
93
|
+
items.value = await c.list();
|
|
94
|
+
}
|
|
95
|
+
function query() {
|
|
96
|
+
if (!cachedCollection) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
"@noy-db/pinia: query() called before the store was ready. Await store.$ready first, or set prefetch: true (default)."
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
return cachedCollection.query();
|
|
102
|
+
}
|
|
103
|
+
function liveQuery(build) {
|
|
104
|
+
if (!cachedCollection) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
"@noy-db/pinia: liveQuery() called before the store was ready. Await store.$ready first, or set prefetch: true (default)."
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
const built = build(cachedCollection.query());
|
|
110
|
+
const live = built.live();
|
|
111
|
+
const items2 = (0, import_vue.shallowRef)(live.value);
|
|
112
|
+
const error = (0, import_vue.ref)(live.error);
|
|
113
|
+
const unsubscribe = live.subscribe(() => {
|
|
114
|
+
items2.value = live.value;
|
|
115
|
+
error.value = live.error;
|
|
116
|
+
});
|
|
117
|
+
let stopped = false;
|
|
118
|
+
const stop = () => {
|
|
119
|
+
if (stopped) return;
|
|
120
|
+
stopped = true;
|
|
121
|
+
unsubscribe();
|
|
122
|
+
live.stop();
|
|
123
|
+
};
|
|
124
|
+
if ((0, import_vue.getCurrentScope)()) (0, import_vue.onScopeDispose)(stop);
|
|
125
|
+
return { items: items2, error, stop };
|
|
126
|
+
}
|
|
127
|
+
const $ready = prefetch ? refresh() : Promise.resolve();
|
|
128
|
+
return {
|
|
129
|
+
items,
|
|
130
|
+
count,
|
|
131
|
+
$ready,
|
|
132
|
+
byId,
|
|
133
|
+
add,
|
|
134
|
+
update,
|
|
135
|
+
remove,
|
|
136
|
+
refresh,
|
|
137
|
+
query,
|
|
138
|
+
liveQuery
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/plugin.ts
|
|
144
|
+
var import_hub = require("@noy-db/hub");
|
|
145
|
+
var STATE_DOC_ID = "__state__";
|
|
146
|
+
function createNoydbPiniaPlugin(opts) {
|
|
147
|
+
let dbPromise = null;
|
|
148
|
+
function getDb() {
|
|
149
|
+
if (!dbPromise) {
|
|
150
|
+
dbPromise = (async () => {
|
|
151
|
+
const secret = await opts.secret();
|
|
152
|
+
return (0, import_hub.createNoydb)({
|
|
153
|
+
store: opts.adapter,
|
|
154
|
+
user: opts.user,
|
|
155
|
+
secret,
|
|
156
|
+
...opts.noydbOptions
|
|
157
|
+
});
|
|
158
|
+
})();
|
|
159
|
+
}
|
|
160
|
+
return dbPromise;
|
|
161
|
+
}
|
|
162
|
+
const vaultCache = /* @__PURE__ */ new Map();
|
|
163
|
+
function getCompartment(name) {
|
|
164
|
+
let p = vaultCache.get(name);
|
|
165
|
+
if (!p) {
|
|
166
|
+
p = getDb().then((db) => db.openVault(name));
|
|
167
|
+
vaultCache.set(name, p);
|
|
168
|
+
}
|
|
169
|
+
return p;
|
|
170
|
+
}
|
|
171
|
+
return (context) => {
|
|
172
|
+
const noydbOption = context.options.noydb;
|
|
173
|
+
if (!noydbOption) {
|
|
174
|
+
context.store.$noydbAugmented = false;
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
context.store.$noydbAugmented = true;
|
|
178
|
+
context.store.$noydbError = null;
|
|
179
|
+
const pending = /* @__PURE__ */ new Set();
|
|
180
|
+
const ready = (async () => {
|
|
181
|
+
try {
|
|
182
|
+
const vault = await getCompartment(noydbOption.vault);
|
|
183
|
+
const collection = vault.collection(
|
|
184
|
+
noydbOption.collection
|
|
185
|
+
);
|
|
186
|
+
const persisted = await collection.get(STATE_DOC_ID);
|
|
187
|
+
if (persisted) {
|
|
188
|
+
const validated = noydbOption.schema ? noydbOption.schema.parse(persisted) : persisted;
|
|
189
|
+
const picked = pickKeys(validated, noydbOption.persist);
|
|
190
|
+
context.store.$patch(picked);
|
|
191
|
+
}
|
|
192
|
+
context.store.$subscribe(
|
|
193
|
+
(_mutation, state) => {
|
|
194
|
+
const subset = pickKeys(state, noydbOption.persist);
|
|
195
|
+
const p = collection.put(STATE_DOC_ID, subset).catch((err) => {
|
|
196
|
+
context.store.$noydbError = err instanceof Error ? err : new Error(String(err));
|
|
197
|
+
}).finally(() => {
|
|
198
|
+
pending.delete(p);
|
|
199
|
+
});
|
|
200
|
+
pending.add(p);
|
|
201
|
+
},
|
|
202
|
+
{ detached: true }
|
|
203
|
+
// outlive the component that triggered the mutation
|
|
204
|
+
);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
context.store.$noydbError = err instanceof Error ? err : new Error(String(err));
|
|
207
|
+
}
|
|
208
|
+
})();
|
|
209
|
+
context.store.$noydbReady = ready;
|
|
210
|
+
context.store.$noydbFlush = async () => {
|
|
211
|
+
await ready;
|
|
212
|
+
while (pending.size > 0) {
|
|
213
|
+
await Promise.all([...pending]);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function pickKeys(state, persist) {
|
|
219
|
+
if (persist === void 0 || persist === "*") {
|
|
220
|
+
return { ...state };
|
|
221
|
+
}
|
|
222
|
+
if (typeof persist === "string") {
|
|
223
|
+
return { [persist]: state[persist] };
|
|
224
|
+
}
|
|
225
|
+
if (Array.isArray(persist)) {
|
|
226
|
+
const out = {};
|
|
227
|
+
for (const key of persist) {
|
|
228
|
+
out[key] = state[key];
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
return { ...state };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/useCapabilityGrant.ts
|
|
236
|
+
var import_vue2 = require("vue");
|
|
237
|
+
var CAPABILITY_REQUESTS_COLLECTION = "_capability_requests";
|
|
238
|
+
function useCapabilityGrant(capability, options) {
|
|
239
|
+
const state = (0, import_vue2.ref)("idle");
|
|
240
|
+
const error = (0, import_vue2.ref)(null);
|
|
241
|
+
const recordRef = (0, import_vue2.shallowRef)(null);
|
|
242
|
+
const inBrowser = typeof window !== "undefined";
|
|
243
|
+
let expiryTimer = null;
|
|
244
|
+
let unsubscribeChangeStream = null;
|
|
245
|
+
let resolvedVault = null;
|
|
246
|
+
let stopped = false;
|
|
247
|
+
async function resolveVault() {
|
|
248
|
+
if (resolvedVault) return resolvedVault;
|
|
249
|
+
if (typeof options.vault === "string") {
|
|
250
|
+
const noydb = resolveNoydb(null);
|
|
251
|
+
resolvedVault = await noydb.openVault(options.vault);
|
|
252
|
+
} else {
|
|
253
|
+
resolvedVault = options.vault;
|
|
254
|
+
}
|
|
255
|
+
resolvedVault.collection(
|
|
256
|
+
CAPABILITY_REQUESTS_COLLECTION
|
|
257
|
+
);
|
|
258
|
+
return resolvedVault;
|
|
259
|
+
}
|
|
260
|
+
function clearExpiryTimer() {
|
|
261
|
+
if (expiryTimer) {
|
|
262
|
+
clearTimeout(expiryTimer);
|
|
263
|
+
expiryTimer = null;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function scheduleExpiry(record) {
|
|
267
|
+
if (!record.expiresAt) return;
|
|
268
|
+
const remaining = new Date(record.expiresAt).getTime() - Date.now();
|
|
269
|
+
if (remaining <= 0) {
|
|
270
|
+
void handleExpiry(record);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
clearExpiryTimer();
|
|
274
|
+
expiryTimer = setTimeout(() => {
|
|
275
|
+
void handleExpiry(record);
|
|
276
|
+
}, remaining);
|
|
277
|
+
}
|
|
278
|
+
async function handleExpiry(record) {
|
|
279
|
+
if (stopped) return;
|
|
280
|
+
if (state.value !== "granted") return;
|
|
281
|
+
state.value = "expired";
|
|
282
|
+
try {
|
|
283
|
+
await options.onRelease?.({
|
|
284
|
+
record,
|
|
285
|
+
vault: resolvedVault,
|
|
286
|
+
cause: "expired"
|
|
287
|
+
});
|
|
288
|
+
} catch (err) {
|
|
289
|
+
error.value = err instanceof Error ? err : new Error(String(err));
|
|
290
|
+
}
|
|
291
|
+
state.value = "idle";
|
|
292
|
+
recordRef.value = null;
|
|
293
|
+
}
|
|
294
|
+
const now = (0, import_vue2.ref)(Date.now());
|
|
295
|
+
const tickTimer = inBrowser ? setInterval(() => {
|
|
296
|
+
now.value = Date.now();
|
|
297
|
+
}, 1e3) : null;
|
|
298
|
+
const timeRemaining = (0, import_vue2.computed)(() => {
|
|
299
|
+
if (state.value !== "granted" || !recordRef.value?.expiresAt) return 0;
|
|
300
|
+
void now.value;
|
|
301
|
+
const ms = new Date(recordRef.value.expiresAt).getTime() - Date.now();
|
|
302
|
+
return ms > 0 ? ms : 0;
|
|
303
|
+
});
|
|
304
|
+
(0, import_vue2.watch)(
|
|
305
|
+
() => recordRef.value?.id,
|
|
306
|
+
async (id) => {
|
|
307
|
+
if (!inBrowser || !id || unsubscribeChangeStream) return;
|
|
308
|
+
const vault = await resolveVault();
|
|
309
|
+
const coll = vault.collection(
|
|
310
|
+
CAPABILITY_REQUESTS_COLLECTION
|
|
311
|
+
);
|
|
312
|
+
unsubscribeChangeStream = coll.subscribe(
|
|
313
|
+
(evt) => {
|
|
314
|
+
if (evt.type !== "put" || evt.id !== id) return;
|
|
315
|
+
const updated = evt.record;
|
|
316
|
+
if (!updated || stopped) return;
|
|
317
|
+
recordRef.value = updated;
|
|
318
|
+
if (updated.status === "granted") {
|
|
319
|
+
state.value = "granted";
|
|
320
|
+
scheduleExpiry(updated);
|
|
321
|
+
} else if (updated.status === "released" || updated.status === "expired") {
|
|
322
|
+
state.value = "idle";
|
|
323
|
+
clearExpiryTimer();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
);
|
|
327
|
+
},
|
|
328
|
+
{ immediate: false }
|
|
329
|
+
);
|
|
330
|
+
async function request() {
|
|
331
|
+
if (state.value !== "idle") {
|
|
332
|
+
error.value = new Error(
|
|
333
|
+
`useCapabilityGrant: cannot request from state "${state.value}"`
|
|
334
|
+
);
|
|
335
|
+
throw error.value;
|
|
336
|
+
}
|
|
337
|
+
error.value = null;
|
|
338
|
+
if (!inBrowser) return;
|
|
339
|
+
try {
|
|
340
|
+
const vault = await resolveVault();
|
|
341
|
+
const coll = vault.collection(
|
|
342
|
+
CAPABILITY_REQUESTS_COLLECTION
|
|
343
|
+
);
|
|
344
|
+
const id = `cap-${Date.now().toString(36)}-${Math.random().toString(16).slice(2, 10)}`;
|
|
345
|
+
const record = {
|
|
346
|
+
id,
|
|
347
|
+
capability,
|
|
348
|
+
requestedBy: vault.userId,
|
|
349
|
+
approverRole: options.approver,
|
|
350
|
+
reason: options.reason,
|
|
351
|
+
ttlMs: options.ttlMs,
|
|
352
|
+
status: "requested",
|
|
353
|
+
requestedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
354
|
+
};
|
|
355
|
+
await coll.put(id, record);
|
|
356
|
+
recordRef.value = record;
|
|
357
|
+
state.value = "requested";
|
|
358
|
+
} catch (err) {
|
|
359
|
+
error.value = err instanceof Error ? err : new Error(String(err));
|
|
360
|
+
throw error.value;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async function approve() {
|
|
364
|
+
const record = recordRef.value;
|
|
365
|
+
if (state.value !== "requested" || !record) {
|
|
366
|
+
error.value = new Error(
|
|
367
|
+
`useCapabilityGrant: cannot approve from state "${state.value}"`
|
|
368
|
+
);
|
|
369
|
+
throw error.value;
|
|
370
|
+
}
|
|
371
|
+
error.value = null;
|
|
372
|
+
try {
|
|
373
|
+
const vault = await resolveVault();
|
|
374
|
+
if (vault.role !== options.approver && vault.role !== "owner") {
|
|
375
|
+
throw new Error(
|
|
376
|
+
`useCapabilityGrant: caller role "${vault.role}" cannot approve a "${options.approver}"-tier grant`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
const approvedAt = /* @__PURE__ */ new Date();
|
|
380
|
+
const expiresAt = new Date(approvedAt.getTime() + options.ttlMs);
|
|
381
|
+
const granted = {
|
|
382
|
+
...record,
|
|
383
|
+
status: "granted",
|
|
384
|
+
approvedBy: vault.userId,
|
|
385
|
+
approvedAt: approvedAt.toISOString(),
|
|
386
|
+
expiresAt: expiresAt.toISOString()
|
|
387
|
+
};
|
|
388
|
+
const coll = vault.collection(
|
|
389
|
+
CAPABILITY_REQUESTS_COLLECTION
|
|
390
|
+
);
|
|
391
|
+
await coll.put(record.id, granted);
|
|
392
|
+
recordRef.value = granted;
|
|
393
|
+
state.value = "granted";
|
|
394
|
+
scheduleExpiry(granted);
|
|
395
|
+
await options.onGrant?.({ record: granted, vault });
|
|
396
|
+
} catch (err) {
|
|
397
|
+
error.value = err instanceof Error ? err : new Error(String(err));
|
|
398
|
+
throw error.value;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
async function release() {
|
|
402
|
+
const record = recordRef.value;
|
|
403
|
+
if (state.value !== "granted" || !record) {
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
error.value = null;
|
|
407
|
+
try {
|
|
408
|
+
clearExpiryTimer();
|
|
409
|
+
const vault = await resolveVault();
|
|
410
|
+
const released = { ...record, status: "released" };
|
|
411
|
+
const coll = vault.collection(
|
|
412
|
+
CAPABILITY_REQUESTS_COLLECTION
|
|
413
|
+
);
|
|
414
|
+
await coll.put(record.id, released);
|
|
415
|
+
recordRef.value = null;
|
|
416
|
+
state.value = "idle";
|
|
417
|
+
await options.onRelease?.({ record, vault, cause: "released" });
|
|
418
|
+
} catch (err) {
|
|
419
|
+
error.value = err instanceof Error ? err : new Error(String(err));
|
|
420
|
+
throw error.value;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if ((0, import_vue2.getCurrentScope)()) {
|
|
424
|
+
(0, import_vue2.onScopeDispose)(() => {
|
|
425
|
+
stopped = true;
|
|
426
|
+
clearExpiryTimer();
|
|
427
|
+
if (tickTimer) clearInterval(tickTimer);
|
|
428
|
+
unsubscribeChangeStream?.();
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return { state, timeRemaining, error, request, approve, release };
|
|
432
|
+
}
|
|
433
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
434
|
+
0 && (module.exports = {
|
|
435
|
+
CAPABILITY_REQUESTS_COLLECTION,
|
|
436
|
+
createNoydbPiniaPlugin,
|
|
437
|
+
defineNoydbStore,
|
|
438
|
+
getActiveNoydb,
|
|
439
|
+
resolveNoydb,
|
|
440
|
+
setActiveNoydb,
|
|
441
|
+
useCapabilityGrant
|
|
442
|
+
});
|
|
443
|
+
//# sourceMappingURL=index.cjs.map
|