memorio 5.0.0 → 5.1.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.
Files changed (60) hide show
  1. package/README.md +80 -449
  2. package/SECURITY.md +152 -42
  3. package/SUMMARY.md +1 -1
  4. package/adr/001-state-proxy-model.md +95 -96
  5. package/adr/002-observer-semantics.md +179 -180
  6. package/adr/003-deep-mutation-semantics.md +7 -8
  7. package/adr/004-array-mutation-semantics.md +127 -128
  8. package/adr/005-scheduler-contract.md +148 -149
  9. package/adr/006-context-isolation.md +91 -92
  10. package/adr/007-mutation-records.md +5 -6
  11. package/adr/008-transactions.md +6 -7
  12. package/adr/009-history-model.md +6 -7
  13. package/adr/README.md +46 -46
  14. package/adr/template.md +48 -49
  15. package/bin/cli.js +68 -0
  16. package/global.cjs +1462 -323
  17. package/global.js +1459 -324
  18. package/index.cjs +1462 -323
  19. package/index.d.ts +1 -0
  20. package/index.js +1459 -324
  21. package/llms.txt +42 -5
  22. package/markdown/AUDIT-REPORT.md +7 -8
  23. package/markdown/CACHE.md +190 -99
  24. package/markdown/DEVTOOLS.md +0 -1
  25. package/markdown/DISPATCH.md +0 -1
  26. package/markdown/HISTORY.md +0 -1
  27. package/markdown/IDB.md +0 -1
  28. package/markdown/IMPORT.md +0 -1
  29. package/markdown/INSPECT.md +0 -1
  30. package/markdown/LOGGER.md +0 -1
  31. package/markdown/MEMORY-ATTACHMENT.md +0 -1
  32. package/markdown/MEMORY.md +0 -1
  33. package/markdown/OBSERVER.md +0 -1
  34. package/markdown/PLATFORM.md +277 -271
  35. package/markdown/REDUX.md +54 -0
  36. package/markdown/SCHEMA.md +0 -1
  37. package/markdown/SESSION.md +0 -1
  38. package/markdown/SQLITE.md +0 -1
  39. package/markdown/STATE.md +0 -1
  40. package/markdown/STORE.md +0 -1
  41. package/markdown/SYNC.md +0 -1
  42. package/markdown/TYPED.md +0 -1
  43. package/markdown/USEOBSERVER.md +0 -1
  44. package/modules/redux.cjs +381 -10
  45. package/modules/redux.cjs.map +1 -1
  46. package/modules/redux.js +381 -10
  47. package/modules/redux.js.map +1 -1
  48. package/package.json +14 -2
  49. package/types/broadcast.d.ts +61 -0
  50. package/types/computed.d.ts +96 -0
  51. package/types/encryption.d.ts +129 -0
  52. package/types/exports.d.ts +9 -0
  53. package/types/memorio.d.ts +19 -12
  54. package/types/security.d.ts +67 -0
  55. package/types/session.d.ts +23 -5
  56. package/types/store.d.ts +19 -3
  57. package/vsix/memorio.vsix +0 -0
  58. package/markdown/CHANGELOG.md +0 -243
  59. package/markdown/PROJECT.md +0 -311
  60. package/markdown/SECURITY.md +0 -330
package/global.js CHANGED
@@ -7,6 +7,10 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
7
7
  var __esm = (fn, res) => function __init() {
8
8
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
9
  };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
10
14
  var init_esm_shims = __esm({
11
15
  "node_modules/tsup/assets/esm_shims.js"() {
12
16
  }
@@ -205,6 +209,241 @@ var init_message = __esm({
205
209
  }
206
210
  });
207
211
 
212
+ // functions/encryption/index.ts
213
+ function _hasWebCrypto() {
214
+ const g3 = globalThis;
215
+ return typeof g3.crypto !== "undefined" && typeof g3.crypto.subtle !== "undefined" && typeof g3.crypto.subtle.encrypt === "function";
216
+ }
217
+ function _b64encode(buf) {
218
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
219
+ if (typeof btoa === "function") {
220
+ let binary = "";
221
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
222
+ return btoa(binary);
223
+ }
224
+ if (typeof Buffer !== "undefined") {
225
+ return Buffer.from(bytes).toString("base64");
226
+ }
227
+ return "";
228
+ }
229
+ function _b64decode(b64) {
230
+ if (typeof Buffer !== "undefined") {
231
+ return new Uint8Array(Buffer.from(b64, "base64"));
232
+ }
233
+ if (typeof atob === "function") {
234
+ const binary = atob(b64);
235
+ const out = new Uint8Array(binary.length);
236
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
237
+ return out;
238
+ }
239
+ throw new Error("memorio encryption: no base64 decoder available");
240
+ }
241
+ function _isEncrypted(value) {
242
+ return typeof value === "object" && value !== null && value.__memorio_encrypted === true && typeof value.alg === "string";
243
+ }
244
+ var AES_GCM, PBKDF2_ITERATIONS, encryption;
245
+ var init_encryption = __esm({
246
+ "functions/encryption/index.ts"() {
247
+ init_esm_shims();
248
+ init_env();
249
+ init_message();
250
+ __name(_hasWebCrypto, "_hasWebCrypto");
251
+ __name(_b64encode, "_b64encode");
252
+ __name(_b64decode, "_b64decode");
253
+ __name(_isEncrypted, "_isEncrypted");
254
+ AES_GCM = { name: "AES-GCM", length: 256 };
255
+ PBKDF2_ITERATIONS = 6e5;
256
+ encryption = {
257
+ ///
258
+ // Capability detection
259
+ ///
260
+ isAvailable() {
261
+ return _hasWebCrypto();
262
+ },
263
+ ///
264
+ // Derive a CryptoKey from a password using PBKDF2.
265
+ //
266
+ // @param password The password string.
267
+ // @param salt Salt (string or Uint8Array). Defaults to a static value.
268
+ // @param alg 'AES-GCM' (default) or 'AES-CBC'.
269
+ // @returns A Promise<CryptoKey>.
270
+ ///
271
+ async deriveKey(password, salt, alg = "AES-GCM", iterations = PBKDF2_ITERATIONS) {
272
+ if (!_hasWebCrypto()) {
273
+ throw new Error("memorio encryption: Web Crypto API is not available in this environment");
274
+ }
275
+ const enc = new TextEncoder();
276
+ const saltBytes = typeof salt === "string" ? enc.encode(salt) : salt ?? enc.encode("memorio:salt");
277
+ const keyMaterial = await globalThis.crypto.subtle.importKey(
278
+ "raw",
279
+ enc.encode(password),
280
+ { name: "PBKDF2" },
281
+ false,
282
+ ["deriveKey"]
283
+ );
284
+ return globalThis.crypto.subtle.deriveKey(
285
+ { name: "PBKDF2", salt: saltBytes, iterations, hash: "SHA-256" },
286
+ keyMaterial,
287
+ { name: alg, length: 256 },
288
+ false,
289
+ ["encrypt", "decrypt"]
290
+ );
291
+ },
292
+ ///
293
+ // Generate a fresh random CryptoKey (AES-GCM, 256-bit).
294
+ ///
295
+ async generateKey(alg = "AES-GCM") {
296
+ if (!_hasWebCrypto()) {
297
+ throw new Error("memorio encryption: Web Crypto API is not available in this environment");
298
+ }
299
+ return globalThis.crypto.subtle.generateKey(
300
+ { name: alg, length: 256 },
301
+ true,
302
+ ["encrypt", "decrypt"]
303
+ );
304
+ },
305
+ ///
306
+ // Generate a random salt for PBKDF2 key derivation.
307
+ ///
308
+ generateSalt(bytes = 16) {
309
+ const arr = new Uint8Array(bytes);
310
+ globalThis.crypto?.getRandomValues?.(arr);
311
+ return _b64encode(arr);
312
+ },
313
+ ///
314
+ // Export a CryptoKey to portable base64 strings so it can be stored
315
+ // (e.g. in an httpOnly cookie) and re-imported later with importKey().
316
+ //
317
+ // @param cryptoKey A raw CryptoKey (not a password string).
318
+ // @returns { key: string, iv: string } base64-encoded.
319
+ ///
320
+ async exportKey(cryptoKey) {
321
+ if (!_hasWebCrypto()) {
322
+ throw new Error("memorio encryption: Web Crypto API is not available in this environment");
323
+ }
324
+ const exported = await globalThis.crypto.subtle.exportKey("raw", cryptoKey);
325
+ return {
326
+ key: _b64encode(exported),
327
+ iv: ""
328
+ };
329
+ },
330
+ ///
331
+ // Import a CryptoKey from base64 strings produced by exportKey().
332
+ //
333
+ // @param keyData Base64-encoded raw key bytes.
334
+ // @param _ivData Ignored (kept for API compatibility with exportKey return).
335
+ // @returns A Promise<CryptoKey>.
336
+ ///
337
+ async importKey(keyData, _ivData) {
338
+ if (!_hasWebCrypto()) {
339
+ throw new Error("memorio encryption: Web Crypto API is not available in this environment");
340
+ }
341
+ const keyBytes = _b64decode(keyData);
342
+ if (keyBytes.length !== 32) {
343
+ throw new Error(`memorio encryption: AES-256 key must be exactly 32 bytes, got ${keyBytes.length}`);
344
+ }
345
+ return globalThis.crypto.subtle.importKey(
346
+ "raw",
347
+ keyBytes,
348
+ AES_GCM,
349
+ true,
350
+ ["encrypt", "decrypt"]
351
+ );
352
+ },
353
+ ///
354
+ // Encrypt a JavaScript value.
355
+ //
356
+ // @param value The value to encrypt (any JSON-serializable object).
357
+ // @param key A CryptoKey or a password string (password is derived via PBKDF2).
358
+ // @param keyId Optional label, stored in the envelope for key rotation.
359
+ // @returns An EncryptedEnvelope object.
360
+ ///
361
+ async encrypt(value, key, keyId) {
362
+ const cryptoKey = typeof key === "string" ? await this.deriveKey(key, void 0, "AES-GCM") : key;
363
+ const data = new TextEncoder().encode(JSON.stringify(value));
364
+ const iv = new Uint8Array(12);
365
+ globalThis.crypto.getRandomValues(iv);
366
+ const ciphertext = await globalThis.crypto.subtle.encrypt(
367
+ { name: "AES-GCM", iv },
368
+ cryptoKey,
369
+ data
370
+ );
371
+ const envelope = {
372
+ __memorio_encrypted: true,
373
+ v: 1,
374
+ alg: "AES-GCM",
375
+ iv: _b64encode(iv),
376
+ data: _b64encode(ciphertext)
377
+ };
378
+ if (keyId) envelope.keyId = keyId;
379
+ if (DEV) message_default(`encryption: encrypted value (alg=${envelope.alg})`);
380
+ return envelope;
381
+ },
382
+ ///
383
+ // Decrypt an EncryptedEnvelope.
384
+ //
385
+ // @param envelope The envelope object returned by encrypt().
386
+ // @param key A CryptoKey or a password string.
387
+ // @returns The original value (parsed from JSON).
388
+ ///
389
+ async decrypt(envelope, key) {
390
+ if (!_isEncrypted(envelope)) {
391
+ throw new Error("memorio encryption: value is not a valid encrypted envelope");
392
+ }
393
+ const cryptoKey = typeof key === "string" ? await this.deriveKey(key, void 0, "AES-GCM") : key;
394
+ const iv = _b64decode(envelope.iv);
395
+ const data = _b64decode(envelope.data);
396
+ const decrypted = await globalThis.crypto.subtle.decrypt(
397
+ { name: "AES-GCM", iv },
398
+ cryptoKey,
399
+ data
400
+ );
401
+ return JSON.parse(new TextDecoder().decode(new Uint8Array(decrypted)));
402
+ },
403
+ ///
404
+ // Convenience: encrypt with a password (derives the key internally).
405
+ // Returns a JSON string you can store anywhere.
406
+ ///
407
+ async encryptWithPassword(value, password, salt, keyId) {
408
+ const env = await this.encrypt(value, password, keyId);
409
+ return JSON.stringify(env);
410
+ },
411
+ ///
412
+ // Convenience: decrypt a JSON envelope string with a password.
413
+ ///
414
+ async decryptWithPassword(envelopeJson, password, _salt) {
415
+ const envelope = JSON.parse(envelopeJson);
416
+ return this.decrypt(envelope, password);
417
+ },
418
+ ///
419
+ // Type guard: check whether a value is an encrypted envelope.
420
+ ///
421
+ isEncrypted(value) {
422
+ return _isEncrypted(value);
423
+ },
424
+ ///
425
+ // Configure a default encryption key for auto-encrypt mode.
426
+ // When set on `store` or `session`, all writes are encrypted and all
427
+ // reads attempt decryption automatically.
428
+ ///
429
+ config(opts) {
430
+ if (opts.key !== void 0) this._defaultKey = opts.key;
431
+ if (opts.keyId !== void 0) this._defaultKeyId = opts.keyId;
432
+ return this;
433
+ },
434
+ ///
435
+ // Internal: resolve the configured default key.
436
+ ///
437
+ get _key() {
438
+ return this._defaultKey ?? null;
439
+ },
440
+ get _keyId() {
441
+ return this._defaultKeyId;
442
+ }
443
+ };
444
+ }
445
+ });
446
+
208
447
  // core/platform.ts
209
448
  function generateSessionId() {
210
449
  const anyGlobal = globalThis;
@@ -219,6 +458,9 @@ function generateSessionId() {
219
458
  return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
220
459
  }
221
460
  function detectPlatform() {
461
+ if (_isBun()) {
462
+ return "bun";
463
+ }
222
464
  const globalAny = globalThis;
223
465
  if (globalAny.Deno && globalAny.Deno.version) {
224
466
  return "deno";
@@ -234,6 +476,13 @@ function detectPlatform() {
234
476
  }
235
477
  return "unknown";
236
478
  }
479
+ function _isBun() {
480
+ const globalAny = globalThis;
481
+ return typeof globalAny.Bun !== "undefined" && typeof globalAny.Bun.version === "string";
482
+ }
483
+ function isBun() {
484
+ return _isBun();
485
+ }
237
486
  function isBrowser() {
238
487
  const platform = detectPlatform();
239
488
  return platform === "browser";
@@ -287,6 +536,9 @@ function hasSqlJs() {
287
536
  }
288
537
  return typeof anyGlobal.window !== "undefined";
289
538
  }
539
+ function hasBunSqlite() {
540
+ return _isBun();
541
+ }
290
542
  function hasDispatchEvent() {
291
543
  return typeof globalThis.dispatchEvent === "function";
292
544
  }
@@ -299,6 +551,7 @@ function getCapabilities() {
299
551
  hasLocalStorage: getLocalStorage() !== null,
300
552
  hasIndexedDB: hasIndexedDB(),
301
553
  hasSqlJs: hasSqlJs(),
554
+ hasBunSqlite: hasBunSqlite(),
302
555
  hasDispatchEvent: hasDispatchEvent(),
303
556
  hasNavigator: typeof navigator !== "undefined",
304
557
  hasProcess: typeof process !== "undefined",
@@ -358,8 +611,9 @@ function initializePlatform() {
358
611
  };
359
612
  }
360
613
  }
361
- function createContext(name) {
614
+ function createContext(name, opts) {
362
615
  const contextId = name || `context_${generateSessionId()}`;
616
+ const encKey = opts?.encryptionKey;
363
617
  setCurrentContext(contextId);
364
618
  const contextStorage = {
365
619
  state: {},
@@ -368,10 +622,31 @@ function createContext(name) {
368
622
  cache: /* @__PURE__ */ new Map()
369
623
  };
370
624
  _contexts.set(contextId, contextStorage);
625
+ function _isEncrypted2(value) {
626
+ return encryption.isEncrypted(value);
627
+ }
628
+ __name(_isEncrypted2, "_isEncrypted");
371
629
  return {
372
630
  id: contextId,
373
631
  state: contextStorage.state,
374
- store: {
632
+ store: encKey ? {
633
+ get: /* @__PURE__ */ __name(async (key) => {
634
+ const data = contextStorage.store.get(key);
635
+ if (!data) return null;
636
+ const parsed = JSON.parse(data);
637
+ if (_isEncrypted2(parsed)) return encryption.decrypt(parsed, encKey);
638
+ return parsed;
639
+ }, "get"),
640
+ set: /* @__PURE__ */ __name(async (key, value) => {
641
+ const env = await encryption.encrypt(value, encKey);
642
+ contextStorage.store.set(key, JSON.stringify(env));
643
+ }, "set"),
644
+ remove: /* @__PURE__ */ __name((key) => contextStorage.store.delete(key), "remove"),
645
+ removeAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "removeAll"),
646
+ clearAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "clearAll"),
647
+ size: /* @__PURE__ */ __name(() => contextStorage.store.size, "size"),
648
+ isPersistent: false
649
+ } : {
375
650
  get: /* @__PURE__ */ __name((key) => {
376
651
  const data = contextStorage.store.get(key);
377
652
  return data ? JSON.parse(data) : null;
@@ -385,7 +660,24 @@ function createContext(name) {
385
660
  size: /* @__PURE__ */ __name(() => contextStorage.store.size, "size"),
386
661
  isPersistent: false
387
662
  },
388
- session: {
663
+ session: encKey ? {
664
+ get: /* @__PURE__ */ __name(async (key) => {
665
+ const data = contextStorage.session.get(key);
666
+ if (!data) return null;
667
+ const parsed = JSON.parse(data);
668
+ if (_isEncrypted2(parsed)) return encryption.decrypt(parsed, encKey);
669
+ return parsed;
670
+ }, "get"),
671
+ set: /* @__PURE__ */ __name(async (key, value) => {
672
+ const env = await encryption.encrypt(value, encKey);
673
+ contextStorage.session.set(key, JSON.stringify(env));
674
+ }, "set"),
675
+ remove: /* @__PURE__ */ __name((key) => contextStorage.session.delete(key), "remove"),
676
+ removeAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "removeAll"),
677
+ clearAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "clearAll"),
678
+ size: /* @__PURE__ */ __name(() => contextStorage.session.size, "size"),
679
+ isPersistent: false
680
+ } : {
389
681
  get: /* @__PURE__ */ __name((key) => {
390
682
  const data = contextStorage.session.get(key);
391
683
  return data ? JSON.parse(data) : null;
@@ -405,7 +697,8 @@ function createContext(name) {
405
697
  remove: /* @__PURE__ */ __name((key) => contextStorage.cache.delete(key), "remove"),
406
698
  removeAll: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "removeAll"),
407
699
  clear: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "clear")
408
- }
700
+ },
701
+ encryptionKey: encKey
409
702
  };
410
703
  }
411
704
  function listContexts() {
@@ -422,8 +715,11 @@ var init_platform = __esm({
422
715
  "core/platform.ts"() {
423
716
  init_esm_shims();
424
717
  init_internal();
718
+ init_encryption();
425
719
  __name(generateSessionId, "generateSessionId");
426
720
  __name(detectPlatform, "detectPlatform");
721
+ __name(_isBun, "_isBun");
722
+ __name(isBun, "isBun");
427
723
  __name(isBrowser, "isBrowser");
428
724
  __name(isNode, "isNode");
429
725
  __name(isDeno, "isDeno");
@@ -432,6 +728,7 @@ var init_platform = __esm({
432
728
  __name(getLocalStorage, "getLocalStorage");
433
729
  __name(hasIndexedDB, "hasIndexedDB");
434
730
  __name(hasSqlJs, "hasSqlJs");
731
+ __name(hasBunSqlite, "hasBunSqlite");
435
732
  __name(hasDispatchEvent, "hasDispatchEvent");
436
733
  __name(getCapabilities, "getCapabilities");
437
734
  _eventListenerStorage = /* @__PURE__ */ new Map();
@@ -457,6 +754,9 @@ function _getFallbackStorage() {
457
754
  }
458
755
  return _fallbackStorageByContext.get(key);
459
756
  }
757
+ function _isEncryptedEnvelope(value) {
758
+ return encryption.isEncrypted(value);
759
+ }
460
760
  function _getPrefix() {
461
761
  const contextName = internal_default.currentContext || "";
462
762
  return contextName ? `${contextName}-` : `memorio_store_`;
@@ -493,17 +793,23 @@ function _remove(prefixedName) {
493
793
  }
494
794
  return false;
495
795
  }
496
- var _localStorage, _fallbackStorageByContext, _hasStorage, STORE_INSTANCE_KEY, store;
796
+ var _localStorage, _fallbackStorageByContext, _hasStorage, _encryptionKey, _onError, _maxObjectSize, _maxTotalSize, STORE_INSTANCE_KEY, store;
497
797
  var init_store = __esm({
498
798
  "functions/store/index.ts"() {
499
799
  init_esm_shims();
500
800
  init_platform();
501
801
  init_internal();
502
802
  init_message();
803
+ init_encryption();
503
804
  _localStorage = getLocalStorage();
504
805
  _fallbackStorageByContext = /* @__PURE__ */ new Map();
505
806
  __name(_getFallbackStorage, "_getFallbackStorage");
506
807
  _hasStorage = _localStorage !== null;
808
+ _encryptionKey = null;
809
+ _onError = null;
810
+ _maxObjectSize = 0;
811
+ _maxTotalSize = 0;
812
+ __name(_isEncryptedEnvelope, "_isEncryptedEnvelope");
507
813
  __name(_getPrefix, "_getPrefix");
508
814
  __name(_prefixKey, "_prefixKey");
509
815
  __name(_read, "_read");
@@ -520,16 +826,24 @@ var init_store = __esm({
520
826
  /**
521
827
  * Gets a value from storage.
522
828
  * @param name The key to retrieve.
523
- * @returns The parsed value or null if not found.
829
+ * @param opts Optional { decrypt: key } to decrypt an encrypted envelope.
830
+ * When no key is passed, encrypted envelopes are returned as-is.
831
+ * If a default key was configured via store.config(), it is used automatically.
832
+ * @returns The parsed value, a Promise<parsed value> when decrypting, or null if not found.
524
833
  */
525
834
  get: {
526
- value: /* @__PURE__ */ __name((name) => {
835
+ value: /* @__PURE__ */ __name((name, opts) => {
527
836
  if (!name) {
528
837
  console.warn("[memorio store] store.get() called with empty or null key - returning null");
529
838
  return null;
530
839
  }
531
840
  try {
532
- return _read(_prefixKey(name));
841
+ const raw = _read(_prefixKey(name));
842
+ const key = opts?.decrypt ?? _encryptionKey;
843
+ if (key && _isEncryptedEnvelope(raw)) {
844
+ return encryption.decrypt(raw, key);
845
+ }
846
+ return raw;
533
847
  } catch (err) {
534
848
  message(`Error parsing store item '${name}': ${err}`);
535
849
  }
@@ -554,10 +868,13 @@ var init_store = __esm({
554
868
  * Sets a value in storage.
555
869
  * @param name The key to set.
556
870
  * @param value The value to store (objects, arrays, primitives).
557
- * @returns true if written, false if the key was rejected.
871
+ * @param opts Optional { encrypt: key } to encrypt the value before storage.
872
+ * If a default key was configured via store.config(), it is used automatically.
873
+ * When encryption is used, returns a Promise<boolean>.
874
+ * @returns true if written, false if rejected or error.
558
875
  */
559
876
  set: {
560
- value: /* @__PURE__ */ __name((name, value) => {
877
+ value: /* @__PURE__ */ __name((name, value, opts) => {
561
878
  if (!name) {
562
879
  console.warn("[memorio store] store.set() called with empty or null key - write aborted");
563
880
  return false;
@@ -569,15 +886,66 @@ var init_store = __esm({
569
886
  message("Storing functions is not secure and is blocked for safety.");
570
887
  return false;
571
888
  }
889
+ if (_maxObjectSize > 0 || _maxTotalSize > 0) {
890
+ let serializedSize = 0;
891
+ try {
892
+ serializedSize = new TextEncoder().encode(JSON.stringify(value)).length;
893
+ } catch {
894
+ serializedSize = 0;
895
+ }
896
+ if (_maxObjectSize > 0 && serializedSize > _maxObjectSize) {
897
+ const err = new Error(`Object size (${serializedSize} bytes) exceeds maxObjectSize (${_maxObjectSize} bytes)`);
898
+ _onError?.(err, { operation: "set" });
899
+ return false;
900
+ }
901
+ if (_maxTotalSize > 0) {
902
+ const currentTotal = store.size() * 1024;
903
+ const existingItemSize = _hasStorage ? _localStorage.getItem(prefixedName)?.length ?? 0 : _getFallbackStorage().get(prefixedName)?.length ?? 0;
904
+ const projected = currentTotal * 1024 - existingItemSize + serializedSize;
905
+ if (projected > _maxTotalSize) {
906
+ const err = new Error(`Total store size (${projected} bytes) exceeds maxTotalSize (${_maxTotalSize} bytes)`);
907
+ _onError?.(err, { operation: "set" });
908
+ return false;
909
+ }
910
+ }
911
+ }
912
+ const key = opts?.encrypt ?? _encryptionKey;
913
+ if (key) {
914
+ return encryption.encrypt(value, key).then((env) => {
915
+ _write(prefixedName, env);
916
+ return true;
917
+ }).catch((err) => {
918
+ message(`Error encrypting store item '${name}': ${err}`);
919
+ _onError?.(err, { operation: "set" });
920
+ return false;
921
+ });
922
+ }
572
923
  try {
573
924
  _write(prefixedName, value);
574
925
  } catch (err) {
575
926
  message(`Error setting store item '${name}': ${err}`);
927
+ _onError?.(err, { operation: "set" });
576
928
  return false;
577
929
  }
578
930
  return true;
579
931
  }, "value")
580
932
  },
933
+ /**
934
+ * Configure store-wide behavior.
935
+ * @param opts Optional { encryptionKey } to enable automatic encryption
936
+ * for all set/get operations. When set, values are encrypted
937
+ * on write and decrypted on read (if the value is an envelope).
938
+ * @returns The store instance for chaining.
939
+ */
940
+ config: {
941
+ value: /* @__PURE__ */ __name((opts) => {
942
+ if (opts.encryptionKey !== void 0) _encryptionKey = opts.encryptionKey;
943
+ if (opts.onError !== void 0) _onError = opts.onError;
944
+ if (opts.maxObjectSize !== void 0) _maxObjectSize = opts.maxObjectSize;
945
+ if (opts.maxTotalSize !== void 0) _maxTotalSize = opts.maxTotalSize;
946
+ return store;
947
+ }, "value")
948
+ },
581
949
  /**
582
950
  * Removes a value from storage.
583
951
  * @param name The key to remove.
@@ -1163,6 +1531,91 @@ var init_idb = __esm({
1163
1531
  }
1164
1532
  });
1165
1533
 
1534
+ // functions/sqlite/tools/bun-sqlite-adapter.ts
1535
+ var bun_sqlite_adapter_exports = {};
1536
+ __export(bun_sqlite_adapter_exports, {
1537
+ BunSqlJsDatabase: () => BunSqlJsDatabase,
1538
+ createBunSqlJs: () => createBunSqlJs
1539
+ });
1540
+ async function _loadDatabase() {
1541
+ if (!_DatabaseClass) {
1542
+ const mod = await import('bun:sqlite');
1543
+ _DatabaseClass = mod.Database;
1544
+ }
1545
+ return _DatabaseClass;
1546
+ }
1547
+ async function createBunSqlJs() {
1548
+ await _loadDatabase();
1549
+ return {
1550
+ Database: BunSqlJsDatabase,
1551
+ version: "bun:sqlite"
1552
+ };
1553
+ }
1554
+ var _DatabaseClass, BunSqlJsDatabase;
1555
+ var init_bun_sqlite_adapter = __esm({
1556
+ "functions/sqlite/tools/bun-sqlite-adapter.ts"() {
1557
+ init_esm_shims();
1558
+ _DatabaseClass = null;
1559
+ __name(_loadDatabase, "_loadDatabase");
1560
+ BunSqlJsDatabase = class {
1561
+ static {
1562
+ __name(this, "BunSqlJsDatabase");
1563
+ }
1564
+ _db;
1565
+ _lastRunChanges = 0;
1566
+ constructor(data) {
1567
+ this._lastRunChanges = 0;
1568
+ if (typeof data === "string") {
1569
+ this._db = new _DatabaseClass(data);
1570
+ } else {
1571
+ this._db = new _DatabaseClass(":memory:");
1572
+ }
1573
+ }
1574
+ run(sql, params = []) {
1575
+ const info = this._db.run(sql, ...params);
1576
+ this._lastRunChanges = info?.changes ?? 0;
1577
+ return info;
1578
+ }
1579
+ getRowsModified() {
1580
+ return this._lastRunChanges;
1581
+ }
1582
+ prepare(sql, params = []) {
1583
+ const rows = params.length > 0 ? this._db.query(sql).all(...params) : this._db.query(sql).all();
1584
+ return {
1585
+ _rows: rows,
1586
+ _idx: -1,
1587
+ step() {
1588
+ this._idx++;
1589
+ return this._idx < this._rows.length;
1590
+ },
1591
+ getAsObject() {
1592
+ return this._rows[this._idx] || {};
1593
+ },
1594
+ get() {
1595
+ return this._rows[this._idx] ? Object.values(this._rows[this._idx]) : [];
1596
+ },
1597
+ free() {
1598
+ this._rows = null;
1599
+ }
1600
+ };
1601
+ }
1602
+ export() {
1603
+ throw new Error("Bun:sqlite does not support in-memory export - use store/session for persistence, or use the sql.js backend for export/import operations");
1604
+ }
1605
+ close() {
1606
+ try {
1607
+ this._db.close();
1608
+ } catch {
1609
+ }
1610
+ }
1611
+ get version() {
1612
+ return "bun:sqlite";
1613
+ }
1614
+ };
1615
+ __name(createBunSqlJs, "createBunSqlJs");
1616
+ }
1617
+ });
1618
+
1166
1619
  // functions/sqlite/tools/db.support.ts
1167
1620
  var db_support_exports2 = {};
1168
1621
  function _inDocument() {
@@ -1223,11 +1676,18 @@ var init_db_support2 = __esm({
1223
1676
  return g3.initSqlJs || g3;
1224
1677
  }, "_loadSqlJsFromCdn");
1225
1678
  sqlite.db.support = () => {
1226
- return hasSqlJs();
1679
+ return hasSqlJs() || hasBunSqlite();
1227
1680
  };
1228
1681
  sqlite.db.getSQL = async () => {
1229
1682
  if (_SQL) return _SQL;
1230
1683
  if (_loading) return _loading;
1684
+ if (hasBunSqlite()) {
1685
+ const { createBunSqlJs: createBunSqlJs2 } = await Promise.resolve().then(() => (init_bun_sqlite_adapter(), bun_sqlite_adapter_exports));
1686
+ _SQL = await createBunSqlJs2();
1687
+ globalThis.sqliteVersion = _SQL.version;
1688
+ message_default("Memorio SQLite: bun:sqlite engine loaded");
1689
+ return _SQL;
1690
+ }
1231
1691
  const g3 = globalThis;
1232
1692
  const cfg = g3.sqliteConfig || {};
1233
1693
  const p = (async () => {
@@ -1254,7 +1714,7 @@ var init_db_support2 = __esm({
1254
1714
  } catch (_) {
1255
1715
  }
1256
1716
  try {
1257
- sqlite._warning = "Memorio SQLite: sql.js could not be loaded. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => <your sql.js import>() }).";
1717
+ sqlite._warning = "Memorio SQLite: sql.js could not be loaded. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => import(<your sql.js import>()) }).";
1258
1718
  } catch (_) {
1259
1719
  }
1260
1720
  console.warn("Memorio SQLite: failed to load sql.js", err);
@@ -1277,7 +1737,7 @@ function _ns() {
1277
1737
  function _key(name) {
1278
1738
  return `memorio:sqlite:db:${_ns()}:${name}`;
1279
1739
  }
1280
- function _b64encode(buf) {
1740
+ function _b64encode2(buf) {
1281
1741
  const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
1282
1742
  let binary = "";
1283
1743
  const len = bytes.byteLength;
@@ -1285,7 +1745,7 @@ function _b64encode(buf) {
1285
1745
  if (typeof btoa === "function") return btoa(binary);
1286
1746
  return typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : "";
1287
1747
  }
1288
- function _b64decode(b64) {
1748
+ function _b64decode2(b64) {
1289
1749
  if (typeof Buffer !== "undefined") {
1290
1750
  return new Uint8Array(Buffer.from(b64, "base64"));
1291
1751
  }
@@ -1307,7 +1767,7 @@ function saveSnapshot(name) {
1307
1767
  }
1308
1768
  try {
1309
1769
  const blob = db.export();
1310
- store.set(_key(name), _b64encode(blob));
1770
+ store.set(_key(name), _b64encode2(blob));
1311
1771
  message_default(`Memorio SQLite: persisted '${name}' to store`);
1312
1772
  resolve(true);
1313
1773
  } catch (err) {
@@ -1320,7 +1780,7 @@ function loadSnapshot(name) {
1320
1780
  const b64 = store.get(_key(name));
1321
1781
  if (!b64) return null;
1322
1782
  try {
1323
- return _b64decode(b64);
1783
+ return _b64decode2(b64);
1324
1784
  } catch {
1325
1785
  return null;
1326
1786
  }
@@ -1355,8 +1815,8 @@ var init_persist = __esm({
1355
1815
  _exportTimers = {};
1356
1816
  __name(_ns, "_ns");
1357
1817
  __name(_key, "_key");
1358
- __name(_b64encode, "_b64encode");
1359
- __name(_b64decode, "_b64decode");
1818
+ __name(_b64encode2, "_b64encode");
1819
+ __name(_b64decode2, "_b64decode");
1360
1820
  __name(saveSnapshot, "saveSnapshot");
1361
1821
  __name(loadSnapshot, "loadSnapshot");
1362
1822
  __name(removeSnapshot, "removeSnapshot");
@@ -1561,7 +2021,14 @@ var init_db_export = __esm({
1561
2021
  init_sqlite();
1562
2022
  sqlite.db.export = async (name = "memorio") => {
1563
2023
  const db = sqlite.db.get(name);
1564
- return db.export();
2024
+ try {
2025
+ return db.export();
2026
+ } catch (err) {
2027
+ if (db && db.version === "bun:sqlite") {
2028
+ throw new Error(`memorio sqlite: export is not supported under Bun's native sqlite. Use \`store\` or \`session\` for persistence instead. If you need a binary dump, run this code under the browser/sql.js backend.`);
2029
+ }
2030
+ throw err;
2031
+ }
1565
2032
  };
1566
2033
  }
1567
2034
  });
@@ -1645,13 +2112,14 @@ var init_data_get2 = __esm({
1645
2112
  });
1646
2113
 
1647
2114
  // functions/sqlite/index.ts
1648
- var _hasSqlJs, sqlite;
2115
+ var _hasSqlJs, _hasBunSqlite, sqlite;
1649
2116
  var init_sqlite = __esm({
1650
2117
  "functions/sqlite/index.ts"() {
1651
2118
  init_esm_shims();
1652
2119
  init_platform();
1653
2120
  init_env();
1654
2121
  _hasSqlJs = hasSqlJs();
2122
+ _hasBunSqlite = hasBunSqlite();
1655
2123
  sqlite = {
1656
2124
  db: {},
1657
2125
  query: {},
@@ -1678,7 +2146,7 @@ var init_sqlite = __esm({
1678
2146
  return g3.sqliteReady;
1679
2147
  }, "get")
1680
2148
  });
1681
- if (_hasSqlJs) {
2149
+ if (_hasSqlJs || _hasBunSqlite) {
1682
2150
  (async () => {
1683
2151
  Object.defineProperty(sqlite, "db", { value: {}, writable: false, configurable: true, enumerable: true });
1684
2152
  Object.defineProperty(sqlite, "query", { value: {}, writable: false, configurable: true, enumerable: true });
@@ -1706,11 +2174,11 @@ var init_sqlite = __esm({
1706
2174
  })();
1707
2175
  } else {
1708
2176
  sqlite._disabled = true;
1709
- sqlite._warning = 'SQLite (sql.js) is not available in this environment. It requires a browser with WebAssembly support. Install the optional "sql.js" package to enable it.';
2177
+ sqlite._warning = 'SQLite is not available in this environment. It requires a browser with WebAssembly (sql.js) or the Bun runtime (bun:sqlite). Install the optional "sql.js" package to enable it in browsers.';
1710
2178
  if (DEV) {
1711
2179
  globalThis.sqliteDisabled = true;
1712
2180
  globalThis.sqliteWarning = sqlite._warning;
1713
- console.warn("Memorio SQLite: sql.js is not available in this environment (requires browser + WebAssembly). Use store or session for persistence.");
2181
+ console.warn("Memorio SQLite: no engine available in this environment (requires browser + WebAssembly, or Bun runtime with bun:sqlite). Use store or session for persistence.");
1714
2182
  }
1715
2183
  }
1716
2184
  }
@@ -2725,6 +3193,7 @@ init_esm_shims();
2725
3193
  init_platform();
2726
3194
  init_internal();
2727
3195
  init_message();
3196
+ init_encryption();
2728
3197
  var _sessionStorage = getSessionStorage();
2729
3198
  var _fallbackStorageByContext2 = /* @__PURE__ */ new Map();
2730
3199
  function _getFallbackStorage2() {
@@ -2737,6 +3206,14 @@ function _getFallbackStorage2() {
2737
3206
  }
2738
3207
  __name(_getFallbackStorage2, "_getFallbackStorage");
2739
3208
  var _hasStorage2 = _sessionStorage !== null;
3209
+ var _encryptionKey2 = null;
3210
+ var _onError2 = null;
3211
+ var _maxObjectSize2 = 0;
3212
+ var _maxTotalSize2 = 0;
3213
+ function _isEncryptedEnvelope2(value) {
3214
+ return encryption.isEncrypted(value);
3215
+ }
3216
+ __name(_isEncryptedEnvelope2, "_isEncryptedEnvelope");
2740
3217
  function _getPrefix2() {
2741
3218
  const contextName = internal_default.currentContext || "";
2742
3219
  return contextName ? `${contextName}-` : `memorio_session_`;
@@ -2790,16 +3267,22 @@ if (globalThis[SESSION_INSTANCE_KEY]) {
2790
3267
  /**
2791
3268
  * Gets a value from storage.
2792
3269
  * @param name The key to retrieve.
2793
- * @returns The parsed value or null if not found.
3270
+ * @param opts Optional { decrypt: key } to decrypt an encrypted envelope.
3271
+ * @returns The parsed value, a Promise when decrypting, or null if not found.
2794
3272
  */
2795
3273
  get: {
2796
- value: /* @__PURE__ */ __name((name) => {
3274
+ value: /* @__PURE__ */ __name((name, opts) => {
2797
3275
  if (!name) {
2798
3276
  console.warn("[memorio session] session.get() called with empty or null key - returning null");
2799
3277
  return null;
2800
3278
  }
2801
3279
  try {
2802
- return _read2(_prefixKey2(name));
3280
+ const raw = _read2(_prefixKey2(name));
3281
+ const key = opts?.decrypt ?? _encryptionKey2;
3282
+ if (key && _isEncryptedEnvelope2(raw)) {
3283
+ return encryption.decrypt(raw, key);
3284
+ }
3285
+ return raw;
2803
3286
  } catch (err) {
2804
3287
  message(`Error parsing session item '${name}':${err}`);
2805
3288
  }
@@ -2810,10 +3293,11 @@ if (globalThis[SESSION_INSTANCE_KEY]) {
2810
3293
  * Sets a value in storage.
2811
3294
  * @param name The key to set.
2812
3295
  * @param value The value to store.
2813
- * @returns true if written, false if the key was rejected.
3296
+ * @param opts Optional { encrypt: key } to encrypt before storage.
3297
+ * @returns true if written, false if rejected. Returns a Promise when encrypting.
2814
3298
  */
2815
3299
  set: {
2816
- value: /* @__PURE__ */ __name((name, value) => {
3300
+ value: /* @__PURE__ */ __name((name, value, opts) => {
2817
3301
  if (!name) {
2818
3302
  console.warn("[memorio session] session.set() called with empty or null key - write aborted");
2819
3303
  return false;
@@ -2825,15 +3309,63 @@ if (globalThis[SESSION_INSTANCE_KEY]) {
2825
3309
  message("It's not secure to session functions.");
2826
3310
  return false;
2827
3311
  }
3312
+ if (_maxObjectSize2 > 0 || _maxTotalSize2 > 0) {
3313
+ let serializedSize = 0;
3314
+ try {
3315
+ serializedSize = new TextEncoder().encode(JSON.stringify(value)).length;
3316
+ } catch {
3317
+ serializedSize = 0;
3318
+ }
3319
+ if (_maxObjectSize2 > 0 && serializedSize > _maxObjectSize2) {
3320
+ const err = new Error(`Object size (${serializedSize} bytes) exceeds maxObjectSize (${_maxObjectSize2} bytes)`);
3321
+ _onError2?.(err, { operation: "set" });
3322
+ return false;
3323
+ }
3324
+ if (_maxTotalSize2 > 0) {
3325
+ const currentTotal = session.size() * 1024;
3326
+ const existingItemSize = _sessionStorage ? _sessionStorage.getItem(prefixedName)?.length ?? 0 : _getFallbackStorage2().get(prefixedName)?.length ?? 0;
3327
+ const projected = currentTotal - existingItemSize + serializedSize;
3328
+ if (projected > _maxTotalSize2) {
3329
+ const err = new Error(`Total session size (${projected} bytes) exceeds maxTotalSize (${_maxTotalSize2} bytes)`);
3330
+ _onError2?.(err, { operation: "set" });
3331
+ return false;
3332
+ }
3333
+ }
3334
+ }
3335
+ const key = opts?.encrypt ?? _encryptionKey2;
3336
+ if (key) {
3337
+ return encryption.encrypt(value, key).then((env) => {
3338
+ _write2(prefixedName, env);
3339
+ return true;
3340
+ }).catch((err) => {
3341
+ message(`Error encrypting session item '${name}': ${err}`);
3342
+ _onError2?.(err, { operation: "set" });
3343
+ return false;
3344
+ });
3345
+ }
2828
3346
  try {
2829
3347
  _write2(prefixedName, value);
2830
3348
  } catch (err) {
2831
3349
  message(`Error setting session item '${name}': ${err}`);
3350
+ _onError2?.(err, { operation: "set" });
2832
3351
  return false;
2833
3352
  }
2834
3353
  return true;
2835
3354
  }, "value")
2836
3355
  },
3356
+ /**
3357
+ * Configure session-wide behavior.
3358
+ * @param opts { encryptionKey, onError, maxObjectSize, maxTotalSize }
3359
+ */
3360
+ config: {
3361
+ value: /* @__PURE__ */ __name((opts) => {
3362
+ if (opts.encryptionKey !== void 0) _encryptionKey2 = opts.encryptionKey;
3363
+ if (opts.onError !== void 0) _onError2 = opts.onError;
3364
+ if (opts.maxObjectSize !== void 0) _maxObjectSize2 = opts.maxObjectSize;
3365
+ if (opts.maxTotalSize !== void 0) _maxTotalSize2 = opts.maxTotalSize;
3366
+ return session;
3367
+ }, "value")
3368
+ },
2837
3369
  /**
2838
3370
  * Removes a value from storage.
2839
3371
  * @param name The key to remove.
@@ -3200,92 +3732,685 @@ var useObserver = /* @__PURE__ */ __name(((func, deps = []) => {
3200
3732
  }), "useObserver");
3201
3733
 
3202
3734
  // index.ts
3203
- init_message();
3735
+ init_encryption();
3204
3736
 
3205
- // functions/logger/index.ts
3737
+ // functions/computed/index.ts
3206
3738
  init_esm_shims();
3207
- init_internal();
3208
- init_message();
3209
3739
  init_env();
3210
- var defaultConfig = {
3211
- enabled: true,
3212
- logToConsole: true,
3213
- modules: ["state", "store", "session", "cache", "idb"],
3214
- maxEntries: 1e3
3215
- };
3216
- function isDebugEnabled() {
3217
- return DEV && internal_default.debug === true;
3740
+ init_message();
3741
+ var DEFAULT_EQUALITY = /* @__PURE__ */ __name((prev, next) => {
3742
+ if (prev === next) return true;
3743
+ if (prev == null || next == null) return false;
3744
+ if (typeof prev !== typeof next) return false;
3745
+ if (typeof prev !== "object") return false;
3746
+ try {
3747
+ return JSON.stringify(prev) === JSON.stringify(next);
3748
+ } catch {
3749
+ return false;
3750
+ }
3751
+ }, "DEFAULT_EQUALITY");
3752
+ var computedMap = /* @__PURE__ */ new Map();
3753
+ function _normalizeKey(key) {
3754
+ if (!key || typeof key !== "string") return "";
3755
+ const normalized = key.startsWith("state.") ? key : `state.${key}`;
3756
+ return normalized;
3757
+ }
3758
+ __name(_normalizeKey, "_normalizeKey");
3759
+ function _invalidate(key) {
3760
+ const entry = computedMap.get(key);
3761
+ if (!entry) return;
3762
+ const newValue = _recompute(entry);
3763
+ if (entry.equality(entry.lastValue, newValue)) {
3764
+ return;
3765
+ }
3766
+ entry.lastValue = newValue;
3767
+ for (const sub of entry.subscribers) {
3768
+ try {
3769
+ sub(newValue);
3770
+ } catch (err) {
3771
+ if (DEV) console.error("[memorio computed] subscriber error:", err);
3772
+ }
3773
+ }
3774
+ dispatch.set("memorio:computed:" + key, { detail: { key, value: newValue } });
3218
3775
  }
3219
- __name(isDebugEnabled, "isDebugEnabled");
3220
- var config = { ...defaultConfig };
3221
- var logHistory = [];
3222
- var configure = /* @__PURE__ */ __name((options) => {
3223
- config = { ...config, ...options };
3224
- }, "configure");
3225
- var enable = /* @__PURE__ */ __name(() => {
3226
- config.enabled = true;
3227
- }, "enable");
3228
- var disable = /* @__PURE__ */ __name(() => {
3229
- config.enabled = false;
3230
- }, "disable");
3231
- var isEnabled = /* @__PURE__ */ __name((module) => {
3232
- return config.enabled && config.modules.includes(module);
3233
- }, "isEnabled");
3234
- var log = /* @__PURE__ */ __name((module, action, path2, value, previousValue) => {
3235
- if (!isEnabled(module)) return;
3236
- const entry = {
3237
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3238
- module,
3239
- action,
3240
- path: path2,
3241
- value,
3242
- previousValue
3243
- };
3244
- logHistory.push(entry);
3245
- if (logHistory.length > config.maxEntries) {
3246
- logHistory.shift();
3776
+ __name(_invalidate, "_invalidate");
3777
+ function _readStatePath(path2) {
3778
+ const entry = computedMap.get(path2);
3779
+ if (entry) {
3780
+ return entry.lastValue;
3247
3781
  }
3248
- if (config.logToConsole && isDebugEnabled()) {
3249
- const prefix = `[Memorio:${module.toUpperCase()}]`;
3250
- const color = getModuleColor(module);
3251
- message_default(
3252
- `%c${prefix}%c ${action} ${path2},
3253
- color: ${color}; font-weight: bold,
3254
- color: inherit`
3255
- );
3256
- if (value !== void 0) {
3257
- message_default(` \u2192 value:${value}`);
3782
+ const normalized = path2.startsWith("state.") ? path2 : `state.${path2}`;
3783
+ const segments = normalized.replace(/^state\./, "").split(".");
3784
+ let current = globalThis.state;
3785
+ if (current) {
3786
+ for (const seg of segments) {
3787
+ if (current === null || current === void 0) break;
3788
+ try {
3789
+ current = current[seg];
3790
+ } catch {
3791
+ return void 0;
3792
+ }
3258
3793
  }
3259
- if (previousValue !== void 0) {
3260
- message_default(` \u2190 previous:${previousValue}`);
3794
+ }
3795
+ return current === void 0 ? null : current;
3796
+ }
3797
+ __name(_readStatePath, "_readStatePath");
3798
+ function _recompute(entry) {
3799
+ const newDeps = /* @__PURE__ */ new Set();
3800
+ const trackerGet = /* @__PURE__ */ __name((path2) => {
3801
+ if (!path2 || typeof path2 !== "string") return void 0;
3802
+ newDeps.add(path2);
3803
+ return _readStatePath(path2);
3804
+ }, "trackerGet");
3805
+ try {
3806
+ return entry.selector(trackerGet);
3807
+ } catch (err) {
3808
+ if (DEV) console.error("[memorio computed] selector error:", err);
3809
+ message_default(`[memorio computed] selector error: ${err}`);
3810
+ return entry.lastValue;
3811
+ }
3812
+ }
3813
+ __name(_recompute, "_recompute");
3814
+ function _setupDeps(key, entry, deps) {
3815
+ for (const off of entry._dispatchUnsubscribers) off();
3816
+ entry._dispatchUnsubscribers = [];
3817
+ for (const dep of deps) {
3818
+ if (computedMap.has(dep)) {
3819
+ const computedEvent = "memorio:computed:" + dep;
3820
+ const off = dispatch.listen(computedEvent, () => _invalidate(key));
3821
+ if (off) entry._dispatchUnsubscribers.push(off);
3822
+ } else {
3823
+ const off = dispatch.listen(dep, () => _invalidate(key));
3824
+ if (off) entry._dispatchUnsubscribers.push(off);
3261
3825
  }
3262
3826
  }
3263
- if (config.customHandler) {
3264
- config.customHandler(entry);
3827
+ entry.deps = deps;
3828
+ }
3829
+ __name(_setupDeps, "_setupDeps");
3830
+ function _compute(key, selector, opts) {
3831
+ const normalizedKey = _normalizeKey(key);
3832
+ const cacheKey = opts?.equalityKey ? `${opts.equalityKey}:${normalizedKey}` : normalizedKey;
3833
+ if (computedMap.has(cacheKey)) {
3834
+ const entry2 = computedMap.get(cacheKey);
3835
+ entry2.selector = selector;
3836
+ entry2.equality = opts?.equality || DEFAULT_EQUALITY;
3837
+ const newDeps2 = /* @__PURE__ */ new Set();
3838
+ const wrappedGet = /* @__PURE__ */ __name((path2) => {
3839
+ newDeps2.add(path2);
3840
+ return _readStatePath(path2);
3841
+ }, "wrappedGet");
3842
+ let newValue;
3843
+ try {
3844
+ newValue = selector(wrappedGet);
3845
+ } catch (err) {
3846
+ if (DEV) console.error("[memorio computed] selector error:", err);
3847
+ return entry2.lastValue;
3848
+ }
3849
+ if (entry2.equality(entry2.lastValue, newValue)) {
3850
+ return entry2.lastValue;
3851
+ }
3852
+ entry2.lastValue = newValue;
3853
+ _setupDeps(cacheKey, entry2, newDeps2);
3854
+ for (const sub of entry2.subscribers) {
3855
+ try {
3856
+ sub(newValue);
3857
+ } catch (err) {
3858
+ if (DEV) console.error("[memorio computed] subscriber error:", err);
3859
+ }
3860
+ }
3861
+ return newValue;
3862
+ }
3863
+ const newDeps = /* @__PURE__ */ new Set();
3864
+ const get = /* @__PURE__ */ __name((path2) => {
3865
+ newDeps.add(path2);
3866
+ return _readStatePath(path2);
3867
+ }, "get");
3868
+ let lastValue;
3869
+ try {
3870
+ lastValue = selector(get);
3871
+ } catch (err) {
3872
+ if (DEV) console.error("[memorio computed] selector error:", err);
3873
+ message_default(`[memorio computed] selector error: ${err}`);
3874
+ lastValue = null;
3265
3875
  }
3266
- }, "log");
3267
- var getModuleColor = /* @__PURE__ */ __name((module) => {
3268
- const colors = {
3269
- state: "#4CAF50",
3270
- store: "#2196F3",
3271
- session: "#FF9800",
3272
- cache: "#9C27B0",
3273
- idb: "#F44336"
3876
+ const entry = {
3877
+ selector,
3878
+ lastValue,
3879
+ deps: newDeps,
3880
+ equality: opts?.equality || DEFAULT_EQUALITY,
3881
+ subscribers: /* @__PURE__ */ new Set(),
3882
+ _dispatchUnsubscribers: []
3274
3883
  };
3275
- return colors[module] || "#888888";
3276
- }, "getModuleColor");
3277
- var getHistory = /* @__PURE__ */ __name(() => {
3278
- return [...logHistory];
3279
- }, "getHistory");
3280
- var clearHistory = /* @__PURE__ */ __name(() => {
3281
- logHistory.length = 0;
3282
- }, "clearHistory");
3283
- var getStats = /* @__PURE__ */ __name(() => {
3284
- const stats = {
3285
- total: logHistory.length,
3286
- state: 0,
3287
- store: 0,
3288
- session: 0,
3884
+ computedMap.set(cacheKey, entry);
3885
+ _setupDeps(cacheKey, entry, newDeps);
3886
+ return lastValue;
3887
+ }
3888
+ __name(_compute, "_compute");
3889
+ function _getValue(key) {
3890
+ const normalizedKey = _normalizeKey(key);
3891
+ const entry = computedMap.get(normalizedKey);
3892
+ if (!entry) return null;
3893
+ return entry.lastValue;
3894
+ }
3895
+ __name(_getValue, "_getValue");
3896
+ function _subscribe(key, cb) {
3897
+ const normalizedKey = _normalizeKey(key);
3898
+ const entry = computedMap.get(normalizedKey);
3899
+ if (!entry) {
3900
+ if (DEV) console.warn(`[memorio computed] subscribe: no computed value registered for key '${key}'`);
3901
+ return () => {
3902
+ };
3903
+ }
3904
+ entry.subscribers.add(cb);
3905
+ return () => {
3906
+ entry.subscribers.delete(cb);
3907
+ };
3908
+ }
3909
+ __name(_subscribe, "_subscribe");
3910
+ function _remove3(key) {
3911
+ const normalizedKey = _normalizeKey(key);
3912
+ if (!computedMap.has(normalizedKey)) return false;
3913
+ const entry = computedMap.get(normalizedKey);
3914
+ for (const off of entry._dispatchUnsubscribers) off();
3915
+ computedMap.delete(normalizedKey);
3916
+ return true;
3917
+ }
3918
+ __name(_remove3, "_remove");
3919
+ function _list() {
3920
+ return Array.from(computedMap.keys());
3921
+ }
3922
+ __name(_list, "_list");
3923
+ function _clear() {
3924
+ for (const [, entry] of computedMap) {
3925
+ for (const off of entry._dispatchUnsubscribers) off();
3926
+ }
3927
+ computedMap.clear();
3928
+ }
3929
+ __name(_clear, "_clear");
3930
+ var computed = {
3931
+ compute: _compute,
3932
+ getValue: _getValue,
3933
+ subscribe: _subscribe,
3934
+ remove: _remove3,
3935
+ list: _list,
3936
+ clear: _clear
3937
+ };
3938
+
3939
+ // functions/broadcast/index.ts
3940
+ init_esm_shims();
3941
+ init_env();
3942
+ init_message();
3943
+ var _channel = null;
3944
+ var _storageListener = null;
3945
+ var _originalDispatchSet = null;
3946
+ var _installed = false;
3947
+ var _targets = "all";
3948
+ var _isLocalChange = false;
3949
+ function _hasBroadcastChannel() {
3950
+ return typeof BroadcastChannel !== "undefined";
3951
+ }
3952
+ __name(_hasBroadcastChannel, "_hasBroadcastChannel");
3953
+ function _hasStorageEvents() {
3954
+ return typeof window !== "undefined" && "addEventListener" in window;
3955
+ }
3956
+ __name(_hasStorageEvents, "_hasStorageEvents");
3957
+ function _shouldSync(target) {
3958
+ if (_targets === "all") return true;
3959
+ return _targets === target;
3960
+ }
3961
+ __name(_shouldSync, "_shouldSync");
3962
+ function _onBroadcastMessage(event) {
3963
+ let msg;
3964
+ try {
3965
+ msg = event.data;
3966
+ } catch {
3967
+ return;
3968
+ }
3969
+ if (!msg || !msg.__memorio_sync) return;
3970
+ if (!_shouldSync(msg.target)) return;
3971
+ if (_isLocalChange) return;
3972
+ try {
3973
+ if (msg.target === "state" || msg.target === "all") {
3974
+ const s = globalThis.state;
3975
+ if (s) {
3976
+ _isLocalChange = true;
3977
+ try {
3978
+ const segments = msg.path.replace(/^state\./, "").split(".");
3979
+ let current = s;
3980
+ for (let i = 0; i < segments.length - 1; i++) {
3981
+ const seg = segments[i];
3982
+ if (current[seg] === void 0 || current[seg] === null) {
3983
+ current[seg] = {};
3984
+ }
3985
+ current = current[seg];
3986
+ }
3987
+ const lastSeg = segments[segments.length - 1];
3988
+ if (msg.action === "set") {
3989
+ current[lastSeg] = msg.value;
3990
+ } else if (msg.action === "delete") {
3991
+ delete current[lastSeg];
3992
+ }
3993
+ } finally {
3994
+ queueMicrotask(() => {
3995
+ _isLocalChange = false;
3996
+ });
3997
+ }
3998
+ }
3999
+ }
4000
+ } catch (err) {
4001
+ if (DEV) console.error("[memorio broadcast] apply state error:", err);
4002
+ }
4003
+ }
4004
+ __name(_onBroadcastMessage, "_onBroadcastMessage");
4005
+ function _onStorageEvent(e) {
4006
+ if (!e.key) return;
4007
+ const prefixes = [
4008
+ ["memorio_store_", "store"],
4009
+ ["memorio_session_", "session"]
4010
+ ];
4011
+ for (const [prefix, target] of prefixes) {
4012
+ if (e.key.startsWith(prefix)) {
4013
+ if (!_shouldSync(target)) continue;
4014
+ const cleanKey = e.key.slice(prefix.length);
4015
+ dispatch.set(`memorio:broadcast:${target}:${cleanKey}`, {
4016
+ detail: { key: cleanKey, oldValue: e.oldValue, newValue: e.newValue }
4017
+ });
4018
+ break;
4019
+ }
4020
+ }
4021
+ }
4022
+ __name(_onStorageEvent, "_onStorageEvent");
4023
+ function _wrapDispatchSet() {
4024
+ if (_originalDispatchSet !== null) return;
4025
+ _originalDispatchSet = dispatch.set;
4026
+ const original = dispatch.set;
4027
+ dispatch.set = (name, value) => {
4028
+ original(name, value);
4029
+ if (name.startsWith("state.") && _shouldSync("state") && _channel) {
4030
+ _isLocalChange = true;
4031
+ try {
4032
+ _channel.postMessage({
4033
+ __memorio_sync: true,
4034
+ target: "state",
4035
+ action: "set",
4036
+ path: name,
4037
+ value: _extractStateValue(name),
4038
+ timestamp: Date.now()
4039
+ });
4040
+ } finally {
4041
+ queueMicrotask(() => {
4042
+ _isLocalChange = false;
4043
+ });
4044
+ }
4045
+ }
4046
+ };
4047
+ }
4048
+ __name(_wrapDispatchSet, "_wrapDispatchSet");
4049
+ function _restoreDispatchSet() {
4050
+ if (_originalDispatchSet !== null) {
4051
+ dispatch.set = _originalDispatchSet;
4052
+ _originalDispatchSet = null;
4053
+ }
4054
+ }
4055
+ __name(_restoreDispatchSet, "_restoreDispatchSet");
4056
+ function _extractStateValue(path2) {
4057
+ const s = globalThis.state;
4058
+ if (!s) return void 0;
4059
+ try {
4060
+ const segments = path2.replace(/^state\./, "").split(".");
4061
+ let current = s;
4062
+ for (const seg of segments) {
4063
+ if (current === null || current === void 0) break;
4064
+ current = current[seg];
4065
+ }
4066
+ return current === void 0 ? null : current;
4067
+ } catch {
4068
+ return null;
4069
+ }
4070
+ }
4071
+ __name(_extractStateValue, "_extractStateValue");
4072
+ var broadcast = {
4073
+ install: /* @__PURE__ */ __name((channelName, opts) => {
4074
+ if (_installed) return;
4075
+ const name = channelName || opts?.channelName || "memorio_sync";
4076
+ _targets = opts?.targets || "all";
4077
+ if (_hasBroadcastChannel()) {
4078
+ _channel = new BroadcastChannel(name);
4079
+ _channel.addEventListener("message", _onBroadcastMessage);
4080
+ _installed = true;
4081
+ _wrapDispatchSet();
4082
+ if (DEV) message_default(`memorio broadcast: installed (channel="${name}", targets="${_targets}")`);
4083
+ }
4084
+ if (_hasStorageEvents()) {
4085
+ _storageListener = _onStorageEvent;
4086
+ window.addEventListener("storage", _storageListener);
4087
+ _installed = true;
4088
+ if (!_hasBroadcastChannel() && DEV) {
4089
+ message_default(`memorio broadcast: using storage event fallback (targets="${_targets}")`);
4090
+ }
4091
+ }
4092
+ if (!_installed) {
4093
+ console.warn("[memorio broadcast] Neither BroadcastChannel nor storage events are available in this environment.");
4094
+ }
4095
+ }, "install"),
4096
+ uninstall: /* @__PURE__ */ __name(() => {
4097
+ if (_channel) {
4098
+ _channel.removeEventListener("message", _onBroadcastMessage);
4099
+ _channel.close();
4100
+ _channel = null;
4101
+ }
4102
+ if (_storageListener && typeof window !== "undefined") {
4103
+ window.removeEventListener("storage", _storageListener);
4104
+ _storageListener = null;
4105
+ }
4106
+ _restoreDispatchSet();
4107
+ _installed = false;
4108
+ }, "uninstall"),
4109
+ isInstalled: /* @__PURE__ */ __name(() => _installed, "isInstalled"),
4110
+ broadcast: /* @__PURE__ */ __name((msg) => {
4111
+ if (!_channel) return;
4112
+ _channel.postMessage({ ...msg, timestamp: Date.now() });
4113
+ }, "broadcast")
4114
+ };
4115
+
4116
+ // functions/security/index.ts
4117
+ init_esm_shims();
4118
+ init_env();
4119
+ function _safeRandomUUID() {
4120
+ const g3 = globalThis;
4121
+ if (typeof g3.crypto !== "undefined" && typeof g3.crypto.randomUUID === "function") {
4122
+ try {
4123
+ return g3.crypto.randomUUID();
4124
+ } catch {
4125
+ }
4126
+ }
4127
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
4128
+ }
4129
+ __name(_safeRandomUUID, "_safeRandomUUID");
4130
+ var REGEX_TIMEOUT_MS = 100;
4131
+ function _safeRegexTest(pattern, key) {
4132
+ if (/\(.*[+*?].*.*\)[+*?]/.test(pattern)) {
4133
+ if (DEV) console.warn(`[memorio security] Potentially dangerous regex blocked: ${pattern}`);
4134
+ return false;
4135
+ }
4136
+ if (pattern.length > 500) {
4137
+ if (DEV) console.warn("[memorio security] Regex pattern exceeds max length (500)");
4138
+ return false;
4139
+ }
4140
+ const startTime = Date.now();
4141
+ try {
4142
+ const regex = new RegExp(pattern);
4143
+ const result = regex.test(key);
4144
+ const elapsed = Date.now() - startTime;
4145
+ if (elapsed > REGEX_TIMEOUT_MS) {
4146
+ if (DEV) console.warn(`[memorio security] Slow regex detected (${elapsed}ms): ${pattern}`);
4147
+ }
4148
+ return result;
4149
+ } catch {
4150
+ return false;
4151
+ }
4152
+ }
4153
+ __name(_safeRegexTest, "_safeRegexTest");
4154
+ function addAccessRule(rules, pattern, perms) {
4155
+ const key = pattern instanceof RegExp ? pattern.source : pattern;
4156
+ rules.set(key, perms);
4157
+ return rules;
4158
+ }
4159
+ __name(addAccessRule, "addAccessRule");
4160
+ function hasPermission(rules, key, action, userId) {
4161
+ if (rules.size === 0) return true;
4162
+ for (const [pattern, perms] of rules) {
4163
+ let matches;
4164
+ if (typeof pattern === "function") {
4165
+ try {
4166
+ matches = pattern(key, userId);
4167
+ } catch {
4168
+ matches = false;
4169
+ }
4170
+ } else {
4171
+ matches = _safeRegexTest(pattern, key);
4172
+ }
4173
+ if (matches) {
4174
+ const allowed = perms.includes(action) || perms.includes("admin");
4175
+ if (!allowed) {
4176
+ logAudit({
4177
+ action,
4178
+ key,
4179
+ userId,
4180
+ success: false,
4181
+ error: "RBAC Denied: insufficient permissions"
4182
+ });
4183
+ }
4184
+ return allowed;
4185
+ }
4186
+ }
4187
+ logAudit({
4188
+ action: "permission_check",
4189
+ key,
4190
+ userId,
4191
+ success: false,
4192
+ error: "RBAC Denied: no matching rule"
4193
+ });
4194
+ return false;
4195
+ }
4196
+ __name(hasPermission, "hasPermission");
4197
+ var _auditLogger = null;
4198
+ function isAuditActive() {
4199
+ return _auditLogger !== null;
4200
+ }
4201
+ __name(isAuditActive, "isAuditActive");
4202
+ function setAuditLogger(logger3) {
4203
+ _auditLogger = logger3;
4204
+ }
4205
+ __name(setAuditLogger, "setAuditLogger");
4206
+ function logAudit(entry) {
4207
+ if (!_auditLogger) return;
4208
+ _auditLogger({
4209
+ timestamp: Date.now(),
4210
+ success: true,
4211
+ ...entry
4212
+ });
4213
+ }
4214
+ __name(logAudit, "logAudit");
4215
+ function sanitizeValue(value) {
4216
+ if (typeof value === "string") {
4217
+ let decoded = value.replace(/&#[xX]?[0-9a-fA-F]+;?/g, (match) => {
4218
+ const hexMatch = match.match(/&#x([0-9a-fA-F]+);?/i);
4219
+ if (hexMatch && hexMatch[1]) {
4220
+ return String.fromCharCode(parseInt(hexMatch[1], 16));
4221
+ }
4222
+ const decMatch = match.match(/&#([0-9]+);?/);
4223
+ if (decMatch && decMatch[1]) {
4224
+ return String.fromCharCode(parseInt(decMatch[1], 10));
4225
+ }
4226
+ return match;
4227
+ });
4228
+ try {
4229
+ decoded = decodeURIComponent(decoded);
4230
+ } catch {
4231
+ }
4232
+ decoded = decoded.replace(/(javascript|vbscript|data:text\/html|about:blank|chrome:)/gi, "[SEC-REMOVED]");
4233
+ return decoded.replace(/<script\b[^>]*>[\s\S]*?<\s*\/\s*script\b[^>]*>/gi, "[SEC-REMOVED]").replace(/on\w+\s*=/gi, "[SEC-REMOVED]=").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, "[SEC-REMOVED]").replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi, "[SEC-REMOVED]").replace(/<embed\b[^>]*>/gi, "[SEC-REMOVED]").replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, "[SEC-REMOVED]").replace(/<form\b[^<]*(?:(?!<\/form>)<[^<]*)*<\/form>/gi, "[SEC-REMOVED]").replace(/<base\b[^<]*(?:(?!<\/base>)<[^<]*)*<\/base>/gi, "[SEC-REMOVED]").replace(/<link\b[^<]*(?:(?!<\/link>)<[^<]*)*<\/link>/gi, "[SEC-REMOVED]").replace(/<meta\b[^<]*(?:(?!<\/meta>)<[^<]*)*<\/meta>/gi, "[SEC-REMOVED]").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, "[SEC-REMOVED]");
4234
+ }
4235
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4236
+ const ctor = value.constructor?.name;
4237
+ if (ctor === "Object" || ctor === void 0) {
4238
+ const sanitized = {};
4239
+ for (const [k, v] of Object.entries(value)) {
4240
+ if (k === "__proto__" || k === "constructor" || k === "prototype") continue;
4241
+ sanitized[k] = sanitizeValue(v);
4242
+ }
4243
+ return sanitized;
4244
+ }
4245
+ return value;
4246
+ }
4247
+ if (Array.isArray(value)) {
4248
+ return value.map((v) => sanitizeValue(v));
4249
+ }
4250
+ return value;
4251
+ }
4252
+ __name(sanitizeValue, "sanitizeValue");
4253
+ function validateKey(key) {
4254
+ return /^[a-zA-Z0-9_.-]+$/.test(key) && key.length <= 256 && key.length > 0;
4255
+ }
4256
+ __name(validateKey, "validateKey");
4257
+ function recordConsent(consents, userId, purpose, granted) {
4258
+ const record = {
4259
+ id: _safeRandomUUID(),
4260
+ purpose,
4261
+ granted,
4262
+ timestamp: Date.now()
4263
+ };
4264
+ const user = consents.get(userId) || [];
4265
+ user.push(record);
4266
+ consents.set(userId, user);
4267
+ return record;
4268
+ }
4269
+ __name(recordConsent, "recordConsent");
4270
+ function hasConsent(consents, userId, purpose) {
4271
+ const userConsents = consents.get(userId);
4272
+ if (!userConsents) return false;
4273
+ for (let i = userConsents.length - 1; i >= 0; i--) {
4274
+ const record = userConsents[i];
4275
+ if (record && record.purpose === purpose) {
4276
+ return record.granted;
4277
+ }
4278
+ }
4279
+ return false;
4280
+ }
4281
+ __name(hasConsent, "hasConsent");
4282
+ function revokeConsent(consents, userId, purpose) {
4283
+ return recordConsent(consents, userId, purpose, false);
4284
+ }
4285
+ __name(revokeConsent, "revokeConsent");
4286
+ function getConsents(consents, userId) {
4287
+ return consents.get(userId) || [];
4288
+ }
4289
+ __name(getConsents, "getConsents");
4290
+ function exportUserData(consents, userId) {
4291
+ return {
4292
+ userId,
4293
+ exportedAt: Date.now(),
4294
+ consents: consents.get(userId) || []
4295
+ };
4296
+ }
4297
+ __name(exportUserData, "exportUserData");
4298
+ function deleteUserData(consents, userId) {
4299
+ const count = consents.get(userId)?.length || 0;
4300
+ consents.delete(userId);
4301
+ return { success: true, deletedConsents: count };
4302
+ }
4303
+ __name(deleteUserData, "deleteUserData");
4304
+ var security = {
4305
+ // Re-exports for convenience
4306
+ safeRandomUUID: _safeRandomUUID,
4307
+ safeRegexTest: _safeRegexTest,
4308
+ // RBAC
4309
+ addAccessRule,
4310
+ hasPermission,
4311
+ // Audit logging
4312
+ isAuditActive,
4313
+ setAuditLogger,
4314
+ logAudit,
4315
+ // Input sanitization
4316
+ sanitizeValue,
4317
+ validateKey,
4318
+ // Consent management
4319
+ recordConsent,
4320
+ hasConsent,
4321
+ revokeConsent,
4322
+ getConsents,
4323
+ exportUserData,
4324
+ deleteUserData
4325
+ };
4326
+
4327
+ // index.ts
4328
+ init_message();
4329
+
4330
+ // functions/logger/index.ts
4331
+ init_esm_shims();
4332
+ init_internal();
4333
+ init_message();
4334
+ init_env();
4335
+ var defaultConfig = {
4336
+ enabled: true,
4337
+ logToConsole: true,
4338
+ modules: ["state", "store", "session", "cache", "idb"],
4339
+ maxEntries: 1e3
4340
+ };
4341
+ function isDebugEnabled() {
4342
+ return DEV && internal_default.debug === true;
4343
+ }
4344
+ __name(isDebugEnabled, "isDebugEnabled");
4345
+ var config = { ...defaultConfig };
4346
+ var logHistory = [];
4347
+ var configure = /* @__PURE__ */ __name((options) => {
4348
+ config = { ...config, ...options };
4349
+ }, "configure");
4350
+ var enable = /* @__PURE__ */ __name(() => {
4351
+ config.enabled = true;
4352
+ }, "enable");
4353
+ var disable = /* @__PURE__ */ __name(() => {
4354
+ config.enabled = false;
4355
+ }, "disable");
4356
+ var isEnabled = /* @__PURE__ */ __name((module) => {
4357
+ return config.enabled && config.modules.includes(module);
4358
+ }, "isEnabled");
4359
+ var log = /* @__PURE__ */ __name((module, action, path2, value, previousValue) => {
4360
+ if (!isEnabled(module)) return;
4361
+ const entry = {
4362
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4363
+ module,
4364
+ action,
4365
+ path: path2,
4366
+ value,
4367
+ previousValue
4368
+ };
4369
+ logHistory.push(entry);
4370
+ if (logHistory.length > config.maxEntries) {
4371
+ logHistory.shift();
4372
+ }
4373
+ if (config.logToConsole && isDebugEnabled()) {
4374
+ const prefix = `[Memorio:${module.toUpperCase()}]`;
4375
+ const color = getModuleColor(module);
4376
+ message_default(
4377
+ `%c${prefix}%c ${action} ${path2},
4378
+ color: ${color}; font-weight: bold,
4379
+ color: inherit`
4380
+ );
4381
+ if (value !== void 0) {
4382
+ message_default(` \u2192 value:${value}`);
4383
+ }
4384
+ if (previousValue !== void 0) {
4385
+ message_default(` \u2190 previous:${previousValue}`);
4386
+ }
4387
+ }
4388
+ if (config.customHandler) {
4389
+ config.customHandler(entry);
4390
+ }
4391
+ }, "log");
4392
+ var getModuleColor = /* @__PURE__ */ __name((module) => {
4393
+ const colors = {
4394
+ state: "#4CAF50",
4395
+ store: "#2196F3",
4396
+ session: "#FF9800",
4397
+ cache: "#9C27B0",
4398
+ idb: "#F44336"
4399
+ };
4400
+ return colors[module] || "#888888";
4401
+ }, "getModuleColor");
4402
+ var getHistory = /* @__PURE__ */ __name(() => {
4403
+ return [...logHistory];
4404
+ }, "getHistory");
4405
+ var clearHistory = /* @__PURE__ */ __name(() => {
4406
+ logHistory.length = 0;
4407
+ }, "clearHistory");
4408
+ var getStats = /* @__PURE__ */ __name(() => {
4409
+ const stats = {
4410
+ total: logHistory.length,
4411
+ state: 0,
4412
+ store: 0,
4413
+ session: 0,
3289
4414
  cache: 0,
3290
4415
  idb: 0,
3291
4416
  set: 0,
@@ -3465,228 +4590,67 @@ function reorder(items, fromIndex, toIndex) {
3465
4590
  if (fromIndex === toIndex) return items.map((i) => i.key);
3466
4591
  const reordered = [...items];
3467
4592
  const [removed] = reordered.splice(fromIndex, 1);
3468
- reordered.splice(toIndex, 0, removed);
3469
- return reordered.map((i) => i.key);
3470
- }
3471
- __name(reorder, "reorder");
3472
- function reindex(items) {
3473
- if (items.length === 0) return items;
3474
- const result = [];
3475
- let prev = null;
3476
- for (let i = 0; i < items.length; i++) {
3477
- const next = i < items.length - 1 ? items[i + 1].key : null;
3478
- const newItem = { ...items[i] };
3479
- if (prev === null) {
3480
- newItem.key = before(items[0].key);
3481
- } else if (next === null) {
3482
- newItem.key = after(prev);
3483
- } else {
3484
- newItem.key = between(prev, next);
3485
- }
3486
- result.push(newItem);
3487
- prev = newItem.key;
3488
- }
3489
- return result;
3490
- }
3491
- __name(reindex, "reindex");
3492
- var fractional = {
3493
- generateBetween,
3494
- firstKey,
3495
- after,
3496
- before,
3497
- between,
3498
- reorder,
3499
- reindex
3500
- };
3501
-
3502
- // index.ts
3503
- init_internal();
3504
- init_platform();
3505
-
3506
- // core/global.ts
3507
- init_esm_shims();
3508
- init_platform();
3509
- init_internal();
3510
-
3511
- // package.json
3512
- var package_default = {
3513
- version: "5.0.0"};
3514
-
3515
- // core/global.ts
3516
- init_env();
3517
- init_store();
3518
- init_idb();
3519
- init_sqlite();
3520
- init_message();
3521
-
3522
- // functions/typed/index.ts
3523
- init_esm_shims();
3524
- function typed() {
3525
- return state2;
3526
- }
3527
- __name(typed, "typed");
3528
-
3529
- // functions/history/index.ts
3530
- init_esm_shims();
3531
- init_internal();
3532
- init_env();
3533
- init_message();
3534
- function _clone(value) {
3535
- if (value === null || typeof value !== "object") return value;
3536
- try {
3537
- return deepRaw(value, /* @__PURE__ */ new WeakSet());
3538
- } catch (err) {
3539
- if (DEV) console.warn("[memorio history] deep clone failed:", err);
3540
- return value;
3541
- }
3542
- }
3543
- __name(_clone, "_clone");
3544
- var snapshot = /* @__PURE__ */ __name(() => {
3545
- return deepRaw(state2, /* @__PURE__ */ new WeakSet());
3546
- }, "snapshot");
3547
- var diff = /* @__PURE__ */ __name((snap) => {
3548
- const changes = [];
3549
- const _walk = /* @__PURE__ */ __name((oldObj, newObj, prefix) => {
3550
- const oldKeys = oldObj ? Object.keys(oldObj) : [];
3551
- const newKeys = newObj ? Object.keys(newObj) : [];
3552
- for (const key of newKeys) {
3553
- const newPath = prefix ? `${prefix}.${key}` : key;
3554
- const oldVal = oldObj ? oldObj[key] : void 0;
3555
- const newVal = newObj[key];
3556
- if (oldVal !== newVal) {
3557
- const oldType = typeof oldVal;
3558
- const newType = typeof newVal;
3559
- if (oldType !== newType || oldVal === void 0) {
3560
- changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
3561
- } else if (oldVal && typeof oldVal === "object") {
3562
- _walk(oldVal, newVal, newPath);
3563
- } else if (oldVal !== newVal) {
3564
- changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
3565
- }
3566
- }
3567
- }
3568
- for (const key of oldKeys) {
3569
- if (!(key in (newObj || {}))) {
3570
- const newPath = prefix ? `${prefix}.${key}` : key;
3571
- changes.push({ path: newPath, oldValue: oldObj[key], newValue: void 0 });
3572
- }
3573
- }
3574
- }, "_walk");
3575
- _walk(snap, deepRaw(state2), "");
3576
- return changes;
3577
- }, "diff");
3578
- var enableHistory = /* @__PURE__ */ __name((enabled = true) => {
3579
- internal_default.historyEnabled = enabled;
3580
- message_default(`[memorio history] Tracking ${enabled ? "enabled" : "disabled"}`);
3581
- }, "enableHistory");
3582
- var trace = /* @__PURE__ */ __name(() => {
3583
- return [...internal_default.mutations];
3584
- }, "trace");
3585
- var canUndo = /* @__PURE__ */ __name(() => {
3586
- return internal_default.canUndo();
3587
- }, "canUndo");
3588
- var canRedo = /* @__PURE__ */ __name(() => {
3589
- return internal_default.canRedo();
3590
- }, "canRedo");
3591
- var undo = /* @__PURE__ */ __name(() => {
3592
- if (!internal_default.historyEnabled) {
3593
- message_default("[memorio history] History is not enabled");
3594
- return void 0;
3595
- }
3596
- const record = internal_default.popUndo();
3597
- if (!record) return void 0;
3598
- _applyInverse2(record);
3599
- message_default(`[memorio history] Undid: ${record.action} ${record.path}`);
3600
- return record;
3601
- }, "undo");
3602
- var redo = /* @__PURE__ */ __name(() => {
3603
- if (!internal_default.historyEnabled) {
3604
- message_default("[memorio history] History is not enabled");
3605
- return void 0;
3606
- }
3607
- const record = internal_default.popRedo();
3608
- if (!record) return void 0;
3609
- _applyForward(record);
3610
- message_default(`[memorio history] Redid: ${record.action} ${record.path}`);
3611
- return record;
3612
- }, "redo");
3613
- function _applyInverse2(record) {
3614
- const wasEnabled = internal_default.historyEnabled;
3615
- internal_default.historyEnabled = false;
3616
- try {
3617
- if (record.action === "set") {
3618
- if (record.previousValue === void 0) {
3619
- _deletePath2(record.path);
3620
- } else {
3621
- _setPath2(record.path, record.previousValue);
3622
- }
3623
- } else if (record.action === "delete") {
3624
- if (record.previousValue !== void 0) {
3625
- _setPath2(record.path, record.previousValue);
3626
- }
3627
- }
3628
- } finally {
3629
- internal_default.historyEnabled = wasEnabled;
3630
- }
3631
- }
3632
- __name(_applyInverse2, "_applyInverse");
3633
- function _applyForward(record) {
3634
- const wasEnabled = internal_default.historyEnabled;
3635
- internal_default.historyEnabled = false;
3636
- try {
3637
- if (record.action === "set") {
3638
- _setPath2(record.path, record.newValue);
3639
- } else if (record.action === "delete") {
3640
- _deletePath2(record.path);
3641
- }
3642
- } finally {
3643
- internal_default.historyEnabled = wasEnabled;
3644
- }
4593
+ reordered.splice(toIndex, 0, removed);
4594
+ return reordered.map((i) => i.key);
3645
4595
  }
3646
- __name(_applyForward, "_applyForward");
3647
- function _setPath2(path2, value) {
3648
- const parts = path2.split(".");
3649
- let current = state2;
3650
- for (let i = 0; i < parts.length - 1; i++) {
3651
- const part = parts[i];
3652
- if (current[part] === void 0) {
3653
- current[part] = {};
4596
+ __name(reorder, "reorder");
4597
+ function reindex(items) {
4598
+ if (items.length === 0) return items;
4599
+ const result = [];
4600
+ let prev = null;
4601
+ for (let i = 0; i < items.length; i++) {
4602
+ const next = i < items.length - 1 ? items[i + 1].key : null;
4603
+ const newItem = { ...items[i] };
4604
+ if (prev === null) {
4605
+ newItem.key = before(items[0].key);
4606
+ } else if (next === null) {
4607
+ newItem.key = after(prev);
4608
+ } else {
4609
+ newItem.key = between(prev, next);
3654
4610
  }
3655
- current = current[part];
4611
+ result.push(newItem);
4612
+ prev = newItem.key;
3656
4613
  }
3657
- current[parts[parts.length - 1]] = value;
4614
+ return result;
3658
4615
  }
3659
- __name(_setPath2, "_setPath");
3660
- function _deletePath2(path2) {
3661
- const parts = path2.split(".");
3662
- if (parts.length === 1) {
3663
- state2.remove(parts[0]);
3664
- return;
3665
- }
3666
- let current = state2;
3667
- for (let i = 0; i < parts.length - 1; i++) {
3668
- const part = parts[i];
3669
- if (current[part] === void 0) return;
3670
- current = current[part];
3671
- }
3672
- delete current[parts[parts.length - 1]];
4616
+ __name(reindex, "reindex");
4617
+ var fractional = {
4618
+ generateBetween,
4619
+ firstKey,
4620
+ after,
4621
+ before,
4622
+ between,
4623
+ reorder,
4624
+ reindex
4625
+ };
4626
+
4627
+ // index.ts
4628
+ init_internal();
4629
+ init_platform();
4630
+
4631
+ // core/global.ts
4632
+ init_esm_shims();
4633
+ init_platform();
4634
+ init_internal();
4635
+
4636
+ // package.json
4637
+ var package_default = {
4638
+ version: "5.1.0"};
4639
+
4640
+ // core/global.ts
4641
+ init_env();
4642
+ init_store();
4643
+ init_idb();
4644
+ init_sqlite();
4645
+ init_encryption();
4646
+ init_message();
4647
+
4648
+ // functions/typed/index.ts
4649
+ init_esm_shims();
4650
+ function typed() {
4651
+ return state2;
3673
4652
  }
3674
- __name(_deletePath2, "_deletePath");
3675
- var rollback = /* @__PURE__ */ __name((snap) => {
3676
- state2.removeAll();
3677
- for (const key of Object.keys(snap)) {
3678
- state2[key] = _clone(snap[key]);
3679
- }
3680
- internal_default.clearHistory();
3681
- message_default("[memorio history] State rolled back to snapshot");
3682
- }, "rollback");
3683
- var clearHistory2 = /* @__PURE__ */ __name(() => {
3684
- internal_default.clearHistory();
3685
- message_default("[memorio history] History cleared");
3686
- }, "clearHistory");
3687
- var clearRedo = /* @__PURE__ */ __name(() => {
3688
- internal_default.clearRedo();
3689
- }, "clearRedo");
4653
+ __name(typed, "typed");
3690
4654
 
3691
4655
  // functions/memory/index.ts
3692
4656
  init_esm_shims();
@@ -4379,6 +5343,168 @@ var memory = {
4379
5343
  }
4380
5344
  };
4381
5345
 
5346
+ // functions/history/index.ts
5347
+ init_esm_shims();
5348
+ init_internal();
5349
+ init_env();
5350
+ init_message();
5351
+ function _clone(value) {
5352
+ if (value === null || typeof value !== "object") return value;
5353
+ try {
5354
+ return deepRaw(value, /* @__PURE__ */ new WeakSet());
5355
+ } catch (err) {
5356
+ if (DEV) console.warn("[memorio history] deep clone failed:", err);
5357
+ return value;
5358
+ }
5359
+ }
5360
+ __name(_clone, "_clone");
5361
+ var snapshot = /* @__PURE__ */ __name(() => {
5362
+ return deepRaw(state2, /* @__PURE__ */ new WeakSet());
5363
+ }, "snapshot");
5364
+ var diff = /* @__PURE__ */ __name((snap) => {
5365
+ const changes = [];
5366
+ const _walk = /* @__PURE__ */ __name((oldObj, newObj, prefix) => {
5367
+ const oldKeys = oldObj ? Object.keys(oldObj) : [];
5368
+ const newKeys = newObj ? Object.keys(newObj) : [];
5369
+ for (const key of newKeys) {
5370
+ const newPath = prefix ? `${prefix}.${key}` : key;
5371
+ const oldVal = oldObj ? oldObj[key] : void 0;
5372
+ const newVal = newObj[key];
5373
+ if (oldVal !== newVal) {
5374
+ const oldType = typeof oldVal;
5375
+ const newType = typeof newVal;
5376
+ if (oldType !== newType || oldVal === void 0) {
5377
+ changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
5378
+ } else if (oldVal && typeof oldVal === "object") {
5379
+ _walk(oldVal, newVal, newPath);
5380
+ } else if (oldVal !== newVal) {
5381
+ changes.push({ path: newPath, oldValue: oldVal, newValue: newVal });
5382
+ }
5383
+ }
5384
+ }
5385
+ for (const key of oldKeys) {
5386
+ if (!(key in (newObj || {}))) {
5387
+ const newPath = prefix ? `${prefix}.${key}` : key;
5388
+ changes.push({ path: newPath, oldValue: oldObj[key], newValue: void 0 });
5389
+ }
5390
+ }
5391
+ }, "_walk");
5392
+ _walk(snap, deepRaw(state2), "");
5393
+ return changes;
5394
+ }, "diff");
5395
+ var enableHistory = /* @__PURE__ */ __name((enabled = true) => {
5396
+ internal_default.historyEnabled = enabled;
5397
+ message_default(`[memorio history] Tracking ${enabled ? "enabled" : "disabled"}`);
5398
+ }, "enableHistory");
5399
+ var trace = /* @__PURE__ */ __name(() => {
5400
+ return [...internal_default.mutations];
5401
+ }, "trace");
5402
+ var canUndo = /* @__PURE__ */ __name(() => {
5403
+ return internal_default.canUndo();
5404
+ }, "canUndo");
5405
+ var canRedo = /* @__PURE__ */ __name(() => {
5406
+ return internal_default.canRedo();
5407
+ }, "canRedo");
5408
+ var undo = /* @__PURE__ */ __name(() => {
5409
+ if (!internal_default.historyEnabled) {
5410
+ message_default("[memorio history] History is not enabled");
5411
+ return void 0;
5412
+ }
5413
+ const record = internal_default.popUndo();
5414
+ if (!record) return void 0;
5415
+ _applyInverse2(record);
5416
+ message_default(`[memorio history] Undid: ${record.action} ${record.path}`);
5417
+ return record;
5418
+ }, "undo");
5419
+ var redo = /* @__PURE__ */ __name(() => {
5420
+ if (!internal_default.historyEnabled) {
5421
+ message_default("[memorio history] History is not enabled");
5422
+ return void 0;
5423
+ }
5424
+ const record = internal_default.popRedo();
5425
+ if (!record) return void 0;
5426
+ _applyForward(record);
5427
+ message_default(`[memorio history] Redid: ${record.action} ${record.path}`);
5428
+ return record;
5429
+ }, "redo");
5430
+ function _applyInverse2(record) {
5431
+ const wasEnabled = internal_default.historyEnabled;
5432
+ internal_default.historyEnabled = false;
5433
+ try {
5434
+ if (record.action === "set") {
5435
+ if (record.previousValue === void 0) {
5436
+ _deletePath2(record.path);
5437
+ } else {
5438
+ _setPath2(record.path, record.previousValue);
5439
+ }
5440
+ } else if (record.action === "delete") {
5441
+ if (record.previousValue !== void 0) {
5442
+ _setPath2(record.path, record.previousValue);
5443
+ }
5444
+ }
5445
+ } finally {
5446
+ internal_default.historyEnabled = wasEnabled;
5447
+ }
5448
+ }
5449
+ __name(_applyInverse2, "_applyInverse");
5450
+ function _applyForward(record) {
5451
+ const wasEnabled = internal_default.historyEnabled;
5452
+ internal_default.historyEnabled = false;
5453
+ try {
5454
+ if (record.action === "set") {
5455
+ _setPath2(record.path, record.newValue);
5456
+ } else if (record.action === "delete") {
5457
+ _deletePath2(record.path);
5458
+ }
5459
+ } finally {
5460
+ internal_default.historyEnabled = wasEnabled;
5461
+ }
5462
+ }
5463
+ __name(_applyForward, "_applyForward");
5464
+ function _setPath2(path2, value) {
5465
+ const parts = path2.split(".");
5466
+ let current = state2;
5467
+ for (let i = 0; i < parts.length - 1; i++) {
5468
+ const part = parts[i];
5469
+ if (current[part] === void 0) {
5470
+ current[part] = {};
5471
+ }
5472
+ current = current[part];
5473
+ }
5474
+ current[parts[parts.length - 1]] = value;
5475
+ }
5476
+ __name(_setPath2, "_setPath");
5477
+ function _deletePath2(path2) {
5478
+ const parts = path2.split(".");
5479
+ if (parts.length === 1) {
5480
+ state2.remove(parts[0]);
5481
+ return;
5482
+ }
5483
+ let current = state2;
5484
+ for (let i = 0; i < parts.length - 1; i++) {
5485
+ const part = parts[i];
5486
+ if (current[part] === void 0) return;
5487
+ current = current[part];
5488
+ }
5489
+ delete current[parts[parts.length - 1]];
5490
+ }
5491
+ __name(_deletePath2, "_deletePath");
5492
+ var rollback = /* @__PURE__ */ __name((snap) => {
5493
+ state2.removeAll();
5494
+ for (const key of Object.keys(snap)) {
5495
+ state2[key] = _clone(snap[key]);
5496
+ }
5497
+ internal_default.clearHistory();
5498
+ message_default("[memorio history] State rolled back to snapshot");
5499
+ }, "rollback");
5500
+ var clearHistory2 = /* @__PURE__ */ __name(() => {
5501
+ internal_default.clearHistory();
5502
+ message_default("[memorio history] History cleared");
5503
+ }, "clearHistory");
5504
+ var clearRedo = /* @__PURE__ */ __name(() => {
5505
+ internal_default.clearRedo();
5506
+ }, "clearRedo");
5507
+
4382
5508
  // core/global.ts
4383
5509
  if (!("memorio" in globalThis)) {
4384
5510
  Object.defineProperty(
@@ -4445,16 +5571,18 @@ if (!("memorio" in globalThis)) {
4445
5571
  }
4446
5572
  );
4447
5573
  memorio.memory = memory;
5574
+ memorio.encryption = encryption;
4448
5575
  initializePlatform();
4449
5576
  memorio.isBrowser = isBrowser;
4450
5577
  memorio.isNode = isNode;
4451
5578
  memorio.isDeno = isDeno;
5579
+ memorio.isBun = isBun;
4452
5580
  memorio.isEdge = isEdge;
4453
5581
  memorio.getCapabilities = getCapabilities;
4454
5582
  memorio.createContext = createContext;
4455
5583
  memorio.listContexts = listContexts;
4456
5584
  memorio.deleteContext = deleteContext;
4457
- memorio.isolate = (name) => createContext(name);
5585
+ memorio.isolate = (name, opts) => createContext(name, opts);
4458
5586
  Object.defineProperty(memorio, "setContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name((id) => setCurrentContext(id), "value") });
4459
5587
  Object.defineProperty(memorio, "getContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name(() => internal_default.currentContext, "value") });
4460
5588
  memorio.registerSchema = schema.register;
@@ -4462,6 +5590,9 @@ if (!("memorio" in globalThis)) {
4462
5590
  memorio.unregisterSchema = schema.unregister;
4463
5591
  memorio.listSchemas = schema.list;
4464
5592
  memorio.typed = typed;
5593
+ memorio.computed = computed;
5594
+ memorio.broadcast = broadcast;
5595
+ memorio.security = security;
4465
5596
  memorio.snapshot = snapshot;
4466
5597
  memorio.diff = diff;
4467
5598
  memorio.undo = undo;
@@ -4495,7 +5626,11 @@ if (!("memorio" in globalThis)) {
4495
5626
  idb,
4496
5627
  sqlite,
4497
5628
  observer,
4498
- useObserver
5629
+ useObserver,
5630
+ encryption,
5631
+ computed,
5632
+ broadcast,
5633
+ security
4499
5634
  };
4500
5635
  for (const key of Object.keys(globalDefinitions)) {
4501
5636
  if (!(key in globalThis)) {
@@ -4527,6 +5662,6 @@ var index_default = memorio2;
4527
5662
  // global.ts
4528
5663
  memorio2.global();
4529
5664
 
4530
- export { DEV, PROD, abortTransaction, activeTransactionId, beginTransaction, cache, canMerge, canRedo, canUndo, clearHistory2 as clearHistory, clearRedo, commitTransaction, createContext, createMutation, currentTimestamp, currentTransaction, index_default as default, deleteContext, devtools, diff, diffToPatch, dispatch, enableHistory, events, fractional, generateCommitId, generateMutationId, generateTransactionId, getCapabilities, getContext, help, hlc, idb, internal_default as internal, isBrowser, isDeno, isEdge, isNode, isolate, listContexts, listSchemas, listTransactions, logger, memorio2 as memorio, memory, mergePatches, message, mutate, mutationToPatch, observer, propertyName, recordMutation, redo, registerSchema, rollback, schema, session, setContext, snapshot, sqlite, state2 as state, store, toPatch, trace, transaction, typed, undo, unregisterSchema, useObserver, validate };
5665
+ export { DEV, PROD, abortTransaction, activeTransactionId, beginTransaction, broadcast, cache, canMerge, canRedo, canUndo, clearHistory2 as clearHistory, clearRedo, commitTransaction, computed, createContext, createMutation, currentTimestamp, currentTransaction, index_default as default, deleteContext, devtools, diff, diffToPatch, dispatch, enableHistory, encryption, events, fractional, generateCommitId, generateMutationId, generateTransactionId, getCapabilities, getContext, help, hlc, idb, internal_default as internal, isBrowser, isBun, isDeno, isEdge, isNode, isolate, listContexts, listSchemas, listTransactions, logger, memorio2 as memorio, memory, mergePatches, message, mutate, mutationToPatch, observer, propertyName, recordMutation, redo, registerSchema, rollback, schema, security, session, setContext, snapshot, sqlite, state2 as state, store, toPatch, trace, transaction, typed, undo, unregisterSchema, useObserver, validate };
4531
5666
  //# sourceMappingURL=global.js.map
4532
5667
  //# sourceMappingURL=global.js.map