memorio 4.9.31 → 5.0.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 (76) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.md +327 -330
  3. package/SECURITY.md +17 -1
  4. package/SUMMARY.md +59 -45
  5. package/adr/001-state-proxy-model.md +96 -0
  6. package/adr/002-observer-semantics.md +180 -0
  7. package/adr/003-deep-mutation-semantics.md +129 -0
  8. package/adr/004-array-mutation-semantics.md +128 -0
  9. package/adr/005-scheduler-contract.md +149 -0
  10. package/adr/006-context-isolation.md +92 -0
  11. package/adr/007-mutation-records.md +118 -0
  12. package/adr/008-transactions.md +106 -0
  13. package/adr/009-history-model.md +110 -0
  14. package/adr/README.md +46 -0
  15. package/adr/template.md +49 -0
  16. package/examples/basic.ts +115 -115
  17. package/examples/browser-vanilla.html +358 -358
  18. package/examples/cache.ts +72 -72
  19. package/examples/cross-platform-guards.ts +57 -57
  20. package/examples/history.ts +104 -0
  21. package/examples/idb.ts +109 -109
  22. package/examples/multi-tenant-context.ts +44 -44
  23. package/examples/node-server.ts +308 -308
  24. package/examples/observer.ts +60 -60
  25. package/examples/platform.ts +115 -115
  26. package/examples/react-app.tsx +362 -362
  27. package/examples/react-observer.tsx +63 -63
  28. package/examples/semantic-memory.ts +60 -60
  29. package/examples/session-advanced.ts +91 -91
  30. package/examples/sqlite-batched-writes.ts +57 -57
  31. package/examples/state-advanced.ts +89 -89
  32. package/examples/store-advanced.ts +117 -117
  33. package/examples/sync.ts +90 -0
  34. package/examples/typed-and-schema.ts +102 -100
  35. package/examples/useObserver.tsx +140 -141
  36. package/global.cjs +4594 -0
  37. package/global.d.ts +8 -0
  38. package/global.js +4532 -0
  39. package/index.cjs +706 -649
  40. package/index.d.ts +1 -0
  41. package/index.js +686 -648
  42. package/llms.txt +72 -4
  43. package/markdown/AUDIT-REPORT.md +135 -0
  44. package/markdown/CACHE.md +100 -0
  45. package/markdown/CHANGELOG.md +243 -0
  46. package/markdown/DEVTOOLS.md +129 -0
  47. package/markdown/DISPATCH.md +177 -0
  48. package/markdown/HISTORY.md +199 -0
  49. package/markdown/IDB.md +178 -0
  50. package/markdown/IMPORT.md +153 -0
  51. package/markdown/INSPECT.md +123 -0
  52. package/markdown/LOGGER.md +154 -0
  53. package/markdown/MEMORY-ATTACHMENT.md +96 -0
  54. package/markdown/MEMORY.md +162 -0
  55. package/markdown/OBSERVER.md +209 -0
  56. package/markdown/PLATFORM.md +271 -0
  57. package/markdown/PROJECT.md +311 -0
  58. package/markdown/SCHEMA.md +176 -0
  59. package/markdown/SECURITY.md +330 -0
  60. package/markdown/SESSION.md +165 -0
  61. package/markdown/SQLITE.md +190 -0
  62. package/markdown/STATE.md +160 -0
  63. package/markdown/STORE.md +171 -0
  64. package/markdown/SYNC.md +319 -0
  65. package/markdown/TYPED.md +165 -0
  66. package/markdown/USEOBSERVER.md +257 -0
  67. package/modules/redux.cjs +561 -374
  68. package/modules/redux.cjs.map +1 -1
  69. package/modules/redux.js +561 -374
  70. package/modules/redux.js.map +1 -1
  71. package/package.json +13 -3
  72. package/types/env.d.ts +19 -9
  73. package/types/exports.d.ts +20 -0
  74. package/types/history.d.ts +13 -1
  75. package/types/memorio.d.ts +17 -5
  76. package/types/mutation.d.ts +75 -0
package/global.js ADDED
@@ -0,0 +1,4532 @@
1
+ import 'path';
2
+ import 'url';
3
+
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var init_esm_shims = __esm({
11
+ "node_modules/tsup/assets/esm_shims.js"() {
12
+ }
13
+ });
14
+
15
+ // core/env.ts
16
+ var DEV, PROD;
17
+ var init_env = __esm({
18
+ "core/env.ts"() {
19
+ init_esm_shims();
20
+ DEV = false ;
21
+ PROD = !DEV;
22
+ if (typeof globalThis !== "undefined") {
23
+ globalThis["__DEV__"] = DEV;
24
+ }
25
+ }
26
+ });
27
+
28
+ // core/internal.ts
29
+ var INTERNAL_KEY, state, internal, protect, propertyName, internal_default;
30
+ var init_internal = __esm({
31
+ "core/internal.ts"() {
32
+ init_esm_shims();
33
+ INTERNAL_KEY = "__memorio_internal_state";
34
+ state = globalThis[INTERNAL_KEY] || {
35
+ debug: false,
36
+ tracking: false,
37
+ trackedPaths: /* @__PURE__ */ new Set(),
38
+ locked: false,
39
+ lastAccessedPath: "",
40
+ stateVersion: 0,
41
+ currentContext: null,
42
+ mutations: [],
43
+ undoStack: [],
44
+ redoStack: [],
45
+ maxHistory: 100,
46
+ historyEnabled: false
47
+ };
48
+ if (!globalThis[INTERNAL_KEY]) {
49
+ globalThis[INTERNAL_KEY] = state;
50
+ }
51
+ internal = {
52
+ get debug() {
53
+ return state.debug;
54
+ },
55
+ set debug(value) {
56
+ state.debug = value;
57
+ },
58
+ get tracking() {
59
+ return state.tracking;
60
+ },
61
+ set tracking(value) {
62
+ state.tracking = value;
63
+ },
64
+ get trackedPaths() {
65
+ return state.trackedPaths;
66
+ },
67
+ clearTrackedPaths() {
68
+ state.trackedPaths.clear();
69
+ },
70
+ get locked() {
71
+ return state.locked;
72
+ },
73
+ set locked(value) {
74
+ state.locked = value;
75
+ },
76
+ get lastAccessedPath() {
77
+ return state.lastAccessedPath;
78
+ },
79
+ set lastAccessedPath(value) {
80
+ state.lastAccessedPath = value;
81
+ },
82
+ get stateVersion() {
83
+ return state.stateVersion;
84
+ },
85
+ bumpStateVersion() {
86
+ state.stateVersion = (state.stateVersion || 0) + 1;
87
+ return state.stateVersion;
88
+ },
89
+ get currentContext() {
90
+ return state.currentContext;
91
+ },
92
+ set currentContext(value) {
93
+ state.currentContext = value;
94
+ },
95
+ get mutations() {
96
+ return state.mutations;
97
+ },
98
+ get undoStack() {
99
+ return state.undoStack;
100
+ },
101
+ get redoStack() {
102
+ return state.redoStack;
103
+ },
104
+ get maxHistory() {
105
+ return state.maxHistory;
106
+ },
107
+ set maxHistory(value) {
108
+ state.maxHistory = value;
109
+ },
110
+ get historyEnabled() {
111
+ return state.historyEnabled;
112
+ },
113
+ set historyEnabled(value) {
114
+ state.historyEnabled = value;
115
+ },
116
+ /**
117
+ * Records a mutation in the trace log and undo/redo stacks.
118
+ * Called by the state proxy's callback.
119
+ */
120
+ recordMutation(record) {
121
+ if (!state.historyEnabled) return;
122
+ state.mutations.push(record);
123
+ if (state.mutations.length > state.maxHistory) {
124
+ state.mutations.shift();
125
+ }
126
+ state.undoStack.push(record);
127
+ if (state.undoStack.length > state.maxHistory) {
128
+ state.undoStack.shift();
129
+ }
130
+ state.redoStack = [];
131
+ },
132
+ /**
133
+ * Pops a record from the undo stack and pushes to redo stack.
134
+ * Returns the record or undefined if empty.
135
+ */
136
+ popUndo() {
137
+ const record = state.undoStack.pop();
138
+ if (record) {
139
+ state.redoStack.push(record);
140
+ }
141
+ return record;
142
+ },
143
+ /**
144
+ * Pops a record from the redo stack and pushes to undo stack.
145
+ * Returns the record or undefined if empty.
146
+ */
147
+ popRedo() {
148
+ const record = state.redoStack.pop();
149
+ if (record) {
150
+ state.undoStack.push(record);
151
+ }
152
+ return record;
153
+ },
154
+ canUndo() {
155
+ return state.undoStack.length > 0;
156
+ },
157
+ canRedo() {
158
+ return state.redoStack.length > 0;
159
+ },
160
+ clearHistory() {
161
+ state.mutations = [];
162
+ state.undoStack = [];
163
+ state.redoStack = [];
164
+ },
165
+ clearRedo() {
166
+ state.redoStack = [];
167
+ }
168
+ };
169
+ protect = [
170
+ "list",
171
+ "state",
172
+ "store",
173
+ "idb",
174
+ "sqlite",
175
+ "observer",
176
+ "useObserver",
177
+ "remove",
178
+ "removeAll",
179
+ // Platform-related protected keys
180
+ "_platform",
181
+ "_capabilities",
182
+ "_sessionId"
183
+ ];
184
+ propertyName = /* @__PURE__ */ __name((container, object) => {
185
+ const target = object !== void 0 ? object : container;
186
+ return String(target).replace("() => ", "");
187
+ }, "propertyName");
188
+ internal_default = internal;
189
+ }
190
+ });
191
+
192
+ // functions/message/index.ts
193
+ var message, message_default;
194
+ var init_message = __esm({
195
+ "functions/message/index.ts"() {
196
+ init_esm_shims();
197
+ init_internal();
198
+ init_env();
199
+ message = /* @__PURE__ */ __name((...args) => {
200
+ if (DEV && internal_default.debug === true) {
201
+ console.debug(...args);
202
+ }
203
+ }, "message");
204
+ message_default = message;
205
+ }
206
+ });
207
+
208
+ // core/platform.ts
209
+ function generateSessionId() {
210
+ const anyGlobal = globalThis;
211
+ if (typeof anyGlobal.crypto !== "undefined" && anyGlobal.crypto.randomUUID) {
212
+ return anyGlobal.crypto.randomUUID();
213
+ }
214
+ if (typeof anyGlobal.crypto !== "undefined" && anyGlobal.crypto.getRandomValues) {
215
+ const array = new Uint8Array(16);
216
+ anyGlobal.crypto.getRandomValues(array);
217
+ return Array.from(array, (b) => b.toString(16).padStart(2, "0")).join("");
218
+ }
219
+ return `session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
220
+ }
221
+ function detectPlatform() {
222
+ const globalAny = globalThis;
223
+ if (globalAny.Deno && globalAny.Deno.version) {
224
+ return "deno";
225
+ }
226
+ if (typeof process !== "undefined" && process.versions && process.versions.node) {
227
+ return "node";
228
+ }
229
+ if (typeof globalThis !== "undefined" && typeof globalThis.ServiceWorkerGlobalScope !== "undefined") {
230
+ return "edge";
231
+ }
232
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
233
+ return "browser";
234
+ }
235
+ return "unknown";
236
+ }
237
+ function isBrowser() {
238
+ const platform = detectPlatform();
239
+ return platform === "browser";
240
+ }
241
+ function isNode() {
242
+ const platform = detectPlatform();
243
+ return platform === "node";
244
+ }
245
+ function isDeno() {
246
+ const platform = detectPlatform();
247
+ return platform === "deno";
248
+ }
249
+ function isEdge() {
250
+ const platform = detectPlatform();
251
+ return platform === "edge";
252
+ }
253
+ function getSessionStorage() {
254
+ try {
255
+ if (typeof sessionStorage !== "undefined") {
256
+ const testKey = "__memorio_test__";
257
+ sessionStorage.setItem(testKey, "1");
258
+ sessionStorage.removeItem(testKey);
259
+ return sessionStorage;
260
+ }
261
+ } catch (_) {
262
+ }
263
+ return null;
264
+ }
265
+ function getLocalStorage() {
266
+ try {
267
+ if (typeof localStorage !== "undefined") {
268
+ const testKey = "__memorio_test__";
269
+ localStorage.setItem(testKey, "1");
270
+ localStorage.removeItem(testKey);
271
+ return localStorage;
272
+ }
273
+ } catch (_) {
274
+ }
275
+ return null;
276
+ }
277
+ function hasIndexedDB() {
278
+ if (typeof indexedDB !== "undefined") {
279
+ return true;
280
+ }
281
+ return false;
282
+ }
283
+ function hasSqlJs() {
284
+ const anyGlobal = globalThis;
285
+ if (typeof anyGlobal.WebAssembly === "undefined" || typeof anyGlobal.WebAssembly.instantiate !== "function") {
286
+ return false;
287
+ }
288
+ return typeof anyGlobal.window !== "undefined";
289
+ }
290
+ function hasDispatchEvent() {
291
+ return typeof globalThis.dispatchEvent === "function";
292
+ }
293
+ function getCapabilities() {
294
+ const platform = detectPlatform();
295
+ const isSecure = typeof globalThis.isSecureContext !== "undefined" ? globalThis.isSecureContext : platform === "browser";
296
+ return {
297
+ platform,
298
+ hasSessionStorage: getSessionStorage() !== null,
299
+ hasLocalStorage: getLocalStorage() !== null,
300
+ hasIndexedDB: hasIndexedDB(),
301
+ hasSqlJs: hasSqlJs(),
302
+ hasDispatchEvent: hasDispatchEvent(),
303
+ hasNavigator: typeof navigator !== "undefined",
304
+ hasProcess: typeof process !== "undefined",
305
+ isSecureContext: isSecure,
306
+ sessionId: generateSessionId()
307
+ };
308
+ }
309
+ function initializePlatform() {
310
+ const capabilities = getCapabilities();
311
+ const anyGlobal = globalThis;
312
+ if (!capabilities.hasDispatchEvent) {
313
+ anyGlobal.dispatchEvent = function(_event) {
314
+ return true;
315
+ };
316
+ if (typeof CustomEvent === "undefined") {
317
+ anyGlobal.CustomEvent = class CustomEvent {
318
+ static {
319
+ __name(this, "CustomEvent");
320
+ }
321
+ type;
322
+ detail;
323
+ constructor(type, detail = {}) {
324
+ this.type = type;
325
+ this.detail = detail;
326
+ }
327
+ };
328
+ }
329
+ }
330
+ if (typeof anyGlobal.addEventListener !== "function") {
331
+ anyGlobal.addEventListener = function(type, listener) {
332
+ if (!_eventListenerStorage.has(type)) {
333
+ _eventListenerStorage.set(type, []);
334
+ }
335
+ _eventListenerStorage.get(type).push(listener);
336
+ };
337
+ anyGlobal.removeEventListener = function(type, listener) {
338
+ const listeners = _eventListenerStorage.get(type);
339
+ if (listeners) {
340
+ const index = listeners.indexOf(listener);
341
+ if (index > -1) {
342
+ listeners.splice(index, 1);
343
+ }
344
+ }
345
+ };
346
+ anyGlobal.dispatchEvent = function(event) {
347
+ const listeners = _eventListenerStorage.get(event.type);
348
+ if (listeners) {
349
+ listeners.forEach((listener) => {
350
+ try {
351
+ listener(event);
352
+ } catch (e) {
353
+ console.error("Event listener error:", e);
354
+ }
355
+ });
356
+ }
357
+ return true;
358
+ };
359
+ }
360
+ }
361
+ function createContext(name) {
362
+ const contextId = name || `context_${generateSessionId()}`;
363
+ setCurrentContext(contextId);
364
+ const contextStorage = {
365
+ state: {},
366
+ store: /* @__PURE__ */ new Map(),
367
+ session: /* @__PURE__ */ new Map(),
368
+ cache: /* @__PURE__ */ new Map()
369
+ };
370
+ _contexts.set(contextId, contextStorage);
371
+ return {
372
+ id: contextId,
373
+ state: contextStorage.state,
374
+ store: {
375
+ get: /* @__PURE__ */ __name((key) => {
376
+ const data = contextStorage.store.get(key);
377
+ return data ? JSON.parse(data) : null;
378
+ }, "get"),
379
+ set: /* @__PURE__ */ __name((key, value) => {
380
+ contextStorage.store.set(key, JSON.stringify(value));
381
+ }, "set"),
382
+ remove: /* @__PURE__ */ __name((key) => contextStorage.store.delete(key), "remove"),
383
+ removeAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "removeAll"),
384
+ clearAll: /* @__PURE__ */ __name(() => contextStorage.store.clear(), "clearAll"),
385
+ size: /* @__PURE__ */ __name(() => contextStorage.store.size, "size"),
386
+ isPersistent: false
387
+ },
388
+ session: {
389
+ get: /* @__PURE__ */ __name((key) => {
390
+ const data = contextStorage.session.get(key);
391
+ return data ? JSON.parse(data) : null;
392
+ }, "get"),
393
+ set: /* @__PURE__ */ __name((key, value) => {
394
+ contextStorage.session.set(key, JSON.stringify(value));
395
+ }, "set"),
396
+ remove: /* @__PURE__ */ __name((key) => contextStorage.session.delete(key), "remove"),
397
+ removeAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "removeAll"),
398
+ clearAll: /* @__PURE__ */ __name(() => contextStorage.session.clear(), "clearAll"),
399
+ size: /* @__PURE__ */ __name(() => contextStorage.session.size, "size"),
400
+ isPersistent: false
401
+ },
402
+ cache: {
403
+ get: /* @__PURE__ */ __name((key) => contextStorage.cache.get(key), "get"),
404
+ set: /* @__PURE__ */ __name((key, value) => contextStorage.cache.set(key, value), "set"),
405
+ remove: /* @__PURE__ */ __name((key) => contextStorage.cache.delete(key), "remove"),
406
+ removeAll: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "removeAll"),
407
+ clear: /* @__PURE__ */ __name(() => contextStorage.cache.clear(), "clear")
408
+ }
409
+ };
410
+ }
411
+ function listContexts() {
412
+ return Array.from(_contexts.keys());
413
+ }
414
+ function deleteContext(id) {
415
+ return _contexts.delete(id);
416
+ }
417
+ function setCurrentContext(id) {
418
+ internal_default.currentContext = id;
419
+ }
420
+ var _eventListenerStorage, CONTEXTS_KEY, _contexts;
421
+ var init_platform = __esm({
422
+ "core/platform.ts"() {
423
+ init_esm_shims();
424
+ init_internal();
425
+ __name(generateSessionId, "generateSessionId");
426
+ __name(detectPlatform, "detectPlatform");
427
+ __name(isBrowser, "isBrowser");
428
+ __name(isNode, "isNode");
429
+ __name(isDeno, "isDeno");
430
+ __name(isEdge, "isEdge");
431
+ __name(getSessionStorage, "getSessionStorage");
432
+ __name(getLocalStorage, "getLocalStorage");
433
+ __name(hasIndexedDB, "hasIndexedDB");
434
+ __name(hasSqlJs, "hasSqlJs");
435
+ __name(hasDispatchEvent, "hasDispatchEvent");
436
+ __name(getCapabilities, "getCapabilities");
437
+ _eventListenerStorage = /* @__PURE__ */ new Map();
438
+ __name(initializePlatform, "initializePlatform");
439
+ CONTEXTS_KEY = "__memorio_contexts__";
440
+ _contexts = globalThis[CONTEXTS_KEY] || /* @__PURE__ */ new Map();
441
+ if (!globalThis[CONTEXTS_KEY]) {
442
+ globalThis[CONTEXTS_KEY] = _contexts;
443
+ }
444
+ __name(createContext, "createContext");
445
+ __name(listContexts, "listContexts");
446
+ __name(deleteContext, "deleteContext");
447
+ __name(setCurrentContext, "setCurrentContext");
448
+ }
449
+ });
450
+
451
+ // functions/store/index.ts
452
+ function _getFallbackStorage() {
453
+ const contextName = internal_default.currentContext || "";
454
+ const key = contextName || "default";
455
+ if (!_fallbackStorageByContext.has(key)) {
456
+ _fallbackStorageByContext.set(key, /* @__PURE__ */ new Map());
457
+ }
458
+ return _fallbackStorageByContext.get(key);
459
+ }
460
+ function _getPrefix() {
461
+ const contextName = internal_default.currentContext || "";
462
+ return contextName ? `${contextName}-` : `memorio_store_`;
463
+ }
464
+ function _prefixKey(name) {
465
+ if (!name || typeof name !== "string") {
466
+ console.warn(`[memorio store] key is empty or not a string - operation aborted`);
467
+ return "";
468
+ }
469
+ if (name.length > 512) {
470
+ console.warn(`[memorio store] key "${name}" exceeds 512 chars - operation aborted`);
471
+ return "";
472
+ }
473
+ return _getPrefix() + name;
474
+ }
475
+ function _read(prefixedName) {
476
+ const raw = _hasStorage ? _localStorage.getItem(prefixedName) : _getFallbackStorage().get(prefixedName);
477
+ return raw ? JSON.parse(raw) : raw;
478
+ }
479
+ function _write(prefixedName, value) {
480
+ const json = JSON.stringify(value);
481
+ if (_hasStorage) _localStorage.setItem(prefixedName, json);
482
+ else _getFallbackStorage().set(prefixedName, json);
483
+ }
484
+ function _remove(prefixedName) {
485
+ if (_hasStorage) {
486
+ if (_localStorage.getItem(prefixedName)) {
487
+ _localStorage.removeItem(prefixedName);
488
+ return true;
489
+ }
490
+ } else if (_getFallbackStorage().has(prefixedName)) {
491
+ _getFallbackStorage().delete(prefixedName);
492
+ return true;
493
+ }
494
+ return false;
495
+ }
496
+ var _localStorage, _fallbackStorageByContext, _hasStorage, STORE_INSTANCE_KEY, store;
497
+ var init_store = __esm({
498
+ "functions/store/index.ts"() {
499
+ init_esm_shims();
500
+ init_platform();
501
+ init_internal();
502
+ init_message();
503
+ _localStorage = getLocalStorage();
504
+ _fallbackStorageByContext = /* @__PURE__ */ new Map();
505
+ __name(_getFallbackStorage, "_getFallbackStorage");
506
+ _hasStorage = _localStorage !== null;
507
+ __name(_getPrefix, "_getPrefix");
508
+ __name(_prefixKey, "_prefixKey");
509
+ __name(_read, "_read");
510
+ __name(_write, "_write");
511
+ __name(_remove, "_remove");
512
+ STORE_INSTANCE_KEY = "__memorio_store_instance__";
513
+ if (globalThis[STORE_INSTANCE_KEY]) {
514
+ store = globalThis[STORE_INSTANCE_KEY];
515
+ } else {
516
+ store = new Proxy({}, {});
517
+ Object.defineProperties(
518
+ store,
519
+ {
520
+ /**
521
+ * Gets a value from storage.
522
+ * @param name The key to retrieve.
523
+ * @returns The parsed value or null if not found.
524
+ */
525
+ get: {
526
+ value: /* @__PURE__ */ __name((name) => {
527
+ if (!name) {
528
+ console.warn("[memorio store] store.get() called with empty or null key - returning null");
529
+ return null;
530
+ }
531
+ try {
532
+ return _read(_prefixKey(name));
533
+ } catch (err) {
534
+ message(`Error parsing store item '${name}': ${err}`);
535
+ }
536
+ return null;
537
+ }, "value")
538
+ },
539
+ getMultiple: {
540
+ value: /* @__PURE__ */ __name((keys) => {
541
+ const result = {};
542
+ for (const key of keys) {
543
+ try {
544
+ const item = store.get(key);
545
+ if (item) result[key] = item;
546
+ } catch (err) {
547
+ console.debug(`[memorio store] getMultiple error for key "${key}":`, err);
548
+ }
549
+ }
550
+ return result;
551
+ }, "value")
552
+ },
553
+ /**
554
+ * Sets a value in storage.
555
+ * @param name The key to set.
556
+ * @param value The value to store (objects, arrays, primitives).
557
+ * @returns true if written, false if the key was rejected.
558
+ */
559
+ set: {
560
+ value: /* @__PURE__ */ __name((name, value) => {
561
+ if (!name) {
562
+ console.warn("[memorio store] store.set() called with empty or null key - write aborted");
563
+ return false;
564
+ }
565
+ const prefixedName = _prefixKey(name);
566
+ if (!prefixedName) return false;
567
+ if (typeof value === "function") {
568
+ console.warn("[memorio store] functions are not storable - write aborted for key: " + name);
569
+ message("Storing functions is not secure and is blocked for safety.");
570
+ return false;
571
+ }
572
+ try {
573
+ _write(prefixedName, value);
574
+ } catch (err) {
575
+ message(`Error setting store item '${name}': ${err}`);
576
+ return false;
577
+ }
578
+ return true;
579
+ }, "value")
580
+ },
581
+ /**
582
+ * Removes a value from storage.
583
+ * @param name The key to remove.
584
+ * @returns True if removed, false if not found.
585
+ */
586
+ remove: {
587
+ value: /* @__PURE__ */ __name((name) => {
588
+ if (!name) {
589
+ console.debug("[memorio store] store.remove() called with empty or null key - returning false");
590
+ return false;
591
+ }
592
+ const prefixedName = _prefixKey(name);
593
+ if (!prefixedName) return false;
594
+ try {
595
+ return _remove(prefixedName);
596
+ } catch (err) {
597
+ message(`Error removing store item '${name}': ${err}`);
598
+ }
599
+ return false;
600
+ }, "value")
601
+ },
602
+ /**
603
+ * Alias for remove.
604
+ * @param name The key to delete.
605
+ */
606
+ delete: {
607
+ value: /* @__PURE__ */ __name((name) => {
608
+ return store.remove(name);
609
+ }, "value")
610
+ },
611
+ /**
612
+ * Clears all memorio items from storage.
613
+ */
614
+ removeAll: {
615
+ value: /* @__PURE__ */ __name(() => {
616
+ if (_hasStorage) {
617
+ const keysToRemove = [];
618
+ for (let i = 0; i < _localStorage.length; i++) {
619
+ const key = _localStorage.key(i);
620
+ if (key?.startsWith(_getPrefix())) keysToRemove.push(key);
621
+ }
622
+ keysToRemove.forEach((key) => _localStorage.removeItem(key));
623
+ } else {
624
+ _getFallbackStorage().clear();
625
+ }
626
+ return true;
627
+ }, "value")
628
+ },
629
+ /**
630
+ * Alias for removeAll.
631
+ */
632
+ clearAll: {
633
+ value: /* @__PURE__ */ __name(() => {
634
+ store.removeAll();
635
+ return true;
636
+ }, "value")
637
+ },
638
+ /**
639
+ * Estimates storage quota usage.
640
+ * @returns Promise with [usage, quota].
641
+ */
642
+ quota: {
643
+ value: /* @__PURE__ */ __name(async () => {
644
+ return [0, 0];
645
+ }, "value")
646
+ },
647
+ /**
648
+ * Calculates total size of all memorio items in kilobytes.
649
+ * Counts each prefixed key and its JSON-serialized value, summing their
650
+ * byte lengths and converting to whole kilobytes (Math.ceil). Replaces
651
+ * the previous character-only total which did not express real usage.
652
+ * @returns Total size in kilobytes (0 when empty / no memorio items).
653
+ */
654
+ size: {
655
+ value: /* @__PURE__ */ __name(() => {
656
+ let totalBytes = 0;
657
+ if (_hasStorage) {
658
+ for (let i = 0; i < _localStorage.length; i++) {
659
+ const key = _localStorage.key(i);
660
+ if (key && key.startsWith(_getPrefix())) {
661
+ const item = _localStorage.getItem(key);
662
+ if (item) totalBytes += key.length + item.length;
663
+ }
664
+ }
665
+ } else {
666
+ _getFallbackStorage().forEach((value, key) => {
667
+ totalBytes += key.length + value.length;
668
+ });
669
+ }
670
+ return totalBytes === 0 ? 0 : Math.ceil(totalBytes / 1024);
671
+ }, "value")
672
+ },
673
+ /**
674
+ * Check if using real localStorage or fallback
675
+ */
676
+ isPersistent: {
677
+ get: /* @__PURE__ */ __name(() => _hasStorage, "get")
678
+ },
679
+ /**
680
+ * Get a list of all memorio store items.
681
+ */
682
+ list: {
683
+ value: /* @__PURE__ */ __name(() => {
684
+ const result = {};
685
+ try {
686
+ if (_hasStorage) {
687
+ for (let i = 0; i < _localStorage.length; i++) {
688
+ const key = _localStorage.key(i);
689
+ if (key?.startsWith(_getPrefix())) {
690
+ const cleanKey = key.replace(_getPrefix(), "");
691
+ const item = _localStorage.getItem(key);
692
+ if (item !== null) {
693
+ try {
694
+ result[cleanKey] = JSON.parse(item);
695
+ } catch {
696
+ result[cleanKey] = item;
697
+ }
698
+ }
699
+ }
700
+ }
701
+ } else {
702
+ _getFallbackStorage().forEach((value, key) => {
703
+ if (key.startsWith(_getPrefix())) {
704
+ const cleanKey = key.replace(_getPrefix(), "");
705
+ try {
706
+ result[cleanKey] = JSON.parse(value);
707
+ } catch {
708
+ result[cleanKey] = value;
709
+ }
710
+ }
711
+ });
712
+ }
713
+ } catch (err) {
714
+ message(`Error listing store items: ${err}`);
715
+ }
716
+ return result;
717
+ }, "value")
718
+ }
719
+ }
720
+ );
721
+ Object.freeze(store);
722
+ globalThis[STORE_INSTANCE_KEY] = store;
723
+ }
724
+ }
725
+ });
726
+
727
+ // functions/idb/tools/db.create.ts
728
+ var db_create_exports = {};
729
+ var init_db_create = __esm({
730
+ "functions/idb/tools/db.create.ts"() {
731
+ init_esm_shims();
732
+ init_idb();
733
+ init_message();
734
+ idb.db.create = (dbName, ver = 1) => {
735
+ return new Promise((resolve, reject) => {
736
+ if (!idb.db.support()) {
737
+ return reject(new Error("IndexedDB not supported"));
738
+ }
739
+ const request = globalThis.indexedDB.open(dbName, ver);
740
+ request.onerror = () => {
741
+ message_default(`IndexedDB error: ${request.error?.message}`);
742
+ reject(request.error);
743
+ };
744
+ request.onsuccess = () => {
745
+ message_default(`Database ${dbName} connected successfully`);
746
+ resolve(request.result);
747
+ };
748
+ request.onupgradeneeded = () => {
749
+ message_default(`Database ${dbName} upgrade/creation initiated`);
750
+ };
751
+ });
752
+ };
753
+ }
754
+ });
755
+
756
+ // functions/idb/tools/db.list.ts
757
+ var db_list_exports = {};
758
+ var init_db_list = __esm({
759
+ "functions/idb/tools/db.list.ts"() {
760
+ init_esm_shims();
761
+ init_idb();
762
+ idb.db.list = async () => {
763
+ if (!("indexedDB" in globalThis) || !indexedDB.databases) return [];
764
+ try {
765
+ const result = await indexedDB.databases();
766
+ globalThis.idbases = result || [];
767
+ await idb.db.size();
768
+ return globalThis.idbases;
769
+ } catch (err) {
770
+ console.error("Error listing databases:", err);
771
+ return [];
772
+ }
773
+ };
774
+ }
775
+ });
776
+
777
+ // functions/idb/tools/db.exist.ts
778
+ var db_exist_exports = {};
779
+ var init_db_exist = __esm({
780
+ "functions/idb/tools/db.exist.ts"() {
781
+ init_esm_shims();
782
+ init_idb();
783
+ idb.db.exist = (storeName) => {
784
+ return idbases?.some((db) => db.name === storeName);
785
+ };
786
+ }
787
+ });
788
+
789
+ // functions/idb/tools/db.quota.ts
790
+ var db_quota_exports = {};
791
+ var init_db_quota = __esm({
792
+ "functions/idb/tools/db.quota.ts"() {
793
+ init_esm_shims();
794
+ init_idb();
795
+ idb.db.quota = () => {
796
+ return navigator.storage.estimate();
797
+ };
798
+ }
799
+ });
800
+
801
+ // functions/idb/tools/db.delete.ts
802
+ var db_delete_exports = {};
803
+ var init_db_delete = __esm({
804
+ "functions/idb/tools/db.delete.ts"() {
805
+ init_esm_shims();
806
+ init_idb();
807
+ init_message();
808
+ idb.db.delete = (storeName) => {
809
+ return new Promise((resolve, reject) => {
810
+ message_default(`Removing database ${storeName}...`);
811
+ const performDelete = /* @__PURE__ */ __name(() => {
812
+ const request = indexedDB.deleteDatabase(storeName);
813
+ request.onsuccess = () => {
814
+ message_default(`${storeName} database removed successfully`);
815
+ idb.db.list();
816
+ resolve();
817
+ };
818
+ request.onerror = () => {
819
+ console.error(`Error removing ${storeName}:`, request.error);
820
+ reject(request.error);
821
+ };
822
+ request.onblocked = () => {
823
+ console.warn(`Deletion of ${storeName} is blocked. Please close other tabs.`);
824
+ };
825
+ }, "performDelete");
826
+ performDelete();
827
+ });
828
+ };
829
+ }
830
+ });
831
+
832
+ // functions/idb/tools/db.size.ts
833
+ var db_size_exports = {};
834
+ var init_db_size = __esm({
835
+ "functions/idb/tools/db.size.ts"() {
836
+ init_esm_shims();
837
+ init_idb();
838
+ init_message();
839
+ idb.db.size = async () => {
840
+ if (!idbases || idbases.length === 0) return;
841
+ for (let i = 0; i < idbases.length; i++) {
842
+ const dbInfo = idbases[i];
843
+ try {
844
+ const db = await idb.db.create(dbInfo.name, dbInfo.version);
845
+ const tableNames = Array.from(db.objectStoreNames);
846
+ let totalDbSize = 0;
847
+ for (const tableName of tableNames) {
848
+ const tableSize = await idb.table.size(db, tableName);
849
+ totalDbSize += tableSize;
850
+ }
851
+ dbInfo.size = totalDbSize;
852
+ db.close();
853
+ } catch (err) {
854
+ message_default(`Could not calculate size for ${dbInfo.name}:${err}`);
855
+ }
856
+ }
857
+ };
858
+ }
859
+ });
860
+
861
+ // functions/idb/tools/db.version.ts
862
+ var db_version_exports = {};
863
+ var init_db_version = __esm({
864
+ "functions/idb/tools/db.version.ts"() {
865
+ init_esm_shims();
866
+ init_idb();
867
+ idb.db.version = (storeName) => {
868
+ let idbVer = 0;
869
+ for (const v of idbases) {
870
+ if (v.name === storeName) idbVer = v.version;
871
+ break;
872
+ }
873
+ return idbVer;
874
+ };
875
+ }
876
+ });
877
+
878
+ // functions/idb/tools/db.support.ts
879
+ var db_support_exports = {};
880
+ var init_db_support = __esm({
881
+ "functions/idb/tools/db.support.ts"() {
882
+ init_esm_shims();
883
+ init_idb();
884
+ init_message();
885
+ idb.db.support = () => {
886
+ const isSupported = "indexedDB" in globalThis;
887
+ if (!isSupported) {
888
+ message_default("Your environment doesn't support IndexedDB");
889
+ }
890
+ return isSupported;
891
+ };
892
+ }
893
+ });
894
+
895
+ // functions/idb/tools/table.create.ts
896
+ var table_create_exports = {};
897
+ var init_table_create = __esm({
898
+ "functions/idb/tools/table.create.ts"() {
899
+ init_esm_shims();
900
+ init_idb();
901
+ init_message();
902
+ idb.table.create = (dbName, dbTable) => {
903
+ return new Promise((resolve, reject) => {
904
+ try {
905
+ const currentVersion = Number(idb.db.version(dbName)) || 0;
906
+ const nextVersion = currentVersion + 1;
907
+ const request = indexedDB.open(dbName, nextVersion);
908
+ request.onupgradeneeded = (e) => {
909
+ const db = e.target.result;
910
+ if (!db.objectStoreNames.contains(dbTable)) {
911
+ const store2 = db.createObjectStore(dbTable, {
912
+ keyPath: "id",
913
+ autoIncrement: true
914
+ });
915
+ store2.createIndex("id", "id", { unique: true });
916
+ store2.createIndex("data", "data", { unique: false });
917
+ message_default(`Table ${dbTable} created in ${dbName}`);
918
+ }
919
+ };
920
+ request.onsuccess = () => {
921
+ request.result.close();
922
+ idb.db.list();
923
+ resolve();
924
+ };
925
+ request.onerror = () => {
926
+ console.error(`Error creating table ${dbTable}:`, request.error);
927
+ reject(request.error);
928
+ };
929
+ } catch (err) {
930
+ console.error("Critical error in table.create:", err);
931
+ reject(err);
932
+ }
933
+ });
934
+ };
935
+ }
936
+ });
937
+
938
+ // functions/idb/tools/table.size.ts
939
+ var table_size_exports = {};
940
+ var init_table_size = __esm({
941
+ "functions/idb/tools/table.size.ts"() {
942
+ init_esm_shims();
943
+ init_idb();
944
+ init_message();
945
+ idb.table.size = (db, table) => {
946
+ return new Promise((resolve, reject) => {
947
+ if (!db) return reject(new Error("Database instance is required"));
948
+ if (!db.objectStoreNames.contains(table)) return resolve(0);
949
+ let size = 0;
950
+ let count = 0;
951
+ const transaction2 = db.transaction([table], "readonly");
952
+ const store2 = transaction2.objectStore(table);
953
+ const request = store2.openCursor();
954
+ request.onsuccess = async (event) => {
955
+ const cursor = event.target.result;
956
+ if (cursor) {
957
+ try {
958
+ const value = cursor.value;
959
+ size += JSON.stringify(value).length;
960
+ } catch (err) {
961
+ message_default(`Error stringifying IDB value tracking size:${err}`);
962
+ }
963
+ count++;
964
+ if (count % 200 === 0) {
965
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
966
+ }
967
+ cursor.continue();
968
+ } else {
969
+ resolve(size);
970
+ }
971
+ };
972
+ request.onerror = () => {
973
+ reject(request.error);
974
+ };
975
+ });
976
+ };
977
+ }
978
+ });
979
+
980
+ // functions/idb/crud/data.delete.ts
981
+ var data_delete_exports = {};
982
+ var init_data_delete = __esm({
983
+ "functions/idb/crud/data.delete.ts"() {
984
+ init_esm_shims();
985
+ init_idb();
986
+ init_message();
987
+ idb.data.delete = (storeName, table, key) => {
988
+ return new Promise((resolve, reject) => {
989
+ const request = indexedDB.open(storeName);
990
+ request.onsuccess = () => {
991
+ const db = request.result;
992
+ if (!db.objectStoreNames.contains(table)) {
993
+ db.close();
994
+ return reject(new Error(`Table ${table} not found`));
995
+ }
996
+ const transaction2 = db.transaction(table, "readwrite");
997
+ const objectStore = transaction2.objectStore(table);
998
+ const deleteRequest = objectStore.delete(key);
999
+ deleteRequest.onsuccess = () => {
1000
+ db.close();
1001
+ message_default(`Record ${key} deleted from ${table}`);
1002
+ resolve();
1003
+ };
1004
+ deleteRequest.onerror = () => {
1005
+ db.close();
1006
+ reject(deleteRequest.error);
1007
+ };
1008
+ };
1009
+ request.onerror = () => reject(request.error);
1010
+ });
1011
+ };
1012
+ idb.data.delete.all = (storeName, table) => {
1013
+ return new Promise((resolve, reject) => {
1014
+ const request = indexedDB.open(storeName);
1015
+ request.onsuccess = (event) => {
1016
+ const db = event.target.result;
1017
+ if (!db.objectStoreNames.contains(table)) {
1018
+ db.close();
1019
+ return reject(new Error(`Table ${table} not found`));
1020
+ }
1021
+ const transaction2 = db.transaction(table, "readwrite");
1022
+ const store2 = transaction2.objectStore(table);
1023
+ const clearRequest = store2.clear();
1024
+ clearRequest.onsuccess = () => {
1025
+ db.close();
1026
+ message_default(`All data cleared from ${table}`);
1027
+ resolve();
1028
+ };
1029
+ clearRequest.onerror = () => {
1030
+ db.close();
1031
+ reject(clearRequest.error);
1032
+ };
1033
+ };
1034
+ request.onerror = () => reject(request.error);
1035
+ });
1036
+ };
1037
+ }
1038
+ });
1039
+
1040
+ // functions/idb/crud/data.set.ts
1041
+ var data_set_exports = {};
1042
+ var init_data_set = __esm({
1043
+ "functions/idb/crud/data.set.ts"() {
1044
+ init_esm_shims();
1045
+ init_idb();
1046
+ init_message();
1047
+ idb.data.set = (storeName, table, value) => {
1048
+ return new Promise((resolve, reject) => {
1049
+ const request = indexedDB.open(storeName);
1050
+ request.onsuccess = () => {
1051
+ const db = request.result;
1052
+ if (!db.objectStoreNames.contains(table)) {
1053
+ db.close();
1054
+ return reject(new Error(`Table ${table} does not exist in ${storeName}`));
1055
+ }
1056
+ const transaction2 = db.transaction(table, "readwrite");
1057
+ const objectStore = transaction2.objectStore(table);
1058
+ const putRequest = objectStore.put(value);
1059
+ putRequest.onsuccess = () => {
1060
+ db.close();
1061
+ message_default(`Data saved in ${storeName}.${table}`);
1062
+ resolve(putRequest.result);
1063
+ };
1064
+ putRequest.onerror = (_) => {
1065
+ db.close();
1066
+ message_default(`Database insert error: ${putRequest.error?.message}`);
1067
+ reject(putRequest.error);
1068
+ };
1069
+ };
1070
+ request.onerror = () => {
1071
+ reject(request.error);
1072
+ };
1073
+ });
1074
+ };
1075
+ }
1076
+ });
1077
+
1078
+ // functions/idb/crud/data.get.ts
1079
+ var data_get_exports = {};
1080
+ var init_data_get = __esm({
1081
+ "functions/idb/crud/data.get.ts"() {
1082
+ init_esm_shims();
1083
+ init_idb();
1084
+ idb.data.get = (storeName, table, key) => {
1085
+ return new Promise((resolve, reject) => {
1086
+ const request = indexedDB.open(storeName);
1087
+ request.onsuccess = (event) => {
1088
+ const db = event.target.result;
1089
+ if (!db.objectStoreNames.contains(table)) {
1090
+ db.close();
1091
+ return reject(new Error(`Table ${table} not found in ${storeName}`));
1092
+ }
1093
+ const transaction2 = db.transaction(table, "readonly");
1094
+ const store2 = transaction2.objectStore(table);
1095
+ const getRequest = store2.get(key);
1096
+ getRequest.onsuccess = () => {
1097
+ db.close();
1098
+ resolve(getRequest.result);
1099
+ };
1100
+ getRequest.onerror = () => {
1101
+ db.close();
1102
+ reject(getRequest.error);
1103
+ };
1104
+ };
1105
+ request.onerror = () => {
1106
+ reject(request.error);
1107
+ };
1108
+ });
1109
+ };
1110
+ }
1111
+ });
1112
+
1113
+ // functions/idb/index.ts
1114
+ var _hasIDB, idb;
1115
+ var init_idb = __esm({
1116
+ "functions/idb/index.ts"() {
1117
+ init_esm_shims();
1118
+ init_platform();
1119
+ init_env();
1120
+ _hasIDB = hasIndexedDB();
1121
+ idb = {
1122
+ db: {},
1123
+ table: {},
1124
+ data: {}
1125
+ };
1126
+ if (_hasIDB) {
1127
+ (async () => {
1128
+ Object.defineProperty(idb, "db", { value: {}, writable: true, configurable: true });
1129
+ Object.defineProperty(idb, "table", { value: {}, writable: true, configurable: true });
1130
+ Object.defineProperty(idb, "data", { value: {}, writable: true, configurable: true });
1131
+ Object.defineProperty(globalThis, "idbases", {
1132
+ value: [],
1133
+ writable: true,
1134
+ configurable: true,
1135
+ enumerable: false
1136
+ });
1137
+ await Promise.all([
1138
+ Promise.resolve().then(() => (init_db_create(), db_create_exports)),
1139
+ Promise.resolve().then(() => (init_db_list(), db_list_exports)),
1140
+ Promise.resolve().then(() => (init_db_exist(), db_exist_exports)),
1141
+ Promise.resolve().then(() => (init_db_quota(), db_quota_exports)),
1142
+ Promise.resolve().then(() => (init_db_delete(), db_delete_exports)),
1143
+ Promise.resolve().then(() => (init_db_size(), db_size_exports)),
1144
+ Promise.resolve().then(() => (init_db_version(), db_version_exports)),
1145
+ Promise.resolve().then(() => (init_db_support(), db_support_exports)),
1146
+ Promise.resolve().then(() => (init_table_create(), table_create_exports)),
1147
+ Promise.resolve().then(() => (init_table_size(), table_size_exports)),
1148
+ Promise.resolve().then(() => (init_data_delete(), data_delete_exports)),
1149
+ Promise.resolve().then(() => (init_data_set(), data_set_exports)),
1150
+ Promise.resolve().then(() => (init_data_get(), data_get_exports))
1151
+ ]);
1152
+ Object.preventExtensions(idb);
1153
+ Object.seal(idb);
1154
+ Object.freeze(idb);
1155
+ })();
1156
+ } else {
1157
+ idb._disabled = true;
1158
+ idb._warning = "IndexedDB is not available in this environment (Node.js/Deno). Use store or session for persistence.";
1159
+ if (DEV) {
1160
+ console.warn("Memorio IDB: IndexedDB is not available in this environment. Use store or session for data persistence.");
1161
+ }
1162
+ }
1163
+ }
1164
+ });
1165
+
1166
+ // functions/sqlite/tools/db.support.ts
1167
+ var db_support_exports2 = {};
1168
+ function _inDocument() {
1169
+ const g3 = globalThis;
1170
+ return typeof g3.document !== "undefined" && typeof g3.document.createElement === "function";
1171
+ }
1172
+ function _loadSqlJsScript(url) {
1173
+ const g3 = globalThis;
1174
+ if (g3.__memorioSqlJsScript === url) return Promise.resolve();
1175
+ if (!_scriptLoaded) {
1176
+ _scriptLoaded = new Promise((resolve, reject) => {
1177
+ if (g3.initSqlJs && typeof g3.initSqlJs === "function") {
1178
+ g3.__memorioSqlJsScript = url;
1179
+ resolve();
1180
+ return;
1181
+ }
1182
+ if (!_inDocument()) {
1183
+ reject(new Error("memorio sqlite: no document available to load sql.js"));
1184
+ return;
1185
+ }
1186
+ const script = g3.document.createElement("script");
1187
+ script.src = url;
1188
+ script.async = true;
1189
+ script.onload = () => {
1190
+ g3.__memorioSqlJsScript = url;
1191
+ resolve();
1192
+ };
1193
+ script.onerror = () => reject(new Error(`memorio sqlite: failed to load sql.js from ${url}`));
1194
+ g3.document.head.appendChild(script);
1195
+ });
1196
+ }
1197
+ return _scriptLoaded;
1198
+ }
1199
+ var _loading, _SQL, _defaultLocateFile, _scriptLoaded, _loadSqlJsFromCdn;
1200
+ var init_db_support2 = __esm({
1201
+ "functions/sqlite/tools/db.support.ts"() {
1202
+ init_esm_shims();
1203
+ init_sqlite();
1204
+ init_platform();
1205
+ init_message();
1206
+ _loading = null;
1207
+ _SQL = null;
1208
+ _defaultLocateFile = /* @__PURE__ */ __name((file) => {
1209
+ const g3 = globalThis;
1210
+ const base = g3.sqliteWasmBase || "";
1211
+ return base + file;
1212
+ }, "_defaultLocateFile");
1213
+ _scriptLoaded = null;
1214
+ __name(_inDocument, "_inDocument");
1215
+ __name(_loadSqlJsScript, "_loadSqlJsScript");
1216
+ _loadSqlJsFromCdn = /* @__PURE__ */ __name(async (url) => {
1217
+ const g3 = globalThis;
1218
+ if (!url) {
1219
+ throw new Error('memorio sqlite: no loader configured. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => import("sql.js") }).');
1220
+ }
1221
+ if (typeof g3.initSqlJs === "function") return g3.initSqlJs;
1222
+ await _loadSqlJsScript(url);
1223
+ return g3.initSqlJs || g3;
1224
+ }, "_loadSqlJsFromCdn");
1225
+ sqlite.db.support = () => {
1226
+ return hasSqlJs();
1227
+ };
1228
+ sqlite.db.getSQL = async () => {
1229
+ if (_SQL) return _SQL;
1230
+ if (_loading) return _loading;
1231
+ const g3 = globalThis;
1232
+ const cfg = g3.sqliteConfig || {};
1233
+ const p = (async () => {
1234
+ if (typeof cfg.loader === "function") {
1235
+ return await cfg.loader();
1236
+ }
1237
+ if (cfg.scriptUrl) {
1238
+ const mod = await _loadSqlJsFromCdn(cfg.scriptUrl);
1239
+ const initSqlJs = typeof mod === "function" ? mod : mod && (mod.default || mod);
1240
+ const SQL = await initSqlJs({ locateFile: cfg.locateFile || _defaultLocateFile });
1241
+ g3.sqliteVersion = SQL?.version || "sql.js";
1242
+ message_default("Memorio SQLite: sql.js engine loaded");
1243
+ return SQL;
1244
+ }
1245
+ throw new Error('memorio sqlite: no loader configured. Install sql.js (npm i sql.js) and pass a loader via sqlite.config({ loader: () => import("sql.js") }).');
1246
+ })();
1247
+ _loading = p;
1248
+ try {
1249
+ _SQL = await p;
1250
+ return _SQL;
1251
+ } catch (err) {
1252
+ try {
1253
+ sqlite._disabled = true;
1254
+ } catch (_) {
1255
+ }
1256
+ 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>() }).";
1258
+ } catch (_) {
1259
+ }
1260
+ console.warn("Memorio SQLite: failed to load sql.js", err);
1261
+ throw err;
1262
+ } finally {
1263
+ _loading = null;
1264
+ }
1265
+ };
1266
+ sqlite.db.version = () => {
1267
+ return globalThis.sqliteVersion || null;
1268
+ };
1269
+ }
1270
+ });
1271
+
1272
+ // functions/sqlite/tools/persist.ts
1273
+ function _ns() {
1274
+ const cfg = g.sqliteConfig || {};
1275
+ return cfg.namespace ? `ns:${cfg.namespace}` : "default";
1276
+ }
1277
+ function _key(name) {
1278
+ return `memorio:sqlite:db:${_ns()}:${name}`;
1279
+ }
1280
+ function _b64encode(buf) {
1281
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
1282
+ let binary = "";
1283
+ const len = bytes.byteLength;
1284
+ for (let i = 0; i < len; i++) binary += String.fromCharCode(bytes[i]);
1285
+ if (typeof btoa === "function") return btoa(binary);
1286
+ return typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : "";
1287
+ }
1288
+ function _b64decode(b64) {
1289
+ if (typeof Buffer !== "undefined") {
1290
+ return new Uint8Array(Buffer.from(b64, "base64"));
1291
+ }
1292
+ if (typeof atob !== "function") {
1293
+ throw new Error("memorio sqlite: no base64 decoder available");
1294
+ }
1295
+ const binary = atob(b64);
1296
+ const len = binary.length;
1297
+ const out = new Uint8Array(len);
1298
+ for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
1299
+ return out;
1300
+ }
1301
+ function saveSnapshot(name) {
1302
+ return new Promise((resolve) => {
1303
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1304
+ if (!db || typeof db.export !== "function") {
1305
+ resolve(false);
1306
+ return;
1307
+ }
1308
+ try {
1309
+ const blob = db.export();
1310
+ store.set(_key(name), _b64encode(blob));
1311
+ message_default(`Memorio SQLite: persisted '${name}' to store`);
1312
+ resolve(true);
1313
+ } catch (err) {
1314
+ console.warn("Memorio SQLite: persist snapshot failed", err);
1315
+ resolve(false);
1316
+ }
1317
+ });
1318
+ }
1319
+ function loadSnapshot(name) {
1320
+ const b64 = store.get(_key(name));
1321
+ if (!b64) return null;
1322
+ try {
1323
+ return _b64decode(b64);
1324
+ } catch {
1325
+ return null;
1326
+ }
1327
+ }
1328
+ function removeSnapshot(name) {
1329
+ store.remove(_key(name));
1330
+ }
1331
+ function attachAutoExport(name, db) {
1332
+ if (!db || typeof db.updateHook !== "function") return;
1333
+ _persistDbs[name] = true;
1334
+ try {
1335
+ db.updateHook(() => {
1336
+ if (_exportTimers[name]) clearTimeout(_exportTimers[name]);
1337
+ _exportTimers[name] = setTimeout(() => {
1338
+ _exportTimers[name] = null;
1339
+ void saveSnapshot(name);
1340
+ }, 250);
1341
+ });
1342
+ } catch (err) {
1343
+ console.warn("Memorio SQLite: could not attach updateHook", err);
1344
+ }
1345
+ }
1346
+ var g, _persistDbs, _exportTimers;
1347
+ var init_persist = __esm({
1348
+ "functions/sqlite/tools/persist.ts"() {
1349
+ init_esm_shims();
1350
+ init_sqlite();
1351
+ init_store();
1352
+ init_message();
1353
+ g = globalThis;
1354
+ _persistDbs = {};
1355
+ _exportTimers = {};
1356
+ __name(_ns, "_ns");
1357
+ __name(_key, "_key");
1358
+ __name(_b64encode, "_b64encode");
1359
+ __name(_b64decode, "_b64decode");
1360
+ __name(saveSnapshot, "saveSnapshot");
1361
+ __name(loadSnapshot, "loadSnapshot");
1362
+ __name(removeSnapshot, "removeSnapshot");
1363
+ __name(attachAutoExport, "attachAutoExport");
1364
+ sqlite.db.persist = async (name = "memorio") => {
1365
+ return saveSnapshot(name);
1366
+ };
1367
+ sqlite.db.download = async (name = "memorio", filename = `${name}.sqlite`) => {
1368
+ const g3 = globalThis;
1369
+ const db = g3.__sqliteDbs && g3.__sqliteDbs[name];
1370
+ if (!db) {
1371
+ console.warn(`Memorio SQLite: cannot download '${name}' - database not found. Create it with sqlite.db.create('${name}').`);
1372
+ return false;
1373
+ }
1374
+ let blob;
1375
+ try {
1376
+ blob = await sqlite.db.export(name);
1377
+ } catch (err) {
1378
+ console.warn("Memorio SQLite: export failed during download", err);
1379
+ return false;
1380
+ }
1381
+ if (!blob) return false;
1382
+ if (typeof g3.document === "undefined" || typeof g3.Blob === "undefined") {
1383
+ console.warn("Memorio SQLite: sqlite.db.download() requires a browser environment.");
1384
+ return false;
1385
+ }
1386
+ const URL = g3.URL || g3.webkitURL;
1387
+ if (!URL || typeof URL.createObjectURL !== "function") return false;
1388
+ const objectUrl = URL.createObjectURL(new Blob([blob], { type: "application/x-sqlite3" }));
1389
+ const a = g3.document.createElement("a");
1390
+ a.style.display = "none";
1391
+ a.href = objectUrl;
1392
+ a.download = filename;
1393
+ g3.document.body.appendChild(a);
1394
+ a.click();
1395
+ setTimeout(() => {
1396
+ try {
1397
+ URL.revokeObjectURL(objectUrl);
1398
+ } catch (_) {
1399
+ }
1400
+ a.remove();
1401
+ }, 1e3);
1402
+ return true;
1403
+ };
1404
+ sqlite.db.close = async (name = "memorio") => {
1405
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1406
+ if (db && typeof db.close === "function") {
1407
+ try {
1408
+ await saveSnapshot(name);
1409
+ } catch (_) {
1410
+ }
1411
+ try {
1412
+ db.close();
1413
+ } catch (err) {
1414
+ console.warn("Memorio SQLite: close failed", err);
1415
+ }
1416
+ }
1417
+ if (g.__sqliteDbs) delete g.__sqliteDbs[name];
1418
+ if (g.sqlbases) {
1419
+ const idx = g.sqlbases.findIndex((x) => x && x.name === name);
1420
+ if (idx > -1) g.sqlbases.splice(idx, 1);
1421
+ }
1422
+ delete _persistDbs[name];
1423
+ if (_exportTimers[name]) {
1424
+ clearTimeout(_exportTimers[name]);
1425
+ _exportTimers[name] = null;
1426
+ }
1427
+ removeSnapshot(name);
1428
+ };
1429
+ sqlite.db.loadSnapshot = loadSnapshot;
1430
+ sqlite.db.saveSnapshot = saveSnapshot;
1431
+ }
1432
+ });
1433
+
1434
+ // functions/sqlite/tools/db.create.ts
1435
+ var db_create_exports2 = {};
1436
+ var init_db_create2 = __esm({
1437
+ "functions/sqlite/tools/db.create.ts"() {
1438
+ init_esm_shims();
1439
+ init_sqlite();
1440
+ init_message();
1441
+ init_persist();
1442
+ sqlite.db.create = async (name = "memorio", opts = {}) => {
1443
+ const SQL = await sqlite.db.getSQL();
1444
+ const g3 = globalThis;
1445
+ const persistence = !!(opts && opts.persistence) || !!(g3.sqliteConfig && g3.sqliteConfig.persistence);
1446
+ let data;
1447
+ if (persistence && !opts.data) {
1448
+ const restored = loadSnapshot(name);
1449
+ if (restored) data = restored;
1450
+ }
1451
+ const useData = opts && opts.data || data;
1452
+ let db;
1453
+ if (useData && typeof useData.byteLength === "number") {
1454
+ db = new SQL.Database(useData);
1455
+ message_default(`Memorio SQLite: database '${name}' opened (persistence=${persistence})`);
1456
+ } else {
1457
+ db = new SQL.Database();
1458
+ message_default(`Memorio SQLite: database '${name}' created (persistence=${persistence})`);
1459
+ }
1460
+ const createOpts = { ...opts, persistence };
1461
+ if (!g3.__sqliteDbs) g3.__sqliteDbs = {};
1462
+ g3.__sqliteDbs[name] = db;
1463
+ if (!g3.sqlbases) g3.sqlbases = [];
1464
+ const idx = g3.sqlbases.findIndex((x) => x && x.name === name);
1465
+ if (idx > -1) {
1466
+ g3.sqlbases[idx] = { name, db, persistence: createOpts.persistence };
1467
+ } else {
1468
+ g3.sqlbases.push({ name, db, persistence: createOpts.persistence });
1469
+ }
1470
+ if (persistence) attachAutoExport(name, db);
1471
+ return db;
1472
+ };
1473
+ }
1474
+ });
1475
+
1476
+ // functions/sqlite/tools/db.get.ts
1477
+ var db_get_exports = {};
1478
+ var init_db_get = __esm({
1479
+ "functions/sqlite/tools/db.get.ts"() {
1480
+ init_esm_shims();
1481
+ init_sqlite();
1482
+ sqlite.db.get = (name = "memorio") => {
1483
+ const dbs = globalThis.__sqliteDbs;
1484
+ if (!dbs || !dbs[name]) {
1485
+ throw new Error(
1486
+ `SQLite database '${name}' does not exist. Create it with sqlite.db.create('${name}').`
1487
+ );
1488
+ }
1489
+ return dbs[name];
1490
+ };
1491
+ }
1492
+ });
1493
+
1494
+ // functions/sqlite/tools/db.delete.ts
1495
+ var db_delete_exports2 = {};
1496
+ var init_db_delete2 = __esm({
1497
+ "functions/sqlite/tools/db.delete.ts"() {
1498
+ init_esm_shims();
1499
+ init_sqlite();
1500
+ init_message();
1501
+ sqlite.db.delete = (name) => {
1502
+ const dbs = globalThis.__sqliteDbs;
1503
+ if (!dbs || !dbs[name]) return false;
1504
+ try {
1505
+ dbs[name].close();
1506
+ } catch (_) {
1507
+ }
1508
+ delete dbs[name];
1509
+ const g3 = globalThis;
1510
+ if (g3.sqlbases) g3.sqlbases = g3.sqlbases.filter((x) => x && x.name !== name);
1511
+ message_default(`Memorio SQLite: database '${name}' deleted`);
1512
+ return true;
1513
+ };
1514
+ }
1515
+ });
1516
+
1517
+ // functions/sqlite/tools/db.list.ts
1518
+ var db_list_exports2 = {};
1519
+ var init_db_list2 = __esm({
1520
+ "functions/sqlite/tools/db.list.ts"() {
1521
+ init_esm_shims();
1522
+ init_sqlite();
1523
+ sqlite.db.list = () => {
1524
+ const dbs = globalThis.__sqliteDbs;
1525
+ return dbs ? Object.keys(dbs) : [];
1526
+ };
1527
+ }
1528
+ });
1529
+
1530
+ // functions/sqlite/tools/db.size.ts
1531
+ var db_size_exports2 = {};
1532
+ var init_db_size2 = __esm({
1533
+ "functions/sqlite/tools/db.size.ts"() {
1534
+ init_esm_shims();
1535
+ init_sqlite();
1536
+ sqlite.db.size = async (name) => {
1537
+ const dbs = globalThis.__sqliteDbs;
1538
+ if (!dbs) return 0;
1539
+ const _bytes = /* @__PURE__ */ __name((b) => b ? b.byteLength || b.length || 0 : 0, "_bytes");
1540
+ if (name) {
1541
+ const db = sqlite.db.get(name);
1542
+ return _bytes(db.export());
1543
+ }
1544
+ let total = 0;
1545
+ for (const n of Object.keys(dbs)) {
1546
+ try {
1547
+ total += _bytes(dbs[n].export());
1548
+ } catch (_) {
1549
+ }
1550
+ }
1551
+ return total;
1552
+ };
1553
+ }
1554
+ });
1555
+
1556
+ // functions/sqlite/tools/db.export.ts
1557
+ var db_export_exports = {};
1558
+ var init_db_export = __esm({
1559
+ "functions/sqlite/tools/db.export.ts"() {
1560
+ init_esm_shims();
1561
+ init_sqlite();
1562
+ sqlite.db.export = async (name = "memorio") => {
1563
+ const db = sqlite.db.get(name);
1564
+ return db.export();
1565
+ };
1566
+ }
1567
+ });
1568
+
1569
+ // functions/sqlite/tools/db.import.ts
1570
+ var db_import_exports = {};
1571
+ var init_db_import = __esm({
1572
+ "functions/sqlite/tools/db.import.ts"() {
1573
+ init_esm_shims();
1574
+ init_sqlite();
1575
+ sqlite.db.import = async (name, data) => {
1576
+ return sqlite.db.create(name, { data });
1577
+ };
1578
+ }
1579
+ });
1580
+
1581
+ // functions/sqlite/crud/query.run.ts
1582
+ var query_run_exports = {};
1583
+ var init_query_run = __esm({
1584
+ "functions/sqlite/crud/query.run.ts"() {
1585
+ init_esm_shims();
1586
+ init_sqlite();
1587
+ init_message();
1588
+ sqlite.query.run = async (name = "memorio", sql, params = []) => {
1589
+ const db = sqlite.db.get(name);
1590
+ message_default(`Memorio SQLite: run -> ${sql}`);
1591
+ db.run(sql, params);
1592
+ return db.getRowsModified();
1593
+ };
1594
+ }
1595
+ });
1596
+
1597
+ // functions/sqlite/crud/query.select.ts
1598
+ var query_select_exports = {};
1599
+ var init_query_select = __esm({
1600
+ "functions/sqlite/crud/query.select.ts"() {
1601
+ init_esm_shims();
1602
+ init_sqlite();
1603
+ sqlite.query.select = async (name = "memorio", sql, params = []) => {
1604
+ const db = sqlite.db.get(name);
1605
+ const stmt = db.prepare(sql, params);
1606
+ const result = [];
1607
+ try {
1608
+ while (stmt.step()) {
1609
+ result.push(stmt.getAsObject());
1610
+ }
1611
+ } finally {
1612
+ try {
1613
+ stmt.free();
1614
+ } catch (_) {
1615
+ }
1616
+ }
1617
+ return result;
1618
+ };
1619
+ }
1620
+ });
1621
+
1622
+ // functions/sqlite/crud/data.set.ts
1623
+ var data_set_exports2 = {};
1624
+ var init_data_set2 = __esm({
1625
+ "functions/sqlite/crud/data.set.ts"() {
1626
+ init_esm_shims();
1627
+ init_sqlite();
1628
+ sqlite.data.set = async (name = "memorio", sql, params = []) => {
1629
+ return sqlite.query.run(name, sql, params);
1630
+ };
1631
+ }
1632
+ });
1633
+
1634
+ // functions/sqlite/crud/data.get.ts
1635
+ var data_get_exports2 = {};
1636
+ var init_data_get2 = __esm({
1637
+ "functions/sqlite/crud/data.get.ts"() {
1638
+ init_esm_shims();
1639
+ init_sqlite();
1640
+ sqlite.data.get = async (name = "memorio", sql, params = []) => {
1641
+ const rows = await sqlite.query.select(name, sql, params);
1642
+ return rows.length ? rows[0] : null;
1643
+ };
1644
+ }
1645
+ });
1646
+
1647
+ // functions/sqlite/index.ts
1648
+ var _hasSqlJs, sqlite;
1649
+ var init_sqlite = __esm({
1650
+ "functions/sqlite/index.ts"() {
1651
+ init_esm_shims();
1652
+ init_platform();
1653
+ init_env();
1654
+ _hasSqlJs = hasSqlJs();
1655
+ sqlite = {
1656
+ db: {},
1657
+ query: {},
1658
+ data: {}
1659
+ };
1660
+ sqlite.config = (opts) => {
1661
+ const g3 = globalThis;
1662
+ g3.sqliteConfig = { ...g3.sqliteConfig, ...opts };
1663
+ if (opts && opts.wasmUrl) {
1664
+ g3.sqliteWasmBase = opts.wasmUrl.endsWith("/") ? opts.wasmUrl : opts.wasmUrl + "/";
1665
+ }
1666
+ return sqlite;
1667
+ };
1668
+ Object.defineProperty(sqlite, "ready", {
1669
+ enumerable: false,
1670
+ configurable: false,
1671
+ get: /* @__PURE__ */ __name(() => {
1672
+ const g3 = globalThis;
1673
+ if (!g3.sqliteReady) {
1674
+ g3.sqliteReady = typeof sqlite.db.getSQL === "function" ? sqlite.db.getSQL().then(() => {
1675
+ }).catch(() => {
1676
+ }) : Promise.resolve();
1677
+ }
1678
+ return g3.sqliteReady;
1679
+ }, "get")
1680
+ });
1681
+ if (_hasSqlJs) {
1682
+ (async () => {
1683
+ Object.defineProperty(sqlite, "db", { value: {}, writable: false, configurable: true, enumerable: true });
1684
+ Object.defineProperty(sqlite, "query", { value: {}, writable: false, configurable: true, enumerable: true });
1685
+ Object.defineProperty(sqlite, "data", { value: {}, writable: false, configurable: true, enumerable: true });
1686
+ Object.defineProperty(globalThis, "sqlbases", {
1687
+ value: [],
1688
+ writable: true,
1689
+ configurable: true,
1690
+ enumerable: false
1691
+ });
1692
+ await Promise.all([
1693
+ Promise.resolve().then(() => (init_db_support2(), db_support_exports2)),
1694
+ Promise.resolve().then(() => (init_db_create2(), db_create_exports2)),
1695
+ Promise.resolve().then(() => (init_db_get(), db_get_exports)),
1696
+ Promise.resolve().then(() => (init_db_delete2(), db_delete_exports2)),
1697
+ Promise.resolve().then(() => (init_db_list2(), db_list_exports2)),
1698
+ Promise.resolve().then(() => (init_db_size2(), db_size_exports2)),
1699
+ Promise.resolve().then(() => (init_db_export(), db_export_exports)),
1700
+ Promise.resolve().then(() => (init_db_import(), db_import_exports)),
1701
+ Promise.resolve().then(() => (init_query_run(), query_run_exports)),
1702
+ Promise.resolve().then(() => (init_query_select(), query_select_exports)),
1703
+ Promise.resolve().then(() => (init_data_set2(), data_set_exports2)),
1704
+ Promise.resolve().then(() => (init_data_get2(), data_get_exports2))
1705
+ ]);
1706
+ })();
1707
+ } else {
1708
+ 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.';
1710
+ if (DEV) {
1711
+ globalThis.sqliteDisabled = true;
1712
+ 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.");
1714
+ }
1715
+ }
1716
+ }
1717
+ });
1718
+
1719
+ // global.ts
1720
+ init_esm_shims();
1721
+
1722
+ // index.ts
1723
+ init_esm_shims();
1724
+ init_env();
1725
+
1726
+ // functions/state/index.ts
1727
+ init_esm_shims();
1728
+ init_internal();
1729
+ init_message();
1730
+
1731
+ // core/dispatch.ts
1732
+ init_esm_shims();
1733
+ var dispatch = {
1734
+ /**
1735
+ * Dispatches a custom event with the specified name and value.
1736
+ * @param name The name of the event.
1737
+ * @param value The value to pass with the event.
1738
+ */
1739
+ set: /* @__PURE__ */ __name((name, value = {}) => {
1740
+ globalThis.dispatchEvent(new CustomEvent(String(name), value));
1741
+ }, "set"),
1742
+ ///
1743
+ /**
1744
+ * Subscribes a callback to an event name. Maintains a *list* of handlers per
1745
+ * name, so multiple subscribers on the same path (e.g. several
1746
+ * `useObserver` calls observing `state.report`) each keep firing and each
1747
+ * get an independent unsubscribe. The previous single-slot-per-name
1748
+ * behaviour silently dropped the second subscriber and let any unsubscribe
1749
+ * cancel every other subscriber on that path.
1750
+ * @param name The name of the event to listen for.
1751
+ * @param cb The callback function to execute when the event is triggered.
1752
+ * @returns An unsubscribe function for this subscriber, or void if no callback.
1753
+ */
1754
+ listen: /* @__PURE__ */ __name((name, cb = null, _flag) => {
1755
+ if (!cb) return;
1756
+ const wrapped = /* @__PURE__ */ __name((e) => {
1757
+ const target = e;
1758
+ if (globalThis.queueMicrotask) {
1759
+ globalThis.queueMicrotask(() => {
1760
+ try {
1761
+ cb(target);
1762
+ } catch (err) {
1763
+ if (typeof console !== "undefined") {
1764
+ console.error("[memorio dispatch] observer error:", err);
1765
+ }
1766
+ }
1767
+ });
1768
+ } else {
1769
+ Promise.resolve().then(() => {
1770
+ try {
1771
+ cb(target);
1772
+ } catch (err) {
1773
+ if (typeof console !== "undefined") {
1774
+ console.error("[memorio dispatch] observer error:", err);
1775
+ }
1776
+ }
1777
+ });
1778
+ }
1779
+ }, "wrapped");
1780
+ globalThis.addEventListener(name, wrapped);
1781
+ const list = globalThis.events[name] = globalThis.events[name] ?? [];
1782
+ list.push(wrapped);
1783
+ return () => {
1784
+ globalThis.removeEventListener(name, wrapped);
1785
+ const idx = list.indexOf(wrapped);
1786
+ if (idx > -1) list.splice(idx, 1);
1787
+ if (!list.length) delete globalThis.events[name];
1788
+ };
1789
+ }, "listen"),
1790
+ ///
1791
+ /**
1792
+ * Removes ALL handlers for the specified event name (imperative bulk
1793
+ * removal). For per-subscriber teardown, use the unsubscribe function
1794
+ * returned by `listen`.
1795
+ * @param name The name of the event to remove the listeners for.
1796
+ */
1797
+ remove: /* @__PURE__ */ __name((name) => {
1798
+ const entry = globalThis.events?.[name];
1799
+ if (Array.isArray(entry)) {
1800
+ entry.forEach((h) => globalThis.removeEventListener(name, h));
1801
+ } else if (typeof entry === "function") {
1802
+ globalThis.removeEventListener(name, entry);
1803
+ }
1804
+ delete globalThis.events[name];
1805
+ }, "remove")
1806
+ };
1807
+
1808
+ // functions/schema/index.ts
1809
+ init_esm_shims();
1810
+ init_message();
1811
+ var _schemas = /* @__PURE__ */ new Map();
1812
+ var _validateValue = /* @__PURE__ */ __name((value, schema2, path2) => {
1813
+ const errors = [];
1814
+ if (schema2.type && schema2.type !== "any") {
1815
+ const actualType = Array.isArray(value) ? "array" : typeof value;
1816
+ if (actualType !== schema2.type) {
1817
+ errors.push(`${path2}: expected ${schema2.type}, got ${actualType}`);
1818
+ return { valid: false, errors };
1819
+ }
1820
+ }
1821
+ if (schema2.enum && !schema2.enum.includes(value)) {
1822
+ errors.push(`${path2}: value must be one of [${schema2.enum.map(String).join(", ")}]`);
1823
+ }
1824
+ if (schema2.validator) {
1825
+ const result = schema2.validator(value);
1826
+ if (result !== true) {
1827
+ errors.push(`${path2}: ${typeof result === "string" ? result : "validation failed"}`);
1828
+ }
1829
+ }
1830
+ if (typeof value === "number") {
1831
+ if (schema2.min !== void 0 && value < schema2.min) {
1832
+ errors.push(`${path2}: value ${value} is less than minimum ${schema2.min}`);
1833
+ }
1834
+ if (schema2.max !== void 0 && value > schema2.max) {
1835
+ errors.push(`${path2}: value ${value} exceeds maximum ${schema2.max}`);
1836
+ }
1837
+ }
1838
+ if (typeof value === "string") {
1839
+ if (schema2.min !== void 0 && value.length < schema2.min) {
1840
+ errors.push(`${path2}: string length ${value.length} is less than minimum ${schema2.min}`);
1841
+ }
1842
+ if (schema2.max !== void 0 && value.length > schema2.max) {
1843
+ errors.push(`${path2}: string length ${value.length} exceeds maximum ${schema2.max}`);
1844
+ }
1845
+ if (schema2.pattern && !schema2.pattern.test(value)) {
1846
+ errors.push(`${path2}: string does not match required pattern`);
1847
+ }
1848
+ }
1849
+ if (schema2.type === "object" && value && typeof value === "object" && !Array.isArray(value)) {
1850
+ if (schema2.required) {
1851
+ for (const req of schema2.required) {
1852
+ if (!(req in value)) {
1853
+ errors.push(`${path2}: missing required property '${req}'`);
1854
+ }
1855
+ }
1856
+ }
1857
+ if (schema2.properties) {
1858
+ for (const [prop, propSchema] of Object.entries(schema2.properties)) {
1859
+ if (prop in value && value[prop] !== void 0) {
1860
+ const propResult = _validateValue(value[prop], propSchema, `${path2}.${prop}`);
1861
+ if (!propResult.valid) {
1862
+ errors.push(...propResult.errors || []);
1863
+ }
1864
+ }
1865
+ }
1866
+ }
1867
+ }
1868
+ if (schema2.type === "array" && Array.isArray(value) && schema2.items) {
1869
+ for (let i = 0; i < value.length; i++) {
1870
+ const itemResult = _validateValue(value[i], schema2.items, `${path2}[${i}]`);
1871
+ if (!itemResult.valid) {
1872
+ errors.push(...itemResult.errors || []);
1873
+ }
1874
+ }
1875
+ }
1876
+ return errors.length === 0 ? { valid: true } : { valid: false, errors };
1877
+ }, "_validateValue");
1878
+ var validate = /* @__PURE__ */ __name((path2, value) => {
1879
+ const schema2 = _schemas.get(path2);
1880
+ if (!schema2) {
1881
+ return { valid: true };
1882
+ }
1883
+ return _validateValue(value, schema2, path2);
1884
+ }, "validate");
1885
+ var registerSchema = /* @__PURE__ */ __name((path2, schema2) => {
1886
+ if (typeof schema2 === "function") {
1887
+ _schemas.set(path2, { validator: schema2 });
1888
+ } else {
1889
+ _schemas.set(path2, schema2);
1890
+ }
1891
+ message_default(`[memorio schema] Registered schema for '${path2}'`);
1892
+ }, "registerSchema");
1893
+ var unregisterSchema = /* @__PURE__ */ __name((path2) => {
1894
+ return _schemas.delete(path2);
1895
+ }, "unregisterSchema");
1896
+ var listSchemas = /* @__PURE__ */ __name(() => {
1897
+ return Array.from(_schemas.keys());
1898
+ }, "listSchemas");
1899
+ var getSchema = /* @__PURE__ */ __name((path2) => {
1900
+ return _schemas.get(path2);
1901
+ }, "getSchema");
1902
+ var schema = {
1903
+ register: registerSchema,
1904
+ validate,
1905
+ unregister: unregisterSchema,
1906
+ list: listSchemas,
1907
+ get: getSchema
1908
+ };
1909
+
1910
+ // functions/state/index.ts
1911
+ init_store();
1912
+ init_env();
1913
+
1914
+ // core/mutation/engine.ts
1915
+ init_esm_shims();
1916
+ init_internal();
1917
+
1918
+ // core/hlc.ts
1919
+ init_esm_shims();
1920
+ var NODE_ID_KEY = "__memorio_hlc_node";
1921
+ function getNodeId() {
1922
+ if (typeof globalThis === "undefined") return "node";
1923
+ try {
1924
+ if (typeof sessionStorage !== "undefined" && sessionStorage) {
1925
+ let id = sessionStorage.getItem(NODE_ID_KEY);
1926
+ if (!id) {
1927
+ id = generateNodeId();
1928
+ sessionStorage.setItem(NODE_ID_KEY, id);
1929
+ }
1930
+ return id;
1931
+ }
1932
+ } catch {
1933
+ }
1934
+ if (!globalThis.__memorioHlcNodeId) {
1935
+ globalThis.__memorioHlcNodeId = generateNodeId();
1936
+ }
1937
+ return globalThis.__memorioHlcNodeId;
1938
+ }
1939
+ __name(getNodeId, "getNodeId");
1940
+ function generateNodeId() {
1941
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1942
+ return crypto.randomUUID().slice(0, 8);
1943
+ }
1944
+ return Math.random().toString(36).slice(2, 10);
1945
+ }
1946
+ __name(generateNodeId, "generateNodeId");
1947
+ var HLC_KEY = "__memorio_hlc_local";
1948
+ var local = globalThis[HLC_KEY] || {
1949
+ physical: 0,
1950
+ logical: 0,
1951
+ node: getNodeId()
1952
+ };
1953
+ if (!globalThis[HLC_KEY]) {
1954
+ globalThis[HLC_KEY] = local;
1955
+ }
1956
+ function tick(_incoming) {
1957
+ const now2 = Date.now();
1958
+ const base = local.physical;
1959
+ let physical;
1960
+ let logical;
1961
+ if (now2 > base) {
1962
+ physical = now2;
1963
+ logical = 0;
1964
+ } else if (now2 < base) {
1965
+ physical = base;
1966
+ logical = local.logical + 1;
1967
+ } else {
1968
+ physical = base;
1969
+ logical = local.logical + 1;
1970
+ }
1971
+ local.physical = physical;
1972
+ local.logical = logical;
1973
+ return { physical, logical, node: local.node };
1974
+ }
1975
+ __name(tick, "tick");
1976
+ function receive(remote) {
1977
+ const now2 = Date.now();
1978
+ if (remote.physical > local.physical) {
1979
+ local.physical = remote.physical > now2 ? remote.physical : now2;
1980
+ local.logical = 1;
1981
+ } else if (remote.physical === local.physical) {
1982
+ local.logical = Math.max(local.logical, remote.logical) + 1;
1983
+ }
1984
+ local.node = getNodeId();
1985
+ return { ...local };
1986
+ }
1987
+ __name(receive, "receive");
1988
+ function compare(a, b) {
1989
+ if (a.physical !== b.physical) {
1990
+ return a.physical < b.physical ? -1 : 1;
1991
+ }
1992
+ if (a.logical !== b.logical) {
1993
+ return a.logical < b.logical ? -1 : 1;
1994
+ }
1995
+ if (a.node !== b.node) {
1996
+ return a.node < b.node ? -1 : 1;
1997
+ }
1998
+ return 0;
1999
+ }
2000
+ __name(compare, "compare");
2001
+ function happenedBefore(a, b) {
2002
+ return compare(a, b) < 0;
2003
+ }
2004
+ __name(happenedBefore, "happenedBefore");
2005
+ function serialize(hlc2) {
2006
+ return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
2007
+ }
2008
+ __name(serialize, "serialize");
2009
+ function parse(serialized) {
2010
+ if (!serialized.startsWith("hlc:")) return null;
2011
+ const parts = serialized.split(":");
2012
+ if (parts.length !== 4) return null;
2013
+ const physical = parseInt(parts[1], 10);
2014
+ const logical = parseInt(parts[2], 10);
2015
+ const node = parts[3];
2016
+ if (isNaN(physical) || isNaN(logical)) return null;
2017
+ return { physical, logical, node };
2018
+ }
2019
+ __name(parse, "parse");
2020
+ var hlc = {
2021
+ tick,
2022
+ receive,
2023
+ compare,
2024
+ happenedBefore,
2025
+ serialize,
2026
+ parse,
2027
+ getNodeId
2028
+ };
2029
+
2030
+ // core/mutation/id.ts
2031
+ init_esm_shims();
2032
+ function generateMutationId() {
2033
+ const now2 = hlc.tick();
2034
+ return "m_" + encodeHLC(now2);
2035
+ }
2036
+ __name(generateMutationId, "generateMutationId");
2037
+ function generateTransactionId() {
2038
+ const now2 = hlc.tick();
2039
+ return "tx_" + encodeHLC(now2);
2040
+ }
2041
+ __name(generateTransactionId, "generateTransactionId");
2042
+ function generateCommitId() {
2043
+ const now2 = hlc.tick();
2044
+ return "c_" + encodeHLC(now2);
2045
+ }
2046
+ __name(generateCommitId, "generateCommitId");
2047
+ function encodeHLC(hlcValue) {
2048
+ const timePart = hlcValue.physical.toString(36);
2049
+ const logicalPart = hlcValue.logical.toString(36).padStart(2, "0");
2050
+ const nodePart = hlcValue.node.slice(0, 4);
2051
+ return `${timePart}${logicalPart}${nodePart}`;
2052
+ }
2053
+ __name(encodeHLC, "encodeHLC");
2054
+
2055
+ // core/mutation/patch.ts
2056
+ init_esm_shims();
2057
+ function mutationToPatch(mutation) {
2058
+ if (mutation.before === mutation.after) return null;
2059
+ const op = mutationToPatchOp(mutation.operation, mutation.before, mutation.after);
2060
+ if (!op) return null;
2061
+ const patch = { op, path: mutation.path };
2062
+ if (op === "add" || op === "replace") {
2063
+ patch.value = mutation.after;
2064
+ }
2065
+ if (op === "replace") {
2066
+ patch.oldValue = mutation.before;
2067
+ }
2068
+ if (op === "remove") {
2069
+ patch.oldValue = mutation.before;
2070
+ }
2071
+ return patch;
2072
+ }
2073
+ __name(mutationToPatch, "mutationToPatch");
2074
+ function mutationToPatchOp(operation, _before, _after) {
2075
+ switch (operation) {
2076
+ case "set":
2077
+ if (_before === void 0) return "add";
2078
+ return "replace";
2079
+ case "delete":
2080
+ return "remove";
2081
+ case "insert":
2082
+ return "add";
2083
+ case "remove":
2084
+ return "remove";
2085
+ case "replace":
2086
+ return "replace";
2087
+ case "length":
2088
+ return "replace";
2089
+ default:
2090
+ return null;
2091
+ }
2092
+ }
2093
+ __name(mutationToPatchOp, "mutationToPatchOp");
2094
+ function diffToPatch(path2, before2, after2) {
2095
+ if (before2 === after2) return null;
2096
+ if (after2 === void 0) {
2097
+ return { op: "remove", path: path2, oldValue: before2 };
2098
+ }
2099
+ if (before2 === void 0) {
2100
+ return { op: "add", path: path2, value: after2 };
2101
+ }
2102
+ return { op: "replace", path: path2, value: after2, oldValue: before2 };
2103
+ }
2104
+ __name(diffToPatch, "diffToPatch");
2105
+ function canMerge(patch1, patch2) {
2106
+ return patch1.path === patch2.path && patch1.op === patch2.op;
2107
+ }
2108
+ __name(canMerge, "canMerge");
2109
+ function mergePatches(patch1, patch2) {
2110
+ const op = patch1.op === "remove" && patch2.op === "remove" ? "remove" : "replace";
2111
+ return {
2112
+ op,
2113
+ path: patch1.path,
2114
+ value: patch2.value ?? patch1.value,
2115
+ oldValue: patch1.oldValue
2116
+ };
2117
+ }
2118
+ __name(mergePatches, "mergePatches");
2119
+
2120
+ // core/mutation/transaction.ts
2121
+ init_esm_shims();
2122
+ init_internal();
2123
+ var TX_REGISTRY_KEY = "__memorio_transaction_registry__";
2124
+ var registry = globalThis[TX_REGISTRY_KEY] || /* @__PURE__ */ new Map();
2125
+ if (!globalThis[TX_REGISTRY_KEY]) {
2126
+ globalThis[TX_REGISTRY_KEY] = registry;
2127
+ }
2128
+ var TX_STACK_KEY = "__memorio_transaction_stack__";
2129
+ var txStack = globalThis[TX_STACK_KEY] || [];
2130
+ if (!globalThis[TX_STACK_KEY]) {
2131
+ globalThis[TX_STACK_KEY] = txStack;
2132
+ }
2133
+ function getActiveTxId() {
2134
+ return txStack.length > 0 ? txStack[txStack.length - 1] : null;
2135
+ }
2136
+ __name(getActiveTxId, "getActiveTxId");
2137
+ function setActiveTx(id) {
2138
+ if (id === null) {
2139
+ txStack.pop();
2140
+ } else {
2141
+ txStack.push(id);
2142
+ }
2143
+ }
2144
+ __name(setActiveTx, "setActiveTx");
2145
+ function beginTransaction(source, message2, metadata) {
2146
+ const id = generateTransactionId();
2147
+ const ctx = {
2148
+ id,
2149
+ startedAt: hlc.serialize(hlc.tick()),
2150
+ source,
2151
+ message: message2,
2152
+ metadata,
2153
+ mutations: [],
2154
+ active: true
2155
+ };
2156
+ registry.set(id, ctx);
2157
+ setActiveTx(id);
2158
+ return ctx;
2159
+ }
2160
+ __name(beginTransaction, "beginTransaction");
2161
+ function tagForTransaction() {
2162
+ const txId = getActiveTxId();
2163
+ if (!txId) return void 0;
2164
+ const ctx = registry.get(txId);
2165
+ if (ctx && ctx.active) {
2166
+ return txId;
2167
+ }
2168
+ return void 0;
2169
+ }
2170
+ __name(tagForTransaction, "tagForTransaction");
2171
+ function commitTransaction() {
2172
+ const txId = getActiveTxId();
2173
+ if (!txId) return null;
2174
+ const ctx = registry.get(txId);
2175
+ if (!ctx || !ctx.active) return null;
2176
+ ctx.active = false;
2177
+ ctx.committedAt = hlc.serialize(hlc.tick());
2178
+ const tx = {
2179
+ id: ctx.id,
2180
+ mutations: ctx.mutations,
2181
+ startedAt: ctx.startedAt,
2182
+ committedAt: ctx.committedAt,
2183
+ source: ctx.source,
2184
+ message: ctx.message,
2185
+ metadata: ctx.metadata
2186
+ };
2187
+ setActiveTx(null);
2188
+ return tx;
2189
+ }
2190
+ __name(commitTransaction, "commitTransaction");
2191
+ function _setPath(path2, value) {
2192
+ const parts = path2.replace(/^state\./, "").split(".");
2193
+ let current = globalThis.state;
2194
+ for (let i = 0; i < parts.length - 1; i++) {
2195
+ const part = parts[i];
2196
+ if (current[part] === void 0) {
2197
+ current[part] = {};
2198
+ }
2199
+ current = current[part];
2200
+ }
2201
+ current[parts[parts.length - 1]] = value;
2202
+ }
2203
+ __name(_setPath, "_setPath");
2204
+ function _deletePath(path2) {
2205
+ const parts = path2.replace(/^state\./, "").split(".");
2206
+ let current = globalThis.state;
2207
+ for (let i = 0; i < parts.length - 1; i++) {
2208
+ const part = parts[i];
2209
+ if (current[part] === void 0) return;
2210
+ current = current[part];
2211
+ }
2212
+ if (current.remove) {
2213
+ current.remove(parts[parts.length - 1]);
2214
+ } else {
2215
+ delete current[parts[parts.length - 1]];
2216
+ }
2217
+ }
2218
+ __name(_deletePath, "_deletePath");
2219
+ function _applyInverse(record) {
2220
+ const wasEnabled = internal_default.historyEnabled;
2221
+ const wasRecording = internal_default._recording;
2222
+ internal_default.historyEnabled = false;
2223
+ internal_default._recording = false;
2224
+ try {
2225
+ if (record.action === "set" || record.operation === "set") {
2226
+ if (record.previousValue === void 0) {
2227
+ _deletePath(record.path);
2228
+ } else {
2229
+ _setPath(record.path, record.previousValue);
2230
+ }
2231
+ } else if (record.action === "delete" || record.operation === "delete") {
2232
+ if (record.previousValue !== void 0) {
2233
+ _setPath(record.path, record.previousValue);
2234
+ }
2235
+ }
2236
+ } finally {
2237
+ internal_default.historyEnabled = wasEnabled;
2238
+ internal_default._recording = wasRecording;
2239
+ }
2240
+ }
2241
+ __name(_applyInverse, "_applyInverse");
2242
+ function abortTransaction() {
2243
+ const txId = getActiveTxId();
2244
+ if (!txId) return null;
2245
+ const ctx = registry.get(txId);
2246
+ if (!ctx || !ctx.active) return null;
2247
+ for (let i = ctx.mutations.length - 1; i >= 0; i--) {
2248
+ const undoStack = internal_default.undoStack;
2249
+ const idx = undoStack.findIndex((r) => r.id === ctx.mutations[i]);
2250
+ if (idx >= 0) {
2251
+ const record = undoStack[idx];
2252
+ internal_default.undoStack.splice(idx, 1);
2253
+ _applyInverse(record);
2254
+ }
2255
+ }
2256
+ ctx.active = false;
2257
+ ctx.committedAt = hlc.serialize(hlc.tick());
2258
+ const tx = {
2259
+ id: ctx.id,
2260
+ mutations: ctx.mutations,
2261
+ startedAt: ctx.startedAt,
2262
+ committedAt: ctx.committedAt,
2263
+ source: ctx.source,
2264
+ message: ctx.message,
2265
+ metadata: ctx.metadata
2266
+ };
2267
+ registry.delete(txId);
2268
+ setActiveTx(null);
2269
+ return tx;
2270
+ }
2271
+ __name(abortTransaction, "abortTransaction");
2272
+ function listTransactions() {
2273
+ const result = [];
2274
+ for (const ctx of registry.values()) {
2275
+ result.push({
2276
+ id: ctx.id,
2277
+ mutations: ctx.mutations,
2278
+ startedAt: ctx.startedAt,
2279
+ committedAt: ctx.committedAt,
2280
+ source: ctx.source,
2281
+ message: ctx.message,
2282
+ metadata: ctx.metadata
2283
+ });
2284
+ }
2285
+ return result;
2286
+ }
2287
+ __name(listTransactions, "listTransactions");
2288
+ function currentTransaction() {
2289
+ const txId = getActiveTxId();
2290
+ if (!txId) return null;
2291
+ const ctx = registry.get(txId);
2292
+ if (!ctx || !ctx.active) return null;
2293
+ return {
2294
+ id: ctx.id,
2295
+ mutations: ctx.mutations,
2296
+ startedAt: ctx.startedAt,
2297
+ source: ctx.source,
2298
+ message: ctx.message,
2299
+ metadata: ctx.metadata
2300
+ };
2301
+ }
2302
+ __name(currentTransaction, "currentTransaction");
2303
+ function registerMutationInTransaction(mutationId) {
2304
+ const txId = getActiveTxId();
2305
+ if (!txId) return;
2306
+ const ctx = registry.get(txId);
2307
+ if (ctx && ctx.active) {
2308
+ ctx.mutations.push(mutationId);
2309
+ }
2310
+ }
2311
+ __name(registerMutationInTransaction, "registerMutationInTransaction");
2312
+
2313
+ // core/mutation/engine.ts
2314
+ function currentTimestamp() {
2315
+ return hlc.serialize(hlc.tick());
2316
+ }
2317
+ __name(currentTimestamp, "currentTimestamp");
2318
+ function createMutation(path2, operation, before2, after2, options) {
2319
+ const now2 = hlc.tick();
2320
+ const mutation = {
2321
+ id: generateMutationId(),
2322
+ path: path2,
2323
+ operation,
2324
+ after: after2,
2325
+ before: before2,
2326
+ timestamp: now2.physical,
2327
+ hlc: hlc.serialize(now2),
2328
+ context: options?.context || internal_default.currentContext || void 0,
2329
+ source: options?.source,
2330
+ transactionId: options?.transactionId || (operation !== "length" ? tagForTransaction() : void 0),
2331
+ // Legacy fields for backward compatibility
2332
+ action: operation === "set" ? "set" : "delete",
2333
+ newValue: after2,
2334
+ previousValue: before2
2335
+ };
2336
+ if (mutation.transactionId) {
2337
+ registerMutationInTransaction(mutation.id);
2338
+ }
2339
+ return mutation;
2340
+ }
2341
+ __name(createMutation, "createMutation");
2342
+ function recordMutation(mutation) {
2343
+ if (!internal_default.historyEnabled) return;
2344
+ internal_default.recordMutation(mutation);
2345
+ }
2346
+ __name(recordMutation, "recordMutation");
2347
+ function toPatch(mutation) {
2348
+ return mutationToPatch(mutation);
2349
+ }
2350
+ __name(toPatch, "toPatch");
2351
+ function mutate(path2, value, options) {
2352
+ const normalizedPath = path2.startsWith("state.") ? path2 : "state." + path2;
2353
+ const keyPath = normalizedPath.replace(/^state\./, "");
2354
+ let current;
2355
+ try {
2356
+ const parts2 = keyPath.split(".");
2357
+ let obj = globalThis.state;
2358
+ for (const part of parts2) {
2359
+ obj = obj?.[part];
2360
+ }
2361
+ current = obj;
2362
+ } catch {
2363
+ current = void 0;
2364
+ }
2365
+ const operation = value === void 0 ? "delete" : "set";
2366
+ const mutation = createMutation(
2367
+ normalizedPath,
2368
+ operation,
2369
+ current,
2370
+ value === void 0 ? void 0 : value,
2371
+ options
2372
+ );
2373
+ const wasRecording = internal_default._recording;
2374
+ internal_default._recording = false;
2375
+ const parts = keyPath.split(".");
2376
+ let target = globalThis.state;
2377
+ for (let i = 0; i < parts.length - 1; i++) {
2378
+ if (target[parts[i]] === void 0) {
2379
+ target[parts[i]] = {};
2380
+ }
2381
+ target = target[parts[i]];
2382
+ }
2383
+ if (operation === "delete") {
2384
+ delete target[parts[parts.length - 1]];
2385
+ } else {
2386
+ target[parts[parts.length - 1]] = value;
2387
+ }
2388
+ internal_default._recording = wasRecording;
2389
+ recordMutation(mutation);
2390
+ return mutation;
2391
+ }
2392
+ __name(mutate, "mutate");
2393
+ function activeTransactionId() {
2394
+ return internal_default.currentTransactionId || null;
2395
+ }
2396
+ __name(activeTransactionId, "activeTransactionId");
2397
+
2398
+ // functions/state/index.ts
2399
+ var TARGET = /* @__PURE__ */ Symbol("memorio.target");
2400
+ var wrapperCache = /* @__PURE__ */ new WeakMap();
2401
+ var arrayRootDedup = /* @__PURE__ */ new Set();
2402
+ var deepRaw = /* @__PURE__ */ __name((val, seen = null) => {
2403
+ if (val === null || typeof val !== "object") return val;
2404
+ if (!seen) seen = /* @__PURE__ */ new WeakSet();
2405
+ if (val[TARGET] !== void 0) return deepRaw(val[TARGET], seen);
2406
+ if (seen) {
2407
+ if (seen.has(val)) return val;
2408
+ seen.add(val);
2409
+ }
2410
+ const ctor = val.constructor?.name;
2411
+ if (ctor !== "Object" && ctor !== "Array") return val;
2412
+ const copy = Array.isArray(val) ? [] : {};
2413
+ for (const k of Reflect.ownKeys(val)) {
2414
+ if (!Object.prototype.propertyIsEnumerable.call(val, k)) continue;
2415
+ copy[k] = deepRaw(val[k], seen);
2416
+ }
2417
+ return copy;
2418
+ }, "deepRaw");
2419
+ var objPath = /* @__PURE__ */ __name((prop, object, separator = ".") => {
2420
+ return object.concat(prop).join(separator);
2421
+ }, "objPath");
2422
+ var buildProxy = /* @__PURE__ */ __name((obj, callback, tree = []) => {
2423
+ const event = /* @__PURE__ */ __name((name) => {
2424
+ try {
2425
+ dispatch.set(name, { detail: { name } });
2426
+ } catch (err) {
2427
+ if (DEV) console.warn("[memorio state] event dispatch failed:", err);
2428
+ }
2429
+ return;
2430
+ }, "event");
2431
+ return new Proxy(
2432
+ obj,
2433
+ {
2434
+ get(target, prop) {
2435
+ if (prop === "__path") {
2436
+ return tree.length > 0 ? "state." + tree.join(".") : "state";
2437
+ }
2438
+ if (prop === TARGET) {
2439
+ return target;
2440
+ }
2441
+ if (target[TARGET] !== void 0) {
2442
+ return target;
2443
+ }
2444
+ if (prop === "list") {
2445
+ message_default('Some state could be hidden when you use "state.list". Use "state" to see the complete list ');
2446
+ return deepRaw(target, /* @__PURE__ */ new WeakSet());
2447
+ }
2448
+ if (typeof prop === "string") {
2449
+ const path2 = tree.length > 0 ? "state." + tree.concat(prop).join(".") : "state." + prop;
2450
+ internal_default.lastAccessedPath = path2;
2451
+ if (internal_default.tracking) {
2452
+ internal_default.trackedPaths.add(path2);
2453
+ }
2454
+ }
2455
+ if (prop === "_lastPath") {
2456
+ return internal_default.lastAccessedPath;
2457
+ }
2458
+ if (prop === "remove") {
2459
+ return (key) => {
2460
+ delete target[key];
2461
+ return true;
2462
+ };
2463
+ }
2464
+ if (prop === "removeAll") {
2465
+ return () => {
2466
+ try {
2467
+ for (const key of Reflect.ownKeys(target)) {
2468
+ if (typeof target[key] !== "function" && !["list", "remove", "removeAll", "lock", "unlock", "persist"].includes(key)) {
2469
+ delete target[key];
2470
+ }
2471
+ }
2472
+ } catch (error) {
2473
+ console.error(error);
2474
+ }
2475
+ return;
2476
+ };
2477
+ }
2478
+ if (Object.isFrozen(target[prop])) return target[prop];
2479
+ if (prop === "lock" || prop === "unlock") {
2480
+ const value = Reflect.get(target, prop);
2481
+ if (value) return value;
2482
+ }
2483
+ try {
2484
+ const value = Reflect.get(target, prop);
2485
+ if (value && typeof value === "object" && ["Array", "Object"].includes(value.constructor.name)) {
2486
+ let wrapper = wrapperCache.get(value);
2487
+ if (!wrapper) {
2488
+ wrapper = buildProxy(value, callback, tree.concat(prop));
2489
+ wrapperCache.set(value, wrapper);
2490
+ }
2491
+ return wrapper;
2492
+ }
2493
+ return value;
2494
+ } catch (error) {
2495
+ console.error("Error: ", error);
2496
+ return void 0;
2497
+ }
2498
+ },
2499
+ set(target, key, value) {
2500
+ if (internal_default.locked) {
2501
+ console.error("Error: state is locked. Use state.unlock() to enable modifications.");
2502
+ return false;
2503
+ }
2504
+ if (protect.includes(key)) {
2505
+ console.error("key " + key + " is protected");
2506
+ return false;
2507
+ }
2508
+ if (target[key] && typeof target[key] === "object" && Object.isFrozen(target[key])) {
2509
+ console.error(`Error: state '${key}' is locked`);
2510
+ return false;
2511
+ }
2512
+ if (target[key] && typeof target[key] === "object" && target[key].__locked) {
2513
+ console.error(`Error: state '${key}' is locked. Use state.${key}.unlock() to enable modifications.`);
2514
+ return false;
2515
+ }
2516
+ try {
2517
+ const path2 = objPath(key, tree);
2518
+ const rawValue = deepRaw(value);
2519
+ const _schemaResult = schema.validate(path2, rawValue);
2520
+ if (!_schemaResult.valid) {
2521
+ if (DEV && internal_default.debug) {
2522
+ console.error(
2523
+ `[memorio schema] Validation failed for '${path2}':`,
2524
+ _schemaResult.errors
2525
+ );
2526
+ }
2527
+ message_default(
2528
+ `[memorio schema] Validation failed for '${path2}': ` + (_schemaResult.errors?.join(", ") || "unknown error")
2529
+ );
2530
+ return false;
2531
+ }
2532
+ callback(
2533
+ {
2534
+ action: "set",
2535
+ path: path2,
2536
+ target,
2537
+ newValue: rawValue,
2538
+ previousValue: Reflect.get(target, key)
2539
+ }
2540
+ );
2541
+ event("state." + path2);
2542
+ if (Array.isArray(target) && tree.length > 0) {
2543
+ const rootName = "state." + tree.join(".");
2544
+ if (!arrayRootDedup.has(rootName)) {
2545
+ arrayRootDedup.add(rootName);
2546
+ event(rootName);
2547
+ if (typeof globalThis.queueMicrotask === "function") {
2548
+ globalThis.queueMicrotask(() => arrayRootDedup.clear());
2549
+ }
2550
+ }
2551
+ }
2552
+ Reflect.set(target, key, rawValue);
2553
+ internal_default.bumpStateVersion();
2554
+ if (target[key] && typeof target[key] === "object") {
2555
+ const lockValue = target[key];
2556
+ if (lockValue && typeof lockValue === "object") {
2557
+ try {
2558
+ Object.defineProperty(lockValue, "__locked", {
2559
+ writable: true,
2560
+ enumerable: false,
2561
+ configurable: false,
2562
+ value: false
2563
+ });
2564
+ Object.defineProperty(lockValue, "lock", {
2565
+ writable: false,
2566
+ enumerable: false,
2567
+ configurable: false,
2568
+ value: /* @__PURE__ */ __name(() => {
2569
+ Object.defineProperty(lockValue, "__locked", {
2570
+ writable: true,
2571
+ enumerable: false,
2572
+ configurable: false,
2573
+ value: true
2574
+ });
2575
+ message_default(`State '${key}' is now locked.`);
2576
+ }, "value")
2577
+ });
2578
+ Object.defineProperty(lockValue, "unlock", {
2579
+ writable: false,
2580
+ enumerable: false,
2581
+ configurable: false,
2582
+ value: /* @__PURE__ */ __name(() => {
2583
+ Object.defineProperty(lockValue, "__locked", {
2584
+ writable: true,
2585
+ enumerable: false,
2586
+ configurable: false,
2587
+ value: false
2588
+ });
2589
+ message_default(`State '${key}' is now unlocked.`);
2590
+ }, "value")
2591
+ });
2592
+ } catch (err) {
2593
+ if (DEV) console.warn("[memorio state] lock/unlock defineProperty failed:", err);
2594
+ }
2595
+ }
2596
+ }
2597
+ return true;
2598
+ } catch (error) {
2599
+ console.error("Error in set trap:", error);
2600
+ return false;
2601
+ }
2602
+ },
2603
+ deleteProperty(target, prop) {
2604
+ try {
2605
+ const path2 = objPath(prop, tree);
2606
+ const previousValue = Reflect.get(target, prop);
2607
+ callback({ action: "delete", path: path2, target, previousValue });
2608
+ event("state." + path2);
2609
+ if (Array.isArray(target) && tree.length > 0) {
2610
+ const rootName = "state." + tree.join(".");
2611
+ if (!arrayRootDedup.has(rootName)) {
2612
+ arrayRootDedup.add(rootName);
2613
+ event(rootName);
2614
+ if (typeof globalThis.queueMicrotask === "function") {
2615
+ globalThis.queueMicrotask(() => arrayRootDedup.clear());
2616
+ }
2617
+ }
2618
+ }
2619
+ return Reflect.deleteProperty(target, prop);
2620
+ } catch (error) {
2621
+ console.error("Error in deleteProperty trap:", error);
2622
+ return false;
2623
+ }
2624
+ },
2625
+ ownKeys(target) {
2626
+ return Reflect.ownKeys(target);
2627
+ },
2628
+ getOwnPropertyDescriptor(target, prop) {
2629
+ return Reflect.getOwnPropertyDescriptor(target, prop);
2630
+ }
2631
+ }
2632
+ );
2633
+ }, "buildProxy");
2634
+ var STATE_INSTANCE_KEY = "__memorio_state_instance__";
2635
+ var state2;
2636
+ if (globalThis[STATE_INSTANCE_KEY]) {
2637
+ state2 = globalThis[STATE_INSTANCE_KEY];
2638
+ } else {
2639
+ state2 = buildProxy({}, (mutation) => {
2640
+ if (internal_default.historyEnabled && internal_default._recording !== false) {
2641
+ const operation = mutation.action === "delete" ? "delete" : "set";
2642
+ const record = createMutation(
2643
+ mutation.path,
2644
+ operation,
2645
+ mutation.previousValue,
2646
+ mutation.newValue,
2647
+ {
2648
+ context: mutation.context,
2649
+ source: mutation.source
2650
+ }
2651
+ );
2652
+ internal_default.recordMutation(record);
2653
+ }
2654
+ });
2655
+ const _rawTarget = state2[TARGET];
2656
+ try {
2657
+ Object.defineProperty(_rawTarget, "lock", {
2658
+ value: /* @__PURE__ */ __name(() => {
2659
+ internal_default.locked = true;
2660
+ message_default("State is now locked. All modifications are blocked.");
2661
+ }, "value"),
2662
+ writable: true,
2663
+ configurable: true,
2664
+ enumerable: false
2665
+ });
2666
+ Object.defineProperty(_rawTarget, "unlock", {
2667
+ value: /* @__PURE__ */ __name(() => {
2668
+ internal_default.locked = false;
2669
+ message_default("State is now unlocked. Modifications are allowed.");
2670
+ }, "value"),
2671
+ writable: true,
2672
+ configurable: true,
2673
+ enumerable: false
2674
+ });
2675
+ } catch (e) {
2676
+ if (DEV) console.warn("[memorio state] lock/unlock defineProperty failed:", e);
2677
+ }
2678
+ try {
2679
+ Object.defineProperty(_rawTarget, "persist", {
2680
+ value: /* @__PURE__ */ __name((path2) => {
2681
+ if (typeof path2 !== "string" || !path2.length) {
2682
+ if (DEV) console.warn('[memorio state] state.persist() requires a non-empty path string (e.g. "state.user")');
2683
+ return () => {
2684
+ };
2685
+ }
2686
+ const normalized = path2.startsWith("state.") ? path2 : "state." + path2;
2687
+ const key = normalized.replace(/^state\./, "");
2688
+ const segments = key.split(".");
2689
+ const initial = store.get(key);
2690
+ if (initial !== void 0 && initial !== null) {
2691
+ let acc = state2;
2692
+ for (let i = 0; i < segments.length - 1; i++) {
2693
+ const seg = segments[i];
2694
+ if (acc[seg] === void 0 || acc[seg] === null) acc[seg] = {};
2695
+ acc = acc[seg];
2696
+ }
2697
+ if (acc) acc[segments[segments.length - 1]] = deepRaw(initial);
2698
+ }
2699
+ const handler = /* @__PURE__ */ __name(() => {
2700
+ let current = state2;
2701
+ for (const seg of segments) {
2702
+ current = current === void 0 || current === null ? void 0 : current[seg];
2703
+ }
2704
+ store.set(key, deepRaw(current));
2705
+ }, "handler");
2706
+ const off = dispatch.listen(normalized, handler);
2707
+ return typeof off === "function" ? off : () => {
2708
+ };
2709
+ }, "value"),
2710
+ writable: true,
2711
+ configurable: true,
2712
+ enumerable: false
2713
+ });
2714
+ } catch (e) {
2715
+ if (DEV) console.warn("[memorio state] persist defineProperty failed:", e);
2716
+ }
2717
+ globalThis[STATE_INSTANCE_KEY] = state2;
2718
+ }
2719
+
2720
+ // index.ts
2721
+ init_store();
2722
+
2723
+ // functions/session/index.ts
2724
+ init_esm_shims();
2725
+ init_platform();
2726
+ init_internal();
2727
+ init_message();
2728
+ var _sessionStorage = getSessionStorage();
2729
+ var _fallbackStorageByContext2 = /* @__PURE__ */ new Map();
2730
+ function _getFallbackStorage2() {
2731
+ const contextName = internal_default.currentContext || "";
2732
+ const key = contextName || "default";
2733
+ if (!_fallbackStorageByContext2.has(key)) {
2734
+ _fallbackStorageByContext2.set(key, /* @__PURE__ */ new Map());
2735
+ }
2736
+ return _fallbackStorageByContext2.get(key);
2737
+ }
2738
+ __name(_getFallbackStorage2, "_getFallbackStorage");
2739
+ var _hasStorage2 = _sessionStorage !== null;
2740
+ function _getPrefix2() {
2741
+ const contextName = internal_default.currentContext || "";
2742
+ return contextName ? `${contextName}-` : `memorio_session_`;
2743
+ }
2744
+ __name(_getPrefix2, "_getPrefix");
2745
+ function _prefixKey2(name) {
2746
+ if (!name || typeof name !== "string") {
2747
+ console.warn("[memorio session] key is empty or not a string - operation aborted");
2748
+ return "";
2749
+ }
2750
+ if (name.length > 512) {
2751
+ console.warn(`[memorio session] key "${name}" exceeds 512 chars - operation aborted`);
2752
+ return "";
2753
+ }
2754
+ return _getPrefix2() + name;
2755
+ }
2756
+ __name(_prefixKey2, "_prefixKey");
2757
+ function _read2(prefixedName) {
2758
+ const raw = _hasStorage2 ? _sessionStorage.getItem(prefixedName) : _getFallbackStorage2().get(prefixedName);
2759
+ return raw ? JSON.parse(raw) : raw;
2760
+ }
2761
+ __name(_read2, "_read");
2762
+ function _write2(prefixedName, value) {
2763
+ const json = JSON.stringify(value);
2764
+ if (_hasStorage2) _sessionStorage.setItem(prefixedName, json);
2765
+ else _getFallbackStorage2().set(prefixedName, json);
2766
+ }
2767
+ __name(_write2, "_write");
2768
+ function _remove2(prefixedName) {
2769
+ if (_hasStorage2) {
2770
+ if (_sessionStorage.getItem(prefixedName)) {
2771
+ _sessionStorage.removeItem(prefixedName);
2772
+ return true;
2773
+ }
2774
+ } else if (_getFallbackStorage2().has(prefixedName)) {
2775
+ _getFallbackStorage2().delete(prefixedName);
2776
+ return true;
2777
+ }
2778
+ return false;
2779
+ }
2780
+ __name(_remove2, "_remove");
2781
+ var SESSION_INSTANCE_KEY = "__memorio_session_instance__";
2782
+ var session;
2783
+ if (globalThis[SESSION_INSTANCE_KEY]) {
2784
+ session = globalThis[SESSION_INSTANCE_KEY];
2785
+ } else {
2786
+ session = new Proxy({}, {});
2787
+ Object.defineProperties(
2788
+ session,
2789
+ {
2790
+ /**
2791
+ * Gets a value from storage.
2792
+ * @param name The key to retrieve.
2793
+ * @returns The parsed value or null if not found.
2794
+ */
2795
+ get: {
2796
+ value: /* @__PURE__ */ __name((name) => {
2797
+ if (!name) {
2798
+ console.warn("[memorio session] session.get() called with empty or null key - returning null");
2799
+ return null;
2800
+ }
2801
+ try {
2802
+ return _read2(_prefixKey2(name));
2803
+ } catch (err) {
2804
+ message(`Error parsing session item '${name}':${err}`);
2805
+ }
2806
+ return null;
2807
+ }, "value")
2808
+ },
2809
+ /**
2810
+ * Sets a value in storage.
2811
+ * @param name The key to set.
2812
+ * @param value The value to store.
2813
+ * @returns true if written, false if the key was rejected.
2814
+ */
2815
+ set: {
2816
+ value: /* @__PURE__ */ __name((name, value) => {
2817
+ if (!name) {
2818
+ console.warn("[memorio session] session.set() called with empty or null key - write aborted");
2819
+ return false;
2820
+ }
2821
+ const prefixedName = _prefixKey2(name);
2822
+ if (!prefixedName) return false;
2823
+ if (typeof value === "function") {
2824
+ console.warn("[memorio session] functions are not storable - write aborted for key: " + name);
2825
+ message("It's not secure to session functions.");
2826
+ return false;
2827
+ }
2828
+ try {
2829
+ _write2(prefixedName, value);
2830
+ } catch (err) {
2831
+ message(`Error setting session item '${name}': ${err}`);
2832
+ return false;
2833
+ }
2834
+ return true;
2835
+ }, "value")
2836
+ },
2837
+ /**
2838
+ * Removes a value from storage.
2839
+ * @param name The key to remove.
2840
+ * @returns True if removed.
2841
+ */
2842
+ remove: {
2843
+ value: /* @__PURE__ */ __name((name) => {
2844
+ if (!name) {
2845
+ console.warn("[memorio session] session.remove() called with empty or null key - returning false");
2846
+ return false;
2847
+ }
2848
+ const prefixedName = _prefixKey2(name);
2849
+ if (!prefixedName) return false;
2850
+ try {
2851
+ return _remove2(prefixedName);
2852
+ } catch (err) {
2853
+ message(`Error removing session item '${name}': ${err}`);
2854
+ }
2855
+ return false;
2856
+ }, "value")
2857
+ },
2858
+ /**
2859
+ * Alias for remove.
2860
+ * @param name The key to delete.
2861
+ * @returns True if removed.
2862
+ */
2863
+ delete: {
2864
+ value: /* @__PURE__ */ __name((name) => {
2865
+ return session.remove(name);
2866
+ }, "value")
2867
+ },
2868
+ /**
2869
+ * Clears all sessionStorage items.
2870
+ */
2871
+ removeAll: {
2872
+ value: /* @__PURE__ */ __name(() => {
2873
+ if (_hasStorage2) {
2874
+ const keysToRemove = [];
2875
+ for (let i = 0; i < _sessionStorage.length; i++) {
2876
+ const key = _sessionStorage.key(i);
2877
+ if (key?.startsWith(_getPrefix2())) {
2878
+ keysToRemove.push(key);
2879
+ }
2880
+ }
2881
+ keysToRemove.forEach((key) => _sessionStorage.removeItem(key));
2882
+ } else {
2883
+ _getFallbackStorage2().clear();
2884
+ }
2885
+ return true;
2886
+ }, "value")
2887
+ },
2888
+ /**
2889
+ * Alias for removeAll.
2890
+ */
2891
+ clearAll: {
2892
+ value: /* @__PURE__ */ __name(() => {
2893
+ session.removeAll();
2894
+ return true;
2895
+ }, "value")
2896
+ },
2897
+ quota: {
2898
+ value: /* @__PURE__ */ __name(async () => {
2899
+ return [0, 0];
2900
+ }, "value")
2901
+ },
2902
+ /**
2903
+ * Calculates total size of all memorio session items in kilobytes.
2904
+ * Counts each prefixed key and its JSON-serialized value, summing their
2905
+ * byte lengths and converting to whole kilobytes (Math.ceil).
2906
+ * @returns Total size in kilobytes (0 when empty / no memorio items).
2907
+ */
2908
+ size: {
2909
+ value: /* @__PURE__ */ __name(() => {
2910
+ let totalBytes = 0;
2911
+ if (_hasStorage2) {
2912
+ for (let i = 0; i < _sessionStorage.length; i++) {
2913
+ const key = _sessionStorage.key(i);
2914
+ if (key && key.startsWith(_getPrefix2())) {
2915
+ const item = _sessionStorage.getItem(key);
2916
+ if (item) totalBytes += key.length + item.length;
2917
+ }
2918
+ }
2919
+ } else {
2920
+ _getFallbackStorage2().forEach((value, key) => {
2921
+ totalBytes += key.length + value.length;
2922
+ });
2923
+ }
2924
+ return totalBytes === 0 ? 0 : Math.ceil(totalBytes / 1024);
2925
+ }, "value")
2926
+ },
2927
+ /**
2928
+ * Check if using real sessionStorage or fallback
2929
+ */
2930
+ isPersistent: {
2931
+ get: /* @__PURE__ */ __name(() => _hasStorage2, "get")
2932
+ },
2933
+ /**
2934
+ * Get a list of all memorio session items.
2935
+ */
2936
+ list: {
2937
+ value: /* @__PURE__ */ __name(() => {
2938
+ const result = {};
2939
+ try {
2940
+ if (_hasStorage2) {
2941
+ for (let i = 0; i < _sessionStorage.length; i++) {
2942
+ const key = _sessionStorage.key(i);
2943
+ if (key?.startsWith(_getPrefix2())) {
2944
+ const cleanKey = key.replace(_getPrefix2(), "");
2945
+ const item = _sessionStorage.getItem(key);
2946
+ if (item !== null) {
2947
+ try {
2948
+ result[cleanKey] = JSON.parse(item);
2949
+ } catch {
2950
+ result[cleanKey] = item;
2951
+ }
2952
+ }
2953
+ }
2954
+ }
2955
+ } else {
2956
+ _getFallbackStorage2().forEach((value, key) => {
2957
+ if (key.startsWith(_getPrefix2())) {
2958
+ const cleanKey = key.replace(_getPrefix2(), "");
2959
+ try {
2960
+ result[cleanKey] = JSON.parse(value);
2961
+ } catch {
2962
+ result[cleanKey] = value;
2963
+ }
2964
+ }
2965
+ });
2966
+ }
2967
+ } catch (err) {
2968
+ message(`Error listing session items: ${err}`);
2969
+ }
2970
+ return result;
2971
+ }, "value")
2972
+ }
2973
+ }
2974
+ );
2975
+ Object.freeze(session);
2976
+ globalThis[SESSION_INSTANCE_KEY] = session;
2977
+ }
2978
+
2979
+ // functions/cache/index.ts
2980
+ init_esm_shims();
2981
+ var CACHE_INSTANCE_KEY = "__memorio_cache_instance__";
2982
+ var cacheData = {};
2983
+ var cache = globalThis[CACHE_INSTANCE_KEY] ? globalThis[CACHE_INSTANCE_KEY] : new Proxy({}, {
2984
+ get(target, prop) {
2985
+ const key = prop;
2986
+ if (key === "get") return (name) => cacheData[name];
2987
+ if (key === "set") return (name, value) => {
2988
+ cacheData[name] = value;
2989
+ };
2990
+ if (key === "remove") return (name) => {
2991
+ delete cacheData[name];
2992
+ return true;
2993
+ };
2994
+ if (key === "removeAll") return () => {
2995
+ Object.keys(cacheData).forEach((k) => delete cacheData[k]);
2996
+ return true;
2997
+ };
2998
+ if (key === "clear") return () => {
2999
+ Object.keys(cacheData).forEach((k) => delete cacheData[k]);
3000
+ return true;
3001
+ };
3002
+ if (key === "list") return () => ({ ...cacheData });
3003
+ return cacheData[key];
3004
+ },
3005
+ set(target, prop, value) {
3006
+ cacheData[prop] = value;
3007
+ return true;
3008
+ },
3009
+ deleteProperty(target, prop) {
3010
+ delete cacheData[prop];
3011
+ return true;
3012
+ }
3013
+ });
3014
+ if (!globalThis[CACHE_INSTANCE_KEY]) {
3015
+ globalThis[CACHE_INSTANCE_KEY] = cache;
3016
+ if (!Object.isFrozen(cache)) {
3017
+ Object.freeze(cache);
3018
+ }
3019
+ }
3020
+
3021
+ // index.ts
3022
+ init_idb();
3023
+ init_sqlite();
3024
+
3025
+ // functions/observer/index.ts
3026
+ init_esm_shims();
3027
+ init_message();
3028
+ var observerFunction = /* @__PURE__ */ __name((s, cb = null, option = true) => {
3029
+ const resolvePath = /* @__PURE__ */ __name((path3) => {
3030
+ if (typeof path3 === "string") return path3;
3031
+ if (path3 && typeof path3 === "object" && path3.__path) return path3.__path;
3032
+ return null;
3033
+ }, "resolvePath");
3034
+ const path2 = resolvePath(s);
3035
+ if (!s && !cb) {
3036
+ console.error("Observer Error: You need to setup observer correctly, Some parameters are missed!");
3037
+ return;
3038
+ }
3039
+ if (!s && cb) {
3040
+ console.error(`Observer Error: You need to declare what state need to be monitored as string like 'state.test'.`);
3041
+ return;
3042
+ }
3043
+ if (path2) {
3044
+ const t = path2.split(".");
3045
+ if (t[0] !== "state" && t[0] !== "store") {
3046
+ console.error(`Observer Error: You need to declare 'state.' or 'store.'. The '${path2}' string is incorrect!`);
3047
+ return;
3048
+ }
3049
+ }
3050
+ if (s && !cb) {
3051
+ const resolvedPath = resolvePath(s);
3052
+ if (!resolvedPath) return;
3053
+ const obs = globalThis.observer;
3054
+ if (obs?.list?.[resolvedPath]) dispatch.remove(resolvedPath);
3055
+ message_default(`called: ${resolvedPath}`);
3056
+ return;
3057
+ }
3058
+ if (s && cb) {
3059
+ const resolvedPath = resolvePath(s);
3060
+ if (!resolvedPath) return;
3061
+ if (typeof s !== "string" && !(s && typeof s === "object")) {
3062
+ console.error(`Observer Error: name of state need to be a 'string' like 'state.test' or a direct state value`);
3063
+ return;
3064
+ }
3065
+ const callbacks = Array.isArray(cb) ? cb : [cb];
3066
+ const obs = globalThis.observer;
3067
+ if (obs?.list?.[resolvedPath]) dispatch.remove(resolvedPath);
3068
+ const unsubs = [];
3069
+ callbacks.forEach((callback) => {
3070
+ if (typeof callback === "function") {
3071
+ const off = dispatch.listen(resolvedPath, callback, option);
3072
+ if (typeof off === "function") unsubs.push(off);
3073
+ }
3074
+ });
3075
+ if (unsubs.length === 1) return unsubs[0];
3076
+ if (unsubs.length > 1) return () => unsubs.forEach((u) => u());
3077
+ return () => {
3078
+ };
3079
+ }
3080
+ }, "observerFunction");
3081
+ var observer = observerFunction;
3082
+ Object.defineProperties(
3083
+ observer,
3084
+ {
3085
+ /**
3086
+ * See the list of all your observer (eventListener) actually installed.
3087
+ * @returns The list of all installed observers.
3088
+ */
3089
+ list: {
3090
+ get: /* @__PURE__ */ __name(() => globalThis.events, "get")
3091
+ },
3092
+ ///
3093
+ /**
3094
+ * Remove an observer.
3095
+ * @param name The name of the observer to remove.
3096
+ */
3097
+ remove: {
3098
+ value: /* @__PURE__ */ __name((name) => {
3099
+ if (!name) return;
3100
+ dispatch.remove(name);
3101
+ delete globalThis.events[name];
3102
+ return;
3103
+ }, "value")
3104
+ },
3105
+ ///
3106
+ /**
3107
+ * Remove all observers.
3108
+ * @returns void
3109
+ */
3110
+ removeAll: {
3111
+ get: /* @__PURE__ */ __name(() => {
3112
+ const obs = globalThis.observer;
3113
+ const list = obs?.list;
3114
+ if (list) {
3115
+ Object.keys(list).forEach((key) => {
3116
+ obs?.remove?.(key);
3117
+ });
3118
+ }
3119
+ return true;
3120
+ }, "get")
3121
+ },
3122
+ ///
3123
+ /**
3124
+ * Check if an observer exists for the given path.
3125
+ * @param name The state path to check.
3126
+ * @returns true if an observer exists for the path, false otherwise.
3127
+ */
3128
+ has: {
3129
+ value: /* @__PURE__ */ __name((name) => {
3130
+ const obs = globalThis.observer;
3131
+ return !!obs?.list?.[name];
3132
+ }, "value")
3133
+ }
3134
+ }
3135
+ );
3136
+
3137
+ // functions/useObserver/index.ts
3138
+ init_esm_shims();
3139
+ init_message();
3140
+ init_internal();
3141
+ var useObserver = /* @__PURE__ */ __name(((func, deps = []) => {
3142
+ if (!deps || typeof func !== "function") {
3143
+ return () => {
3144
+ };
3145
+ }
3146
+ const handlers = [];
3147
+ const unsubs = [];
3148
+ const depList = Array.isArray(deps) && !deps.__path ? deps : [deps];
3149
+ try {
3150
+ depList.forEach((dep) => {
3151
+ let t = "";
3152
+ if (typeof dep === "function") {
3153
+ const result = propertyName(dep);
3154
+ if (result) t = result;
3155
+ } else if (typeof dep === "object" && dep !== null) {
3156
+ t = dep.__path || (typeof dep.toString === "function" && dep.toString() !== "[object Object]" ? dep.toString() : "");
3157
+ }
3158
+ if (t) {
3159
+ t = t.replace(/^(\(\)\s*=>\s*)/, "").replace(/^globalThis\./, "").replace(/^state\./, "");
3160
+ const path2 = t.startsWith("store.") || t.startsWith("state.") ? t : "state." + t;
3161
+ if (!handlers.includes(path2)) {
3162
+ handlers.push(path2);
3163
+ const off = dispatch.listen(path2, () => func());
3164
+ if (typeof off === "function") unsubs.push({ path: path2, off });
3165
+ }
3166
+ } else {
3167
+ internal_default.clearTrackedPaths();
3168
+ internal_default.tracking = true;
3169
+ try {
3170
+ func();
3171
+ } catch (_) {
3172
+ }
3173
+ internal_default.tracking = false;
3174
+ internal_default.trackedPaths.forEach((path2) => {
3175
+ if (!handlers.includes(path2)) {
3176
+ message_default(`useObserver: [Auto-Discovery] -> "${path2}"`);
3177
+ handlers.push(path2);
3178
+ const off = dispatch.listen(path2, () => func());
3179
+ if (typeof off === "function") unsubs.push({ path: path2, off });
3180
+ }
3181
+ });
3182
+ }
3183
+ });
3184
+ if (handlers.length > 0) {
3185
+ message_default(`useObserver: Monitoring ${handlers.length} paths.`);
3186
+ } else {
3187
+ console.warn(`useObserver: No paths resolved for monitoring. Check your dependencies!`);
3188
+ }
3189
+ return () => {
3190
+ unsubs.forEach(({ path: path2, off }) => {
3191
+ off();
3192
+ message_default(`useObserver: Stopped monitoring "${path2}"`);
3193
+ });
3194
+ };
3195
+ } catch (err) {
3196
+ message_default(`useObserver Error: ${err}`);
3197
+ return () => {
3198
+ };
3199
+ }
3200
+ }), "useObserver");
3201
+
3202
+ // index.ts
3203
+ init_message();
3204
+
3205
+ // functions/logger/index.ts
3206
+ init_esm_shims();
3207
+ init_internal();
3208
+ init_message();
3209
+ 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;
3218
+ }
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();
3247
+ }
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}`);
3258
+ }
3259
+ if (previousValue !== void 0) {
3260
+ message_default(` \u2190 previous:${previousValue}`);
3261
+ }
3262
+ }
3263
+ if (config.customHandler) {
3264
+ config.customHandler(entry);
3265
+ }
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"
3274
+ };
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,
3289
+ cache: 0,
3290
+ idb: 0,
3291
+ set: 0,
3292
+ get: 0,
3293
+ delete: 0,
3294
+ clear: 0
3295
+ };
3296
+ for (const entry of logHistory) {
3297
+ if (entry) {
3298
+ const module = entry.module;
3299
+ const action = entry.action;
3300
+ if (module && typeof stats[module] === "number") stats[module]++;
3301
+ if (action && typeof stats[action] === "number") stats[action]++;
3302
+ }
3303
+ }
3304
+ return stats;
3305
+ }, "getStats");
3306
+ var exportLogs = /* @__PURE__ */ __name(() => {
3307
+ return JSON.stringify(logHistory, null, 2);
3308
+ }, "exportLogs");
3309
+ var logger = {
3310
+ configure,
3311
+ enable,
3312
+ disable,
3313
+ isEnabled,
3314
+ log,
3315
+ getHistory,
3316
+ clearHistory,
3317
+ getStats,
3318
+ exportLogs
3319
+ };
3320
+
3321
+ // core/fractional.ts
3322
+ init_esm_shims();
3323
+ function generateBetween(left, right, minChars = 2) {
3324
+ if (left !== null && right !== null && left >= right) {
3325
+ throw new Error(`left (${left}) must be < right (${right})`);
3326
+ }
3327
+ if (left === null && right === null) {
3328
+ return "a";
3329
+ }
3330
+ if (left === null) {
3331
+ return generateLower(right, minChars);
3332
+ }
3333
+ if (right === null) {
3334
+ return generateUpper(left, minChars);
3335
+ }
3336
+ return generateMiddle(left, right, minChars);
3337
+ }
3338
+ __name(generateBetween, "generateBetween");
3339
+ function generateLower(right, minChars) {
3340
+ const rightDigits = right.split(".");
3341
+ const first = rightDigits[0];
3342
+ const firstChar = first.charCodeAt(0);
3343
+ if (firstChar > "a".charCodeAt(0)) {
3344
+ const prev = String.fromCharCode(firstChar - 1);
3345
+ const rest = first.slice(1);
3346
+ if (rest === "") {
3347
+ return leftPad(prev, minChars);
3348
+ }
3349
+ return prev + rest;
3350
+ }
3351
+ if (first[0] === "a") {
3352
+ let i = 0;
3353
+ while (i < first.length && first[i] === "a") i++;
3354
+ if (i === first.length) {
3355
+ return ".z." + ".z".repeat(Math.floor(minChars / 2) + 1);
3356
+ }
3357
+ const char = first.charCodeAt(i);
3358
+ const next = String.fromCharCode(char - 1);
3359
+ if (next >= "a") {
3360
+ return next + first.slice(i + 1);
3361
+ }
3362
+ return "a" + next + first.slice(i + 1);
3363
+ }
3364
+ return ".z." + ".z".repeat(Math.floor(minChars / 2) + 1);
3365
+ }
3366
+ __name(generateLower, "generateLower");
3367
+ function generateUpper(left, minChars) {
3368
+ const leftDigits = left.split(".");
3369
+ const first = leftDigits[0];
3370
+ const firstChar = first.charCodeAt(0);
3371
+ const nextChar = String.fromCharCode(firstChar + 1);
3372
+ if (nextChar <= "z") {
3373
+ const rest = first.slice(1);
3374
+ if (rest === "") {
3375
+ return rightPad(nextChar, minChars);
3376
+ }
3377
+ return nextChar + rest;
3378
+ }
3379
+ if (first.length > 1) {
3380
+ const lastChar = first[first.length - 1];
3381
+ if (lastChar < "z") {
3382
+ return first.slice(0, -1) + String.fromCharCode(lastChar.charCodeAt(0) + 1);
3383
+ }
3384
+ }
3385
+ const carry = handleCarry(first, 0);
3386
+ if (carry !== null) {
3387
+ return carry + leftPad("a", minChars);
3388
+ }
3389
+ return "b" + leftPad("a", minChars);
3390
+ }
3391
+ __name(generateUpper, "generateUpper");
3392
+ function handleCarry(digits, carryPos) {
3393
+ if (carryPos >= digits.length) return null;
3394
+ const char = digits.charCodeAt(carryPos);
3395
+ if (char < "z".charCodeAt(0)) {
3396
+ return digits.slice(0, carryPos) + String.fromCharCode(char + 1);
3397
+ }
3398
+ return handleCarry(digits, carryPos + 1);
3399
+ }
3400
+ __name(handleCarry, "handleCarry");
3401
+ function generateMiddle(left, right, minChars) {
3402
+ const leftDigits = left.split(".");
3403
+ const rightDigits = right.split(".");
3404
+ const maxLen = Math.max(leftDigits.length, rightDigits.length);
3405
+ const leftParts = padParts(leftDigits, maxLen);
3406
+ const rightParts = padParts(rightDigits, maxLen);
3407
+ let prefix = [];
3408
+ for (let i = 0; i < maxLen; i++) {
3409
+ const l = leftParts[i] || "a";
3410
+ const r = rightParts[i] || "z";
3411
+ if (l === r) {
3412
+ prefix.push(l);
3413
+ } else {
3414
+ const lCode = l.charCodeAt(0);
3415
+ const rCode = r.charCodeAt(0);
3416
+ if (rCode - lCode > 1) {
3417
+ prefix.push(String.fromCharCode(lCode + 1));
3418
+ while (prefix.length < minChars) {
3419
+ prefix.push("a");
3420
+ }
3421
+ return prefix.join(".");
3422
+ }
3423
+ prefix.push(l);
3424
+ prefix.push(generateUpper(l, minChars));
3425
+ return prefix.join(".");
3426
+ }
3427
+ }
3428
+ return generateUpper(left, minChars);
3429
+ }
3430
+ __name(generateMiddle, "generateMiddle");
3431
+ function padParts(parts, maxLen) {
3432
+ while (parts.length < maxLen) parts.push("a");
3433
+ return parts;
3434
+ }
3435
+ __name(padParts, "padParts");
3436
+ function leftPad(key, minChars) {
3437
+ let result = key;
3438
+ while (result.length < minChars) result = "a" + result;
3439
+ return result;
3440
+ }
3441
+ __name(leftPad, "leftPad");
3442
+ function rightPad(key, minChars) {
3443
+ let result = key;
3444
+ while (result.length < minChars) result = result + "a";
3445
+ return result;
3446
+ }
3447
+ __name(rightPad, "rightPad");
3448
+ function firstKey() {
3449
+ return generateBetween(null, null);
3450
+ }
3451
+ __name(firstKey, "firstKey");
3452
+ function after(left) {
3453
+ return generateBetween(left, null);
3454
+ }
3455
+ __name(after, "after");
3456
+ function before(right) {
3457
+ return generateBetween(null, right);
3458
+ }
3459
+ __name(before, "before");
3460
+ function between(left, right) {
3461
+ return generateBetween(left, right);
3462
+ }
3463
+ __name(between, "between");
3464
+ function reorder(items, fromIndex, toIndex) {
3465
+ if (fromIndex === toIndex) return items.map((i) => i.key);
3466
+ const reordered = [...items];
3467
+ 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
+ }
3645
+ }
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] = {};
3654
+ }
3655
+ current = current[part];
3656
+ }
3657
+ current[parts[parts.length - 1]] = value;
3658
+ }
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]];
3673
+ }
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");
3690
+
3691
+ // functions/memory/index.ts
3692
+ init_esm_shims();
3693
+ init_store();
3694
+ init_idb();
3695
+ init_env();
3696
+
3697
+ // functions/memory/journal.ts
3698
+ init_esm_shims();
3699
+ init_env();
3700
+ init_store();
3701
+ var g2 = globalThis;
3702
+ function namespace() {
3703
+ const cfg = g2.memorioSyncConfig;
3704
+ if (cfg && typeof cfg.namespace === "string" && cfg.namespace) return `ns:${cfg.namespace}`;
3705
+ const ctx = g2.memorio ? g2.memorio._currentContext : void 0;
3706
+ const ctxName = typeof ctx === "string" && ctx ? ctx : "";
3707
+ return ctxName ? `ctx:${ctxName}` : "default";
3708
+ }
3709
+ __name(namespace, "namespace");
3710
+ function isSyncEnabled() {
3711
+ return !!g2.memorioSyncConfig;
3712
+ }
3713
+ __name(isSyncEnabled, "isSyncEnabled");
3714
+ var STORE_PREFIX = /* @__PURE__ */ __name((ns) => `memorio:sync:${ns}:`, "STORE_PREFIX");
3715
+ var INDEX_KEY = /* @__PURE__ */ __name((ns) => `${STORE_PREFIX(ns)}index`, "INDEX_KEY");
3716
+ function parseEntry(raw) {
3717
+ try {
3718
+ if (typeof raw === "string") return JSON.parse(raw);
3719
+ return raw;
3720
+ } catch (err) {
3721
+ if (DEV) console.warn("[memorio memory] failed to parse journal entry:", err);
3722
+ return null;
3723
+ }
3724
+ }
3725
+ __name(parseEntry, "parseEntry");
3726
+ var journal = {
3727
+ /** Append (or replace) a journal row for the current namespace. */
3728
+ async append(entry, operation) {
3729
+ const ns = namespace();
3730
+ const row = {
3731
+ ...entry,
3732
+ operation,
3733
+ updatedAt: entry.updatedAt || Date.now(),
3734
+ version: entry.version || 1,
3735
+ sync: "pending",
3736
+ hlc: entry.hlc || hlc.serialize(hlc.tick())
3737
+ };
3738
+ const key = `${STORE_PREFIX(ns)}${row.id}`;
3739
+ store.set(key, row);
3740
+ const idx = store.get(INDEX_KEY(ns)) || [];
3741
+ if (!idx.includes(row.id)) idx.push(row.id);
3742
+ store.set(INDEX_KEY(ns), idx);
3743
+ return row;
3744
+ },
3745
+ /** All pending (not-yet-synced) entries for the current namespace. */
3746
+ async pending() {
3747
+ const ns = namespace();
3748
+ const out = [];
3749
+ const idx = store.get(INDEX_KEY(ns)) || [];
3750
+ for (const id of idx) {
3751
+ const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
3752
+ if (!raw) continue;
3753
+ const e = parseEntry(raw);
3754
+ if (e && e.sync !== "synced") out.push(e);
3755
+ }
3756
+ out.sort((a, b) => {
3757
+ if (a.hlc && b.hlc) {
3758
+ const ha = hlc.parse(a.hlc);
3759
+ const hb = hlc.parse(b.hlc);
3760
+ if (ha && hb) return hlc.compare(ha, hb);
3761
+ }
3762
+ return (a.updatedAt || 0) - (b.updatedAt || 0);
3763
+ });
3764
+ return out;
3765
+ },
3766
+ /**
3767
+ * Mark entries as synced. Returns the number of rows actually advanced to
3768
+ * `synced` (namespace-scoped).
3769
+ */
3770
+ async markSynced(ids) {
3771
+ if (!ids.length) return 0;
3772
+ const ns = namespace();
3773
+ let count = 0;
3774
+ const idx = store.get(INDEX_KEY(ns)) || [];
3775
+ for (const id of idx) {
3776
+ if (!ids.includes(id)) continue;
3777
+ const key = `${STORE_PREFIX(ns)}${id}`;
3778
+ const raw = store.get(key);
3779
+ if (!raw) continue;
3780
+ const e = parseEntry(raw);
3781
+ if (!e || e.sync === "synced") continue;
3782
+ e.sync = "synced";
3783
+ store.set(key, e);
3784
+ count++;
3785
+ }
3786
+ return count;
3787
+ },
3788
+ async get(id) {
3789
+ const ns = namespace();
3790
+ const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
3791
+ return parseEntry(raw ?? "");
3792
+ },
3793
+ /** Remove all journal rows for the current namespace. */
3794
+ async clear() {
3795
+ const ns = namespace();
3796
+ const idx = store.get(INDEX_KEY(ns)) || [];
3797
+ for (const id of idx) store.remove(`${STORE_PREFIX(ns)}${id}`);
3798
+ store.remove(INDEX_KEY(ns));
3799
+ },
3800
+ /**
3801
+ * Reconcile the local journal against the configured provider. Pushes pending
3802
+ * local operations, then optionally pulls newer remote operations and applies
3803
+ * them. No-op (empty ack) when no provider is configured.
3804
+ *
3805
+ * When pulling remote entries, HLC timestamps are used to order operations
3806
+ * causally. Concurrent writes to the same key (HLC tie) are resolved via the
3807
+ * provider's `resolveConflict` method (if provided), otherwise the REMOTE
3808
+ * entry wins by default (logged at warn level in dev). Provide a resolver on
3809
+ * the sync provider to override this behaviour and prevent silent local data
3810
+ * loss.
3811
+ */
3812
+ async replay() {
3813
+ const ack = { synced: [], resolved: [] };
3814
+ if (!isSyncEnabled()) return ack;
3815
+ const transport = g2.memorioSyncConfig || {};
3816
+ const provider = transport.provider;
3817
+ if (!provider || typeof provider.push !== "function") return ack;
3818
+ const pending = await this.pending();
3819
+ if (pending.length) {
3820
+ try {
3821
+ const res = await provider.push(pending);
3822
+ ack.synced = res?.synced || [];
3823
+ ack.conflicts = res?.conflicts;
3824
+ ack.error = res?.error;
3825
+ if (ack.synced.length) await this.markSynced(ack.synced);
3826
+ } catch (err) {
3827
+ ack.error = String(err);
3828
+ }
3829
+ }
3830
+ if (typeof provider.pull === "function") {
3831
+ try {
3832
+ const since = pending.length ? Math.min(...pending.map((p) => p.updatedAt || 0)) : 0;
3833
+ const remote = await provider.pull(since);
3834
+ for (const e of remote || []) {
3835
+ if (e.hlc) {
3836
+ const parsed = hlc.parse(e.hlc);
3837
+ if (parsed) hlc.receive(parsed);
3838
+ }
3839
+ const localEntry = await this.get(e.id);
3840
+ if (localEntry && e.hlc && localEntry.hlc) {
3841
+ const ha = hlc.parse(localEntry.hlc);
3842
+ const hb = hlc.parse(e.hlc);
3843
+ if (ha && hb) {
3844
+ const cmp = hlc.compare(ha, hb);
3845
+ if (cmp === 0) {
3846
+ const hasResolver = typeof provider.resolveConflict === "function";
3847
+ const resolution = hasResolver ? await provider.resolveConflict(localEntry, e) : "remote";
3848
+ if (!hasResolver && DEV) {
3849
+ console.warn(`[memorio memory] replay() conflict for "${e.id}": no resolveConflict handler provided, defaulting to remote-wins`);
3850
+ }
3851
+ ack.resolved?.push({ id: e.id, resolution });
3852
+ if (resolution === "local") continue;
3853
+ } else if (cmp > 0) {
3854
+ continue;
3855
+ }
3856
+ }
3857
+ }
3858
+ await this.append(e, e.operation || "confirm");
3859
+ await this.markSynced([e.id]);
3860
+ }
3861
+ } catch (err) {
3862
+ if (DEV) console.warn("[memorio memory] sync pull failed:", err);
3863
+ }
3864
+ }
3865
+ return ack;
3866
+ },
3867
+ status() {
3868
+ return Promise.resolve("store");
3869
+ }
3870
+ };
3871
+ function configure2(opts) {
3872
+ const prev = g2.memorioSyncConfig || {};
3873
+ g2.memorioSyncConfig = { ...prev, ...opts };
3874
+ return journal;
3875
+ }
3876
+ __name(configure2, "configure");
3877
+ if (typeof g2.addEventListener === "function") {
3878
+ let armed = false;
3879
+ g2.addEventListener("focus", () => {
3880
+ if (armed || !isSyncEnabled()) return;
3881
+ armed = true;
3882
+ void journal.replay().finally(() => {
3883
+ armed = false;
3884
+ });
3885
+ });
3886
+ }
3887
+ var journal_default = journal;
3888
+
3889
+ // functions/memory/index.ts
3890
+ var MEMORY_INDEX_KEY = "__memorio_memory_index__";
3891
+ var SUPERSEDED_PREFIX = "__memorio_superseded__";
3892
+ function isSyncEnabled2() {
3893
+ return !!globalThis.memorioSyncConfig;
3894
+ }
3895
+ __name(isSyncEnabled2, "isSyncEnabled");
3896
+ async function recordJournal(entry, operation) {
3897
+ if (!isSyncEnabled2()) return;
3898
+ if (entry.scope === "hot") return;
3899
+ try {
3900
+ await journal_default.append(entry, operation);
3901
+ } catch (err) {
3902
+ if (DEV) console.warn("[memorio memory] journal append failed:", err);
3903
+ }
3904
+ }
3905
+ __name(recordJournal, "recordJournal");
3906
+ function memoryEntryKey(id) {
3907
+ return id.startsWith(SUPERSEDED_PREFIX) ? id : `${SUPERSEDED_PREFIX}${id}`;
3908
+ }
3909
+ __name(memoryEntryKey, "memoryEntryKey");
3910
+ function normalizeTags(tags) {
3911
+ if (!tags) return [];
3912
+ return Array.isArray(tags) ? tags : [tags];
3913
+ }
3914
+ __name(normalizeTags, "normalizeTags");
3915
+ function resolveScope(value, opts) {
3916
+ if (opts.scope) return opts.scope;
3917
+ const size = JSON.stringify(value).length;
3918
+ if (size > 1e6) return "durable";
3919
+ if (size > 1e5) return "local";
3920
+ return "local";
3921
+ }
3922
+ __name(resolveScope, "resolveScope");
3923
+ function now() {
3924
+ return Date.now();
3925
+ }
3926
+ __name(now, "now");
3927
+ function isExpired(entry) {
3928
+ if (entry.ttl === null || entry.ttl === void 0) return false;
3929
+ return now() - entry.createdAt > entry.ttl;
3930
+ }
3931
+ __name(isExpired, "isExpired");
3932
+ function matchesFilters(entry, opts) {
3933
+ if (entry.status === "obsolete") return opts.includeObsolete ?? false;
3934
+ if (entry.status === "superseded") return opts.includeObsolete ?? false;
3935
+ if (isExpired(entry)) {
3936
+ return opts.includeObsolete ?? false;
3937
+ }
3938
+ if (opts.type) {
3939
+ const types = Array.isArray(opts.type) ? opts.type : [opts.type];
3940
+ if (!types.includes(entry.type)) return false;
3941
+ }
3942
+ if (opts.minConfidence !== void 0 && entry.confidence < opts.minConfidence) return false;
3943
+ return true;
3944
+ }
3945
+ __name(matchesFilters, "matchesFilters");
3946
+ function matchesContextFilters(entry, opts) {
3947
+ if (entry.status !== "active") return false;
3948
+ if (isExpired(entry)) return false;
3949
+ if (opts.tags) {
3950
+ const tags = Array.isArray(opts.tags) ? opts.tags : [opts.tags];
3951
+ const hasMatch = tags.some((t) => entry.tags.includes(t));
3952
+ if (!hasMatch) return false;
3953
+ }
3954
+ if (opts.types) {
3955
+ const types = Array.isArray(opts.types) ? opts.types : [opts.types];
3956
+ if (!types.includes(entry.type)) return false;
3957
+ }
3958
+ if (opts.minConfidence !== void 0 && entry.confidence < opts.minConfidence) return false;
3959
+ if (opts.scopes && !opts.scopes.includes(entry.scope)) return false;
3960
+ return true;
3961
+ }
3962
+ __name(matchesContextFilters, "matchesContextFilters");
3963
+ function computeRelevance(entry) {
3964
+ const ageHours = (now() - entry.createdAt) / (1e3 * 3600);
3965
+ const recencyScore = Math.max(0.1, 1 / (1 + ageHours * 0.5));
3966
+ const confidenceScore = entry.confidence;
3967
+ const accessScore = 1 + entry.tags.length * 0.1;
3968
+ const typeBoost = {
3969
+ decision: 1.5,
3970
+ context: 1.3,
3971
+ preference: 1.2,
3972
+ task: 1,
3973
+ fact: 0.8
3974
+ };
3975
+ const scopeBoost = {
3976
+ hot: 1.5,
3977
+ session: 1.2,
3978
+ local: 1,
3979
+ durable: 0.8
3980
+ };
3981
+ return recencyScore * confidenceScore * accessScore * typeBoost[entry.type] * scopeBoost[entry.scope];
3982
+ }
3983
+ __name(computeRelevance, "computeRelevance");
3984
+ function getNestedPath(obj, path2) {
3985
+ if (!path2 || typeof path2 !== "string") return void 0;
3986
+ const parts = path2.replace(/^state\./, "").split(".");
3987
+ let current = obj;
3988
+ for (const part of parts) {
3989
+ if (current === null || current === void 0) return void 0;
3990
+ current = current[part];
3991
+ }
3992
+ return current;
3993
+ }
3994
+ __name(getNestedPath, "getNestedPath");
3995
+ function setNestedPath(obj, path2, value) {
3996
+ if (!path2 || typeof path2 !== "string") return;
3997
+ const parts = path2.replace(/^state\./, "").split(".");
3998
+ let current = obj;
3999
+ for (let i = 0; i < parts.length - 1; i++) {
4000
+ const part = parts[i];
4001
+ if (current[part] === void 0 || current[part] === null) {
4002
+ current[part] = {};
4003
+ }
4004
+ current = current[part];
4005
+ }
4006
+ current[parts[parts.length - 1]] = value;
4007
+ }
4008
+ __name(setNestedPath, "setNestedPath");
4009
+ function deleteNestedPath(obj, path2) {
4010
+ if (!path2 || typeof path2 !== "string") return;
4011
+ const parts = path2.replace(/^state\./, "").split(".");
4012
+ let current = obj;
4013
+ for (let i = 0; i < parts.length - 1; i++) {
4014
+ const part = parts[i];
4015
+ if (current[part] === void 0 || current[part] === null) return;
4016
+ current = current[part];
4017
+ }
4018
+ delete current[parts[parts.length - 1]];
4019
+ }
4020
+ __name(deleteNestedPath, "deleteNestedPath");
4021
+ async function saveToScope(entry) {
4022
+ const storageKey = entry.status === "superseded" ? memoryEntryKey(entry.id || entry.key) : entry.key;
4023
+ const serialized = JSON.stringify(entry);
4024
+ switch (entry.scope) {
4025
+ case "hot":
4026
+ setNestedPath(state2, storageKey, entry.value);
4027
+ break;
4028
+ case "session":
4029
+ session.set(storageKey, serialized);
4030
+ break;
4031
+ case "local":
4032
+ store.set(storageKey, serialized);
4033
+ break;
4034
+ case "durable":
4035
+ await idb.set("memories", storageKey, serialized);
4036
+ break;
4037
+ }
4038
+ await updateIndex(entry.id || entry.key, entry.scope, entry.status === "superseded");
4039
+ }
4040
+ __name(saveToScope, "saveToScope");
4041
+ async function loadFromScope(id, scope, isSuperseded = false) {
4042
+ const storageKey = isSuperseded ? memoryEntryKey(id) : id;
4043
+ let raw;
4044
+ switch (scope) {
4045
+ case "hot": {
4046
+ const val = getNestedPath(state2, storageKey);
4047
+ if (val === void 0) return null;
4048
+ return reconstructEntry(id, val, scope);
4049
+ }
4050
+ case "session":
4051
+ raw = session.get(storageKey);
4052
+ break;
4053
+ case "local":
4054
+ raw = store.get(storageKey);
4055
+ break;
4056
+ case "durable":
4057
+ raw = await idb.get("memories", storageKey);
4058
+ break;
4059
+ }
4060
+ if (!raw) return null;
4061
+ try {
4062
+ const entry = JSON.parse(raw);
4063
+ entry.id = entry.id || id;
4064
+ return entry;
4065
+ } catch (err) {
4066
+ if (DEV) console.warn("[memorio memory] failed to parse memory entry:", err);
4067
+ return null;
4068
+ }
4069
+ }
4070
+ __name(loadFromScope, "loadFromScope");
4071
+ function reconstructEntry(key, value, scope) {
4072
+ return {
4073
+ id: key,
4074
+ key,
4075
+ value,
4076
+ type: "fact",
4077
+ confidence: 1,
4078
+ scope,
4079
+ ttl: null,
4080
+ tags: [],
4081
+ status: "active",
4082
+ createdAt: now(),
4083
+ lastConfirmedAt: now(),
4084
+ supersededId: null
4085
+ };
4086
+ }
4087
+ __name(reconstructEntry, "reconstructEntry");
4088
+ async function removeFromScope(id, scope, isSuperseded = false) {
4089
+ const storageKey = isSuperseded ? memoryEntryKey(id) : id;
4090
+ switch (scope) {
4091
+ case "hot":
4092
+ setNestedPath(state2, storageKey, void 0);
4093
+ break;
4094
+ case "session":
4095
+ session.remove(storageKey);
4096
+ break;
4097
+ case "local":
4098
+ store.remove(storageKey);
4099
+ break;
4100
+ case "durable":
4101
+ await idb.deleteKey("memories", storageKey);
4102
+ break;
4103
+ }
4104
+ await removeFromIndex(id, isSuperseded);
4105
+ }
4106
+ __name(removeFromScope, "removeFromScope");
4107
+ async function getAllIndexes() {
4108
+ try {
4109
+ const raw = store.get(MEMORY_INDEX_KEY);
4110
+ if (!raw) return {};
4111
+ return JSON.parse(raw);
4112
+ } catch (err) {
4113
+ if (DEV) console.warn("[memorio memory] failed to parse memory index:", err);
4114
+ return {};
4115
+ }
4116
+ }
4117
+ __name(getAllIndexes, "getAllIndexes");
4118
+ async function updateIndex(id, scope, isSuperseded = false) {
4119
+ const index = await getAllIndexes();
4120
+ index[id] = { scope, superseded: isSuperseded };
4121
+ store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
4122
+ }
4123
+ __name(updateIndex, "updateIndex");
4124
+ async function removeFromIndex(id, isSuperseded = false) {
4125
+ const index = await getAllIndexes();
4126
+ const entry = index[id];
4127
+ if (entry) {
4128
+ if (isSuperseded && entry.superseded) {
4129
+ delete index[id];
4130
+ } else if (!isSuperseded && !entry.superseded) {
4131
+ delete index[id];
4132
+ }
4133
+ }
4134
+ store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
4135
+ }
4136
+ __name(removeFromIndex, "removeFromIndex");
4137
+ async function loadAll() {
4138
+ const index = await getAllIndexes();
4139
+ const entries = [];
4140
+ for (const [id, info] of Object.entries(index)) {
4141
+ const entry = await loadFromScope(id, info.scope, info.superseded);
4142
+ if (entry) {
4143
+ entry.id = entry.id || id;
4144
+ entry.supersededId = entry.supersededId ?? null;
4145
+ entries.push(entry);
4146
+ }
4147
+ }
4148
+ return entries;
4149
+ }
4150
+ __name(loadAll, "loadAll");
4151
+ var memory = {
4152
+ async remember(key, value, opts = {}) {
4153
+ const existing = await this._getEntry(key);
4154
+ if (existing && existing.status === "active") {
4155
+ const supersededId = `${existing.id}__v${Date.now()}`;
4156
+ const superseded = {
4157
+ ...existing,
4158
+ id: supersededId,
4159
+ key: existing.key,
4160
+ status: "superseded",
4161
+ supersededId: null,
4162
+ lastConfirmedAt: now()
4163
+ };
4164
+ await saveToScope(superseded);
4165
+ await recordJournal(superseded, "supersede");
4166
+ }
4167
+ const scope = resolveScope(value, opts);
4168
+ const tags = normalizeTags(opts.tags);
4169
+ const entry = {
4170
+ id: opts.id || key,
4171
+ key,
4172
+ value,
4173
+ type: opts.type || "fact",
4174
+ confidence: opts.confidence ?? 1,
4175
+ scope,
4176
+ ttl: opts.ttl ?? null,
4177
+ tags,
4178
+ source: opts.source,
4179
+ status: "active",
4180
+ createdAt: now(),
4181
+ lastConfirmedAt: now(),
4182
+ updatedAt: now(),
4183
+ version: existing ? existing.version ? existing.version + 1 : 1 : 1,
4184
+ sync: isSyncEnabled2() ? "pending" : void 0,
4185
+ supersededId: existing ? existing.id : null,
4186
+ hlc: hlc.serialize(hlc.tick())
4187
+ };
4188
+ await saveToScope(entry);
4189
+ await recordJournal(entry, "remember");
4190
+ dispatch.set("memorio:memory:remembered", { key, scope, entryId: entry.id });
4191
+ },
4192
+ async recall(query, opts = {}) {
4193
+ const entry = await this._getEntry(query);
4194
+ if (!entry) return null;
4195
+ if (!matchesFilters(entry, opts)) return null;
4196
+ entry.lastConfirmedAt = now();
4197
+ await saveToScope(entry);
4198
+ dispatch.set("memorio:memory:recalled", { key: query });
4199
+ return entry.value;
4200
+ },
4201
+ async context(opts = {}) {
4202
+ const entries = await loadAll();
4203
+ const filtered = entries.filter((e) => matchesContextFilters(e, opts));
4204
+ const ranked = filtered.map((entry) => ({
4205
+ entry,
4206
+ score: computeRelevance(entry)
4207
+ })).sort((a, b) => b.score - a.score).slice(0, opts.maxEntries ?? 25);
4208
+ return ranked.map(({ entry }) => ({
4209
+ key: entry.key,
4210
+ value: entry.value,
4211
+ type: entry.type,
4212
+ confidence: entry.confidence,
4213
+ scope: entry.scope,
4214
+ tags: entry.tags,
4215
+ age: now() - entry.createdAt,
4216
+ accessCount: entry.tags.length + 1,
4217
+ lastAccessedAt: entry.lastConfirmedAt
4218
+ }));
4219
+ },
4220
+ async forget(key) {
4221
+ const entry = await this._getEntry(key);
4222
+ if (!entry) {
4223
+ const tombstone2 = {
4224
+ id: key,
4225
+ key,
4226
+ value: null,
4227
+ type: "fact",
4228
+ confidence: 1,
4229
+ scope: "local",
4230
+ ttl: null,
4231
+ tags: [],
4232
+ status: "obsolete",
4233
+ operation: "delete",
4234
+ createdAt: now(),
4235
+ lastConfirmedAt: now(),
4236
+ updatedAt: now(),
4237
+ version: 1,
4238
+ sync: isSyncEnabled2() ? "pending" : void 0,
4239
+ hlc: hlc.serialize(hlc.tick())
4240
+ };
4241
+ await recordJournal(tombstone2, "delete");
4242
+ return;
4243
+ }
4244
+ await removeFromScope(entry.id || key, entry.scope, entry.status === "superseded");
4245
+ const tombstone = {
4246
+ ...entry,
4247
+ value: null,
4248
+ status: "obsolete",
4249
+ operation: "delete",
4250
+ updatedAt: now(),
4251
+ version: (entry.version ? entry.version : 0) + 1,
4252
+ sync: isSyncEnabled2() ? "pending" : void 0,
4253
+ hlc: hlc.serialize(hlc.tick())
4254
+ };
4255
+ await recordJournal(tombstone, "delete");
4256
+ dispatch.set("memorio:memory:forgotten", { key });
4257
+ },
4258
+ async update(key, value, opts = {}) {
4259
+ const existing = await this._getEntry(key);
4260
+ if (!existing) {
4261
+ await this.remember(key, value, opts);
4262
+ return;
4263
+ }
4264
+ const supersededId = `${existing.id}__v${now()}`;
4265
+ const superseded = {
4266
+ ...existing,
4267
+ id: supersededId,
4268
+ key: existing.key,
4269
+ status: "superseded",
4270
+ supersededId: null,
4271
+ lastConfirmedAt: now()
4272
+ };
4273
+ await saveToScope(superseded);
4274
+ await recordJournal(superseded, "supersede");
4275
+ const updated = {
4276
+ ...existing,
4277
+ value,
4278
+ lastConfirmedAt: now(),
4279
+ updatedAt: now(),
4280
+ version: (existing.version ? existing.version : 0) + 1,
4281
+ sync: isSyncEnabled2() ? "pending" : void 0,
4282
+ hlc: hlc.serialize(hlc.tick()),
4283
+ ...opts.scope ? { scope: opts.scope } : {},
4284
+ ...opts.ttl !== void 0 ? { ttl: opts.ttl } : {},
4285
+ ...opts.type ? { type: opts.type } : {},
4286
+ ...opts.confidence !== void 0 ? { confidence: opts.confidence } : {},
4287
+ ...opts.tags !== void 0 ? { tags: normalizeTags(opts.tags) } : {},
4288
+ ...opts.source ? { source: opts.source } : {}
4289
+ };
4290
+ await saveToScope(updated);
4291
+ await recordJournal(updated, "update");
4292
+ dispatch.set("memorio:memory:updated", { key, entryId: updated.id });
4293
+ },
4294
+ async stats() {
4295
+ const entries = await loadAll();
4296
+ const byScope = { hot: 0, session: 0, local: 0, durable: 0 };
4297
+ const byType = {};
4298
+ let expired = 0;
4299
+ for (const entry of entries) {
4300
+ byScope[entry.scope] = (byScope[entry.scope] || 0) + 1;
4301
+ if (isExpired(entry)) expired++;
4302
+ byType[entry.type] = (byType[entry.type] || 0) + 1;
4303
+ }
4304
+ return { total: entries.length, byScope, byType, expired };
4305
+ },
4306
+ async forgetExpired() {
4307
+ const entries = await loadAll();
4308
+ let count = 0;
4309
+ for (const entry of entries) {
4310
+ if (isExpired(entry) && entry.status === "active") {
4311
+ entry.status = "obsolete";
4312
+ entry.updatedAt = now();
4313
+ entry.operation = "expire";
4314
+ await saveToScope(entry);
4315
+ await recordJournal(entry, "expire");
4316
+ count++;
4317
+ }
4318
+ }
4319
+ return count;
4320
+ },
4321
+ async clear() {
4322
+ const index = await getAllIndexes();
4323
+ for (const [id, info] of Object.entries(index)) {
4324
+ await removeFromScope(id, info.scope, info.superseded);
4325
+ }
4326
+ store.remove(MEMORY_INDEX_KEY);
4327
+ },
4328
+ async _getEntry(key) {
4329
+ const index = await getAllIndexes();
4330
+ const info = index[key];
4331
+ if (!info) {
4332
+ const val = getNestedPath(state2, key);
4333
+ if (val !== void 0) return reconstructEntry(key, val, "hot");
4334
+ return null;
4335
+ }
4336
+ return loadFromScope(key, info.scope, info.superseded);
4337
+ },
4338
+ async _loadAll() {
4339
+ return loadAll();
4340
+ },
4341
+ async _save(entry) {
4342
+ await saveToScope(entry);
4343
+ },
4344
+ /** Apply a field-level path patch to an existing memory entry. */
4345
+ async patch(key, patches) {
4346
+ const entry = await this._getEntry(key);
4347
+ if (!entry) return;
4348
+ let patched = false;
4349
+ for (const p of patches) {
4350
+ if (p.op === "set") {
4351
+ setNestedPath({ [entry.key]: entry.value }, p.path.replace(/^[^.]+\./, ""), p.value);
4352
+ patched = true;
4353
+ } else if (p.op === "delete") {
4354
+ deleteNestedPath({ [entry.key]: entry.value }, p.path.replace(/^[^.]+\./, ""));
4355
+ patched = true;
4356
+ }
4357
+ }
4358
+ if (!patched) return;
4359
+ const updated = {
4360
+ ...entry,
4361
+ updatedAt: now(),
4362
+ lastConfirmedAt: now(),
4363
+ version: (entry.version ? entry.version : 0) + 1,
4364
+ sync: isSyncEnabled2() ? "pending" : void 0,
4365
+ hlc: hlc.serialize(hlc.tick()),
4366
+ patches,
4367
+ path: patches[0]?.path
4368
+ };
4369
+ await saveToScope(updated);
4370
+ await recordJournal(updated, "patch");
4371
+ dispatch.set("memorio:memory:patched", { key, patches });
4372
+ },
4373
+ /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
4374
+ journal: journal_default,
4375
+ /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
4376
+ configure(opts) {
4377
+ configure2(opts);
4378
+ return this;
4379
+ }
4380
+ };
4381
+
4382
+ // core/global.ts
4383
+ if (!("memorio" in globalThis)) {
4384
+ Object.defineProperty(
4385
+ globalThis,
4386
+ "memorio",
4387
+ {
4388
+ value: {
4389
+ setProps: /* @__PURE__ */ __name(() => {
4390
+ }, "setProps"),
4391
+ obj: {},
4392
+ array: [],
4393
+ dispatch,
4394
+ message,
4395
+ setDescription: /* @__PURE__ */ __name(() => {
4396
+ }, "setDescription")
4397
+ },
4398
+ writable: false,
4399
+ configurable: true,
4400
+ enumerable: false
4401
+ }
4402
+ );
4403
+ if (!("events" in globalThis)) {
4404
+ Object.defineProperty(
4405
+ globalThis,
4406
+ "events",
4407
+ {
4408
+ value: {},
4409
+ writable: true,
4410
+ enumerable: false,
4411
+ configurable: true
4412
+ }
4413
+ );
4414
+ }
4415
+ if (typeof globalThis.addEventListener !== "function") {
4416
+ const listeners = {};
4417
+ globalThis.addEventListener = (name, cb) => {
4418
+ (listeners[name] = listeners[name] ?? []).push(cb);
4419
+ };
4420
+ globalThis.removeEventListener = (name, cb) => {
4421
+ const arr = listeners[name];
4422
+ if (arr) {
4423
+ const idx = arr.indexOf(cb);
4424
+ if (idx > -1) arr.splice(idx, 1);
4425
+ }
4426
+ };
4427
+ globalThis.dispatchEvent = (e) => {
4428
+ const type = (e && typeof e === "object" ? e.type : null) || String(e);
4429
+ const arr = listeners[type];
4430
+ if (arr) {
4431
+ arr.slice().forEach((cb) => cb(e));
4432
+ }
4433
+ };
4434
+ }
4435
+ if (typeof globalThis.addEventListener === "function") {
4436
+ dispatch.listen("memorio:memory:cleanup", async () => memory.forgetExpired?.());
4437
+ }
4438
+ Object.defineProperty(
4439
+ memorio,
4440
+ "version",
4441
+ {
4442
+ writable: false,
4443
+ enumerable: false,
4444
+ value: package_default.version
4445
+ }
4446
+ );
4447
+ memorio.memory = memory;
4448
+ initializePlatform();
4449
+ memorio.isBrowser = isBrowser;
4450
+ memorio.isNode = isNode;
4451
+ memorio.isDeno = isDeno;
4452
+ memorio.isEdge = isEdge;
4453
+ memorio.getCapabilities = getCapabilities;
4454
+ memorio.createContext = createContext;
4455
+ memorio.listContexts = listContexts;
4456
+ memorio.deleteContext = deleteContext;
4457
+ memorio.isolate = (name) => createContext(name);
4458
+ Object.defineProperty(memorio, "setContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name((id) => setCurrentContext(id), "value") });
4459
+ Object.defineProperty(memorio, "getContext", { writable: false, enumerable: false, value: /* @__PURE__ */ __name(() => internal_default.currentContext, "value") });
4460
+ memorio.registerSchema = schema.register;
4461
+ memorio.validate = schema.validate;
4462
+ memorio.unregisterSchema = schema.unregister;
4463
+ memorio.listSchemas = schema.list;
4464
+ memorio.typed = typed;
4465
+ memorio.snapshot = snapshot;
4466
+ memorio.diff = diff;
4467
+ memorio.undo = undo;
4468
+ memorio.redo = redo;
4469
+ memorio.canUndo = canUndo;
4470
+ memorio.canRedo = canRedo;
4471
+ memorio.rollback = rollback;
4472
+ memorio.trace = trace;
4473
+ memorio.enableHistory = enableHistory;
4474
+ memorio.clearHistory = clearHistory2;
4475
+ memorio.clearRedo = clearRedo;
4476
+ memorio.mutate = mutate;
4477
+ memorio.createMutation = createMutation;
4478
+ memorio.recordMutation = recordMutation;
4479
+ memorio.toPatch = toPatch;
4480
+ memorio.transaction = beginTransaction;
4481
+ memorio.commitTransaction = commitTransaction;
4482
+ memorio.abortTransaction = abortTransaction;
4483
+ memorio.currentTransaction = currentTransaction;
4484
+ Object.defineProperty(memorio, "dispatch", { value: dispatch, writable: true, enumerable: false, configurable: true });
4485
+ memorio.env = {
4486
+ isDev: DEV,
4487
+ isProd: PROD
4488
+ };
4489
+ memorio.global = function() {
4490
+ const globalDefinitions = {
4491
+ state: state2,
4492
+ store,
4493
+ session,
4494
+ cache,
4495
+ idb,
4496
+ sqlite,
4497
+ observer,
4498
+ useObserver
4499
+ };
4500
+ for (const key of Object.keys(globalDefinitions)) {
4501
+ if (!(key in globalThis)) {
4502
+ Object.defineProperty(globalThis, key, {
4503
+ value: globalDefinitions[key],
4504
+ writable: true,
4505
+ configurable: true,
4506
+ enumerable: false
4507
+ });
4508
+ }
4509
+ }
4510
+ if (typeof globalThis.useObserver === "function") {
4511
+ Object.freeze(globalThis.useObserver);
4512
+ }
4513
+ };
4514
+ }
4515
+
4516
+ // index.ts
4517
+ var transaction = beginTransaction;
4518
+ var devtools = void 0;
4519
+ var memorio2 = globalThis.memorio;
4520
+ var events = globalThis.events;
4521
+ var isolate = /* @__PURE__ */ __name((name) => createContext(name), "isolate");
4522
+ var help = globalThis.memorio?.help;
4523
+ var setContext = /* @__PURE__ */ __name((id) => internal_default.currentContext = id, "setContext");
4524
+ var getContext = /* @__PURE__ */ __name(() => internal_default.currentContext, "getContext");
4525
+ var index_default = memorio2;
4526
+
4527
+ // global.ts
4528
+ memorio2.global();
4529
+
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 };
4531
+ //# sourceMappingURL=global.js.map
4532
+ //# sourceMappingURL=global.js.map