@asaidimu/hestia-mock 1.15.0

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/index.cjs ADDED
@@ -0,0 +1,3989 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _asaidimu_hestia = require("@asaidimu/hestia");
3
+ let _asaidimu_utils_error = require("@asaidimu/utils-error");
4
+ //#region src/bus.ts
5
+ var EventBus = class {
6
+ topics = /* @__PURE__ */ new Map();
7
+ subscribe(topic, listener) {
8
+ let set = this.topics.get(topic);
9
+ if (!set) {
10
+ set = /* @__PURE__ */ new Set();
11
+ this.topics.set(topic, set);
12
+ }
13
+ set.add(listener);
14
+ return () => {
15
+ set.delete(listener);
16
+ if (set.size === 0) this.topics.delete(topic);
17
+ };
18
+ }
19
+ emit(topic, payload) {
20
+ const set = this.topics.get(topic);
21
+ if (!set || set.size === 0) return;
22
+ for (const listener of [...set]) try {
23
+ listener(payload);
24
+ } catch {}
25
+ }
26
+ listenerCount(topic) {
27
+ if (topic) return this.topics.get(topic)?.size ?? 0;
28
+ let total = 0;
29
+ for (const set of this.topics.values()) total += set.size;
30
+ return total;
31
+ }
32
+ clear() {
33
+ this.topics.clear();
34
+ }
35
+ };
36
+ /** Canonical topic names used by the mock server. */
37
+ const Topics = {
38
+ notifications: (userId) => `notifications:${userId}`,
39
+ notificationsAll: "notifications:all",
40
+ audit: "audit",
41
+ logs: (level) => level ? `logs:${level}` : "logs",
42
+ workflowRun: (runId) => `workflow:run:${runId}`,
43
+ collections: (name) => `collection:${name}`
44
+ };
45
+ //#endregion
46
+ //#region src/idb.ts
47
+ /** Thrown when IndexedDB is unavailable or a request fails at the event level. */
48
+ var IdbError = class extends Error {
49
+ cause;
50
+ constructor(message, cause) {
51
+ super(message);
52
+ this.cause = cause;
53
+ this.name = "IdbError";
54
+ }
55
+ };
56
+ function reqToPromise(req) {
57
+ return new Promise((resolve, reject) => {
58
+ req.onsuccess = () => resolve(req.result);
59
+ req.onerror = () => reject(new IdbError("IndexedDB request failed", req.error));
60
+ });
61
+ }
62
+ /** Open (and upgrade) a database, caching the connection. */
63
+ async function openDatabase(opts) {
64
+ if (typeof indexedDB === "undefined") throw new IdbError("IndexedDB is not available in this environment. In Node tests add `fake-indexeddb`.");
65
+ return await new Promise((resolve, reject) => {
66
+ const req = indexedDB.open(opts.name, opts.version);
67
+ req.onupgradeneeded = (event) => {
68
+ const db = req.result;
69
+ const tx = req.transaction;
70
+ opts.upgrade(db, event.oldVersion, tx);
71
+ };
72
+ req.onsuccess = () => {
73
+ const db = req.result;
74
+ db.onversionchange = () => db.close();
75
+ resolve(db);
76
+ };
77
+ req.onerror = () => reject(new IdbError(`Failed to open database "${opts.name}"`, req.error));
78
+ req.onblocked = () => reject(new IdbError(`Database "${opts.name}" is blocked by another connection`));
79
+ });
80
+ }
81
+ /**
82
+ * Run `fn` inside a transaction on the given stores. The transaction commits
83
+ * when the returned promise settles (via `txn.oncomplete`) — callers only need
84
+ * to perform requests inside `fn`.
85
+ */
86
+ async function withTransaction(db, stores, mode, fn) {
87
+ const tx = db.transaction(stores, mode);
88
+ const done = new Promise((resolve, reject) => {
89
+ tx.oncomplete = () => resolve();
90
+ tx.onabort = () => reject(new IdbError("Transaction aborted", tx.error));
91
+ tx.onerror = () => reject(new IdbError("Transaction failed", tx.error));
92
+ });
93
+ let result;
94
+ try {
95
+ result = await fn(tx);
96
+ } catch (err) {
97
+ done.catch(() => void 0);
98
+ try {
99
+ tx.abort();
100
+ } catch {}
101
+ throw err;
102
+ }
103
+ await done;
104
+ return result;
105
+ }
106
+ /** Typed helpers bound to one object store within an existing transaction. */
107
+ var Store = class {
108
+ tx;
109
+ name;
110
+ constructor(tx, name) {
111
+ this.tx = tx;
112
+ this.name = name;
113
+ }
114
+ get raw() {
115
+ return this.tx.objectStore(this.name);
116
+ }
117
+ get(key) {
118
+ return reqToPromise(this.raw.get(key));
119
+ }
120
+ getAll(query, count) {
121
+ return reqToPromise(this.raw.getAll(query, count));
122
+ }
123
+ getAllByIndex(index, query, count) {
124
+ return reqToPromise(this.raw.index(index).getAll(query, count));
125
+ }
126
+ count(query) {
127
+ return reqToPromise(this.raw.count(query));
128
+ }
129
+ getKey(query) {
130
+ return reqToPromise(this.raw.getKey(query));
131
+ }
132
+ put(value, key) {
133
+ return reqToPromise(this.raw.put(value, key));
134
+ }
135
+ add(value, key) {
136
+ return reqToPromise(this.raw.add(value, key));
137
+ }
138
+ delete(key) {
139
+ return reqToPromise(this.raw.delete(key));
140
+ }
141
+ clear() {
142
+ return reqToPromise(this.raw.clear());
143
+ }
144
+ /** Iterate all values with a cursor (supports range + direction). */
145
+ async forEach(opts, visit) {
146
+ const cursorReq = (opts.index ? this.raw.index(opts.index) : this.raw).openCursor(opts.query, opts.direction);
147
+ return await new Promise((resolve, reject) => {
148
+ cursorReq.onsuccess = async () => {
149
+ const cursor = cursorReq.result;
150
+ if (!cursor) return resolve();
151
+ try {
152
+ await visit(cursor.value, cursor.key);
153
+ cursor.continue();
154
+ } catch (err) {
155
+ reject(err);
156
+ }
157
+ };
158
+ cursorReq.onerror = () => reject(new IdbError("Cursor failed", cursorReq.error));
159
+ });
160
+ }
161
+ };
162
+ /** A thin typed table facade over one object store. */
163
+ var Table = class {
164
+ db;
165
+ name;
166
+ constructor(db, name) {
167
+ this.db = db;
168
+ this.name = name;
169
+ }
170
+ async get(key) {
171
+ return await withTransaction(this.db, [this.name], "readonly", async (tx) => await new Store(tx, this.name).get(key));
172
+ }
173
+ async getAll() {
174
+ return await withTransaction(this.db, [this.name], "readonly", async (tx) => await new Store(tx, this.name).getAll());
175
+ }
176
+ async getAllByIndex(index, query) {
177
+ return await withTransaction(this.db, [this.name], "readonly", async (tx) => await new Store(tx, this.name).getAllByIndex(index, query));
178
+ }
179
+ async count(query) {
180
+ return await withTransaction(this.db, [this.name], "readonly", async (tx) => await new Store(tx, this.name).count(query));
181
+ }
182
+ async put(value) {
183
+ await withTransaction(this.db, [this.name], "readwrite", async (tx) => {
184
+ await new Store(tx, this.name).put(value);
185
+ });
186
+ }
187
+ async delete(key) {
188
+ await withTransaction(this.db, [this.name], "readwrite", async (tx) => {
189
+ await new Store(tx, this.name).delete(key);
190
+ });
191
+ }
192
+ async clear() {
193
+ await withTransaction(this.db, [this.name], "readwrite", async (tx) => {
194
+ await new Store(tx, this.name).clear();
195
+ });
196
+ }
197
+ /** Low-level access for multi-store transactions. */
198
+ store(tx) {
199
+ return new Store(tx, this.name);
200
+ }
201
+ };
202
+ function table(db, name) {
203
+ return new Table(db, name);
204
+ }
205
+ //#endregion
206
+ //#region src/schema.ts
207
+ /**
208
+ * Database schema for the mock Hestia server.
209
+ *
210
+ * All server state lives in IndexedDB: documents, sessions, blobs, workflows,
211
+ * settings, logs — everything. Closing the tab and reopening later restores a
212
+ * fully functional "server".
213
+ */
214
+ const DEFAULT_DB_NAME = "hestia-mock";
215
+ /** Every object store in the mock server, with its key configuration. */
216
+ const STORES = {
217
+ /** Generic key-value store (seed flags, update state, pointers). */
218
+ kv: { keyPath: "k" },
219
+ /** Active sessions: {token, user_id, created_at, expires_at}. */
220
+ sessions: {
221
+ keyPath: "token",
222
+ indexes: [{
223
+ name: "by_user",
224
+ keyPath: "user_id"
225
+ }]
226
+ },
227
+ /** Collection metadata (anansi SchemaDefinition documents). */
228
+ collections: { keyPath: "name" },
229
+ /** Every document in every collection — system and user — keyed [collection, _id_]. */
230
+ documents: {
231
+ keyPath: ["collection", "_id_"],
232
+ indexes: [{
233
+ name: "by_collection",
234
+ keyPath: "collection"
235
+ }]
236
+ },
237
+ /** Blob namespaces. */
238
+ namespaces: { keyPath: "ns" },
239
+ /** Stored blobs: {ns, key, meta, data}. */
240
+ blobs: {
241
+ keyPath: ["ns", "key"],
242
+ indexes: [{
243
+ name: "by_ns",
244
+ keyPath: "ns"
245
+ }]
246
+ },
247
+ /** Resumable/staged upload sessions. */
248
+ upload_sessions: { keyPath: "session_id" },
249
+ /** IAM policy rules (raw PolicyRule records). */
250
+ rules: { keyPath: "id" },
251
+ /** In-app notifications. */
252
+ notifications: {
253
+ keyPath: "_id_",
254
+ indexes: [{
255
+ name: "by_user",
256
+ keyPath: "user_id"
257
+ }]
258
+ },
259
+ /** Application log entries. */
260
+ logs: {
261
+ keyPath: "id",
262
+ indexes: [{
263
+ name: "by_level",
264
+ keyPath: "level"
265
+ }]
266
+ },
267
+ /** Cron schedules. */
268
+ schedules: {
269
+ keyPath: "_id_",
270
+ indexes: [{
271
+ name: "by_user",
272
+ keyPath: "user_id"
273
+ }]
274
+ },
275
+ /** Workflow definitions. */
276
+ workflows: { keyPath: "_id_" },
277
+ /** Workflow runs. */
278
+ runs: { keyPath: "run_id" },
279
+ /** Workflow timeline events keyed [run_id, seq]. */
280
+ run_events: {
281
+ keyPath: ["run_id", "seq"],
282
+ indexes: [{
283
+ name: "by_run",
284
+ keyPath: "run_id"
285
+ }]
286
+ },
287
+ /** Platform capabilities. */
288
+ capabilities: { keyPath: "name" },
289
+ /** Password reset tokens. */
290
+ password_resets: {
291
+ keyPath: "token",
292
+ indexes: [{
293
+ name: "by_email",
294
+ keyPath: "email"
295
+ }]
296
+ }
297
+ };
298
+ function createStores(db) {
299
+ for (const [name, def] of Object.entries(STORES)) {
300
+ if (db.objectStoreNames.contains(name)) continue;
301
+ const store = db.createObjectStore(name, { keyPath: def.keyPath });
302
+ for (const index of def.indexes ?? []) store.createIndex(index.name, index.keyPath);
303
+ }
304
+ }
305
+ /** Open (and lazily create) the mock server database. */
306
+ async function openMockDatabase(name = DEFAULT_DB_NAME) {
307
+ const db = await openDatabase({
308
+ name,
309
+ version: 1,
310
+ upgrade: (_db, _old) => createStores(_db)
311
+ });
312
+ return {
313
+ db,
314
+ tables: {
315
+ kv: table(db, "kv"),
316
+ sessions: table(db, "sessions"),
317
+ collections: table(db, "collections"),
318
+ documents: table(db, "documents"),
319
+ namespaces: table(db, "namespaces"),
320
+ blobs: table(db, "blobs"),
321
+ upload_sessions: table(db, "upload_sessions"),
322
+ rules: table(db, "rules"),
323
+ notifications: table(db, "notifications"),
324
+ logs: table(db, "logs"),
325
+ schedules: table(db, "schedules"),
326
+ workflows: table(db, "workflows"),
327
+ runs: table(db, "runs"),
328
+ run_events: table(db, "run_events"),
329
+ capabilities: table(db, "capabilities"),
330
+ password_resets: table(db, "password_resets")
331
+ }
332
+ };
333
+ }
334
+ const ALL_STORE_NAMES = Object.keys(STORES);
335
+ /** Wipe every object store (used by `system:core:reset` and tests). */
336
+ async function wipeAllStores(db) {
337
+ const names = ALL_STORE_NAMES.filter((n) => db.objectStoreNames.contains(n));
338
+ await withTransaction(db, names, "readwrite", async (tx) => {
339
+ await Promise.all(names.map((n) => new Store(tx, n).clear()));
340
+ });
341
+ }
342
+ //#endregion
343
+ //#region src/util.ts
344
+ /** Shared runtime utilities: ids, hashing, time, bytes. */
345
+ /** RFC4122 v4 UUID (crypto-backed with a deterministic fallback). */
346
+ function uuid() {
347
+ const c = globalThis.crypto;
348
+ if (c && "randomUUID" in c) return c.randomUUID();
349
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
350
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
351
+ bytes[6] = bytes[6] & 15 | 64;
352
+ bytes[8] = bytes[8] & 63 | 128;
353
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
354
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
355
+ }
356
+ function randomHex(bytes) {
357
+ const buf = new Uint8Array(bytes);
358
+ globalThis.crypto.getRandomValues(buf);
359
+ return [...buf].map((b) => b.toString(16).padStart(2, "0")).join("");
360
+ }
361
+ function randomToken(prefix = "hst") {
362
+ return `${prefix}_${randomHex(24)}`;
363
+ }
364
+ /** SHA-256 hex digest of a string or byte sequence. */
365
+ async function sha256Hex(input) {
366
+ const data = typeof input === "string" ? new TextEncoder().encode(input) : input;
367
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
368
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
369
+ }
370
+ /** Salted password hash — `sha256(salt:password)` stored as `salt:hash`. */
371
+ async function hashPassword(password) {
372
+ const salt = randomHex(12);
373
+ return `${salt}:${await sha256Hex(`${salt}:${password}`)}`;
374
+ }
375
+ async function verifyPassword(password, stored) {
376
+ const [salt, hash] = stored.split(":");
377
+ if (!salt || !hash) return false;
378
+ return await sha256Hex(`${salt}:${password}`) === hash;
379
+ }
380
+ /** Deterministic JSON stringify (stable key order) for checksums. */
381
+ function stableStringify(value) {
382
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
383
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
384
+ return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
385
+ }
386
+ function nowIso() {
387
+ return (/* @__PURE__ */ new Date()).toISOString();
388
+ }
389
+ function sleep(ms) {
390
+ if (!ms || ms <= 0) return Promise.resolve();
391
+ return new Promise((resolve) => setTimeout(resolve, ms));
392
+ }
393
+ /** Convert any binary payload (Blob/File/ArrayBuffer/TypedArray) to bytes. */
394
+ async function toBytes(payload) {
395
+ if (payload == null) return /* @__PURE__ */ new Uint8Array(0);
396
+ if (payload instanceof Uint8Array) return payload;
397
+ if (payload instanceof ArrayBuffer) return new Uint8Array(payload);
398
+ if (typeof Blob !== "undefined" && payload instanceof Blob) return new Uint8Array(await payload.arrayBuffer());
399
+ if (ArrayBuffer.isView(payload)) return new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
400
+ if (typeof payload === "string") return new TextEncoder().encode(payload);
401
+ throw new Error(`Unsupported binary payload type: ${typeof payload}`);
402
+ }
403
+ /** True when the value looks like a binary body (Blob/File/ArrayBuffer/TypedArray). */
404
+ function isBinary(payload) {
405
+ return payload instanceof ArrayBuffer || ArrayBuffer.isView(payload) || typeof Blob !== "undefined" && payload instanceof Blob || typeof File !== "undefined" && payload instanceof File;
406
+ }
407
+ /** Safe structural clone for values returned to callers. */
408
+ function clone(value) {
409
+ return structuredClone(value);
410
+ }
411
+ /** Compare two values with numeric coercion when both sides are numeric-like. */
412
+ function compareValues(a, b) {
413
+ if (a === b) return 0;
414
+ if (a == null) return -1;
415
+ if (b == null) return 1;
416
+ const na = toNumber(a);
417
+ const nb = toNumber(b);
418
+ if (na !== null && nb !== null) return na === nb ? 0 : na < nb ? -1 : 1;
419
+ const sa = String(a);
420
+ const sb = String(b);
421
+ return sa === sb ? 0 : sa < sb ? -1 : 1;
422
+ }
423
+ function toNumber(v) {
424
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
425
+ if (typeof v === "boolean") return v ? 1 : 0;
426
+ if (typeof v === "string" && v.trim() !== "") {
427
+ const n = Number(v);
428
+ if (Number.isFinite(n)) return n;
429
+ const d = Date.parse(v);
430
+ if (!Number.isNaN(d)) return d;
431
+ }
432
+ if (v instanceof Date) return v.getTime();
433
+ return null;
434
+ }
435
+ /**
436
+ * Minimal deep equality used by `eq`/`neq`/`in` filters — primitives by
437
+ * value, arrays element-wise, plain objects key-wise.
438
+ */
439
+ function deepEqual(a, b) {
440
+ if (a === b) return true;
441
+ if (a == null || b == null) return a === b;
442
+ if (typeof a !== "object" || typeof b !== "object") return a === b;
443
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
444
+ if (Array.isArray(a) && Array.isArray(b)) {
445
+ if (a.length !== b.length) return false;
446
+ return a.every((v, i) => deepEqual(v, b[i]));
447
+ }
448
+ const ka = Object.keys(a);
449
+ const kb = Object.keys(b);
450
+ if (ka.length !== kb.length) return false;
451
+ return ka.every((k) => deepEqual(a[k], b[k]));
452
+ }
453
+ //#endregion
454
+ //#region src/errors.ts
455
+ /**
456
+ * Server-side error factories.
457
+ *
458
+ * The mock throws real `SystemError` instances (from `@asaidimu/utils-error`)
459
+ * so the Hestia client's catch-sites — which inspect `err.code` — behave
460
+ * identically against the mock and a real server.
461
+ */
462
+ const STATUS = {
463
+ "SYNC-001-NF": 404,
464
+ "SYNC-002-DUP": 409,
465
+ "SYNC-003-VC": 409,
466
+ "VAL-001": 400,
467
+ "VAL-002": 400,
468
+ "AUTH-001-DENIED": 403,
469
+ "AUTH-002-UNAUTH": 401,
470
+ "AUTH-003-CRED": 401,
471
+ NOT_FOUND: 404,
472
+ NO_ACTIVE_SESSION: 404,
473
+ ROUTE_NOT_FOUND: 404,
474
+ NOT_IMPLEMENTED: 501,
475
+ RESTART_REQUIRED: 503,
476
+ INTERNAL_ERROR: 500
477
+ };
478
+ /** HTTP status the mock would have answered with for this error code. */
479
+ function statusForError(err) {
480
+ if (err && typeof err === "object" && "code" in err) {
481
+ const code = err.code;
482
+ return STATUS[code] ?? 500;
483
+ }
484
+ return 500;
485
+ }
486
+ var MockHttpError = class extends _asaidimu_utils_error.SystemError {
487
+ /** HTTP status the mock transport associates with this error. */
488
+ httpStatus;
489
+ constructor(code, message, issues) {
490
+ super({
491
+ code,
492
+ message,
493
+ issues
494
+ });
495
+ this.name = "SystemError";
496
+ this.httpStatus = STATUS[code] ?? 500;
497
+ }
498
+ };
499
+ const err = {
500
+ notFound: (what) => new MockHttpError("SYNC-001-NF", `${what} not found`),
501
+ /** Blob-store style not found (the SDK's blob client checks `NOT_FOUND`). */
502
+ blobNotFound: (what) => new MockHttpError("NOT_FOUND", `${what} not found`),
503
+ duplicate: (what) => new MockHttpError("SYNC-002-DUP", `${what} already exists`),
504
+ conflict: (message) => new MockHttpError("SYNC-003-VC", message),
505
+ validation: (message, issues) => new MockHttpError("VAL-001", message, issues),
506
+ required: (field) => new MockHttpError("VAL-002", `Required field missing: ${field}`),
507
+ denied: (operation = "operation") => new MockHttpError("AUTH-001-DENIED", `You do not have permission to perform ${operation}`),
508
+ unauthenticated: () => new MockHttpError("AUTH-002-UNAUTH", "This operation requires an authenticated session"),
509
+ invalidCredentials: () => new MockHttpError("AUTH-003-CRED", "invalid email or password"),
510
+ noActiveSession: () => new MockHttpError("NO_ACTIVE_SESSION", "no active session to revoke"),
511
+ routeNotFound: (name) => new MockHttpError("ROUTE_NOT_FOUND", `No registered route for handler: ${name}`),
512
+ notImplemented: (what) => new MockHttpError("NOT_IMPLEMENTED", `${what} is not implemented by the mock server`),
513
+ restartRequired: (message = "the change requires a server restart") => new MockHttpError("RESTART_REQUIRED", message),
514
+ internal: (message, cause) => {
515
+ return new MockHttpError("INTERNAL_ERROR", cause ? `${message}: ${String(cause)}` : message);
516
+ }
517
+ };
518
+ //#endregion
519
+ //#region src/server/store.ts
520
+ const USER_COLLECTION = "_user_";
521
+ const API_KEY_COLLECTION = "_api_key_";
522
+ const POLICY_COLLECTION = "_operation_policy_";
523
+ const AUDIT_LOG_COLLECTION = "_audit_log_";
524
+ function stripInternal(doc) {
525
+ const { collection: _ignored, ...rest } = doc;
526
+ return rest;
527
+ }
528
+ /** Remove the password hash from a user document before returning it. */
529
+ function sanitizeUser(doc) {
530
+ const { password: _ignored, ...rest } = doc;
531
+ return rest;
532
+ }
533
+ async function getDoc(tables, collection, id) {
534
+ return await tables.documents.get([collection, id]);
535
+ }
536
+ async function requireDoc(tables, collection, id) {
537
+ const doc = await tables.documents.get([collection, id]);
538
+ if (!doc) throw err.notFound(`document "${id}" in collection "${collection}"`);
539
+ return doc;
540
+ }
541
+ async function putDoc(tables, doc) {
542
+ await tables.documents.put(doc);
543
+ }
544
+ async function listDocs(tables, collection) {
545
+ return await tables.documents.getAllByIndex("by_collection", collection);
546
+ }
547
+ async function deleteDoc(tables, collection, id) {
548
+ if (!await tables.documents.get([collection, id])) throw err.notFound(`document "${id}" in collection "${collection}"`);
549
+ await tables.documents.delete([collection, id]);
550
+ }
551
+ async function computeChecksum(data) {
552
+ return await sha256Hex(stableStringify(data));
553
+ }
554
+ /**
555
+ * Create a new stored document: assigns `_id_`, stamps `_metadata_` with a
556
+ * checksum, timestamps, and version 1 (optimistic-locking baseline).
557
+ */
558
+ async function newDoc(collection, data) {
559
+ const { _id_, _metadata_, ...rest } = data;
560
+ const id = typeof _id_ === "string" && _id_ ? _id_ : uuid();
561
+ const now = nowIso();
562
+ return {
563
+ collection,
564
+ _id_: id,
565
+ _metadata_: {
566
+ checksum: await computeChecksum(rest),
567
+ created: now,
568
+ updated: now,
569
+ version: 1
570
+ },
571
+ ...rest
572
+ };
573
+ }
574
+ /**
575
+ * Merge a patch into an existing document with optimistic-locking semantics:
576
+ * bumps `version`, refreshes the checksum, and rejects stale `_metadata_`
577
+ * versions supplied by the caller.
578
+ */
579
+ async function applyUpdate(current, patch) {
580
+ const incomingMeta = patch._metadata_;
581
+ if (incomingMeta && typeof incomingMeta.version === "number" && incomingMeta.version !== current._metadata_.version) throw err.conflict(`Version conflict: expected ${incomingMeta.version}, document is at version ${current._metadata_.version}`);
582
+ const { _id_: _ignoredId, _metadata_: _ignoredMeta, collection: _ignoredCollection, ...changes } = patch;
583
+ const merged = {
584
+ ...current,
585
+ ...changes,
586
+ collection: current.collection,
587
+ _id_: current._id_
588
+ };
589
+ const now = nowIso();
590
+ merged._metadata_ = {
591
+ checksum: await computeChecksum(withoutEnvelope(merged)),
592
+ created: current._metadata_.created,
593
+ updated: now,
594
+ version: current._metadata_.version + 1
595
+ };
596
+ return merged;
597
+ }
598
+ function withoutEnvelope(doc) {
599
+ const { collection: _c, _id_: _i, _metadata_: _m, ...rest } = doc;
600
+ return rest;
601
+ }
602
+ /**
603
+ * Ensure a collection exists. The real server rejects writes to unknown
604
+ * collections; the mock auto-registers a schema-less collection instead so
605
+ * ad-hoc `api.collection("x")` usage works out of the box.
606
+ */
607
+ async function ensureCollection(tables, name) {
608
+ if (await tables.collections.get(name)) return;
609
+ await tables.collections.put({
610
+ name,
611
+ version: "1.0.0",
612
+ fields: {
613
+ _id_: {
614
+ name: "_id_",
615
+ type: "string",
616
+ required: true,
617
+ unique: true
618
+ },
619
+ _metadata_: {
620
+ name: "_metadata_",
621
+ type: "object"
622
+ }
623
+ },
624
+ _auto_created_: true
625
+ });
626
+ }
627
+ async function deleteCollectionData(tables, name) {
628
+ const docs = await listDocs(tables, name);
629
+ for (const doc of docs) await tables.documents.delete([name, doc._id_]);
630
+ await tables.collections.delete(name);
631
+ }
632
+ //#endregion
633
+ //#region src/seed.ts
634
+ const DEFAULT_SEED = {
635
+ email: "admin@test.local",
636
+ password: "password123",
637
+ name: "Administrator",
638
+ admin: true,
639
+ permissions: ["root", "authenticated"],
640
+ tenantId: "root"
641
+ };
642
+ const IAM_RULES = [
643
+ {
644
+ id: "root",
645
+ name: "root",
646
+ description: "Full root access",
647
+ expression: "true"
648
+ },
649
+ {
650
+ id: "authenticated",
651
+ name: "authenticated",
652
+ description: "Any authenticated session",
653
+ expression: "true"
654
+ },
655
+ {
656
+ id: "owner",
657
+ name: "owner",
658
+ description: "Owner of the resource",
659
+ expression: "identity.user._id_ == resource.user_id"
660
+ },
661
+ {
662
+ id: "anonymous",
663
+ name: "anonymous",
664
+ description: "Unauthenticated access",
665
+ expression: "false"
666
+ }
667
+ ];
668
+ const OPERATION_POLICIES = [
669
+ {
670
+ name: "system:auth:session:create",
671
+ rule: "anonymous"
672
+ },
673
+ {
674
+ name: "system:auth:session:delete",
675
+ rule: "authenticated"
676
+ },
677
+ {
678
+ name: "system:auth:password:reset",
679
+ rule: "anonymous"
680
+ },
681
+ {
682
+ name: "system:auth:password:confirm",
683
+ rule: "anonymous"
684
+ },
685
+ {
686
+ name: "system:users:user:create",
687
+ rule: "anonymous"
688
+ },
689
+ {
690
+ name: "system:users:user:get",
691
+ rule: "authenticated"
692
+ },
693
+ {
694
+ name: "system:users:user:update",
695
+ rule: "authenticated"
696
+ },
697
+ {
698
+ name: "system:users:user:delete",
699
+ rule: "root"
700
+ },
701
+ {
702
+ name: "system:users:password:change",
703
+ rule: "authenticated"
704
+ },
705
+ {
706
+ name: "system:collections:collection:list",
707
+ rule: "authenticated"
708
+ },
709
+ {
710
+ name: "system:collections:document:create",
711
+ rule: "authenticated"
712
+ },
713
+ {
714
+ name: "system:collections:document:query",
715
+ rule: "authenticated"
716
+ },
717
+ {
718
+ name: "system:apikeys:key:create",
719
+ rule: "authenticated"
720
+ },
721
+ {
722
+ name: "system:apikeys:key:list",
723
+ rule: "authenticated"
724
+ },
725
+ {
726
+ name: "system:apikeys:key:rotate",
727
+ rule: "authenticated"
728
+ },
729
+ {
730
+ name: "system:notifications:notification:create",
731
+ rule: "root"
732
+ },
733
+ {
734
+ name: "system:notifications:notification:list",
735
+ rule: "authenticated"
736
+ },
737
+ {
738
+ name: "system:schedules:schedule:create",
739
+ rule: "authenticated"
740
+ },
741
+ {
742
+ name: "system:schedules:schedule:all",
743
+ rule: "root"
744
+ },
745
+ {
746
+ name: "system:audit:log:export",
747
+ rule: "root"
748
+ },
749
+ {
750
+ name: "system:audit:log:stream",
751
+ rule: "root"
752
+ },
753
+ {
754
+ name: "system:logs:list",
755
+ rule: "root"
756
+ },
757
+ {
758
+ name: "system:updates:status:get",
759
+ rule: "root"
760
+ },
761
+ {
762
+ name: "system:core:health:check",
763
+ rule: "anonymous"
764
+ },
765
+ {
766
+ name: "system:core:heartbeat",
767
+ rule: "authenticated"
768
+ },
769
+ {
770
+ name: "system:core:reset",
771
+ rule: "root"
772
+ }
773
+ ];
774
+ const CAPABILITIES = [
775
+ {
776
+ name: "collections",
777
+ display_name: "Collections",
778
+ enabled: true,
779
+ version: "1.0.0"
780
+ },
781
+ {
782
+ name: "blobs",
783
+ display_name: "Blob Storage",
784
+ enabled: true,
785
+ version: "1.0.0"
786
+ },
787
+ {
788
+ name: "workflows",
789
+ display_name: "Workflows (hermes)",
790
+ enabled: true,
791
+ version: "1.0.0"
792
+ },
793
+ {
794
+ name: "schedules",
795
+ display_name: "Schedules",
796
+ enabled: true,
797
+ version: "1.0.0"
798
+ },
799
+ {
800
+ name: "notifications",
801
+ display_name: "Notifications",
802
+ enabled: true,
803
+ version: "1.0.0"
804
+ },
805
+ {
806
+ name: "updates",
807
+ display_name: "Self-Update",
808
+ enabled: false,
809
+ version: "1.0.0"
810
+ }
811
+ ];
812
+ const SETTINGS = [
813
+ {
814
+ key: "platform",
815
+ value: {
816
+ name: "hestia-mock",
817
+ version: "1.0.1",
818
+ environment: "mock"
819
+ }
820
+ },
821
+ {
822
+ key: "mailer",
823
+ value: {
824
+ enabled: false,
825
+ from: "mock@hestia.local"
826
+ }
827
+ },
828
+ {
829
+ key: "security",
830
+ value: {
831
+ session_ttl_days: 7,
832
+ password_min_length: 8
833
+ }
834
+ }
835
+ ];
836
+ const CORE_DOCS = [
837
+ {
838
+ _id_: "doc-getting-started",
839
+ title: "Getting Started",
840
+ body: "Create a collection, then read and write documents."
841
+ },
842
+ {
843
+ _id_: "doc-collections",
844
+ title: "Collections",
845
+ body: "Schema-less document storage with a rich query DSL."
846
+ },
847
+ {
848
+ _id_: "doc-blobs",
849
+ title: "Blobs",
850
+ body: "Namespaced binary storage with resumable uploads."
851
+ }
852
+ ];
853
+ /** System collections that must be queryable through the generic document routes. */
854
+ const SYSTEM_COLLECTIONS = [
855
+ "_user_",
856
+ "_api_key_",
857
+ "_operation_policy_",
858
+ "_audit_log_",
859
+ "_scheduled_messages_",
860
+ "_workflow_definitions_",
861
+ "_settings_"
862
+ ];
863
+ /** Seed a fresh database. Idempotent: skips when the admin user exists. */
864
+ async function seedDatabase(tables, config) {
865
+ if ((await tables.documents.getAllByIndex("by_collection", "_user_")).length > 0) return;
866
+ for (const name of SYSTEM_COLLECTIONS) if (!await tables.collections.get(name)) await tables.collections.put({
867
+ name,
868
+ version: "1.0.0",
869
+ fields: {
870
+ _id_: {
871
+ name: "_id_",
872
+ type: "string",
873
+ required: true,
874
+ unique: true
875
+ },
876
+ _metadata_: {
877
+ name: "_metadata_",
878
+ type: "object"
879
+ }
880
+ },
881
+ _system_: true
882
+ });
883
+ await putDoc(tables, await newDoc(USER_COLLECTION, {
884
+ email: config.email,
885
+ name: config.name ?? "Administrator",
886
+ password: await hashPassword(config.password),
887
+ verified: true,
888
+ permissions: config.permissions ?? (config.admin !== false ? ["root"] : ["authenticated"]),
889
+ tenant_id: config.tenantId ?? "root",
890
+ deleted: null
891
+ }));
892
+ for (const rule of IAM_RULES) await tables.rules.put({
893
+ ...rule,
894
+ ruleType: "expression",
895
+ syntax: "anansi-rule",
896
+ protected: rule.id === "root" || rule.id === "authenticated",
897
+ created_at: nowIso(),
898
+ updated_at: nowIso()
899
+ });
900
+ for (const policy of OPERATION_POLICIES) await tables.documents.put(await newDoc(POLICY_COLLECTION, {
901
+ _id_: policy.name,
902
+ operation: policy.name,
903
+ key: policy.name,
904
+ rule: policy.rule,
905
+ enabled: true,
906
+ protected: true,
907
+ rateLimit: null,
908
+ throttle: null
909
+ }));
910
+ for (const capability of CAPABILITIES) await tables.capabilities.put({
911
+ ...capability,
912
+ id: uuid()
913
+ });
914
+ for (const setting of SETTINGS) await tables.documents.put(await newDoc("_settings_", {
915
+ _id_: setting.key,
916
+ ...setting
917
+ }));
918
+ await tables.kv.put({
919
+ k: "core_docs",
920
+ v: CORE_DOCS
921
+ });
922
+ }
923
+ //#endregion
924
+ //#region src/server/context.ts
925
+ function header(ctx, name) {
926
+ const target = name.toLowerCase();
927
+ for (const [key, value] of Object.entries(ctx.headers)) if (key.toLowerCase() === target) return value;
928
+ }
929
+ function modifier(ctx, name) {
930
+ const raw = ctx.modifiers?.[name];
931
+ const value = Array.isArray(raw) ? raw[0] : raw;
932
+ return value == null ? void 0 : String(value);
933
+ }
934
+ function payloadAs(ctx, fallback) {
935
+ return ctx.payload ?? fallback;
936
+ }
937
+ function requirePayload(ctx) {
938
+ if (ctx.payload == null || typeof ctx.payload !== "object" || Array.isArray(ctx.payload)) throw new Error("expected a JSON object payload");
939
+ return ctx.payload;
940
+ }
941
+ //#endregion
942
+ //#region src/server/auth.ts
943
+ const CURRENT_SESSION_KEY = "current_session";
944
+ const SESSION_TTL_MS = 10080 * 60 * 1e3;
945
+ async function userById(tables, id) {
946
+ return await tables.documents.get([USER_COLLECTION, id]);
947
+ }
948
+ async function resolveApiKeyIdentity(tables, apiKey) {
949
+ const match = (await tables.documents.getAllByIndex("by_collection", API_KEY_COLLECTION)).find((k) => k["key"] === apiKey && k["status"] === "active");
950
+ if (!match) return null;
951
+ const user = await userById(tables, String(match["user_id"] ?? ""));
952
+ if (!user) return null;
953
+ return {
954
+ user,
955
+ auth_method: "api_key",
956
+ api_key_id: match._id_,
957
+ is_admin: isAdmin(user)
958
+ };
959
+ }
960
+ function isAdmin(user) {
961
+ const permissions = user["permissions"];
962
+ return Array.isArray(permissions) && permissions.includes("root");
963
+ }
964
+ /**
965
+ * Resolve the caller identity from, in order of precedence:
966
+ * 1. `X-API-Key` header (active API key owned by a user)
967
+ * 2. the persisted current session token
968
+ */
969
+ async function resolveIdentity(tables, ctx) {
970
+ const apiKey = header(ctx, "X-API-Key");
971
+ if (apiKey) {
972
+ const identity = await resolveApiKeyIdentity(tables, apiKey);
973
+ if (identity) return {
974
+ ...identity,
975
+ auth_method: "bootstrap_key"
976
+ };
977
+ return null;
978
+ }
979
+ const pointer = await tables.kv.get(CURRENT_SESSION_KEY);
980
+ const token = pointer?.v;
981
+ if (!token) return null;
982
+ const session = await tables.sessions.get(token);
983
+ if (!session) return null;
984
+ if (session.expires_at < Date.now()) {
985
+ await tables.sessions.delete(token);
986
+ if (await tables.kv.get("current_session") === pointer) await tables.kv.delete(CURRENT_SESSION_KEY);
987
+ return null;
988
+ }
989
+ const user = await userById(tables, session.user_id);
990
+ if (!user) return null;
991
+ return {
992
+ user,
993
+ auth_method: "password",
994
+ session_id: session.token,
995
+ is_admin: isAdmin(user)
996
+ };
997
+ }
998
+ function checkAccess(access, identity) {
999
+ if (access === "public") return;
1000
+ if (!identity) throw err.unauthenticated();
1001
+ if (access === "admin" && !identity.is_admin) throw err.denied("this root-only operation");
1002
+ }
1003
+ async function createSession(tables, userId) {
1004
+ const now = Date.now();
1005
+ const record = {
1006
+ token: randomToken("hst_sess"),
1007
+ user_id: userId,
1008
+ created_at: now,
1009
+ expires_at: now + SESSION_TTL_MS
1010
+ };
1011
+ await tables.sessions.put(record);
1012
+ await tables.kv.put({
1013
+ k: CURRENT_SESSION_KEY,
1014
+ v: record.token
1015
+ });
1016
+ return record;
1017
+ }
1018
+ async function revokeCurrentSession(tables) {
1019
+ const token = (await tables.kv.get(CURRENT_SESSION_KEY))?.v;
1020
+ if (!token) throw err.noActiveSession();
1021
+ if (!await tables.sessions.get(token)) {
1022
+ await tables.kv.delete(CURRENT_SESSION_KEY);
1023
+ throw err.noActiveSession();
1024
+ }
1025
+ await tables.sessions.delete(token);
1026
+ await tables.kv.delete(CURRENT_SESSION_KEY);
1027
+ }
1028
+ async function setCredentials(tables, userId, password) {
1029
+ const user = await userById(tables, userId);
1030
+ if (!user) throw err.notFound("user");
1031
+ user["password"] = await hashPassword(password);
1032
+ await tables.documents.put(user);
1033
+ }
1034
+ async function verifyCredentials(tables, email, password) {
1035
+ const user = (await tables.documents.getAllByIndex("by_collection", USER_COLLECTION)).find((u) => u["email"] === email && u["deleted"] == null);
1036
+ if (!user) return null;
1037
+ return await verifyPassword(password, String(user["password"] ?? "")) ? user : null;
1038
+ }
1039
+ //#endregion
1040
+ //#region src/envelope.ts
1041
+ function ok(data, opts) {
1042
+ return {
1043
+ status: opts?.status ?? 200,
1044
+ body: {
1045
+ data,
1046
+ metadata: {
1047
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1048
+ request: opts?.request ?? "",
1049
+ ...opts?.page ? { page: opts.page } : {}
1050
+ }
1051
+ }
1052
+ };
1053
+ }
1054
+ function noContent() {
1055
+ return {
1056
+ status: 204,
1057
+ body: void 0
1058
+ };
1059
+ }
1060
+ //#endregion
1061
+ //#region src/server/handlers/core.ts
1062
+ function coreHandlers(deps) {
1063
+ const { tables } = deps;
1064
+ return {
1065
+ "system:core:health:check": {
1066
+ access: "public",
1067
+ handler: async () => {
1068
+ return ok({
1069
+ ok: true,
1070
+ bootstrapped: await deps.isBootstrapped()
1071
+ });
1072
+ }
1073
+ },
1074
+ "system:core:heartbeat": {
1075
+ access: "authenticated",
1076
+ handler: async () => ok({
1077
+ ok: true,
1078
+ ts: Date.now()
1079
+ })
1080
+ },
1081
+ "system:core:capability:list": {
1082
+ access: "authenticated",
1083
+ handler: async () => {
1084
+ return ok(await tables.capabilities.getAll());
1085
+ }
1086
+ },
1087
+ "system:core:capability:set": {
1088
+ access: "admin",
1089
+ handler: async (ctx) => {
1090
+ const name = ctx.args["name"];
1091
+ if (!name) throw err.required("name");
1092
+ const payload = requirePayload(ctx);
1093
+ const doc = {
1094
+ ...await tables.capabilities.get(name) ?? {},
1095
+ name,
1096
+ ...payload
1097
+ };
1098
+ await tables.capabilities.put(doc);
1099
+ return ok(doc);
1100
+ }
1101
+ },
1102
+ "system:core:docs:list": {
1103
+ access: "authenticated",
1104
+ handler: async () => {
1105
+ return ok((await tables.kv.get("core_docs"))?.v ?? []);
1106
+ }
1107
+ },
1108
+ "system:core:reset": {
1109
+ access: "admin",
1110
+ noAudit: true,
1111
+ handler: async () => {
1112
+ await deps.reset();
1113
+ return noContent();
1114
+ }
1115
+ }
1116
+ };
1117
+ }
1118
+ //#endregion
1119
+ //#region src/query.ts
1120
+ /** Resolve a possibly-dotted path against a document. */
1121
+ function getField(doc, path) {
1122
+ if (!path.includes(".")) return doc?.[path];
1123
+ const parts = path.split(".");
1124
+ let cur = doc;
1125
+ for (const part of parts) {
1126
+ if (cur == null) return void 0;
1127
+ if (Array.isArray(cur)) {
1128
+ const idx = Number(part);
1129
+ cur = Number.isInteger(idx) ? cur[idx] : void 0;
1130
+ continue;
1131
+ }
1132
+ cur = cur[part];
1133
+ }
1134
+ return cur;
1135
+ }
1136
+ function asString(v) {
1137
+ if (v == null) return null;
1138
+ if (typeof v === "string") return v;
1139
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
1140
+ return null;
1141
+ }
1142
+ function evaluateCondition(doc, cond) {
1143
+ const actual = getField(doc, cond.field);
1144
+ const expected = cond.value;
1145
+ switch (cond.operator) {
1146
+ case "eq": return deepEqual(actual, expected);
1147
+ case "neq": return !deepEqual(actual, expected);
1148
+ case "lt": return actual != null && expected != null && compareValues(actual, expected) < 0;
1149
+ case "lte": return actual != null && expected != null && compareValues(actual, expected) <= 0;
1150
+ case "gt": return actual != null && expected != null && compareValues(actual, expected) > 0;
1151
+ case "gte": return actual != null && expected != null && compareValues(actual, expected) >= 0;
1152
+ case "in": return (Array.isArray(expected) ? expected : [expected]).some((v) => deepEqual(actual, v));
1153
+ case "nin": return !(Array.isArray(expected) ? expected : [expected]).some((v) => deepEqual(actual, v));
1154
+ case "contains": {
1155
+ if (Array.isArray(actual)) return actual.some((v) => deepEqual(v, expected));
1156
+ const s = asString(actual);
1157
+ const needle = asString(expected);
1158
+ return s != null && needle != null && s.includes(needle);
1159
+ }
1160
+ case "ncontains": {
1161
+ if (Array.isArray(actual)) return !actual.some((v) => deepEqual(v, expected));
1162
+ const s = asString(actual);
1163
+ const needle = asString(expected);
1164
+ return s == null || needle == null || !s.includes(needle);
1165
+ }
1166
+ case "startswith": {
1167
+ const s = asString(actual);
1168
+ const prefix = asString(expected);
1169
+ return s != null && prefix != null && s.startsWith(prefix);
1170
+ }
1171
+ case "endswith": {
1172
+ const s = asString(actual);
1173
+ const suffix = asString(expected);
1174
+ return s != null && suffix != null && s.endsWith(suffix);
1175
+ }
1176
+ case "exists": return expected === false ? actual === void 0 : actual !== void 0;
1177
+ case "nexists": return actual === void 0;
1178
+ default: return false;
1179
+ }
1180
+ }
1181
+ function isGroup(filter) {
1182
+ return typeof filter.operator === "string" && Array.isArray(filter.conditions);
1183
+ }
1184
+ function evaluateFilter(doc, filter) {
1185
+ if (isGroup(filter)) {
1186
+ const results = filter.conditions.map((c) => evaluateFilter(doc, c));
1187
+ switch (filter.operator) {
1188
+ case "and": return results.every(Boolean);
1189
+ case "or": return results.some(Boolean);
1190
+ case "not": return !results.every(Boolean);
1191
+ case "nor": return !results.some(Boolean);
1192
+ case "xor": return results.filter(Boolean).length % 2 === 1;
1193
+ default: return results.every(Boolean);
1194
+ }
1195
+ }
1196
+ return evaluateCondition(doc, filter);
1197
+ }
1198
+ /** Multi-field sort. Missing values sort last regardless of direction. */
1199
+ function sortDocs(docs, sort) {
1200
+ if (!sort || sort.length === 0) return docs;
1201
+ const specs = sort.map((s) => ({
1202
+ field: String(s.field),
1203
+ dir: s.direction === "desc" ? -1 : 1
1204
+ }));
1205
+ return [...docs].sort((a, b) => {
1206
+ for (const spec of specs) {
1207
+ const av = getField(a, spec.field);
1208
+ const bv = getField(b, spec.field);
1209
+ if (av == null && bv == null) continue;
1210
+ if (av == null) return 1;
1211
+ if (bv == null) return -1;
1212
+ const cmp = compareValues(av, bv);
1213
+ if (cmp !== 0) return cmp * spec.dir;
1214
+ }
1215
+ return 0;
1216
+ });
1217
+ }
1218
+ /** Execute a full DSL query against an in-memory array of documents. */
1219
+ function executeQuery(docs, dsl) {
1220
+ const query = dsl ?? {};
1221
+ let out = docs;
1222
+ if (query.filters) out = out.filter((d) => evaluateFilter(d, query.filters));
1223
+ const total = out.length;
1224
+ if (query.sort?.length) out = sortDocs(out, query.sort);
1225
+ const pagination = query.pagination;
1226
+ let offset = 0;
1227
+ let limit = out.length;
1228
+ if (pagination) if (pagination.type === "offset") {
1229
+ offset = Math.max(0, pagination.offset ?? 0);
1230
+ limit = pagination.limit ?? out.length;
1231
+ } else {
1232
+ offset = 0;
1233
+ limit = pagination.limit ?? out.length;
1234
+ }
1235
+ return {
1236
+ items: out.slice(offset, offset + limit),
1237
+ total
1238
+ };
1239
+ }
1240
+ //#endregion
1241
+ //#region src/server/handlers/users.ts
1242
+ function userHandlers(deps) {
1243
+ const { tables } = deps;
1244
+ return {
1245
+ "system:auth:session:create": {
1246
+ access: "public",
1247
+ handler: async (ctx) => {
1248
+ const payload = requirePayload(ctx);
1249
+ const email = String(payload["email"] ?? "");
1250
+ const password = String(payload["password"] ?? "");
1251
+ if (!email || !password) throw err.invalidCredentials();
1252
+ const user = await verifyCredentials(tables, email, password);
1253
+ if (!user) throw err.invalidCredentials();
1254
+ ctx.identity = {
1255
+ user,
1256
+ auth_method: "password",
1257
+ session_id: (await createSession(tables, user._id_)).token,
1258
+ is_admin: isAdmin(user)
1259
+ };
1260
+ return ok({ user: sanitizeUser(clone(user)) });
1261
+ }
1262
+ },
1263
+ "system:auth:session:delete": {
1264
+ access: "authenticated",
1265
+ handler: async () => {
1266
+ await revokeCurrentSession(tables);
1267
+ return noContent();
1268
+ }
1269
+ },
1270
+ "system:auth:token:elevate": {
1271
+ access: "authenticated",
1272
+ handler: async (ctx) => {
1273
+ return ok({
1274
+ token: ctx.identity.session_id,
1275
+ elevated: true,
1276
+ ts: nowIso()
1277
+ });
1278
+ }
1279
+ },
1280
+ "system:auth:password:reset": {
1281
+ access: "public",
1282
+ handler: async (ctx) => {
1283
+ const payload = requirePayload(ctx);
1284
+ const email = String(payload["email"] ?? "");
1285
+ if (!email) throw err.required("email");
1286
+ const token = randomToken("hst_reset");
1287
+ await tables.password_resets.put({
1288
+ token,
1289
+ email,
1290
+ created_at: Date.now(),
1291
+ expires_at: Date.now() + 3600 * 1e3
1292
+ });
1293
+ return ok({
1294
+ email,
1295
+ token
1296
+ });
1297
+ }
1298
+ },
1299
+ "system:auth:password:confirm": {
1300
+ access: "public",
1301
+ handler: async (ctx) => {
1302
+ const payload = requirePayload(ctx);
1303
+ const token = String(payload["token"] ?? "");
1304
+ const password = String(payload["password"] ?? "");
1305
+ if (!token) throw err.required("token");
1306
+ if (!password) throw err.required("password");
1307
+ const record = await tables.password_resets.get(token);
1308
+ if (!record || record.expires_at < Date.now()) throw err.validation("reset token is invalid or expired");
1309
+ const user = (await tables.documents.getAllByIndex("by_collection", USER_COLLECTION)).find((u) => u["email"] === record.email);
1310
+ if (!user) throw err.notFound("user");
1311
+ await setCredentials(tables, user._id_, password);
1312
+ await tables.password_resets.delete(token);
1313
+ return noContent();
1314
+ }
1315
+ },
1316
+ "system:auth:bootstrap:password:set": {
1317
+ access: "public",
1318
+ handler: async (ctx) => {
1319
+ if (!ctx.identity || ctx.identity.auth_method !== "bootstrap_key") throw err.unauthenticated();
1320
+ const payload = requirePayload(ctx);
1321
+ const password = String(payload["password"] ?? "");
1322
+ const email = String(payload["email"] ?? "");
1323
+ if (!password) throw err.required("password");
1324
+ const user = ctx.identity.user;
1325
+ if (email) user["email"] = email;
1326
+ await setCredentials(tables, user._id_, password);
1327
+ await deps.setBootstrapped(true);
1328
+ return noContent();
1329
+ }
1330
+ },
1331
+ "system:users:user:create": {
1332
+ access: "public",
1333
+ handler: async (ctx) => {
1334
+ const payload = requirePayload(ctx);
1335
+ const email = String(payload["email"] ?? "");
1336
+ const password = String(payload["password"] ?? "");
1337
+ const name = String(payload["name"] ?? "");
1338
+ if (!email || !password) throw err.validation("email and password are required");
1339
+ if ((await tables.documents.getAllByIndex("by_collection", "_user_")).some((u) => u["email"] === email)) throw err.duplicate(`user with email "${email}"`);
1340
+ const doc = await newDoc(USER_COLLECTION, {
1341
+ email,
1342
+ name,
1343
+ password: await hashPassword(password),
1344
+ verified: payload["verified"] === true,
1345
+ permissions: Array.isArray(payload["permissions"]) ? payload["permissions"] : ["authenticated"],
1346
+ tenant_id: String(payload["tenant_id"] ?? "root"),
1347
+ deleted: null
1348
+ });
1349
+ await putDoc(tables, doc);
1350
+ return ok(sanitizeUser(clone(doc)));
1351
+ }
1352
+ },
1353
+ "system:users:user:get": {
1354
+ access: "authenticated",
1355
+ handler: async (ctx) => {
1356
+ return ok(sanitizeUser(clone(await requireDoc(tables, USER_COLLECTION, ctx.args["user_id"]))));
1357
+ }
1358
+ },
1359
+ "system:users:user:update": {
1360
+ access: "authenticated",
1361
+ handler: async (ctx) => {
1362
+ const current = await requireDoc(tables, USER_COLLECTION, ctx.args["user_id"]);
1363
+ const payload = requirePayload(ctx);
1364
+ if (!ctx.identity.is_admin && current._id_ !== ctx.identity.user._id_) throw err.denied("updating another user");
1365
+ if (payload["password"] !== void 0) throw err.denied("changing a password through user:update");
1366
+ const updated = await applyUpdate(current, payload);
1367
+ await putDoc(tables, updated);
1368
+ return ok(sanitizeUser(clone(updated)));
1369
+ }
1370
+ },
1371
+ "system:users:user:delete": {
1372
+ access: "admin",
1373
+ handler: async (ctx) => {
1374
+ const current = await requireDoc(tables, USER_COLLECTION, ctx.args["user_id"]);
1375
+ const updated = await applyUpdate(current, { deleted: nowIso() });
1376
+ await putDoc(tables, updated);
1377
+ const sessions = await tables.sessions.getAllByIndex("by_user", current._id_);
1378
+ for (const session of sessions) await tables.sessions.delete(session.token);
1379
+ return noContent();
1380
+ }
1381
+ },
1382
+ "system:users:password:change": {
1383
+ access: "authenticated",
1384
+ handler: async (ctx) => {
1385
+ const targetId = ctx.args["user_id"];
1386
+ const isSelf = ctx.identity.user._id_ === targetId;
1387
+ if (!isSelf && !ctx.identity.is_admin) throw err.denied("changing another user's password");
1388
+ const payload = requirePayload(ctx);
1389
+ const current = String(payload["current"] ?? "");
1390
+ const next = String(payload["new"] ?? "");
1391
+ const user = await requireDoc(tables, USER_COLLECTION, targetId);
1392
+ if (isSelf && !await verifyPassword(current, String(user["password"] ?? ""))) throw err.invalidCredentials();
1393
+ await setCredentials(tables, targetId, next);
1394
+ const sessions = await tables.sessions.getAllByIndex("by_user", targetId);
1395
+ for (const session of sessions) if (ctx.identity.session_id && session.token !== ctx.identity.session_id) await tables.sessions.delete(session.token);
1396
+ return noContent();
1397
+ }
1398
+ },
1399
+ "system:collections:user:query": {
1400
+ access: "authenticated",
1401
+ handler: async (ctx) => {
1402
+ const live = (await tables.documents.getAllByIndex("by_collection", USER_COLLECTION)).filter((u) => u["deleted"] == null).map(sanitizeUser);
1403
+ const offset = payloadOffset(ctx.payload);
1404
+ const limit = payloadLimit(ctx.payload);
1405
+ const { items, total } = executeQuery(live, ctx.payload);
1406
+ return ok(items, { page: page(total, offset, limit, items.length) });
1407
+ }
1408
+ }
1409
+ };
1410
+ }
1411
+ function payloadOffset(payload) {
1412
+ return Math.max(0, payload?.pagination?.offset ?? 0);
1413
+ }
1414
+ function payloadLimit(payload) {
1415
+ return Math.max(1, payload?.pagination?.limit ?? 50);
1416
+ }
1417
+ function page(total, offset, limit, count) {
1418
+ const size = Math.max(1, limit);
1419
+ return {
1420
+ number: Math.floor(offset / size) + 1,
1421
+ size,
1422
+ count,
1423
+ total,
1424
+ pages: Math.max(1, Math.ceil(total / size))
1425
+ };
1426
+ }
1427
+ //#endregion
1428
+ //#region src/server/handlers/collections.ts
1429
+ function collectionHandlers(deps) {
1430
+ const { tables } = deps;
1431
+ const queryCollection = (collection, sanitize) => async (ctx) => {
1432
+ const payload = payloadAs(ctx, {});
1433
+ let docs = await listDocs(tables, collection);
1434
+ if (sanitize) docs = docs.map(sanitize);
1435
+ const offset = Math.max(0, payload.pagination?.offset ?? 0);
1436
+ const limit = Math.max(1, payload.pagination?.limit ?? docs.length);
1437
+ const { items, total } = executeQuery(docs, ctx.payload);
1438
+ return ok(items, { page: {
1439
+ number: Math.floor(offset / limit) + 1,
1440
+ size: limit,
1441
+ count: items.length,
1442
+ total,
1443
+ pages: Math.max(1, Math.ceil(total / limit))
1444
+ } });
1445
+ };
1446
+ return {
1447
+ "system:collections:collection:list": {
1448
+ access: "authenticated",
1449
+ handler: async () => {
1450
+ return ok(await tables.collections.getAll());
1451
+ }
1452
+ },
1453
+ "system:collections:collection:get": {
1454
+ access: "authenticated",
1455
+ handler: async (ctx) => {
1456
+ const meta = await tables.collections.get(ctx.args["name"]);
1457
+ if (!meta) throw err.notFound(`collection "${ctx.args["name"]}"`);
1458
+ return ok(meta);
1459
+ }
1460
+ },
1461
+ "system:collections:collection:create": {
1462
+ access: "authenticated",
1463
+ handler: async (ctx) => {
1464
+ const schema = requirePayload(ctx);
1465
+ const name = String(schema["name"] ?? "");
1466
+ if (!name) throw err.required("schema.name");
1467
+ if (await tables.collections.get(name)) throw err.duplicate(`collection "${name}"`);
1468
+ await tables.collections.put(schema);
1469
+ return ok(schema);
1470
+ }
1471
+ },
1472
+ "system:collections:collection:delete": {
1473
+ access: "authenticated",
1474
+ handler: async (ctx) => {
1475
+ const name = ctx.args["name"];
1476
+ if (!await tables.collections.get(name)) throw err.notFound(`collection "${name}"`);
1477
+ await deleteCollectionData(tables, name);
1478
+ return noContent();
1479
+ }
1480
+ },
1481
+ "system:collections:document:query": {
1482
+ access: "authenticated",
1483
+ handler: async (ctx) => {
1484
+ const name = ctx.args["name"];
1485
+ if (!await tables.collections.get(name)) throw err.notFound(`collection "${name}"`);
1486
+ const docs = await listDocs(tables, name);
1487
+ const sanitized = name === "_user_" ? docs.map(sanitizeUser) : docs;
1488
+ const payload = payloadAs(ctx, {});
1489
+ const offset = Math.max(0, payload.pagination?.offset ?? 0);
1490
+ const limit = Math.max(1, payload.pagination?.limit ?? sanitized.length);
1491
+ const { items, total } = executeQuery(sanitized, ctx.payload);
1492
+ return ok(items, { page: {
1493
+ number: Math.floor(offset / limit) + 1,
1494
+ size: limit,
1495
+ count: items.length,
1496
+ total,
1497
+ pages: Math.max(1, Math.ceil(total / limit))
1498
+ } });
1499
+ }
1500
+ },
1501
+ "system:collections:document:get": {
1502
+ access: "authenticated",
1503
+ handler: async (ctx) => {
1504
+ const { name, doc_id } = ctx.args;
1505
+ const doc = await getDoc(tables, name, doc_id);
1506
+ if (!doc) throw err.notFound(`document "${doc_id}" in collection "${name}"`);
1507
+ const view = stripInternal(clone(doc));
1508
+ return ok(name === "_user_" ? sanitizeUser(view) : view);
1509
+ }
1510
+ },
1511
+ "system:collections:document:create": {
1512
+ access: "authenticated",
1513
+ handler: async (ctx) => {
1514
+ const name = ctx.args["name"];
1515
+ const payload = payloadAs(ctx, {});
1516
+ await ensureCollection(tables, name);
1517
+ const doc = await newDoc(name, clone(payload));
1518
+ await putDoc(tables, doc);
1519
+ deps.bus.emit(`collection:${name}`, {
1520
+ event: "created",
1521
+ document: stripInternal(clone(doc))
1522
+ });
1523
+ return ok(stripInternal(clone(doc)));
1524
+ }
1525
+ },
1526
+ "system:collections:document:update": {
1527
+ access: "authenticated",
1528
+ handler: async (ctx) => {
1529
+ const { name, doc_id } = ctx.args;
1530
+ const updated = await applyUpdate(await requireDoc(tables, name, doc_id), clone(payloadAs(ctx, {})));
1531
+ await putDoc(tables, updated);
1532
+ deps.bus.emit(`collection:${name}`, {
1533
+ event: "updated",
1534
+ document: stripInternal(clone(updated))
1535
+ });
1536
+ return ok(stripInternal(clone(updated)));
1537
+ }
1538
+ },
1539
+ "system:collections:document:delete": {
1540
+ access: "authenticated",
1541
+ handler: async (ctx) => {
1542
+ const { name, doc_id } = ctx.args;
1543
+ await deleteDoc(tables, name, doc_id);
1544
+ deps.bus.emit(`collection:${name}`, {
1545
+ event: "deleted",
1546
+ document: { _id_: doc_id }
1547
+ });
1548
+ return noContent();
1549
+ }
1550
+ },
1551
+ "system:collections:audit_log:query": {
1552
+ access: "authenticated",
1553
+ noAudit: true,
1554
+ handler: queryCollection(AUDIT_LOG_COLLECTION)
1555
+ }
1556
+ };
1557
+ }
1558
+ //#endregion
1559
+ //#region src/server/handlers/apikeys.ts
1560
+ function apiKeyHandlers(deps) {
1561
+ const { tables } = deps;
1562
+ const publicKey = (doc) => {
1563
+ const { key: _ignored, ...rest } = doc;
1564
+ return rest;
1565
+ };
1566
+ return {
1567
+ "system:apikeys:key:create": {
1568
+ access: "authenticated",
1569
+ handler: async (ctx) => {
1570
+ const payload = requirePayload(ctx);
1571
+ const name = String(payload["name"] ?? "");
1572
+ if (!name) throw err.required("name");
1573
+ const secret = `hst_${randomHex(20)}`;
1574
+ const doc = await newDoc(API_KEY_COLLECTION, {
1575
+ name,
1576
+ prefix: secret.slice(0, 10),
1577
+ key: secret,
1578
+ operations: Array.isArray(payload["operations"]) ? payload["operations"] : ["*"],
1579
+ status: "active",
1580
+ environment: payload["environment"] ?? "development",
1581
+ expiry: payload["expiry"] ?? null,
1582
+ usage: 0,
1583
+ last_used: null,
1584
+ user_id: ctx.identity.user._id_,
1585
+ tenant_id: ctx.identity.user["tenant_id"] ?? "root"
1586
+ });
1587
+ await putDoc(tables, doc);
1588
+ return ok(clone(doc));
1589
+ }
1590
+ },
1591
+ "system:apikeys:key:list": {
1592
+ access: "authenticated",
1593
+ handler: async (ctx) => {
1594
+ return ok((await tables.documents.getAllByIndex("by_collection", API_KEY_COLLECTION)).filter((k) => k["user_id"] === ctx.identity.user._id_ || ctx.identity.is_admin).map(publicKey));
1595
+ }
1596
+ },
1597
+ "system:apikeys:key:get": {
1598
+ access: "authenticated",
1599
+ handler: async (ctx) => {
1600
+ const doc = await requireDoc(tables, API_KEY_COLLECTION, ctx.args["key_id"]);
1601
+ return ok(publicKey(clone(doc)));
1602
+ }
1603
+ },
1604
+ "system:apikeys:key:update": {
1605
+ access: "authenticated",
1606
+ handler: async (ctx) => {
1607
+ const current = await requireDoc(tables, API_KEY_COLLECTION, ctx.args["key_id"]);
1608
+ const payload = requirePayload(ctx);
1609
+ const allowed = {};
1610
+ for (const field of [
1611
+ "name",
1612
+ "environment",
1613
+ "operations",
1614
+ "status",
1615
+ "expiry"
1616
+ ]) if (payload[field] !== void 0) allowed[field] = payload[field];
1617
+ const updated = await applyUpdate(current, allowed);
1618
+ await putDoc(tables, updated);
1619
+ return ok(publicKey(clone(updated)));
1620
+ }
1621
+ },
1622
+ "system:apikeys:key:rotate": {
1623
+ access: "authenticated",
1624
+ handler: async (ctx) => {
1625
+ const current = await requireDoc(tables, API_KEY_COLLECTION, ctx.args["key_id"]);
1626
+ const secret = `hst_${randomHex(20)}`;
1627
+ const updated = await applyUpdate(current, {
1628
+ key: secret,
1629
+ prefix: secret.slice(0, 10)
1630
+ });
1631
+ await putDoc(tables, updated);
1632
+ return ok(clone(updated));
1633
+ }
1634
+ },
1635
+ "system:apikeys:key:delete": {
1636
+ access: "authenticated",
1637
+ handler: async (ctx) => {
1638
+ await requireDoc(tables, API_KEY_COLLECTION, ctx.args["key_id"]);
1639
+ await tables.documents.delete([API_KEY_COLLECTION, ctx.args["key_id"]]);
1640
+ return noContent();
1641
+ }
1642
+ }
1643
+ };
1644
+ }
1645
+ //#endregion
1646
+ //#region src/server/handlers/notifications.ts
1647
+ function notificationHandlers(deps) {
1648
+ const { tables } = deps;
1649
+ const visible = async (ctx) => {
1650
+ const all = await tables.notifications.getAll();
1651
+ const userId = ctx.identity.user._id_;
1652
+ return ctx.identity.is_admin ? all : all.filter((n) => n["user_id"] === userId);
1653
+ };
1654
+ const publish = (doc) => {
1655
+ const userId = String(doc["user_id"] ?? "");
1656
+ const payload = { data: doc };
1657
+ deps.bus.emit(Topics.notifications(userId), payload);
1658
+ deps.bus.emit(Topics.notificationsAll, payload);
1659
+ };
1660
+ return {
1661
+ "system:notifications:notification:create": {
1662
+ access: "admin",
1663
+ handler: async (ctx) => {
1664
+ const payload = requirePayload(ctx);
1665
+ const userId = String(payload["user_id"] ?? "");
1666
+ const subject = String(payload["subject"] ?? "");
1667
+ if (!userId || !subject) throw err.validation("user_id and subject are required");
1668
+ const doc = await newDoc("_notifications_", {
1669
+ _id_: uuid(),
1670
+ user_id: userId,
1671
+ type: payload["type"] ?? "info",
1672
+ subject,
1673
+ body: payload["body"] ?? "",
1674
+ data: payload["data"] ?? {},
1675
+ actions: payload["actions"] ?? [],
1676
+ read: false,
1677
+ created_at: Date.now(),
1678
+ expires_at: payload["expires_at"] ?? null
1679
+ });
1680
+ await tables.notifications.put(doc);
1681
+ publish(doc);
1682
+ return ok(clone(doc));
1683
+ }
1684
+ },
1685
+ "system:notifications:notification:list": {
1686
+ access: "authenticated",
1687
+ handler: async (ctx) => {
1688
+ return ok(await visible(ctx));
1689
+ }
1690
+ },
1691
+ "system:notifications:notification:read": {
1692
+ access: "authenticated",
1693
+ handler: async (ctx) => {
1694
+ const id = ctx.args["notification_id"];
1695
+ const doc = await tables.notifications.get(id);
1696
+ if (!doc) throw err.notFound(`notification "${id}"`);
1697
+ doc["read"] = true;
1698
+ await tables.notifications.put(doc);
1699
+ return noContent();
1700
+ }
1701
+ },
1702
+ "system:notifications:read:all": {
1703
+ access: "authenticated",
1704
+ handler: async (ctx) => {
1705
+ const items = await visible(ctx);
1706
+ for (const doc of items) if (!doc["read"]) {
1707
+ doc["read"] = true;
1708
+ await tables.notifications.put(doc);
1709
+ }
1710
+ return noContent();
1711
+ }
1712
+ },
1713
+ "system:notifications:unread:count": {
1714
+ access: "authenticated",
1715
+ handler: async (ctx) => {
1716
+ return ok({ count: (await visible(ctx)).filter((n) => !n["read"]).length });
1717
+ }
1718
+ }
1719
+ };
1720
+ }
1721
+ function settingHandlers(deps) {
1722
+ const { tables } = deps;
1723
+ const toDoc = (key, value) => ({
1724
+ _id_: key,
1725
+ key,
1726
+ value
1727
+ });
1728
+ return {
1729
+ "system:settings:list": {
1730
+ access: "authenticated",
1731
+ handler: async () => {
1732
+ return ok((await tables.documents.getAllByIndex("by_collection", "_settings_")).map((r) => toDoc(String(r["key"]), r["value"] ?? {})));
1733
+ }
1734
+ },
1735
+ "system:settings:get": {
1736
+ access: "authenticated",
1737
+ handler: async (ctx) => {
1738
+ const key = ctx.args["key"];
1739
+ const doc = await tables.documents.get(["_settings_", key]);
1740
+ if (!doc) throw err.notFound(`setting "${key}"`);
1741
+ return ok(toDoc(key, doc["value"] ?? {}));
1742
+ }
1743
+ },
1744
+ "system:settings:set": {
1745
+ access: "authenticated",
1746
+ handler: async (ctx) => {
1747
+ const key = ctx.args["key"];
1748
+ const value = requirePayload(ctx)["value"] ?? {};
1749
+ const existing = await tables.documents.get(["_settings_", key]);
1750
+ const doc = await newDoc("_settings_", {
1751
+ _id_: key,
1752
+ key,
1753
+ value
1754
+ });
1755
+ if (existing) doc._metadata_ = {
1756
+ ...existing._metadata_,
1757
+ updated: doc._metadata_.updated,
1758
+ version: existing._metadata_.version + 1
1759
+ };
1760
+ await tables.documents.put(doc);
1761
+ return ok(toDoc(key, value));
1762
+ }
1763
+ },
1764
+ "system:settings:delete": {
1765
+ access: "authenticated",
1766
+ handler: async (ctx) => {
1767
+ const key = ctx.args["key"];
1768
+ if (!await tables.documents.get(["_settings_", key])) throw err.notFound(`setting "${key}"`);
1769
+ await tables.documents.delete(["_settings_", key]);
1770
+ return noContent();
1771
+ }
1772
+ }
1773
+ };
1774
+ }
1775
+ //#endregion
1776
+ //#region src/server/handlers/policies.ts
1777
+ function policyHandlers(deps) {
1778
+ const { tables } = deps;
1779
+ const policyDoc = (raw) => ({
1780
+ operation: raw["operation"],
1781
+ key: raw["key"] ?? raw["operation"],
1782
+ rule: raw["rule"] ?? "",
1783
+ enabled: raw["enabled"] ?? true,
1784
+ protected: raw["protected"] ?? false,
1785
+ rateLimit: raw["rateLimit"],
1786
+ throttle: raw["throttle"]
1787
+ });
1788
+ return {
1789
+ "system:policies:policy:create": {
1790
+ access: "admin",
1791
+ handler: async (ctx) => {
1792
+ const name = ctx.args["name"];
1793
+ const payload = requirePayload(ctx);
1794
+ if (await findByOperation(name)) throw err.duplicate(`policy "${name}"`);
1795
+ const doc = await newDoc(POLICY_COLLECTION, {
1796
+ _id_: name,
1797
+ operation: name,
1798
+ key: name,
1799
+ rule: String(payload["rule"] ?? "authenticated"),
1800
+ enabled: true,
1801
+ protected: false,
1802
+ rateLimit: payload["rateLimit"] ?? null,
1803
+ throttle: payload["throttle"] ?? null
1804
+ });
1805
+ await putDoc(tables, doc);
1806
+ return ok(policyDoc(clone(doc)));
1807
+ }
1808
+ },
1809
+ "system:policies:policy:list": {
1810
+ access: "authenticated",
1811
+ handler: async () => {
1812
+ return ok({ policies: (await tables.documents.getAllByIndex("by_collection", POLICY_COLLECTION)).map(policyDoc) });
1813
+ }
1814
+ },
1815
+ "system:policies:policy:update": {
1816
+ access: "admin",
1817
+ handler: async (ctx) => {
1818
+ const name = ctx.args["name"];
1819
+ const current = await findByOperation(name);
1820
+ if (!current) throw err.notFound(`policy "${name}"`);
1821
+ const payload = requirePayload(ctx);
1822
+ const patch = {};
1823
+ for (const field of [
1824
+ "rule",
1825
+ "enabled",
1826
+ "rateLimit",
1827
+ "throttle"
1828
+ ]) if (payload[field] !== void 0) patch[field] = payload[field];
1829
+ const updated = await applyUpdate(current, patch);
1830
+ await putDoc(tables, updated);
1831
+ return ok(policyDoc(clone(updated)));
1832
+ }
1833
+ },
1834
+ "system:policies:rule:create": {
1835
+ access: "admin",
1836
+ handler: async (ctx) => {
1837
+ const name = ctx.args["name"];
1838
+ const payload = requirePayload(ctx);
1839
+ if (await tables.rules.get(name)) throw err.duplicate(`rule "${name}"`);
1840
+ const doc = {
1841
+ id: name,
1842
+ name,
1843
+ ruleType: String(payload["ruleType"] ?? "expression"),
1844
+ syntax: String(payload["syntax"] ?? "anansi-rule"),
1845
+ expression: payload["expression"] == null ? void 0 : String(payload["expression"]),
1846
+ rules: payload["rules"],
1847
+ description: payload["description"] == null ? "" : String(payload["description"]),
1848
+ protected: false,
1849
+ created_at: nowIso(),
1850
+ updated_at: nowIso()
1851
+ };
1852
+ await tables.rules.put(doc);
1853
+ return ok(clone(doc));
1854
+ }
1855
+ },
1856
+ "system:policies:rule:get": {
1857
+ access: "authenticated",
1858
+ handler: async (ctx) => {
1859
+ const doc = await tables.rules.get(ctx.args["name"]);
1860
+ if (!doc) throw err.notFound(`rule "${ctx.args["name"]}"`);
1861
+ return ok(clone(doc));
1862
+ }
1863
+ },
1864
+ "system:policies:rule:list": {
1865
+ access: "authenticated",
1866
+ handler: async () => {
1867
+ return ok({ rules: await tables.rules.getAll() });
1868
+ }
1869
+ },
1870
+ "system:policies:rule:update": {
1871
+ access: "admin",
1872
+ handler: async (ctx) => {
1873
+ const name = ctx.args["name"];
1874
+ const current = await tables.rules.get(name);
1875
+ if (!current) throw err.notFound(`rule "${name}"`);
1876
+ const payload = requirePayload(ctx);
1877
+ const updated = {
1878
+ ...current,
1879
+ ...payload,
1880
+ name,
1881
+ updated_at: nowIso()
1882
+ };
1883
+ await tables.rules.put(updated);
1884
+ return ok(clone(updated));
1885
+ }
1886
+ },
1887
+ "system:policies:rule:delete": {
1888
+ access: "admin",
1889
+ handler: async (ctx) => {
1890
+ const name = ctx.args["name"];
1891
+ const current = await tables.rules.get(name);
1892
+ if (!current) throw err.notFound(`rule "${name}"`);
1893
+ if (current["protected"]) throw err.denied("deleting a protected rule");
1894
+ await tables.rules.delete(name);
1895
+ return noContent();
1896
+ }
1897
+ },
1898
+ "system:policies:rule:validate": {
1899
+ access: "admin",
1900
+ handler: async (ctx) => {
1901
+ const rule = requirePayload(ctx)["rule"];
1902
+ if (rule == null) return ok({
1903
+ valid: false,
1904
+ error: "rule is required"
1905
+ });
1906
+ if (typeof rule === "boolean") return ok({
1907
+ valid: true,
1908
+ result: rule
1909
+ });
1910
+ if (rule === "true") return ok({
1911
+ valid: true,
1912
+ result: true
1913
+ });
1914
+ if (rule === "false") return ok({
1915
+ valid: true,
1916
+ result: false
1917
+ });
1918
+ return ok({
1919
+ valid: true,
1920
+ result: true,
1921
+ error: void 0
1922
+ });
1923
+ }
1924
+ },
1925
+ "system:policies:reload": {
1926
+ access: "admin",
1927
+ handler: async () => {
1928
+ return ok({
1929
+ operations: await tables.documents.count(),
1930
+ rules: await tables.rules.count()
1931
+ });
1932
+ }
1933
+ },
1934
+ "system:policies:binding:get": {
1935
+ access: "admin",
1936
+ handler: async (ctx) => {
1937
+ const doc = await findByOperation(ctx.args["name"]);
1938
+ if (!doc) throw err.notFound(`binding "${ctx.args["name"]}"`);
1939
+ return ok({
1940
+ operation: doc["operation"],
1941
+ rule: doc["rule"],
1942
+ enabled: doc["enabled"]
1943
+ });
1944
+ }
1945
+ },
1946
+ "system:policies:binding:list": {
1947
+ access: "admin",
1948
+ handler: async () => {
1949
+ return ok({ data: (await tables.documents.getAllByIndex("by_collection", POLICY_COLLECTION)).map((d) => ({
1950
+ operation: d["operation"],
1951
+ rule: d["rule"],
1952
+ enabled: d["enabled"]
1953
+ })) });
1954
+ }
1955
+ }
1956
+ };
1957
+ async function findByOperation(operation) {
1958
+ return await tables.documents.get([POLICY_COLLECTION, operation]);
1959
+ }
1960
+ }
1961
+ //#endregion
1962
+ //#region src/server/handlers/schedules.ts
1963
+ const SCHEDULES_COLLECTION = "_scheduled_messages_";
1964
+ function scheduleHandlers(deps) {
1965
+ const { tables } = deps;
1966
+ const collection = () => SCHEDULES_COLLECTION;
1967
+ return {
1968
+ "system:schedules:schedule:create": {
1969
+ access: "authenticated",
1970
+ handler: async (ctx) => {
1971
+ const payload = requirePayload(ctx);
1972
+ const message = String(payload["message"] ?? "");
1973
+ const cron = String(payload["cron"] ?? "");
1974
+ if (!message) throw err.required("message");
1975
+ if (!cron) throw err.required("cron");
1976
+ const doc = await newDoc(collection(), {
1977
+ user_id: String(payload["user_id"] ?? ctx.identity.user._id_),
1978
+ message,
1979
+ input: payload["input"] ?? {},
1980
+ cron,
1981
+ disabled: payload["disabled"] === true,
1982
+ tenant_id: ctx.identity.user["tenant_id"] ?? "root",
1983
+ created_at: Date.now()
1984
+ });
1985
+ await putDoc(tables, doc);
1986
+ return ok({ id: doc._id_ });
1987
+ }
1988
+ },
1989
+ "system:schedules:schedule:list": {
1990
+ access: "authenticated",
1991
+ handler: async (ctx) => {
1992
+ return ok((await tables.documents.getAllByIndex("by_collection", collection())).filter((s) => s["user_id"] === ctx.identity.user._id_ || ctx.identity.is_admin).map(clone));
1993
+ }
1994
+ },
1995
+ "system:schedules:schedule:all": {
1996
+ access: "admin",
1997
+ handler: async () => {
1998
+ return ok((await tables.documents.getAllByIndex("by_collection", collection())).map(clone));
1999
+ }
2000
+ },
2001
+ "system:schedules:schedule:get": {
2002
+ access: "authenticated",
2003
+ handler: async (ctx) => {
2004
+ return ok(clone(await requireDoc(tables, collection(), ctx.args["id"])));
2005
+ }
2006
+ },
2007
+ "system:schedules:schedule:update": {
2008
+ access: "authenticated",
2009
+ handler: async (ctx) => {
2010
+ const current = await requireDoc(tables, collection(), ctx.args["id"]);
2011
+ const payload = requirePayload(ctx);
2012
+ const patch = {};
2013
+ for (const field of [
2014
+ "message",
2015
+ "input",
2016
+ "cron",
2017
+ "disabled"
2018
+ ]) if (payload[field] !== void 0) patch[field] = payload[field];
2019
+ const updated = await applyUpdate(current, patch);
2020
+ await putDoc(tables, updated);
2021
+ return noContent();
2022
+ }
2023
+ },
2024
+ "system:schedules:schedule:delete": {
2025
+ access: "authenticated",
2026
+ handler: async (ctx) => {
2027
+ await requireDoc(tables, collection(), ctx.args["id"]);
2028
+ await tables.documents.delete([collection(), ctx.args["id"]]);
2029
+ return noContent();
2030
+ }
2031
+ }
2032
+ };
2033
+ }
2034
+ //#endregion
2035
+ //#region src/server/handlers/workflows.ts
2036
+ const WORKFLOW_COLLECTION = "_workflow_definitions_";
2037
+ const REGISTRY_NODES = [
2038
+ {
2039
+ kind: "trigger.event",
2040
+ label: "Event Trigger",
2041
+ type: "resource",
2042
+ description: "Starts a pipeline when an event arrives"
2043
+ },
2044
+ {
2045
+ kind: "trigger.cron",
2046
+ label: "Cron Trigger",
2047
+ type: "resource",
2048
+ description: "Starts a pipeline on a schedule"
2049
+ },
2050
+ {
2051
+ kind: "http.request",
2052
+ label: "HTTP Request",
2053
+ type: "executable",
2054
+ description: "Performs an HTTP request"
2055
+ },
2056
+ {
2057
+ kind: "log.message",
2058
+ label: "Log Message",
2059
+ type: "executable",
2060
+ description: "Writes a structured log line"
2061
+ },
2062
+ {
2063
+ kind: "data.transform",
2064
+ label: "Transform",
2065
+ type: "executable",
2066
+ description: "JQ-like state transformation"
2067
+ },
2068
+ {
2069
+ kind: "flow.condition",
2070
+ label: "Condition",
2071
+ type: "executable",
2072
+ description: "Branches pipeline execution"
2073
+ },
2074
+ {
2075
+ kind: "flow.end",
2076
+ label: "End",
2077
+ type: "executable",
2078
+ description: "Terminal node"
2079
+ }
2080
+ ];
2081
+ function workflowHandlers(deps) {
2082
+ const { tables } = deps;
2083
+ const emitEvent = async (event, persist = true) => {
2084
+ if (persist) await tables.run_events.put(event);
2085
+ deps.bus.emit(Topics.workflowRun(event.run_id), { data: event });
2086
+ };
2087
+ const countTriggers = (nodes) => nodes.filter((n) => {
2088
+ return String(n.data?.["kind"] ?? "").startsWith("trigger");
2089
+ }).length;
2090
+ return {
2091
+ "system:workflows:definition:compile": {
2092
+ access: "authenticated",
2093
+ handler: async (ctx) => {
2094
+ const payload = requirePayload(ctx);
2095
+ const nodes = payload["nodes"] ?? [];
2096
+ const edges = payload["edges"] ?? [];
2097
+ return ok({
2098
+ workflow_id: `wf_${uuid().slice(0, 8)}`,
2099
+ label: "adhoc",
2100
+ triggers: countTriggers(nodes),
2101
+ pipelines: edges.length > 0 ? 1 : nodes.length > 0 ? 1 : 0
2102
+ });
2103
+ }
2104
+ },
2105
+ "system:workflows:definition:create": {
2106
+ access: "authenticated",
2107
+ handler: async (ctx) => {
2108
+ const payload = requirePayload(ctx);
2109
+ const doc = await newDoc(WORKFLOW_COLLECTION, {
2110
+ name: String(payload["name"] ?? "workflow"),
2111
+ description: payload["description"] ?? "",
2112
+ nodes: payload["nodes"] ?? [],
2113
+ edges: payload["edges"] ?? [],
2114
+ tenant_id: ctx.identity.user["tenant_id"] ?? "root",
2115
+ created_at: Date.now(),
2116
+ updated_at: Date.now()
2117
+ });
2118
+ await tables.documents.put(doc);
2119
+ return ok({ id: doc._id_ });
2120
+ }
2121
+ },
2122
+ "system:workflows:definition:get": {
2123
+ access: "authenticated",
2124
+ handler: async (ctx) => {
2125
+ const doc = await tables.documents.get([WORKFLOW_COLLECTION, ctx.args["id"]]);
2126
+ if (!doc) throw err.notFound(`workflow definition "${ctx.args["id"]}"`);
2127
+ return ok(clone(doc));
2128
+ }
2129
+ },
2130
+ "system:workflows:definition:update": {
2131
+ access: "authenticated",
2132
+ handler: async (ctx) => {
2133
+ const id = ctx.args["id"];
2134
+ const current = await tables.documents.get([WORKFLOW_COLLECTION, id]);
2135
+ if (!current) throw err.notFound(`workflow definition "${id}"`);
2136
+ const payload = requirePayload(ctx);
2137
+ const updated = {
2138
+ ...current,
2139
+ ...payload,
2140
+ updated_at: Date.now()
2141
+ };
2142
+ await tables.documents.put(updated);
2143
+ return noContent();
2144
+ }
2145
+ },
2146
+ "system:workflows:definition:delete": {
2147
+ access: "authenticated",
2148
+ handler: async (ctx) => {
2149
+ const id = ctx.args["id"];
2150
+ if (!await tables.documents.get(["_workflow_definitions_", id])) throw err.notFound(`workflow definition "${id}"`);
2151
+ await tables.documents.delete([WORKFLOW_COLLECTION, id]);
2152
+ return noContent();
2153
+ }
2154
+ },
2155
+ "system:workflows:definition:list": {
2156
+ access: "authenticated",
2157
+ handler: async () => {
2158
+ return ok((await tables.documents.getAllByIndex("by_collection", WORKFLOW_COLLECTION)).map(clone));
2159
+ }
2160
+ },
2161
+ "system:workflows:runtime:run": {
2162
+ access: "authenticated",
2163
+ handler: async (ctx) => {
2164
+ const payload = requirePayload(ctx);
2165
+ return ok({ run_id: await startRun(deps, emitEvent, {
2166
+ nodes: payload["nodes"] ?? [],
2167
+ label: "adhoc"
2168
+ }) });
2169
+ }
2170
+ },
2171
+ "system:workflows:runtime:invoke": {
2172
+ access: "authenticated",
2173
+ handler: async (ctx) => {
2174
+ const payload = requirePayload(ctx);
2175
+ const workflowId = String(payload["workflow_id"] ?? "");
2176
+ const doc = await tables.documents.get([WORKFLOW_COLLECTION, workflowId]);
2177
+ if (!doc) throw err.notFound(`workflow definition "${workflowId}"`);
2178
+ return ok({
2179
+ run_id: await startRun(deps, emitEvent, {
2180
+ nodes: doc["nodes"] ?? [],
2181
+ label: String(doc["name"] ?? workflowId)
2182
+ }),
2183
+ status: "recording",
2184
+ ok: true
2185
+ });
2186
+ }
2187
+ },
2188
+ "system:workflows:runtime:resume": {
2189
+ access: "authenticated",
2190
+ handler: async (ctx) => {
2191
+ const payload = requirePayload(ctx);
2192
+ const runId = String(payload["run_id"] ?? "");
2193
+ const run = await tables.runs.get(runId);
2194
+ if (!run) throw err.notFound(`run "${runId}"`);
2195
+ if (run.status !== "paused") return ok({
2196
+ run_id: runId,
2197
+ status: run.status,
2198
+ ok: false,
2199
+ error: "run is not paused"
2200
+ });
2201
+ run.status = "recording";
2202
+ await tables.runs.put(run);
2203
+ if (deps.options.executeWorkflows !== false) executeRun(deps, run, emitEvent);
2204
+ return ok({
2205
+ run_id: runId,
2206
+ status: "recording",
2207
+ ok: true
2208
+ });
2209
+ }
2210
+ },
2211
+ "system:workflows:runtime:events": {
2212
+ access: "authenticated",
2213
+ handler: async (ctx) => {
2214
+ const payload = requirePayload(ctx);
2215
+ await emitEvent({
2216
+ run_id: `external_${uuid().slice(0, 8)}`,
2217
+ seq: Date.now(),
2218
+ timestamp: Date.now(),
2219
+ source: "api",
2220
+ type: String(payload["type"] ?? "event"),
2221
+ payload: payload["payload"] ?? {}
2222
+ }, false);
2223
+ return noContent();
2224
+ }
2225
+ },
2226
+ "system:workflows:runtime:abort": {
2227
+ access: "authenticated",
2228
+ handler: async (ctx) => {
2229
+ const runId = ctx.args["run_id"];
2230
+ const run = await tables.runs.get(runId);
2231
+ if (!run) throw err.notFound(`run "${runId}"`);
2232
+ run.status = "failed";
2233
+ run.end_time = Date.now();
2234
+ run.error = "aborted by client";
2235
+ await tables.runs.put(run);
2236
+ await emitEvent({
2237
+ run_id: runId,
2238
+ seq: run.event_count + 1,
2239
+ timestamp: Date.now(),
2240
+ source: "runtime",
2241
+ type: "pipeline:failure",
2242
+ payload: { error: "aborted by client" }
2243
+ });
2244
+ return noContent();
2245
+ }
2246
+ },
2247
+ "system:workflows:runtime:has": {
2248
+ access: "authenticated",
2249
+ handler: async (ctx) => {
2250
+ return ok({ has: !!await tables.documents.get([WORKFLOW_COLLECTION, ctx.args["id"]]) });
2251
+ }
2252
+ },
2253
+ "system:workflows:runtime:list": {
2254
+ access: "authenticated",
2255
+ handler: async () => {
2256
+ return ok({ workflow_ids: (await tables.documents.getAllByIndex("by_collection", WORKFLOW_COLLECTION)).map((d) => d._id_) });
2257
+ }
2258
+ },
2259
+ "system:workflows:run:list": {
2260
+ access: "authenticated",
2261
+ handler: async () => {
2262
+ return ok((await tables.runs.getAll()).map(publicRun));
2263
+ }
2264
+ },
2265
+ "system:workflows:run:get": {
2266
+ access: "authenticated",
2267
+ handler: async (ctx) => {
2268
+ const run = await tables.runs.get(ctx.args["run_id"]);
2269
+ if (!run) throw err.notFound(`run "${ctx.args["run_id"]}"`);
2270
+ return ok(publicRun(run));
2271
+ }
2272
+ },
2273
+ "system:workflows:run:outcome": {
2274
+ access: "authenticated",
2275
+ handler: async (ctx) => {
2276
+ const run = await tables.runs.get(ctx.args["run_id"]);
2277
+ if (!run) throw err.notFound(`run "${ctx.args["run_id"]}"`);
2278
+ return ok({
2279
+ ok: run.status === "complete",
2280
+ run_id: run.run_id,
2281
+ status: run.status,
2282
+ final_state: run.final_state ?? {},
2283
+ error: run.error
2284
+ });
2285
+ }
2286
+ },
2287
+ "system:workflows:run:events": {
2288
+ access: "authenticated",
2289
+ handler: async (ctx) => {
2290
+ return ok({ events: (await tables.run_events.getAllByIndex("by_run", ctx.args["run_id"])).sort((a, b) => a.seq - b.seq) });
2291
+ }
2292
+ },
2293
+ "system:workflows:run:store": {
2294
+ access: "authenticated",
2295
+ handler: async (ctx) => {
2296
+ const run = await tables.runs.get(ctx.args["run_id"]);
2297
+ if (!run) throw err.notFound(`run "${ctx.args["run_id"]}"`);
2298
+ return ok({ state: run.final_state ?? {} });
2299
+ }
2300
+ },
2301
+ "system:workflows:registry:list": {
2302
+ access: "authenticated",
2303
+ handler: async () => ok({ nodes: REGISTRY_NODES })
2304
+ },
2305
+ "system:workflows:registry:get": {
2306
+ access: "authenticated",
2307
+ handler: async (ctx) => {
2308
+ const node = REGISTRY_NODES.find((n) => n.kind === ctx.args["kind"]);
2309
+ if (!node) throw err.notFound(`node kind "${ctx.args["kind"]}"`);
2310
+ return ok(node);
2311
+ }
2312
+ },
2313
+ "system:workflows:registry:handles": {
2314
+ access: "authenticated",
2315
+ handler: async () => ok({ code: "({})" })
2316
+ }
2317
+ };
2318
+ }
2319
+ function publicRun(run) {
2320
+ return {
2321
+ run_id: run.run_id,
2322
+ pipeline_id: run.pipeline_id,
2323
+ start_time: run.start_time,
2324
+ end_time: run.end_time,
2325
+ event_count: run.event_count,
2326
+ status: run.status,
2327
+ metadata: run.metadata
2328
+ };
2329
+ }
2330
+ async function startRun(deps, emitEvent, spec) {
2331
+ const { tables } = deps;
2332
+ const runId = `run_${uuid().slice(0, 12)}`;
2333
+ const run = {
2334
+ run_id: runId,
2335
+ pipeline_id: spec.label,
2336
+ start_time: Date.now(),
2337
+ event_count: 0,
2338
+ status: "recording",
2339
+ final_state: {}
2340
+ };
2341
+ await tables.runs.put(run);
2342
+ if (deps.options.executeWorkflows !== false) executeRun(deps, run, emitEvent, spec.nodes);
2343
+ return runId;
2344
+ }
2345
+ /** Stub executor: one timeline event per node, then settle. */
2346
+ async function executeRun(deps, run, emitEvent, nodes = []) {
2347
+ await sleep(5);
2348
+ let seq = 0;
2349
+ try {
2350
+ await emitEvent({
2351
+ run_id: run.run_id,
2352
+ seq: ++seq,
2353
+ timestamp: Date.now(),
2354
+ source: "runtime",
2355
+ type: "pipeline:started",
2356
+ payload: {}
2357
+ });
2358
+ for (const [index, node] of nodes.entries()) {
2359
+ const n = node;
2360
+ const kind = String(n.data?.["kind"] ?? "node");
2361
+ await emitEvent({
2362
+ run_id: run.run_id,
2363
+ seq: ++seq,
2364
+ timestamp: Date.now(),
2365
+ source: String(n.id ?? `node_${index}`),
2366
+ type: `${kind}:success`,
2367
+ payload: {
2368
+ index,
2369
+ label: String(n.data?.["label"] ?? kind)
2370
+ },
2371
+ delta: {}
2372
+ });
2373
+ if (run.status === "failed") return;
2374
+ }
2375
+ await emitEvent({
2376
+ run_id: run.run_id,
2377
+ seq: ++seq,
2378
+ timestamp: Date.now(),
2379
+ source: "runtime",
2380
+ type: "pipeline:success",
2381
+ payload: {}
2382
+ });
2383
+ run.status = "complete";
2384
+ run.end_time = Date.now();
2385
+ run.event_count = seq;
2386
+ await deps.tables.runs.put(run);
2387
+ } catch (error) {
2388
+ run.status = "failed";
2389
+ run.end_time = Date.now();
2390
+ run.error = String(error);
2391
+ await deps.tables.runs.put(run);
2392
+ await emitEvent({
2393
+ run_id: run.run_id,
2394
+ seq: ++seq,
2395
+ timestamp: Date.now(),
2396
+ source: "runtime",
2397
+ type: "pipeline:failure",
2398
+ payload: { error: String(error) }
2399
+ });
2400
+ }
2401
+ }
2402
+ //#endregion
2403
+ //#region src/server/handlers/updates.ts
2404
+ async function getUpdateState(deps) {
2405
+ return (await deps.tables.kv.get("update_state"))?.v ?? {
2406
+ staged_version: "",
2407
+ prepared: false,
2408
+ last_check: 0
2409
+ };
2410
+ }
2411
+ async function putUpdateState(deps, state) {
2412
+ await deps.tables.kv.put({
2413
+ k: "update_state",
2414
+ v: state
2415
+ });
2416
+ }
2417
+ function updateHandlers(deps) {
2418
+ const version = () => deps.options.serverVersion ?? "1.0.1-mock";
2419
+ return {
2420
+ "system:updates:status:get": {
2421
+ access: "admin",
2422
+ handler: async () => {
2423
+ const state = await getUpdateState(deps);
2424
+ return ok({
2425
+ version: version(),
2426
+ staged_version: state.staged_version,
2427
+ prepared: state.prepared,
2428
+ last_check: state.last_check
2429
+ });
2430
+ }
2431
+ },
2432
+ "system:updates:changelog:get": {
2433
+ access: "admin",
2434
+ handler: async () => {
2435
+ const state = await getUpdateState(deps);
2436
+ if (!state.staged_version) throw err.notFound("no staged update changelog");
2437
+ return ok({
2438
+ version: state.staged_version,
2439
+ asset_name: `hestia-${state.staged_version}.tar.gz`,
2440
+ changelog: `# ${state.staged_version}\n\nMock release notes.`
2441
+ });
2442
+ }
2443
+ },
2444
+ "system:updates:check:get": {
2445
+ access: "admin",
2446
+ handler: async () => {
2447
+ const available = deps.options.updateAvailable ?? null;
2448
+ return ok({
2449
+ available: !!available,
2450
+ version: available ?? version()
2451
+ });
2452
+ }
2453
+ },
2454
+ "system:updates:check:create": {
2455
+ access: "admin",
2456
+ handler: async () => {
2457
+ const available = deps.options.updateAvailable ?? null;
2458
+ const state = await getUpdateState(deps);
2459
+ state.last_check = Date.now();
2460
+ let staged = false;
2461
+ if (available) {
2462
+ state.staged_version = available;
2463
+ state.prepared = true;
2464
+ staged = true;
2465
+ }
2466
+ await putUpdateState(deps, state);
2467
+ return ok({
2468
+ checked: true,
2469
+ staged,
2470
+ version: available ?? version(),
2471
+ auto_apply: false
2472
+ });
2473
+ }
2474
+ },
2475
+ "system:updates:stage:create": {
2476
+ access: "admin",
2477
+ handler: async () => {
2478
+ const available = deps.options.updateAvailable ?? null;
2479
+ const state = await getUpdateState(deps);
2480
+ if (!available) {
2481
+ await putUpdateState(deps, {
2482
+ ...state,
2483
+ last_check: Date.now()
2484
+ });
2485
+ return ok({
2486
+ staged: false,
2487
+ version: version()
2488
+ });
2489
+ }
2490
+ state.staged_version = available;
2491
+ state.prepared = true;
2492
+ state.last_check = Date.now();
2493
+ await putUpdateState(deps, state);
2494
+ return ok({
2495
+ staged: true,
2496
+ version: available
2497
+ });
2498
+ }
2499
+ },
2500
+ "system:updates:update:apply": {
2501
+ access: "admin",
2502
+ handler: async () => {
2503
+ const state = await getUpdateState(deps);
2504
+ if (!state.staged_version || !state.prepared) throw err.validation("no staged update to apply");
2505
+ return ok({ message: `update to ${state.staged_version} prepared; restart required` });
2506
+ }
2507
+ },
2508
+ "system:updates:update:discard": {
2509
+ access: "admin",
2510
+ handler: async () => {
2511
+ await putUpdateState(deps, {
2512
+ staged_version: "",
2513
+ prepared: false,
2514
+ last_check: Date.now()
2515
+ });
2516
+ return noContent();
2517
+ }
2518
+ }
2519
+ };
2520
+ }
2521
+ function logHandlers(deps) {
2522
+ return {
2523
+ "system:logs:list": {
2524
+ access: "admin",
2525
+ noAudit: true,
2526
+ handler: async (ctx) => {
2527
+ const q = ctx.payload ?? {};
2528
+ let entries = await deps.tables.logs.getAll();
2529
+ if (q.level) entries = entries.filter((e) => e.level === q.level);
2530
+ if (q.from) entries = entries.filter((e) => e.ts >= Date.parse(q.from));
2531
+ if (q.to) entries = entries.filter((e) => e.ts <= Date.parse(q.to));
2532
+ if (q.search) {
2533
+ const needle = q.search.toLowerCase();
2534
+ entries = entries.filter((e) => (e.msg ?? "").toLowerCase().includes(needle));
2535
+ }
2536
+ entries.sort((a, b) => b.ts - a.ts);
2537
+ const offset = Math.max(0, q.offset ?? 0);
2538
+ const limit = Math.max(1, q.limit ?? 100);
2539
+ return ok({
2540
+ entries: entries.slice(offset, offset + limit),
2541
+ total: entries.length,
2542
+ has_more: offset + limit < entries.length
2543
+ });
2544
+ }
2545
+ },
2546
+ "system:scheduler:job:list": {
2547
+ access: "authenticated",
2548
+ handler: async () => {
2549
+ return ok({ data: (await deps.tables.documents.getAllByIndex("by_collection", "_scheduled_messages_")).filter((s) => !s["disabled"]).map((s) => ({
2550
+ id: s["_id_"],
2551
+ message: s["message"],
2552
+ cron: s["cron"],
2553
+ next_run: null
2554
+ })) });
2555
+ }
2556
+ }
2557
+ };
2558
+ }
2559
+ //#endregion
2560
+ //#region src/server/handlers/blobs.ts
2561
+ function publicMeta(record) {
2562
+ return { ...record.meta };
2563
+ }
2564
+ function blobHandlers(deps) {
2565
+ const { tables } = deps;
2566
+ const requireNamespace = async (ns) => {
2567
+ const record = await tables.namespaces.get(ns);
2568
+ if (!record) throw err.blobNotFound(`namespace "${ns}"`);
2569
+ return record;
2570
+ };
2571
+ const parseSession = async (ctx) => {
2572
+ const sessionId = header(ctx, "X-Session-ID") ?? modifier(ctx, "session_id") ?? "";
2573
+ if (!sessionId) throw err.required("X-Session-ID");
2574
+ const session = await tables.upload_sessions.get(sessionId);
2575
+ if (!session) throw err.blobNotFound(`upload session "${sessionId}"`);
2576
+ return session;
2577
+ };
2578
+ return {
2579
+ "system:blobs:namespace:create": {
2580
+ access: "authenticated",
2581
+ handler: async (ctx) => {
2582
+ const ns = ctx.args["ns"];
2583
+ if (!ns) throw err.required("ns");
2584
+ if (await tables.namespaces.get(ns)) throw err.duplicate(`namespace "${ns}"`);
2585
+ const payload = ctx.payload ?? {};
2586
+ const record = {
2587
+ ns,
2588
+ id: ns,
2589
+ display_name: String(payload["display_name"] ?? ns),
2590
+ custom: payload["custom"] ?? {},
2591
+ created_at: nowIso()
2592
+ };
2593
+ await tables.namespaces.put(record);
2594
+ return ok(clone(record));
2595
+ }
2596
+ },
2597
+ "system:blobs:namespace:list": {
2598
+ access: "authenticated",
2599
+ handler: async () => {
2600
+ return ok({ namespaces: (await tables.namespaces.getAll()).map((r) => ({
2601
+ id: r.id,
2602
+ display_name: r.display_name,
2603
+ custom: r.custom
2604
+ })) });
2605
+ }
2606
+ },
2607
+ "system:blobs:namespace:delete": {
2608
+ access: "authenticated",
2609
+ handler: async (ctx) => {
2610
+ const ns = ctx.args["ns"];
2611
+ await requireNamespace(ns);
2612
+ await tables.namespaces.delete(ns);
2613
+ const blobs = await tables.blobs.getAllByIndex("by_ns", ns);
2614
+ for (const blob of blobs) await tables.blobs.delete([ns, blob.key]);
2615
+ return noContent();
2616
+ }
2617
+ },
2618
+ "system:blobs:namespace:stats": {
2619
+ access: "authenticated",
2620
+ handler: async (ctx) => {
2621
+ const ns = ctx.args["ns"];
2622
+ await requireNamespace(ns);
2623
+ const blobs = await tables.blobs.getAllByIndex("by_ns", ns);
2624
+ const bytes = blobs.reduce((sum, b) => sum + (b.meta.size ?? 0), 0);
2625
+ return ok({
2626
+ namespace_id: ns,
2627
+ blob_count: blobs.length,
2628
+ bytes_stored: bytes,
2629
+ bytes_physical: bytes,
2630
+ chunk_count: blobs.length,
2631
+ dead_bytes: 0,
2632
+ dead_chunks: 0,
2633
+ segment_count: Math.max(1, blobs.length)
2634
+ });
2635
+ }
2636
+ },
2637
+ "system:blobs:namespace:verify": {
2638
+ access: "authenticated",
2639
+ handler: async (ctx) => {
2640
+ await requireNamespace(ctx.args["ns"]);
2641
+ return noContent();
2642
+ }
2643
+ },
2644
+ "system:blobs:namespace:compact": {
2645
+ access: "authenticated",
2646
+ handler: async (ctx) => {
2647
+ await requireNamespace(ctx.args["ns"]);
2648
+ return ok({
2649
+ blobs_removed: 0,
2650
+ chunks_removed: 0,
2651
+ bytes_freed: 0,
2652
+ segments_compacted: 0
2653
+ });
2654
+ }
2655
+ },
2656
+ "system:blobs:blob:upload": {
2657
+ access: "authenticated",
2658
+ handler: async (ctx) => {
2659
+ const { ns, key } = ctx.args;
2660
+ await requireNamespace(ns);
2661
+ if (!isBinary(ctx.payload)) throw err.validation("expected a binary upload body");
2662
+ const overwrite = modifier(ctx, "overwrite") === "true";
2663
+ const existing = await tables.blobs.get([ns, key]);
2664
+ if (existing && !overwrite) throw err.duplicate(`blob "${ns}/${key}"`);
2665
+ const data = await toBytes(ctx.payload);
2666
+ const contentType = header(ctx, "Content-Type") ?? "application/octet-stream";
2667
+ const now = nowIso();
2668
+ const record = {
2669
+ ns,
2670
+ key,
2671
+ meta: {
2672
+ key,
2673
+ namespace_id: ns,
2674
+ content_type: contentType,
2675
+ size: data.byteLength,
2676
+ created_at: existing?.meta.created_at ?? now,
2677
+ updated_at: existing ? now : void 0
2678
+ },
2679
+ data
2680
+ };
2681
+ await tables.blobs.put(record);
2682
+ return ok(publicMeta(record));
2683
+ }
2684
+ },
2685
+ "system:blobs:blob:begin": {
2686
+ access: "authenticated",
2687
+ handler: async (ctx) => {
2688
+ const ns = ctx.args["ns"];
2689
+ await requireNamespace(ns);
2690
+ const payload = requirePayload(ctx);
2691
+ const key = String(payload["key"] ?? "");
2692
+ if (!key) throw err.required("key");
2693
+ const size = Number(payload["size"] ?? 0);
2694
+ if (!Number.isFinite(size) || size <= 0) throw err.validation("size must be a positive number");
2695
+ const existing = await tables.blobs.get([ns, key]);
2696
+ const overwrite = modifier(ctx, "overwrite") === "true";
2697
+ if (existing && !overwrite) throw err.duplicate(`blob "${ns}/${key}"`);
2698
+ const session = {
2699
+ session_id: randomToken("hst_upl"),
2700
+ ns,
2701
+ key,
2702
+ expected_size: size,
2703
+ content_type: String(payload["content_type"] ?? "application/octet-stream"),
2704
+ block_size: Number(payload["block_size"] ?? 8 * 1024 * 1024),
2705
+ overwrite,
2706
+ chunks: [],
2707
+ received: 0,
2708
+ created_at: Date.now()
2709
+ };
2710
+ await tables.upload_sessions.put(session);
2711
+ return ok({
2712
+ session_id: session.session_id,
2713
+ key,
2714
+ offset: 0,
2715
+ block_size: session.block_size
2716
+ });
2717
+ }
2718
+ },
2719
+ "system:blobs:blob:chunk": {
2720
+ access: "authenticated",
2721
+ handler: async (ctx) => {
2722
+ const ns = ctx.args["ns"];
2723
+ const session = await parseSession(ctx);
2724
+ if (session.ns !== ns) throw err.validation("upload session namespace mismatch");
2725
+ if (!isBinary(ctx.payload)) throw err.validation("expected a binary chunk body");
2726
+ const offset = Number(header(ctx, "X-Offset") ?? "0");
2727
+ if (!Number.isFinite(offset) || offset < 0) throw err.validation("X-Offset must be a non-negative number");
2728
+ const data = await toBytes(ctx.payload);
2729
+ session.chunks.push({
2730
+ offset,
2731
+ data
2732
+ });
2733
+ session.received += data.byteLength;
2734
+ await tables.upload_sessions.put(session);
2735
+ return ok({ total: session.received });
2736
+ }
2737
+ },
2738
+ "system:blobs:blob:progress": {
2739
+ access: "authenticated",
2740
+ handler: async (ctx) => {
2741
+ const session = await parseSession(ctx);
2742
+ const ranges = session.chunks.sort((a, b) => a.offset - b.offset).map((c) => ({
2743
+ start: c.offset,
2744
+ end: c.offset + c.data.byteLength
2745
+ }));
2746
+ return ok({
2747
+ total: session.received,
2748
+ ranges,
2749
+ block_size: session.block_size,
2750
+ expected_size: session.expected_size
2751
+ });
2752
+ }
2753
+ },
2754
+ "system:blobs:blob:complete": {
2755
+ access: "authenticated",
2756
+ handler: async (ctx) => {
2757
+ const ns = ctx.args["ns"];
2758
+ const session = await parseSession(ctx);
2759
+ if (session.ns !== ns) throw err.validation("upload session namespace mismatch");
2760
+ session.chunks.sort((a, b) => a.offset - b.offset);
2761
+ const totalLength = session.chunks.reduce((max, c) => Math.max(max, c.offset + c.data.byteLength), 0);
2762
+ const assembled = new Uint8Array(totalLength);
2763
+ for (const chunk of session.chunks) assembled.set(chunk.data, chunk.offset);
2764
+ const now = nowIso();
2765
+ const existing = await tables.blobs.get([ns, session.key]);
2766
+ const record = {
2767
+ ns,
2768
+ key: session.key,
2769
+ meta: {
2770
+ key: session.key,
2771
+ namespace_id: ns,
2772
+ content_type: session.content_type,
2773
+ size: assembled.byteLength,
2774
+ created_at: existing?.meta.created_at ?? now,
2775
+ updated_at: existing ? now : void 0
2776
+ },
2777
+ data: assembled
2778
+ };
2779
+ await tables.blobs.put(record);
2780
+ await tables.upload_sessions.delete(session.session_id);
2781
+ return ok(publicMeta(record));
2782
+ }
2783
+ },
2784
+ "system:blobs:blob:abort": {
2785
+ access: "authenticated",
2786
+ handler: async (ctx) => {
2787
+ const session = await parseSession(ctx);
2788
+ await tables.upload_sessions.delete(session.session_id);
2789
+ return noContent();
2790
+ }
2791
+ },
2792
+ "system:blobs:blob:head": {
2793
+ access: "authenticated",
2794
+ handler: async (ctx) => {
2795
+ const { ns, key } = ctx.args;
2796
+ await requireNamespace(ns);
2797
+ const record = await tables.blobs.get([ns, key]);
2798
+ if (!record) throw err.blobNotFound(`blob "${ns}/${key}"`);
2799
+ return ok(publicMeta(record));
2800
+ }
2801
+ },
2802
+ "system:blobs:blob:download": {
2803
+ access: "authenticated",
2804
+ handler: async (ctx) => {
2805
+ const { ns, key } = ctx.args;
2806
+ await requireNamespace(ns);
2807
+ const record = await tables.blobs.get([ns, key]);
2808
+ if (!record) throw err.blobNotFound(`blob "${ns}/${key}"`);
2809
+ return {
2810
+ status: 200,
2811
+ body: {
2812
+ data: new Uint8Array(record.data),
2813
+ metadata: {
2814
+ timestamp: nowIso(),
2815
+ request: ctx.request_id,
2816
+ content_type: record.meta.content_type
2817
+ }
2818
+ }
2819
+ };
2820
+ }
2821
+ },
2822
+ "system:blobs:blob:list": {
2823
+ access: "authenticated",
2824
+ handler: async (ctx) => {
2825
+ const ns = ctx.args["ns"];
2826
+ await requireNamespace(ns);
2827
+ const payload = ctx.payload ?? {};
2828
+ let blobs = await tables.blobs.getAllByIndex("by_ns", ns);
2829
+ if (payload.prefix) blobs = blobs.filter((b) => b.key.startsWith(payload.prefix));
2830
+ if (payload.limit) blobs = blobs.slice(0, payload.limit);
2831
+ return ok({ blobs: blobs.map(publicMeta) });
2832
+ }
2833
+ },
2834
+ "system:blobs:blob:rename": {
2835
+ access: "authenticated",
2836
+ handler: async (ctx) => {
2837
+ const { ns, key } = ctx.args;
2838
+ const payload = requirePayload(ctx);
2839
+ const newKey = String(payload["new_key"] ?? "");
2840
+ if (!newKey) throw err.required("new_key");
2841
+ const record = await tables.blobs.get([ns, key]);
2842
+ if (!record) throw err.blobNotFound(`blob "${ns}/${key}"`);
2843
+ if (await tables.blobs.get([ns, newKey])) throw err.duplicate(`blob "${ns}/${newKey}"`);
2844
+ await tables.blobs.delete([ns, key]);
2845
+ await tables.blobs.put({
2846
+ ...record,
2847
+ key: newKey,
2848
+ meta: {
2849
+ ...record.meta,
2850
+ key: newKey,
2851
+ updated_at: nowIso()
2852
+ }
2853
+ });
2854
+ return noContent();
2855
+ }
2856
+ },
2857
+ "system:blobs:blob:update": {
2858
+ access: "authenticated",
2859
+ handler: async (ctx) => {
2860
+ const { ns, key } = ctx.args;
2861
+ const payload = requirePayload(ctx);
2862
+ const record = await tables.blobs.get([ns, key]);
2863
+ if (!record) throw err.blobNotFound(`blob "${ns}/${key}"`);
2864
+ if (payload["custom"] !== void 0) {
2865
+ record.meta.custom = payload["custom"];
2866
+ record.meta.updated_at = nowIso();
2867
+ await tables.blobs.put(record);
2868
+ }
2869
+ return ok(publicMeta(record));
2870
+ }
2871
+ },
2872
+ "system:blobs:blob:delete": {
2873
+ access: "authenticated",
2874
+ handler: async (ctx) => {
2875
+ const { ns, key } = ctx.args;
2876
+ if (!await tables.blobs.get([ns, key])) throw err.blobNotFound(`blob "${ns}/${key}"`);
2877
+ await tables.blobs.delete([ns, key]);
2878
+ return noContent();
2879
+ }
2880
+ }
2881
+ };
2882
+ }
2883
+ //#endregion
2884
+ //#region src/server/server.ts
2885
+ /**
2886
+ * MockHestiaServer — the IndexedDB-backed emulation of the Hestia backend.
2887
+ *
2888
+ * Responsibilities:
2889
+ * - route every `system:*` handler name to its handler with the correct
2890
+ * access level (public / authenticated / admin)
2891
+ * - resolve the caller identity (session token or X-API-Key)
2892
+ * - wrap results in the server envelope (`{data, metadata}`)
2893
+ * - write an audit-trail entry for every audited dispatch
2894
+ * - emit realtime events on the internal bus (SSE substitute)
2895
+ */
2896
+ var MockHestiaServer = class MockHestiaServer {
2897
+ tables;
2898
+ bus;
2899
+ options;
2900
+ databaseName;
2901
+ db;
2902
+ routes;
2903
+ booted;
2904
+ schedulerTimer = null;
2905
+ constructor(db, tables, bus, options) {
2906
+ this.db = db;
2907
+ this.tables = tables;
2908
+ this.bus = bus;
2909
+ this.options = options;
2910
+ this.databaseName = db.name;
2911
+ this.routes = /* @__PURE__ */ new Map();
2912
+ this.booted = Promise.resolve();
2913
+ }
2914
+ /** Open (or attach to) the database, seed on first run, and wire routes. */
2915
+ static async create(config = {}) {
2916
+ const { db, tables } = await openMockDatabase(config.database);
2917
+ const bus = new EventBus();
2918
+ const server = new MockHestiaServer(db, tables, bus, config.options ?? {});
2919
+ if (config.reset) await wipeAllStores(db);
2920
+ const deps = server.buildDeps();
2921
+ server.routes = server.buildRoutes(deps);
2922
+ await seedDatabase(tables, (config.seed === false ? null : config.seed ?? DEFAULT_SEED) ?? DEFAULT_SEED);
2923
+ server.booted = Promise.resolve();
2924
+ server.startScheduler();
2925
+ return server;
2926
+ }
2927
+ ready() {
2928
+ return this.booted;
2929
+ }
2930
+ /** Dispatch a named route — the heart of the mock server. */
2931
+ async dispatch(route, input = {}) {
2932
+ await this.ready();
2933
+ const entry = this.routes.get(route);
2934
+ if (!entry) throw err.routeNotFound(route);
2935
+ const ctx = {
2936
+ route,
2937
+ args: input.arguments ?? {},
2938
+ modifiers: input.modifiers ?? {},
2939
+ payload: input.payload,
2940
+ headers: input.headers ?? {},
2941
+ identity: null,
2942
+ request_id: uuid()
2943
+ };
2944
+ ctx.identity = await resolveIdentity(this.tables, ctx);
2945
+ checkAccess(entry.access ?? "authenticated", ctx.identity);
2946
+ const started = Date.now();
2947
+ let response;
2948
+ let failure = null;
2949
+ try {
2950
+ response = await entry.handler(ctx);
2951
+ } catch (error) {
2952
+ failure = error;
2953
+ throw error;
2954
+ } finally {
2955
+ if (!entry.noAudit) try {
2956
+ await this.writeAuditEntry(ctx, started, failure);
2957
+ } catch {}
2958
+ }
2959
+ return response;
2960
+ }
2961
+ /** Resolve the user id of the persisted current session (used by streams). */
2962
+ async currentUserId() {
2963
+ return (await resolveIdentity(this.tables, { headers: {} }))?.user._id_ ?? null;
2964
+ }
2965
+ /** Fire a schedule manually (the mock has no cron daemon). */
2966
+ async fireSchedule(scheduleId) {
2967
+ const doc = await this.tables.documents.get(["_scheduled_messages_", scheduleId]);
2968
+ if (!doc || doc["disabled"]) return;
2969
+ const message = String(doc["message"] ?? "");
2970
+ if (!message) return;
2971
+ const input = JSON.parse(JSON.stringify(doc["input"] ?? {}).replaceAll("{{ .schedule._id }}", String(doc["_id_"])).replaceAll("{{ .now }}", (/* @__PURE__ */ new Date()).toISOString()));
2972
+ try {
2973
+ await this.dispatch(message, { payload: input });
2974
+ await this.pushLog({
2975
+ level: "info",
2976
+ msg: `schedule ${scheduleId} dispatched ${message}`
2977
+ });
2978
+ } catch (error) {
2979
+ await this.pushLog({
2980
+ level: "error",
2981
+ msg: `schedule ${scheduleId} failed: ${String(error)}`
2982
+ });
2983
+ }
2984
+ }
2985
+ /** Push an application log entry (visible to `appLogs.query`). */
2986
+ async pushLog(entry) {
2987
+ const record = {
2988
+ id: uuid(),
2989
+ level: entry.level,
2990
+ ts: Date.now(),
2991
+ caller: entry.caller ?? "mock",
2992
+ msg: entry.msg,
2993
+ ...entry.fields
2994
+ };
2995
+ await this.tables.logs.put(record);
2996
+ this.bus.emit(Topics.logs(), { data: record });
2997
+ this.bus.emit(Topics.logs(entry.level), { data: record });
2998
+ }
2999
+ /** Manually write an audit entry (tests / custom instrumentation). */
3000
+ async writeAuditEntry(ctx, startedAt, failure) {
3001
+ const latency = Date.now() - startedAt;
3002
+ const segments = ctx.route.split(":");
3003
+ const action = segments[segments.length - 1] ?? "other";
3004
+ const module = segments[1] ?? "system";
3005
+ let operation;
3006
+ if (module === "auth" && action === "create") operation = "login";
3007
+ else if (module === "auth" && action === "delete") operation = "logout";
3008
+ else if (action === "create") operation = "create";
3009
+ else if (action === "delete") operation = "delete";
3010
+ else if (action === "update" || action === "set") operation = "update";
3011
+ else if (/^(get|list|query|stream|check|head|progress|status|has)$/.test(action)) operation = "read";
3012
+ else if (/^(rotate|elevate|apply|run|invoke|resume|reload|validate|upload|compile|dispatch|abort|export)$/.test(action)) operation = "execute";
3013
+ else operation = "other";
3014
+ let status = "success";
3015
+ let errorMessage;
3016
+ if (failure) {
3017
+ status = "failure";
3018
+ errorMessage = failure instanceof Error ? failure.message : String(failure);
3019
+ }
3020
+ const doc = await newDoc(AUDIT_LOG_COLLECTION, {
3021
+ event_id: uuid(),
3022
+ occurred_at: new Date(startedAt).toISOString(),
3023
+ recorded_at: (/* @__PURE__ */ new Date()).toISOString(),
3024
+ trace_id: ctx.request_id,
3025
+ request_id: ctx.request_id,
3026
+ actor_id: ctx.identity?.user._id_ ?? "anonymous",
3027
+ actor_type: ctx.identity ? "user" : "anonymous",
3028
+ auth_method: ctx.identity?.auth_method === "api_key" ? "api_key" : ctx.identity ? "password" : "none",
3029
+ session_id: ctx.identity?.session_id,
3030
+ operation,
3031
+ resource_type: module,
3032
+ resource_id: Object.values(ctx.args)[0],
3033
+ event_name: ctx.route,
3034
+ status,
3035
+ severity: status === "failure" ? "warning" : "info",
3036
+ error_message: errorMessage,
3037
+ latency_ms: latency,
3038
+ user_agent: "hestia-mock",
3039
+ service_name: "hestia-mock"
3040
+ });
3041
+ await putDoc(this.tables, doc);
3042
+ if (await this.tables.documents.count() > 2e3) {
3043
+ const entries = await this.tables.documents.getAllByIndex("by_collection", AUDIT_LOG_COLLECTION);
3044
+ entries.sort((a, b) => String(a["occurred_at"]).localeCompare(String(b["occurred_at"])));
3045
+ const excess = entries.slice(0, entries.length - 500);
3046
+ for (const entry of excess) await this.tables.documents.delete([AUDIT_LOG_COLLECTION, entry._id_]);
3047
+ }
3048
+ this.bus.emit(Topics.audit, { data: doc });
3049
+ }
3050
+ /** Simulated latency, if configured. */
3051
+ async applyLatency() {
3052
+ const latency = this.options.latency;
3053
+ if (!latency) return;
3054
+ await sleep(typeof latency === "function" ? latency() : latency);
3055
+ }
3056
+ /** Close the database connection and stop background timers. */
3057
+ async close() {
3058
+ this.stopScheduler();
3059
+ this.bus.clear();
3060
+ this.db.close();
3061
+ }
3062
+ /** Start auto-ticking `@every` schedules (opt-in via options). */
3063
+ startScheduler() {
3064
+ const interval = this.options.autoTickSchedulesMs;
3065
+ if (!interval) return;
3066
+ this.schedulerTimer = setInterval(() => {
3067
+ this.tickSchedules();
3068
+ }, interval);
3069
+ }
3070
+ stopScheduler() {
3071
+ if (this.schedulerTimer !== null) {
3072
+ clearInterval(this.schedulerTimer);
3073
+ this.schedulerTimer = null;
3074
+ }
3075
+ }
3076
+ /** Fire every enabled `@every <n><unit>` schedule whose interval elapsed. */
3077
+ async tickSchedules() {
3078
+ const schedules = await this.tables.documents.getAllByIndex("by_collection", "_scheduled_messages_");
3079
+ const now = Date.now();
3080
+ for (const schedule of schedules) {
3081
+ if (schedule["disabled"]) continue;
3082
+ const cron = String(schedule["cron"] ?? "");
3083
+ const match = /^@every\s+(\d+)(ms|s|m|h)$/.exec(cron);
3084
+ if (!match) continue;
3085
+ const period = Number(match[1]) * {
3086
+ ms: 1,
3087
+ s: 1e3,
3088
+ m: 6e4,
3089
+ h: 36e5
3090
+ }[match[2]];
3091
+ const lastKey = `schedule_tick_${schedule["_id_"]}`;
3092
+ const last = await this.tables.kv.get(lastKey);
3093
+ if (last?.v && now - last.v < period) continue;
3094
+ await this.tables.kv.put({
3095
+ k: lastKey,
3096
+ v: now
3097
+ });
3098
+ await this.fireSchedule(String(schedule["_id_"]));
3099
+ }
3100
+ }
3101
+ buildDeps() {
3102
+ return {
3103
+ tables: this.tables,
3104
+ bus: this.bus,
3105
+ options: this.options,
3106
+ reset: async () => {
3107
+ await wipeAllStores(this.db);
3108
+ await seedDatabase(this.tables, DEFAULT_SEED);
3109
+ },
3110
+ pushLog: async (entry) => {
3111
+ await this.pushLog(entry);
3112
+ },
3113
+ setBootstrapped: async (value) => {
3114
+ await this.tables.kv.put({
3115
+ k: "bootstrapped",
3116
+ v: value
3117
+ });
3118
+ },
3119
+ isBootstrapped: async () => {
3120
+ const flag = await this.tables.kv.get("bootstrapped");
3121
+ if (flag?.v != null) return flag.v;
3122
+ return (await this.tables.documents.getAllByIndex("by_collection", "_user_")).some((u) => Array.isArray(u["permissions"]) && u["permissions"].includes("root"));
3123
+ }
3124
+ };
3125
+ }
3126
+ buildRoutes(deps) {
3127
+ const groups = [
3128
+ coreHandlers(deps),
3129
+ userHandlers(deps),
3130
+ collectionHandlers(deps),
3131
+ apiKeyHandlers(deps),
3132
+ notificationHandlers(deps),
3133
+ settingHandlers(deps),
3134
+ policyHandlers(deps),
3135
+ scheduleHandlers(deps),
3136
+ workflowHandlers(deps),
3137
+ updateHandlers(deps),
3138
+ logHandlers(deps),
3139
+ blobHandlers(deps)
3140
+ ];
3141
+ const map = /* @__PURE__ */ new Map();
3142
+ for (const group of groups) for (const [name, spec] of Object.entries(group)) map.set(name, {
3143
+ ...spec,
3144
+ name
3145
+ });
3146
+ return map;
3147
+ }
3148
+ /** Route names the mock answers, useful for tests and diagnostics. */
3149
+ routeNames() {
3150
+ return [...this.routes.keys()];
3151
+ }
3152
+ /** Number of live store names (diagnostics). */
3153
+ get storeNames() {
3154
+ return Object.keys(STORES);
3155
+ }
3156
+ };
3157
+ //#endregion
3158
+ //#region src/routes.ts
3159
+ const MOCK_ROUTE_TABLE = {
3160
+ "system:apikeys:key:create": {
3161
+ method: "POST",
3162
+ route: "/system/apikeys/key/create"
3163
+ },
3164
+ "system:apikeys:key:delete": {
3165
+ method: "DELETE",
3166
+ route: "/system/apikeys/key/delete/{key_id}"
3167
+ },
3168
+ "system:apikeys:key:get": {
3169
+ method: "GET",
3170
+ route: "/system/apikeys/key/get/{key_id}"
3171
+ },
3172
+ "system:apikeys:key:list": {
3173
+ method: "GET",
3174
+ route: "/system/apikeys/key/list"
3175
+ },
3176
+ "system:apikeys:key:rotate": {
3177
+ method: "POST",
3178
+ route: "/system/apikeys/key/rotate/{key_id}"
3179
+ },
3180
+ "system:apikeys:key:update": {
3181
+ method: "PATCH",
3182
+ route: "/system/apikeys/key/update/{key_id}"
3183
+ },
3184
+ "system:audit:log:export": {
3185
+ method: "PATCH",
3186
+ route: "/system/audit/log/export"
3187
+ },
3188
+ "system:audit:log:stream": {
3189
+ method: "GET",
3190
+ route: "/system/audit/log/stream"
3191
+ },
3192
+ "system:auth:bootstrap:password:set": {
3193
+ method: "PATCH",
3194
+ route: "/system/auth/bootstrap/password/set"
3195
+ },
3196
+ "system:auth:password:confirm": {
3197
+ method: "PATCH",
3198
+ route: "/system/auth/password/confirm"
3199
+ },
3200
+ "system:auth:password:reset": {
3201
+ method: "POST",
3202
+ route: "/system/auth/password/reset"
3203
+ },
3204
+ "system:auth:session:create": {
3205
+ method: "POST",
3206
+ route: "/system/auth/session/create"
3207
+ },
3208
+ "system:auth:session:delete": {
3209
+ method: "DELETE",
3210
+ route: "/system/auth/session/delete"
3211
+ },
3212
+ "system:auth:token:elevate": {
3213
+ method: "POST",
3214
+ route: "/system/auth/token/elevate"
3215
+ },
3216
+ "system:blobs:blob:abort": {
3217
+ method: "POST",
3218
+ route: "/system/blobs/blob/abort/{ns}"
3219
+ },
3220
+ "system:blobs:blob:begin": {
3221
+ method: "POST",
3222
+ route: "/system/blobs/blob/begin/{ns}"
3223
+ },
3224
+ "system:blobs:blob:chunk": {
3225
+ method: "POST",
3226
+ route: "/system/blobs/blob/chunk/{ns}"
3227
+ },
3228
+ "system:blobs:blob:complete": {
3229
+ method: "POST",
3230
+ route: "/system/blobs/blob/complete/{ns}"
3231
+ },
3232
+ "system:blobs:blob:delete": {
3233
+ method: "DELETE",
3234
+ route: "/system/blobs/blob/delete/{ns}/{key*}"
3235
+ },
3236
+ "system:blobs:blob:download": {
3237
+ method: "GET",
3238
+ route: "/system/blobs/blob/download/{ns}/{key*}"
3239
+ },
3240
+ "system:blobs:blob:head": {
3241
+ method: "POST",
3242
+ route: "/system/blobs/blob/head/{ns}/{key*}"
3243
+ },
3244
+ "system:blobs:blob:list": {
3245
+ method: "POST",
3246
+ route: "/system/blobs/blob/list/{ns}"
3247
+ },
3248
+ "system:blobs:blob:progress": {
3249
+ method: "POST",
3250
+ route: "/system/blobs/blob/progress/{ns}"
3251
+ },
3252
+ "system:blobs:blob:rename": {
3253
+ method: "PATCH",
3254
+ route: "/system/blobs/blob/rename/{ns}/{key*}"
3255
+ },
3256
+ "system:blobs:blob:update": {
3257
+ method: "PATCH",
3258
+ route: "/system/blobs/blob/update/{ns}/{key*}"
3259
+ },
3260
+ "system:blobs:blob:upload": {
3261
+ method: "POST",
3262
+ route: "/system/blobs/blob/upload/{ns}/{key*}"
3263
+ },
3264
+ "system:blobs:namespace:compact": {
3265
+ method: "POST",
3266
+ route: "/system/blobs/namespace/compact/{ns}"
3267
+ },
3268
+ "system:blobs:namespace:create": {
3269
+ method: "POST",
3270
+ route: "/system/blobs/namespace/create/{ns}"
3271
+ },
3272
+ "system:blobs:namespace:delete": {
3273
+ method: "DELETE",
3274
+ route: "/system/blobs/namespace/delete/{ns}"
3275
+ },
3276
+ "system:blobs:namespace:list": {
3277
+ method: "POST",
3278
+ route: "/system/blobs/namespace/list"
3279
+ },
3280
+ "system:blobs:namespace:stats": {
3281
+ method: "POST",
3282
+ route: "/system/blobs/namespace/stats/{ns}"
3283
+ },
3284
+ "system:blobs:namespace:verify": {
3285
+ method: "POST",
3286
+ route: "/system/blobs/namespace/verify/{ns}"
3287
+ },
3288
+ "system:collections:audit_log:query": {
3289
+ method: "POST",
3290
+ route: "/system/collections/audit_log/query"
3291
+ },
3292
+ "system:collections:collection:create": {
3293
+ method: "POST",
3294
+ route: "/system/collections/collection/create"
3295
+ },
3296
+ "system:collections:collection:delete": {
3297
+ method: "DELETE",
3298
+ route: "/system/collections/collection/delete/{name}"
3299
+ },
3300
+ "system:collections:collection:get": {
3301
+ method: "GET",
3302
+ route: "/system/collections/collection/get/{name}"
3303
+ },
3304
+ "system:collections:collection:list": {
3305
+ method: "GET",
3306
+ route: "/system/collections/collection/list"
3307
+ },
3308
+ "system:collections:document:create": {
3309
+ method: "POST",
3310
+ route: "/system/collections/document/create/{name}"
3311
+ },
3312
+ "system:collections:document:delete": {
3313
+ method: "DELETE",
3314
+ route: "/system/collections/document/delete/{name}/{doc_id}"
3315
+ },
3316
+ "system:collections:document:get": {
3317
+ method: "GET",
3318
+ route: "/system/collections/document/get/{name}/{doc_id}"
3319
+ },
3320
+ "system:collections:document:query": {
3321
+ method: "POST",
3322
+ route: "/system/collections/document/query/{name}"
3323
+ },
3324
+ "system:collections:document:update": {
3325
+ method: "PATCH",
3326
+ route: "/system/collections/document/update/{name}/{doc_id}"
3327
+ },
3328
+ "system:collections:document:update_many": {
3329
+ method: "PATCH",
3330
+ route: "/system/collections/document/update_many/{name}"
3331
+ },
3332
+ "system:collections:user:query": {
3333
+ method: "POST",
3334
+ route: "/system/collections/user/query"
3335
+ },
3336
+ "system:collections:operation_policy:query": {
3337
+ method: "POST",
3338
+ route: "/system/collections/operation_policy/query"
3339
+ },
3340
+ "system:collections:view:create": {
3341
+ method: "POST",
3342
+ route: "/system/collections/view/create/{name}"
3343
+ },
3344
+ "system:collections:view:refresh": {
3345
+ method: "PATCH",
3346
+ route: "/system/collections/view/refresh/{name}"
3347
+ },
3348
+ "system:core:capability:list": {
3349
+ method: "GET",
3350
+ route: "/system/core/capability/list"
3351
+ },
3352
+ "system:core:capability:set": {
3353
+ method: "PATCH",
3354
+ route: "/system/core/capability/set/{name}"
3355
+ },
3356
+ "system:core:docs:list": {
3357
+ method: "GET",
3358
+ route: "/system/core/docs/list"
3359
+ },
3360
+ "system:core:health:check": {
3361
+ method: "GET",
3362
+ route: "/system/core/health/check"
3363
+ },
3364
+ "system:core:heartbeat": {
3365
+ method: "GET",
3366
+ route: "/system/core/heartbeat"
3367
+ },
3368
+ "system:core:reset": {
3369
+ method: "DELETE",
3370
+ route: "/system/core/reset"
3371
+ },
3372
+ "system:logs:list": {
3373
+ method: "POST",
3374
+ route: "/system/logs/list"
3375
+ },
3376
+ "system:logs:stream": {
3377
+ method: "GET",
3378
+ route: "/system/logs/stream"
3379
+ },
3380
+ "system:notifications:notification:create": {
3381
+ method: "POST",
3382
+ route: "/system/notifications/notification/create"
3383
+ },
3384
+ "system:notifications:notification:list": {
3385
+ method: "GET",
3386
+ route: "/system/notifications/notification/list"
3387
+ },
3388
+ "system:notifications:notification:read": {
3389
+ method: "PATCH",
3390
+ route: "/system/notifications/notification/read/{notification_id}"
3391
+ },
3392
+ "system:notifications:notification:stream": {
3393
+ method: "GET",
3394
+ route: "/system/notifications/notification/stream"
3395
+ },
3396
+ "system:notifications:read:all": {
3397
+ method: "PATCH",
3398
+ route: "/system/notifications/read/all"
3399
+ },
3400
+ "system:notifications:unread:count": {
3401
+ method: "GET",
3402
+ route: "/system/notifications/unread/count"
3403
+ },
3404
+ "system:policies:binding:get": {
3405
+ method: "GET",
3406
+ route: "/system/policies/binding/get/{name}"
3407
+ },
3408
+ "system:policies:binding:list": {
3409
+ method: "GET",
3410
+ route: "/system/policies/binding/list"
3411
+ },
3412
+ "system:policies:policy:create": {
3413
+ method: "POST",
3414
+ route: "/system/policies/policy/create/{name}"
3415
+ },
3416
+ "system:policies:policy:list": {
3417
+ method: "GET",
3418
+ route: "/system/policies/policy/list"
3419
+ },
3420
+ "system:policies:policy:update": {
3421
+ method: "PATCH",
3422
+ route: "/system/policies/policy/update/{name}"
3423
+ },
3424
+ "system:policies:reload": {
3425
+ method: "GET",
3426
+ route: "/system/policies/reload"
3427
+ },
3428
+ "system:policies:rule:create": {
3429
+ method: "POST",
3430
+ route: "/system/policies/rule/create/{name}"
3431
+ },
3432
+ "system:policies:rule:delete": {
3433
+ method: "DELETE",
3434
+ route: "/system/policies/rule/delete/{name}"
3435
+ },
3436
+ "system:policies:rule:get": {
3437
+ method: "GET",
3438
+ route: "/system/policies/rule/get/{name}"
3439
+ },
3440
+ "system:policies:rule:list": {
3441
+ method: "GET",
3442
+ route: "/system/policies/rule/list"
3443
+ },
3444
+ "system:policies:rule:update": {
3445
+ method: "PATCH",
3446
+ route: "/system/policies/rule/update/{name}"
3447
+ },
3448
+ "system:policies:rule:validate": {
3449
+ method: "POST",
3450
+ route: "/system/policies/rule/validate"
3451
+ },
3452
+ "system:scheduler:job:list": {
3453
+ method: "GET",
3454
+ route: "/system/scheduler/job/list"
3455
+ },
3456
+ "system:schedules:schedule:all": {
3457
+ method: "GET",
3458
+ route: "/system/schedules/schedule/all"
3459
+ },
3460
+ "system:schedules:schedule:create": {
3461
+ method: "POST",
3462
+ route: "/system/schedules/schedule/create"
3463
+ },
3464
+ "system:schedules:schedule:delete": {
3465
+ method: "DELETE",
3466
+ route: "/system/schedules/schedule/delete/{id}"
3467
+ },
3468
+ "system:schedules:schedule:get": {
3469
+ method: "GET",
3470
+ route: "/system/schedules/schedule/get/{id}"
3471
+ },
3472
+ "system:schedules:schedule:list": {
3473
+ method: "GET",
3474
+ route: "/system/schedules/schedule/list"
3475
+ },
3476
+ "system:schedules:schedule:update": {
3477
+ method: "PATCH",
3478
+ route: "/system/schedules/schedule/update/{id}"
3479
+ },
3480
+ "system:settings:delete": {
3481
+ method: "DELETE",
3482
+ route: "/system/settings/delete/{key}"
3483
+ },
3484
+ "system:settings:get": {
3485
+ method: "GET",
3486
+ route: "/system/settings/get/{key}"
3487
+ },
3488
+ "system:settings:list": {
3489
+ method: "GET",
3490
+ route: "/system/settings/list"
3491
+ },
3492
+ "system:settings:set": {
3493
+ method: "POST",
3494
+ route: "/system/settings/set/{key}"
3495
+ },
3496
+ "system:updates:changelog:get": {
3497
+ method: "GET",
3498
+ route: "/system/updates/changelog/get"
3499
+ },
3500
+ "system:updates:check:create": {
3501
+ method: "POST",
3502
+ route: "/system/updates/check/create"
3503
+ },
3504
+ "system:updates:check:get": {
3505
+ method: "GET",
3506
+ route: "/system/updates/check/get"
3507
+ },
3508
+ "system:updates:stage:create": {
3509
+ method: "POST",
3510
+ route: "/system/updates/stage/create"
3511
+ },
3512
+ "system:updates:status:get": {
3513
+ method: "GET",
3514
+ route: "/system/updates/status/get"
3515
+ },
3516
+ "system:updates:update:apply": {
3517
+ method: "POST",
3518
+ route: "/system/updates/update/apply"
3519
+ },
3520
+ "system:updates:update:discard": {
3521
+ method: "DELETE",
3522
+ route: "/system/updates/update/discard"
3523
+ },
3524
+ "system:users:password:change": {
3525
+ method: "PATCH",
3526
+ route: "/system/users/password/change/{user_id}"
3527
+ },
3528
+ "system:users:user:create": {
3529
+ method: "POST",
3530
+ route: "/system/users/user/create"
3531
+ },
3532
+ "system:users:user:delete": {
3533
+ method: "DELETE",
3534
+ route: "/system/users/user/delete/{user_id}"
3535
+ },
3536
+ "system:users:user:get": {
3537
+ method: "GET",
3538
+ route: "/system/users/user/get/{user_id}"
3539
+ },
3540
+ "system:users:user:update": {
3541
+ method: "PATCH",
3542
+ route: "/system/users/user/update/{user_id}"
3543
+ },
3544
+ "system:workflows:definition:compile": {
3545
+ method: "POST",
3546
+ route: "/system/workflows/definition/compile"
3547
+ },
3548
+ "system:workflows:definition:create": {
3549
+ method: "POST",
3550
+ route: "/system/workflows/definition/create"
3551
+ },
3552
+ "system:workflows:definition:delete": {
3553
+ method: "DELETE",
3554
+ route: "/system/workflows/definition/delete/{id}"
3555
+ },
3556
+ "system:workflows:definition:get": {
3557
+ method: "GET",
3558
+ route: "/system/workflows/definition/get/{id}"
3559
+ },
3560
+ "system:workflows:definition:list": {
3561
+ method: "GET",
3562
+ route: "/system/workflows/definition/list"
3563
+ },
3564
+ "system:workflows:definition:update": {
3565
+ method: "PATCH",
3566
+ route: "/system/workflows/definition/update/{id}"
3567
+ },
3568
+ "system:workflows:registry:get": {
3569
+ method: "GET",
3570
+ route: "/system/workflows/registry/get/{kind}"
3571
+ },
3572
+ "system:workflows:registry:handles": {
3573
+ method: "GET",
3574
+ route: "/system/workflows/registry/handles"
3575
+ },
3576
+ "system:workflows:registry:list": {
3577
+ method: "GET",
3578
+ route: "/system/workflows/registry/list"
3579
+ },
3580
+ "system:workflows:run:events": {
3581
+ method: "GET",
3582
+ route: "/system/workflows/run/events/{run_id}"
3583
+ },
3584
+ "system:workflows:run:get": {
3585
+ method: "GET",
3586
+ route: "/system/workflows/run/get/{run_id}"
3587
+ },
3588
+ "system:workflows:run:list": {
3589
+ method: "GET",
3590
+ route: "/system/workflows/run/list"
3591
+ },
3592
+ "system:workflows:run:outcome": {
3593
+ method: "GET",
3594
+ route: "/system/workflows/run/outcome/{run_id}"
3595
+ },
3596
+ "system:workflows:run:store": {
3597
+ method: "GET",
3598
+ route: "/system/workflows/run/store/{run_id}"
3599
+ },
3600
+ "system:workflows:run:stream": {
3601
+ method: "GET",
3602
+ route: "/system/workflows/run/stream/{run_id}"
3603
+ },
3604
+ "system:workflows:runtime:abort": {
3605
+ method: "DELETE",
3606
+ route: "/system/workflows/runtime/abort/{run_id}"
3607
+ },
3608
+ "system:workflows:runtime:events": {
3609
+ method: "POST",
3610
+ route: "/system/workflows/runtime/events"
3611
+ },
3612
+ "system:workflows:runtime:has": {
3613
+ method: "GET",
3614
+ route: "/system/workflows/runtime/has/{id}"
3615
+ },
3616
+ "system:workflows:runtime:invoke": {
3617
+ method: "POST",
3618
+ route: "/system/workflows/runtime/invoke"
3619
+ },
3620
+ "system:workflows:runtime:list": {
3621
+ method: "GET",
3622
+ route: "/system/workflows/runtime/list"
3623
+ },
3624
+ "system:workflows:runtime:resume": {
3625
+ method: "POST",
3626
+ route: "/system/workflows/runtime/resume"
3627
+ },
3628
+ "system:workflows:runtime:run": {
3629
+ method: "POST",
3630
+ route: "/system/workflows/runtime/run"
3631
+ }
3632
+ };
3633
+ //#endregion
3634
+ //#region src/transport.ts
3635
+ /**
3636
+ * IndexedDbTransport — implements the Hestia `Transport` interface on top of
3637
+ * `MockHestiaServer` (IndexedDB). Drop-in replacement for `HttpTransport`:
3638
+ *
3639
+ * ```ts
3640
+ * const api = new HestiaClient({ baseUrl: "idb://hestia-mock", transport })
3641
+ * ```
3642
+ *
3643
+ * Implements the full surface: named dispatch, raw path methods (the audit
3644
+ * and app-log stores use `client.post(path, ...)` directly), SSE-style
3645
+ * `openStream`, 401 → onUnauthorized notification, and simulated latency.
3646
+ */
3647
+ var IndexedDbTransport = class {
3648
+ server;
3649
+ baseUrl;
3650
+ apiPrefix;
3651
+ onUnauthorizedCb;
3652
+ constructor(server, options = {}) {
3653
+ this.server = server;
3654
+ this.baseUrl = options.baseUrl ?? "idb://hestia-mock";
3655
+ this.apiPrefix = options.apiPrefix ?? "/api";
3656
+ this.onUnauthorizedCb = options.onUnauthorized;
3657
+ }
3658
+ setOnUnauthorized(cb) {
3659
+ this.onUnauthorizedCb = cb;
3660
+ }
3661
+ base() {
3662
+ return this.baseUrl;
3663
+ }
3664
+ prefix() {
3665
+ return this.apiPrefix;
3666
+ }
3667
+ routeUrl(name, args) {
3668
+ const entry = MOCK_ROUTE_TABLE[name];
3669
+ if (!entry) throw new _asaidimu_utils_error.SystemError({
3670
+ code: "ROUTE_NOT_FOUND",
3671
+ message: `No registered route for handler: ${name}`
3672
+ });
3673
+ return `${this.baseUrl.replace(/\/+$/, "")}${this.substituteArgs(entry.route, args ?? {})}`;
3674
+ }
3675
+ async ready() {
3676
+ await this.server.ready();
3677
+ }
3678
+ async dispatch(name, input) {
3679
+ await this.server.applyLatency();
3680
+ const notify = input?.notifyAuthStateChange ?? true;
3681
+ try {
3682
+ const response = await this.server.dispatch(name, {
3683
+ arguments: input?.arguments,
3684
+ modifiers: input?.modifiers,
3685
+ payload: input?.payload,
3686
+ headers: input?.headers
3687
+ });
3688
+ if (response.status === 204 || response.body === void 0) return new _asaidimu_hestia.HestiaResponse(void 0, 204);
3689
+ if (input?.responseType === "blob" && response.body.data instanceof Uint8Array) {
3690
+ const contentType = response.body.metadata?.["content_type"];
3691
+ return new _asaidimu_hestia.HestiaResponse(new Blob([response.body.data], { type: contentType ?? "application/octet-stream" }), response.status);
3692
+ }
3693
+ return new _asaidimu_hestia.HestiaResponse(response.body, response.status);
3694
+ } catch (error) {
3695
+ if (statusForError(error) === 401 && notify) this.onUnauthorizedCb?.();
3696
+ throw error;
3697
+ }
3698
+ }
3699
+ async get(path, options) {
3700
+ return await this.dispatchPath("GET", path, void 0, options);
3701
+ }
3702
+ async post(path, body, options) {
3703
+ return await this.dispatchPath("POST", path, body, options);
3704
+ }
3705
+ async patch(path, body, options) {
3706
+ return await this.dispatchPath("PATCH", path, body, options);
3707
+ }
3708
+ async put(path, body, options) {
3709
+ return await this.dispatchPath("PUT", path, body, options);
3710
+ }
3711
+ async delete(path, body, options) {
3712
+ return await this.dispatchPath("DELETE", path, body, options);
3713
+ }
3714
+ async check(path, body, options) {
3715
+ return await this.dispatchPath("POST", `${path}/check`, body, options);
3716
+ }
3717
+ async dispatchPath(method, path, body, options) {
3718
+ await this.server.applyLatency();
3719
+ const resolved = this.resolvePath(method, path);
3720
+ if (!resolved) throw new _asaidimu_utils_error.SystemError({
3721
+ code: "ROUTE_NOT_FOUND",
3722
+ message: `No registered route matches ${method} ${path}`
3723
+ });
3724
+ return await this.dispatch(resolved.route, {
3725
+ arguments: resolved.args,
3726
+ payload: body,
3727
+ headers: options?.headers,
3728
+ responseType: options?.responseType,
3729
+ bodyType: options?.bodyType,
3730
+ signal: options?.signal
3731
+ });
3732
+ }
3733
+ resolvePath(method, rawPath) {
3734
+ let path = rawPath.split("?")[0] ?? rawPath;
3735
+ if (this.apiPrefix) {
3736
+ const prefix = this.apiPrefix.replace(/\/+$/, "");
3737
+ path = path.replace(new RegExp(`^${prefix}/?`), "/");
3738
+ }
3739
+ if (!path.startsWith("/")) path = `/${path}`;
3740
+ const segments = path.split("/").filter(Boolean);
3741
+ for (const [route, entry] of Object.entries(MOCK_ROUTE_TABLE)) {
3742
+ if (entry.method !== method) continue;
3743
+ const template = entry.route.split("/").filter(Boolean);
3744
+ const last = template[template.length - 1] ?? "";
3745
+ const greedy = last.startsWith("{") && last.endsWith("*}");
3746
+ if (greedy ? segments.length < template.length : template.length !== segments.length) continue;
3747
+ const args = {};
3748
+ let matched = true;
3749
+ for (let i = 0; i < template.length; i++) {
3750
+ const tpl = template[i];
3751
+ if (greedy && i === template.length - 1) {
3752
+ args[tpl.slice(1, -2)] = segments.slice(i).map(decodeURIComponent).join("/");
3753
+ break;
3754
+ }
3755
+ const actual = segments[i];
3756
+ if (tpl.startsWith("{") && tpl.endsWith("}")) args[tpl.slice(1, -1)] = decodeURIComponent(actual);
3757
+ else if (tpl !== actual) {
3758
+ matched = false;
3759
+ break;
3760
+ }
3761
+ }
3762
+ if (matched) return {
3763
+ route,
3764
+ args
3765
+ };
3766
+ }
3767
+ return null;
3768
+ }
3769
+ substituteArgs(route, args) {
3770
+ return route.replace(/\{(\w+)(\*)?\}/g, (_, key, greedy) => {
3771
+ if (args[key] === void 0) return `{${key}}`;
3772
+ if (greedy) return args[key].split("/").map(encodeURIComponent).join("/");
3773
+ return encodeURIComponent(args[key]);
3774
+ });
3775
+ }
3776
+ /**
3777
+ * Subscribes to a server event stream. Message payloads are rendered as
3778
+ * SSE `data:` frames exactly like the Go transport (`data: {"data": ...}\n\n`),
3779
+ * and delivered through `handlers.onMessage` as the JSON string.
3780
+ */
3781
+ async openStream(path, handlers, options) {
3782
+ await this.server.ready();
3783
+ if (options?.signal?.aborted) {
3784
+ handlers.onClose?.();
3785
+ return;
3786
+ }
3787
+ const cleanPath = (path.split("?")[0] ?? path).replace(/^\/+/, "").replace(/^(api\/)?/, "/");
3788
+ const query = new URLSearchParams(path.split("?")[1] ?? "");
3789
+ let unsubscribe = null;
3790
+ let closeRequested = false;
3791
+ let notifyClosed = () => void 0;
3792
+ const closed = new Promise((resolve) => notifyClosed = resolve);
3793
+ const close = () => {
3794
+ if (closeRequested) return;
3795
+ closeRequested = true;
3796
+ unsubscribe?.();
3797
+ unsubscribe = null;
3798
+ handlers.onClose?.();
3799
+ notifyClosed();
3800
+ };
3801
+ options?.signal?.addEventListener("abort", close, { once: true });
3802
+ try {
3803
+ if (cleanPath === "/system/notifications/notification/stream") {
3804
+ const userId = await this.server.currentUserId();
3805
+ const topic = userId ? Topics.notifications(userId) : Topics.notificationsAll;
3806
+ unsubscribe = this.server.bus.subscribe(topic, (payload) => {
3807
+ handlers.onMessage(JSON.stringify(payload));
3808
+ });
3809
+ } else if (cleanPath === "/system/audit/log/stream") unsubscribe = this.server.bus.subscribe(Topics.audit, (payload) => {
3810
+ handlers.onMessage(JSON.stringify(payload));
3811
+ });
3812
+ else if (cleanPath === "/system/logs/stream") {
3813
+ const level = query.get("level") ?? void 0;
3814
+ unsubscribe = this.server.bus.subscribe(Topics.logs(level), (payload) => {
3815
+ handlers.onMessage(JSON.stringify(payload));
3816
+ });
3817
+ } else if (cleanPath.startsWith("/system/workflows/run/stream/")) {
3818
+ const runId = cleanPath.split("/").filter(Boolean).pop();
3819
+ unsubscribe = await this.subscribeWorkflowRun(runId, handlers, close);
3820
+ if (!unsubscribe) return;
3821
+ } else {
3822
+ handlers.onError?.(/* @__PURE__ */ new Error(`Stream request failed: no stream endpoint matches ${path}`));
3823
+ handlers.onClose?.();
3824
+ return;
3825
+ }
3826
+ handlers.onOpen?.();
3827
+ await closed;
3828
+ } catch (error) {
3829
+ handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
3830
+ close();
3831
+ }
3832
+ }
3833
+ /** Replay persisted run events, then forward live ones. Returns null when the stream closed during replay. */
3834
+ async subscribeWorkflowRun(runId, handlers, close) {
3835
+ const TERMINAL = /* @__PURE__ */ new Set([
3836
+ "pipeline:success",
3837
+ "pipeline:failure",
3838
+ "pipeline:pause"
3839
+ ]);
3840
+ const existing = await this.server.tables.run_events.getAllByIndex("by_run", runId);
3841
+ existing.sort((a, b) => a.seq - b.seq);
3842
+ for (const event of existing) {
3843
+ handlers.onMessage(JSON.stringify({ data: event }));
3844
+ if (TERMINAL.has(event.type)) {
3845
+ close();
3846
+ return () => void 0;
3847
+ }
3848
+ }
3849
+ return this.server.bus.subscribe(Topics.workflowRun(runId), (payload) => {
3850
+ handlers.onMessage(JSON.stringify(payload));
3851
+ const type = payload?.data?.type;
3852
+ if (type && TERMINAL.has(type)) setTimeout(close, 0);
3853
+ });
3854
+ }
3855
+ };
3856
+ //#endregion
3857
+ //#region src/persistence.ts
3858
+ const AUTH_STATE_KEY = "auth_state";
3859
+ /**
3860
+ * Create a `SimplePersistence<T>` backed by the mock server's `kv` store.
3861
+ *
3862
+ * @typeParam T the persisted state shape (typically `AuthState`).
3863
+ */
3864
+ function createIdbPersistence(server, config = {}) {
3865
+ const app = config.app ?? "hestia-mock";
3866
+ const version = config.version ?? "1.0.0";
3867
+ const listeners = /* @__PURE__ */ new Map();
3868
+ const read = async () => {
3869
+ return (await server.tables.kv.get(AUTH_STATE_KEY))?.v ?? null;
3870
+ };
3871
+ return {
3872
+ async set(_id, state) {
3873
+ try {
3874
+ await server.tables.kv.put({
3875
+ k: AUTH_STATE_KEY,
3876
+ v: state
3877
+ });
3878
+ for (const [id, set] of listeners) {
3879
+ if (id === _id) continue;
3880
+ for (const listener of set) listener(state);
3881
+ }
3882
+ return true;
3883
+ } catch {
3884
+ return false;
3885
+ }
3886
+ },
3887
+ async get() {
3888
+ try {
3889
+ return await read();
3890
+ } catch {
3891
+ return null;
3892
+ }
3893
+ },
3894
+ subscribe(id, callback) {
3895
+ let set = listeners.get(id);
3896
+ if (!set) {
3897
+ set = /* @__PURE__ */ new Set();
3898
+ listeners.set(id, set);
3899
+ }
3900
+ set.add(callback);
3901
+ return () => {
3902
+ set.delete(callback);
3903
+ if (set.size === 0) listeners.delete(id);
3904
+ };
3905
+ },
3906
+ async clear() {
3907
+ try {
3908
+ await server.tables.kv.delete(AUTH_STATE_KEY);
3909
+ return true;
3910
+ } catch {
3911
+ return false;
3912
+ }
3913
+ },
3914
+ stats() {
3915
+ return {
3916
+ version,
3917
+ id: app
3918
+ };
3919
+ }
3920
+ };
3921
+ }
3922
+ //#endregion
3923
+ //#region src/client.ts
3924
+ /**
3925
+ * One-call wiring: a fully-functional `HestiaClient` whose backend is
3926
+ * IndexedDB. Auth identity is persisted through the same database, so login
3927
+ * state and all data survive reloads.
3928
+ *
3929
+ * ```ts
3930
+ * const mock = await createMockHestia({ seed: { email: "admin@x.dev", password: "s3cret" } });
3931
+ * await mock.client.auth.login("admin@x.dev", "s3cret");
3932
+ * await mock.client.collection("todos").create({ data: { title: "ship it" } });
3933
+ * ```
3934
+ */
3935
+ /**
3936
+ * Create a mock-backed Hestia client.
3937
+ *
3938
+ * Every call the client makes is served from IndexedDB; sessions, documents,
3939
+ * blobs, and streams all behave like the real server. When the mock answers
3940
+ * 401 the client's identity is cleared automatically (mirroring HttpTransport).
3941
+ */
3942
+ async function createMockHestia(options = {}) {
3943
+ const server = await MockHestiaServer.create({
3944
+ database: options.database,
3945
+ seed: options.seed,
3946
+ reset: options.reset,
3947
+ options: options.serverOptions ?? options.options
3948
+ });
3949
+ const transport = new IndexedDbTransport(server);
3950
+ const persistence = createIdbPersistence(server);
3951
+ const client = new _asaidimu_hestia.HestiaClient({
3952
+ baseUrl: transport.base(),
3953
+ transport,
3954
+ persistence
3955
+ });
3956
+ transport.setOnUnauthorized(() => {
3957
+ client.store.set({ identity: null });
3958
+ });
3959
+ return {
3960
+ client,
3961
+ transport,
3962
+ server,
3963
+ destroy: async () => {
3964
+ await server.close();
3965
+ }
3966
+ };
3967
+ }
3968
+ //#endregion
3969
+ exports.DEFAULT_DB_NAME = DEFAULT_DB_NAME;
3970
+ exports.DEFAULT_SEED = DEFAULT_SEED;
3971
+ exports.EventBus = EventBus;
3972
+ exports.IndexedDbTransport = IndexedDbTransport;
3973
+ exports.MockHestiaServer = MockHestiaServer;
3974
+ exports.MockHttpError = MockHttpError;
3975
+ exports.STORES = STORES;
3976
+ exports.Topics = Topics;
3977
+ exports.createIdbPersistence = createIdbPersistence;
3978
+ exports.createMockHestia = createMockHestia;
3979
+ exports.evaluateFilter = evaluateFilter;
3980
+ exports.executeQuery = executeQuery;
3981
+ exports.getField = getField;
3982
+ exports.mockErrors = err;
3983
+ exports.openMockDatabase = openMockDatabase;
3984
+ exports.seedDatabase = seedDatabase;
3985
+ exports.sortDocs = sortDocs;
3986
+ exports.statusForError = statusForError;
3987
+ exports.wipeAllStores = wipeAllStores;
3988
+
3989
+ //# sourceMappingURL=index.cjs.map