memorio 5.1.2 → 5.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1095,6 +1095,123 @@ var init_store = __esm({
1095
1095
  }
1096
1096
  });
1097
1097
 
1098
+ // core/hlc.ts
1099
+ function getNodeId() {
1100
+ if (typeof globalThis === "undefined") return "node";
1101
+ try {
1102
+ if (typeof sessionStorage !== "undefined" && sessionStorage) {
1103
+ let id = sessionStorage.getItem(NODE_ID_KEY);
1104
+ if (!id) {
1105
+ id = generateNodeId();
1106
+ sessionStorage.setItem(NODE_ID_KEY, id);
1107
+ }
1108
+ return id;
1109
+ }
1110
+ } catch {
1111
+ }
1112
+ if (!globalThis.__memorioHlcNodeId) {
1113
+ globalThis.__memorioHlcNodeId = generateNodeId();
1114
+ }
1115
+ return globalThis.__memorioHlcNodeId;
1116
+ }
1117
+ function generateNodeId() {
1118
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1119
+ return crypto.randomUUID().slice(0, 8);
1120
+ }
1121
+ return Math.random().toString(36).slice(2, 10);
1122
+ }
1123
+ function tick(_incoming) {
1124
+ const now2 = Date.now();
1125
+ const base = local.physical;
1126
+ let physical;
1127
+ let logical;
1128
+ if (now2 > base) {
1129
+ physical = now2;
1130
+ logical = 0;
1131
+ } else if (now2 < base) {
1132
+ physical = base;
1133
+ logical = local.logical + 1;
1134
+ } else {
1135
+ physical = base;
1136
+ logical = local.logical + 1;
1137
+ }
1138
+ local.physical = physical;
1139
+ local.logical = logical;
1140
+ return { physical, logical, node: local.node };
1141
+ }
1142
+ function receive(remote) {
1143
+ const now2 = Date.now();
1144
+ if (remote.physical > local.physical) {
1145
+ local.physical = remote.physical > now2 ? remote.physical : now2;
1146
+ local.logical = 1;
1147
+ } else if (remote.physical === local.physical) {
1148
+ local.logical = Math.max(local.logical, remote.logical) + 1;
1149
+ }
1150
+ local.node = getNodeId();
1151
+ return { ...local };
1152
+ }
1153
+ function compare(a, b) {
1154
+ if (a.physical !== b.physical) {
1155
+ return a.physical < b.physical ? -1 : 1;
1156
+ }
1157
+ if (a.logical !== b.logical) {
1158
+ return a.logical < b.logical ? -1 : 1;
1159
+ }
1160
+ if (a.node !== b.node) {
1161
+ return a.node < b.node ? -1 : 1;
1162
+ }
1163
+ return 0;
1164
+ }
1165
+ function happenedBefore(a, b) {
1166
+ return compare(a, b) < 0;
1167
+ }
1168
+ function serialize(hlc2) {
1169
+ return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
1170
+ }
1171
+ function parse(serialized) {
1172
+ if (!serialized.startsWith("hlc:")) return null;
1173
+ const parts = serialized.split(":");
1174
+ if (parts.length !== 4) return null;
1175
+ const physical = parseInt(parts[1], 10);
1176
+ const logical = parseInt(parts[2], 10);
1177
+ const node = parts[3];
1178
+ if (isNaN(physical) || isNaN(logical)) return null;
1179
+ return { physical, logical, node };
1180
+ }
1181
+ var NODE_ID_KEY, HLC_KEY, local; exports.hlc = void 0;
1182
+ var init_hlc = __esm({
1183
+ "core/hlc.ts"() {
1184
+ init_cjs_shims();
1185
+ NODE_ID_KEY = "__memorio_hlc_node";
1186
+ __name(getNodeId, "getNodeId");
1187
+ __name(generateNodeId, "generateNodeId");
1188
+ HLC_KEY = "__memorio_hlc_local";
1189
+ local = globalThis[HLC_KEY] || {
1190
+ physical: 0,
1191
+ logical: 0,
1192
+ node: getNodeId()
1193
+ };
1194
+ if (!globalThis[HLC_KEY]) {
1195
+ globalThis[HLC_KEY] = local;
1196
+ }
1197
+ __name(tick, "tick");
1198
+ __name(receive, "receive");
1199
+ __name(compare, "compare");
1200
+ __name(happenedBefore, "happenedBefore");
1201
+ __name(serialize, "serialize");
1202
+ __name(parse, "parse");
1203
+ exports.hlc = {
1204
+ tick,
1205
+ receive,
1206
+ compare,
1207
+ happenedBefore,
1208
+ serialize,
1209
+ parse,
1210
+ getNodeId
1211
+ };
1212
+ }
1213
+ });
1214
+
1098
1215
  // functions/idb/tools/db.create.ts
1099
1216
  var db_create_exports = {};
1100
1217
  var init_db_create = __esm({
@@ -1733,13 +1850,41 @@ var init_db_support2 = __esm({
1733
1850
  });
1734
1851
 
1735
1852
  // functions/sqlite/tools/persist.ts
1853
+ var persist_exports = {};
1854
+ __export(persist_exports, {
1855
+ CHECKPOINT_INTERVAL: () => CHECKPOINT_INTERVAL,
1856
+ DEBOUNCE_MS: () => DEBOUNCE_MS,
1857
+ _attachJournal: () => _attachJournal,
1858
+ _checkpoint: () => _checkpoint,
1859
+ _clearJournal: () => _clearJournal,
1860
+ _journalAppend: () => _journalAppend,
1861
+ _journalCount: () => _journalCount,
1862
+ _journalEntries: () => _journalEntries,
1863
+ _journalReplay: () => _journalReplay,
1864
+ _loadCheckpoint: () => _loadCheckpoint,
1865
+ _removeCheckpoint: () => _removeCheckpoint,
1866
+ _saveCheckpoint: () => _saveCheckpoint,
1867
+ _scheduleCheckpoint: () => _scheduleCheckpoint
1868
+ });
1736
1869
  function _ns() {
1737
1870
  const cfg = g.sqliteConfig || {};
1738
1871
  return cfg.namespace ? `ns:${cfg.namespace}` : "default";
1739
1872
  }
1740
- function _key(name) {
1873
+ function _dbKey(name) {
1741
1874
  return `memorio:sqlite:db:${_ns()}:${name}`;
1742
1875
  }
1876
+ function _journalKey(name, seq) {
1877
+ return `memorio:sqlite:journal:${_ns()}:${name}:${seq}`;
1878
+ }
1879
+ function _journalIndexKey(name) {
1880
+ return `memorio:sqlite:journal:${_ns()}:${name}:index`;
1881
+ }
1882
+ function _journalSeqKey(name) {
1883
+ return `memorio:sqlite:journal:${_ns()}:${name}:seq`;
1884
+ }
1885
+ function _opCounterKey(name) {
1886
+ return `memorio:sqlite:journal:${_ns()}:${name}:ops`;
1887
+ }
1743
1888
  function _b64encode2(buf) {
1744
1889
  const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
1745
1890
  let binary = "";
@@ -1752,35 +1897,81 @@ function _b64decode2(b64) {
1752
1897
  if (typeof Buffer !== "undefined") {
1753
1898
  return new Uint8Array(Buffer.from(b64, "base64"));
1754
1899
  }
1755
- if (typeof atob !== "function") {
1756
- throw new Error("memorio sqlite: no base64 decoder available");
1900
+ if (typeof atob === "function") {
1901
+ const binary = atob(b64);
1902
+ const len = binary.length;
1903
+ const out = new Uint8Array(len);
1904
+ for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
1905
+ return out;
1757
1906
  }
1758
- const binary = atob(b64);
1759
- const len = binary.length;
1760
- const out = new Uint8Array(len);
1761
- for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
1762
- return out;
1907
+ throw new Error("memorio sqlite: no base64 decoder available");
1763
1908
  }
1764
- function saveSnapshot(name) {
1765
- return new Promise((resolve) => {
1766
- const db = g.__sqliteDbs && g.__sqliteDbs[name];
1767
- if (!db || typeof db.export !== "function") {
1768
- resolve(false);
1769
- return;
1770
- }
1771
- try {
1772
- const blob = db.export();
1773
- exports.store.set(_key(name), _b64encode2(blob));
1774
- message_default(`Memorio SQLite: persisted '${name}' to store`);
1775
- resolve(true);
1776
- } catch (err) {
1777
- console.warn("Memorio SQLite: persist snapshot failed", err);
1778
- resolve(false);
1779
- }
1909
+ function _nextSeq(name) {
1910
+ const seq = (exports.store.get(_journalSeqKey(name)) || 0) + 1;
1911
+ exports.store.set(_journalSeqKey(name), seq);
1912
+ return seq;
1913
+ }
1914
+ function _journalAppend(name, sql, params) {
1915
+ const seq = _nextSeq(name);
1916
+ const entry = {
1917
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
1918
+ sql,
1919
+ params: params || [],
1920
+ seq,
1921
+ ts: Date.now()
1922
+ };
1923
+ exports.store.set(_journalKey(name, seq), entry);
1924
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1925
+ idx.push(seq);
1926
+ exports.store.set(_journalIndexKey(name), idx);
1927
+ return seq;
1928
+ }
1929
+ function _journalEntries(name) {
1930
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1931
+ const entries = [];
1932
+ for (const seq of idx) {
1933
+ const raw = exports.store.get(_journalKey(name, seq));
1934
+ if (raw && typeof raw === "object" && raw.hlc) entries.push(raw);
1935
+ }
1936
+ entries.sort((a, b) => {
1937
+ const ha = exports.hlc.parse(a.hlc);
1938
+ const hb = exports.hlc.parse(b.hlc);
1939
+ if (ha && hb) return exports.hlc.compare(ha, hb);
1940
+ return a.seq - b.seq;
1780
1941
  });
1942
+ return entries;
1943
+ }
1944
+ function _journalCount(name) {
1945
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1946
+ return idx.length;
1947
+ }
1948
+ function _clearJournal(name) {
1949
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1950
+ for (const seq of idx) {
1951
+ exports.store.remove(_journalKey(name, seq));
1952
+ }
1953
+ exports.store.remove(_journalIndexKey(name));
1954
+ exports.store.remove(_journalSeqKey(name));
1955
+ exports.store.remove(_opCounterKey(name));
1956
+ }
1957
+ async function _saveCheckpoint(name) {
1958
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1959
+ if (!db || typeof db.export !== "function") return false;
1960
+ try {
1961
+ const blob = db.export();
1962
+ exports.store.set(_dbKey(name), _b64encode2(blob));
1963
+ message_default(`Memorio SQLite: checkpoint saved for '${name}'`);
1964
+ return true;
1965
+ } catch (err) {
1966
+ if (db && db.version === "bun:sqlite") {
1967
+ return false;
1968
+ }
1969
+ console.warn("Memorio SQLite: checkpoint failed", err);
1970
+ return false;
1971
+ }
1781
1972
  }
1782
- function loadSnapshot(name) {
1783
- const b64 = exports.store.get(_key(name));
1973
+ function _loadCheckpoint(name) {
1974
+ const b64 = exports.store.get(_dbKey(name));
1784
1975
  if (!b64) return null;
1785
1976
  try {
1786
1977
  return _b64decode2(b64);
@@ -1788,48 +1979,108 @@ function loadSnapshot(name) {
1788
1979
  return null;
1789
1980
  }
1790
1981
  }
1791
- function removeSnapshot(name) {
1792
- exports.store.remove(_key(name));
1982
+ function _removeCheckpoint(name) {
1983
+ exports.store.remove(_dbKey(name));
1793
1984
  }
1794
- function attachAutoExport(name, db) {
1795
- if (!db || typeof db.updateHook !== "function") return;
1796
- _persistDbs[name] = true;
1797
- try {
1798
- db.updateHook(() => {
1799
- if (_exportTimers[name]) clearTimeout(_exportTimers[name]);
1800
- _exportTimers[name] = setTimeout(() => {
1801
- _exportTimers[name] = null;
1802
- void saveSnapshot(name);
1803
- }, 250);
1804
- });
1805
- } catch (err) {
1806
- console.warn("Memorio SQLite: could not attach updateHook", err);
1985
+ async function _journalReplay(name, db) {
1986
+ const entries = _journalEntries(name);
1987
+ if (!entries.length) return 0;
1988
+ let replayed = 0;
1989
+ for (const entry of entries) {
1990
+ try {
1991
+ db.run(entry.sql, entry.params || []);
1992
+ replayed++;
1993
+ } catch (err) {
1994
+ console.warn(`Memorio SQLite: failed to replay journal entry ${entry.seq} for '${name}'`, err);
1995
+ }
1996
+ }
1997
+ message_default(`Memorio SQLite: replayed ${replayed} journal entries for '${name}'`);
1998
+ return replayed;
1999
+ }
2000
+ function _scheduleCheckpoint(name) {
2001
+ if (_checkpointTimers[name]) clearTimeout(_checkpointTimers[name]);
2002
+ _checkpointTimers[name] = setTimeout(() => {
2003
+ _checkpointTimers[name] = null;
2004
+ void _checkpoint(name);
2005
+ }, DEBOUNCE_MS);
2006
+ }
2007
+ async function _checkpoint(name) {
2008
+ if (_checkpointTimers[name]) {
2009
+ clearTimeout(_checkpointTimers[name]);
2010
+ _checkpointTimers[name] = null;
2011
+ }
2012
+ const saved = await _saveCheckpoint(name);
2013
+ if (saved) _clearJournal(name);
2014
+ return saved;
2015
+ }
2016
+ function _attachJournal(name, db) {
2017
+ if (!db || typeof db.run !== "function") return;
2018
+ if (db.__memorioJournalAttached) return;
2019
+ db.__memorioJournalAttached = true;
2020
+ const originalRun = db.run.bind(db);
2021
+ db.run = function(sql, params) {
2022
+ const paramArr = Array.isArray(params) ? params : params !== void 0 ? [params] : [];
2023
+ _journalAppend(name, sql, paramArr);
2024
+ const ops = (exports.store.get(_opCounterKey(name)) || 0) + 1;
2025
+ exports.store.set(_opCounterKey(name), ops);
2026
+ if (ops >= CHECKPOINT_INTERVAL) {
2027
+ exports.store.set(_opCounterKey(name), 0);
2028
+ void _checkpoint(name);
2029
+ } else {
2030
+ _scheduleCheckpoint(name);
2031
+ }
2032
+ return originalRun(sql, params);
2033
+ };
2034
+ if (typeof db.updateHook === "function") {
2035
+ try {
2036
+ db.updateHook(() => {
2037
+ _scheduleCheckpoint(name);
2038
+ });
2039
+ } catch (err) {
2040
+ console.warn("Memorio SQLite: could not attach updateHook", err);
2041
+ }
1807
2042
  }
1808
2043
  }
1809
- var g, _persistDbs, _exportTimers;
2044
+ var g, CHECKPOINT_INTERVAL, DEBOUNCE_MS, _checkpointTimers;
1810
2045
  var init_persist = __esm({
1811
2046
  "functions/sqlite/tools/persist.ts"() {
1812
2047
  init_cjs_shims();
1813
2048
  init_sqlite();
1814
2049
  init_store();
2050
+ init_hlc();
1815
2051
  init_message();
1816
2052
  g = globalThis;
1817
- _persistDbs = {};
1818
- _exportTimers = {};
2053
+ CHECKPOINT_INTERVAL = 50;
2054
+ DEBOUNCE_MS = 250;
2055
+ _checkpointTimers = {};
1819
2056
  __name(_ns, "_ns");
1820
- __name(_key, "_key");
2057
+ __name(_dbKey, "_dbKey");
2058
+ __name(_journalKey, "_journalKey");
2059
+ __name(_journalIndexKey, "_journalIndexKey");
2060
+ __name(_journalSeqKey, "_journalSeqKey");
2061
+ __name(_opCounterKey, "_opCounterKey");
1821
2062
  __name(_b64encode2, "_b64encode");
1822
2063
  __name(_b64decode2, "_b64decode");
1823
- __name(saveSnapshot, "saveSnapshot");
1824
- __name(loadSnapshot, "loadSnapshot");
1825
- __name(removeSnapshot, "removeSnapshot");
1826
- __name(attachAutoExport, "attachAutoExport");
2064
+ __name(_nextSeq, "_nextSeq");
2065
+ __name(_journalAppend, "_journalAppend");
2066
+ __name(_journalEntries, "_journalEntries");
2067
+ __name(_journalCount, "_journalCount");
2068
+ __name(_clearJournal, "_clearJournal");
2069
+ __name(_saveCheckpoint, "_saveCheckpoint");
2070
+ __name(_loadCheckpoint, "_loadCheckpoint");
2071
+ __name(_removeCheckpoint, "_removeCheckpoint");
2072
+ __name(_journalReplay, "_journalReplay");
2073
+ __name(_scheduleCheckpoint, "_scheduleCheckpoint");
2074
+ __name(_checkpoint, "_checkpoint");
2075
+ __name(_attachJournal, "_attachJournal");
1827
2076
  exports.sqlite.db.persist = async (name = "memorio") => {
1828
- return saveSnapshot(name);
2077
+ return _checkpoint(name);
2078
+ };
2079
+ exports.sqlite.db.flush = async (name = "memorio") => {
2080
+ return _checkpoint(name);
1829
2081
  };
1830
2082
  exports.sqlite.db.download = async (name = "memorio", filename = `${name}.sqlite`) => {
1831
- const g3 = globalThis;
1832
- const db = g3.__sqliteDbs && g3.__sqliteDbs[name];
2083
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1833
2084
  if (!db) {
1834
2085
  console.warn(`Memorio SQLite: cannot download '${name}' - database not found. Create it with sqlite.db.create('${name}').`);
1835
2086
  return false;
@@ -1842,18 +2093,18 @@ var init_persist = __esm({
1842
2093
  return false;
1843
2094
  }
1844
2095
  if (!blob) return false;
1845
- if (typeof g3.document === "undefined" || typeof g3.Blob === "undefined") {
2096
+ if (typeof g.document === "undefined" || typeof g.Blob === "undefined") {
1846
2097
  console.warn("Memorio SQLite: sqlite.db.download() requires a browser environment.");
1847
2098
  return false;
1848
2099
  }
1849
- const URL2 = g3.URL || g3.webkitURL;
2100
+ const URL2 = g.URL || g.webkitURL;
1850
2101
  if (!URL2 || typeof URL2.createObjectURL !== "function") return false;
1851
2102
  const objectUrl = URL2.createObjectURL(new Blob([blob], { type: "application/x-sqlite3" }));
1852
- const a = g3.document.createElement("a");
2103
+ const a = g.document.createElement("a");
1853
2104
  a.style.display = "none";
1854
2105
  a.href = objectUrl;
1855
2106
  a.download = filename;
1856
- g3.document.body.appendChild(a);
2107
+ g.document.body.appendChild(a);
1857
2108
  a.click();
1858
2109
  setTimeout(() => {
1859
2110
  try {
@@ -1868,7 +2119,7 @@ var init_persist = __esm({
1868
2119
  const db = g.__sqliteDbs && g.__sqliteDbs[name];
1869
2120
  if (db && typeof db.close === "function") {
1870
2121
  try {
1871
- await saveSnapshot(name);
2122
+ await _checkpoint(name);
1872
2123
  } catch (_) {
1873
2124
  }
1874
2125
  try {
@@ -1882,15 +2133,22 @@ var init_persist = __esm({
1882
2133
  const idx = g.sqlbases.findIndex((x) => x && x.name === name);
1883
2134
  if (idx > -1) g.sqlbases.splice(idx, 1);
1884
2135
  }
1885
- delete _persistDbs[name];
1886
- if (_exportTimers[name]) {
1887
- clearTimeout(_exportTimers[name]);
1888
- _exportTimers[name] = null;
2136
+ if (_checkpointTimers[name]) {
2137
+ clearTimeout(_checkpointTimers[name]);
2138
+ _checkpointTimers[name] = null;
1889
2139
  }
1890
- removeSnapshot(name);
1891
2140
  };
1892
- exports.sqlite.db.loadSnapshot = loadSnapshot;
1893
- exports.sqlite.db.saveSnapshot = saveSnapshot;
2141
+ exports.sqlite.db.loadSnapshot = _loadCheckpoint;
2142
+ exports.sqlite.db.saveSnapshot = _saveCheckpoint;
2143
+ exports.sqlite.db.removeSnapshot = _removeCheckpoint;
2144
+ exports.sqlite.db.journal = {
2145
+ append: _journalAppend,
2146
+ entries: _journalEntries,
2147
+ count: _journalCount,
2148
+ clear: _clearJournal,
2149
+ replay: _journalReplay,
2150
+ checkpoint: _checkpoint
2151
+ };
1894
2152
  }
1895
2153
  });
1896
2154
 
@@ -1908,7 +2166,7 @@ var init_db_create2 = __esm({
1908
2166
  const persistence = !!(opts && opts.persistence) || !!(g3.sqliteConfig && g3.sqliteConfig.persistence);
1909
2167
  let data;
1910
2168
  if (persistence && !opts.data) {
1911
- const restored = loadSnapshot(name);
2169
+ const restored = _loadCheckpoint(name);
1912
2170
  if (restored) data = restored;
1913
2171
  }
1914
2172
  const useData = opts && opts.data || data;
@@ -1930,7 +2188,13 @@ var init_db_create2 = __esm({
1930
2188
  } else {
1931
2189
  g3.sqlbases.push({ name, db, persistence: createOpts.persistence });
1932
2190
  }
1933
- if (persistence) attachAutoExport(name, db);
2191
+ if (persistence && !opts.data) {
2192
+ _attachJournal(name, db);
2193
+ const replayed = await _journalReplay(name, db);
2194
+ if (replayed > 0) {
2195
+ message_default(`Memorio SQLite: replayed ${replayed} journal entries for '${name}'`);
2196
+ }
2197
+ }
1934
2198
  return db;
1935
2199
  };
1936
2200
  }
@@ -1961,9 +2225,14 @@ var init_db_delete2 = __esm({
1961
2225
  init_cjs_shims();
1962
2226
  init_sqlite();
1963
2227
  init_message();
1964
- exports.sqlite.db.delete = (name) => {
2228
+ init_persist();
2229
+ exports.sqlite.db.delete = async (name) => {
1965
2230
  const dbs = globalThis.__sqliteDbs;
1966
2231
  if (!dbs || !dbs[name]) return false;
2232
+ try {
2233
+ await _checkpoint(name);
2234
+ } catch (_) {
2235
+ }
1967
2236
  try {
1968
2237
  dbs[name].close();
1969
2238
  } catch (_) {
@@ -1971,6 +2240,7 @@ var init_db_delete2 = __esm({
1971
2240
  delete dbs[name];
1972
2241
  const g3 = globalThis;
1973
2242
  if (g3.sqlbases) g3.sqlbases = g3.sqlbases.filter((x) => x && x.name !== name);
2243
+ _removeCheckpoint(name);
1974
2244
  message_default(`Memorio SQLite: database '${name}' deleted`);
1975
2245
  return true;
1976
2246
  };
@@ -2115,7 +2385,7 @@ var init_data_get2 = __esm({
2115
2385
  });
2116
2386
 
2117
2387
  // functions/sqlite/index.ts
2118
- var _hasSqlJs, _hasBunSqlite; exports.sqlite = void 0;
2388
+ var _hasSqlJs, _hasBunSqlite; exports.sqlite = void 0; var _toolsLoaded;
2119
2389
  var init_sqlite = __esm({
2120
2390
  "functions/sqlite/index.ts"() {
2121
2391
  init_cjs_shims();
@@ -2128,6 +2398,7 @@ var init_sqlite = __esm({
2128
2398
  query: {},
2129
2399
  data: {}
2130
2400
  };
2401
+ _toolsLoaded = Promise.resolve();
2131
2402
  exports.sqlite.config = (opts) => {
2132
2403
  const g3 = globalThis;
2133
2404
  g3.sqliteConfig = { ...g3.sqliteConfig, ...opts };
@@ -2142,15 +2413,19 @@ var init_sqlite = __esm({
2142
2413
  get: /* @__PURE__ */ __name(() => {
2143
2414
  const g3 = globalThis;
2144
2415
  if (!g3.sqliteReady) {
2145
- g3.sqliteReady = typeof exports.sqlite.db.getSQL === "function" ? exports.sqlite.db.getSQL().then(() => {
2416
+ g3.sqliteReady = _toolsLoaded.then(() => {
2417
+ if (typeof exports.sqlite.db.getSQL !== "function") return;
2418
+ return exports.sqlite.db.getSQL().then(() => {
2419
+ }).catch(() => {
2420
+ });
2146
2421
  }).catch(() => {
2147
- }) : Promise.resolve();
2422
+ });
2148
2423
  }
2149
2424
  return g3.sqliteReady;
2150
2425
  }, "get")
2151
2426
  });
2152
2427
  if (_hasSqlJs || _hasBunSqlite) {
2153
- (async () => {
2428
+ _toolsLoaded = (async () => {
2154
2429
  Object.defineProperty(exports.sqlite, "db", { value: {}, writable: false, configurable: true, enumerable: true });
2155
2430
  Object.defineProperty(exports.sqlite, "query", { value: {}, writable: false, configurable: true, enumerable: true });
2156
2431
  Object.defineProperty(exports.sqlite, "data", { value: {}, writable: false, configurable: true, enumerable: true });
@@ -2162,6 +2437,7 @@ var init_sqlite = __esm({
2162
2437
  });
2163
2438
  await Promise.all([
2164
2439
  Promise.resolve().then(() => (init_db_support2(), db_support_exports2)),
2440
+ Promise.resolve().then(() => (init_persist(), persist_exports)),
2165
2441
  Promise.resolve().then(() => (init_db_create2(), db_create_exports2)),
2166
2442
  Promise.resolve().then(() => (init_db_get(), db_get_exports)),
2167
2443
  Promise.resolve().then(() => (init_db_delete2(), db_delete_exports2)),
@@ -2382,133 +2658,23 @@ init_env();
2382
2658
  // core/mutation/engine.ts
2383
2659
  init_cjs_shims();
2384
2660
  init_internal();
2385
-
2386
- // core/hlc.ts
2387
- init_cjs_shims();
2388
- var NODE_ID_KEY = "__memorio_hlc_node";
2389
- function getNodeId() {
2390
- if (typeof globalThis === "undefined") return "node";
2391
- try {
2392
- if (typeof sessionStorage !== "undefined" && sessionStorage) {
2393
- let id = sessionStorage.getItem(NODE_ID_KEY);
2394
- if (!id) {
2395
- id = generateNodeId();
2396
- sessionStorage.setItem(NODE_ID_KEY, id);
2397
- }
2398
- return id;
2399
- }
2400
- } catch {
2401
- }
2402
- if (!globalThis.__memorioHlcNodeId) {
2403
- globalThis.__memorioHlcNodeId = generateNodeId();
2404
- }
2405
- return globalThis.__memorioHlcNodeId;
2406
- }
2407
- __name(getNodeId, "getNodeId");
2408
- function generateNodeId() {
2409
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2410
- return crypto.randomUUID().slice(0, 8);
2411
- }
2412
- return Math.random().toString(36).slice(2, 10);
2413
- }
2414
- __name(generateNodeId, "generateNodeId");
2415
- var HLC_KEY = "__memorio_hlc_local";
2416
- var local = globalThis[HLC_KEY] || {
2417
- physical: 0,
2418
- logical: 0,
2419
- node: getNodeId()
2420
- };
2421
- if (!globalThis[HLC_KEY]) {
2422
- globalThis[HLC_KEY] = local;
2423
- }
2424
- function tick(_incoming) {
2425
- const now2 = Date.now();
2426
- const base = local.physical;
2427
- let physical;
2428
- let logical;
2429
- if (now2 > base) {
2430
- physical = now2;
2431
- logical = 0;
2432
- } else if (now2 < base) {
2433
- physical = base;
2434
- logical = local.logical + 1;
2435
- } else {
2436
- physical = base;
2437
- logical = local.logical + 1;
2438
- }
2439
- local.physical = physical;
2440
- local.logical = logical;
2441
- return { physical, logical, node: local.node };
2442
- }
2443
- __name(tick, "tick");
2444
- function receive(remote) {
2445
- const now2 = Date.now();
2446
- if (remote.physical > local.physical) {
2447
- local.physical = remote.physical > now2 ? remote.physical : now2;
2448
- local.logical = 1;
2449
- } else if (remote.physical === local.physical) {
2450
- local.logical = Math.max(local.logical, remote.logical) + 1;
2451
- }
2452
- local.node = getNodeId();
2453
- return { ...local };
2454
- }
2455
- __name(receive, "receive");
2456
- function compare(a, b) {
2457
- if (a.physical !== b.physical) {
2458
- return a.physical < b.physical ? -1 : 1;
2459
- }
2460
- if (a.logical !== b.logical) {
2461
- return a.logical < b.logical ? -1 : 1;
2462
- }
2463
- if (a.node !== b.node) {
2464
- return a.node < b.node ? -1 : 1;
2465
- }
2466
- return 0;
2467
- }
2468
- __name(compare, "compare");
2469
- function happenedBefore(a, b) {
2470
- return compare(a, b) < 0;
2471
- }
2472
- __name(happenedBefore, "happenedBefore");
2473
- function serialize(hlc2) {
2474
- return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
2475
- }
2476
- __name(serialize, "serialize");
2477
- function parse(serialized) {
2478
- if (!serialized.startsWith("hlc:")) return null;
2479
- const parts = serialized.split(":");
2480
- if (parts.length !== 4) return null;
2481
- const physical = parseInt(parts[1], 10);
2482
- const logical = parseInt(parts[2], 10);
2483
- const node = parts[3];
2484
- if (isNaN(physical) || isNaN(logical)) return null;
2485
- return { physical, logical, node };
2486
- }
2487
- __name(parse, "parse");
2488
- var hlc = {
2489
- tick,
2490
- receive,
2491
- compare,
2492
- happenedBefore,
2493
- serialize,
2494
- parse,
2495
- getNodeId
2496
- };
2661
+ init_hlc();
2497
2662
 
2498
2663
  // core/mutation/id.ts
2499
2664
  init_cjs_shims();
2665
+ init_hlc();
2500
2666
  function generateMutationId() {
2501
- const now2 = hlc.tick();
2667
+ const now2 = exports.hlc.tick();
2502
2668
  return "m_" + encodeHLC(now2);
2503
2669
  }
2504
2670
  __name(generateMutationId, "generateMutationId");
2505
2671
  function generateTransactionId() {
2506
- const now2 = hlc.tick();
2672
+ const now2 = exports.hlc.tick();
2507
2673
  return "tx_" + encodeHLC(now2);
2508
2674
  }
2509
2675
  __name(generateTransactionId, "generateTransactionId");
2510
2676
  function generateCommitId() {
2511
- const now2 = hlc.tick();
2677
+ const now2 = exports.hlc.tick();
2512
2678
  return "c_" + encodeHLC(now2);
2513
2679
  }
2514
2680
  __name(generateCommitId, "generateCommitId");
@@ -2588,6 +2754,7 @@ __name(mergePatches, "mergePatches");
2588
2754
  // core/mutation/transaction.ts
2589
2755
  init_cjs_shims();
2590
2756
  init_internal();
2757
+ init_hlc();
2591
2758
  var TX_REGISTRY_KEY = "__memorio_transaction_registry__";
2592
2759
  var registry = globalThis[TX_REGISTRY_KEY] || /* @__PURE__ */ new Map();
2593
2760
  if (!globalThis[TX_REGISTRY_KEY]) {
@@ -2614,7 +2781,7 @@ function beginTransaction(source, message2, metadata) {
2614
2781
  const id = generateTransactionId();
2615
2782
  const ctx = {
2616
2783
  id,
2617
- startedAt: hlc.serialize(hlc.tick()),
2784
+ startedAt: exports.hlc.serialize(exports.hlc.tick()),
2618
2785
  source,
2619
2786
  message: message2,
2620
2787
  metadata,
@@ -2642,7 +2809,7 @@ function commitTransaction() {
2642
2809
  const ctx = registry.get(txId);
2643
2810
  if (!ctx || !ctx.active) return null;
2644
2811
  ctx.active = false;
2645
- ctx.committedAt = hlc.serialize(hlc.tick());
2812
+ ctx.committedAt = exports.hlc.serialize(exports.hlc.tick());
2646
2813
  const tx = {
2647
2814
  id: ctx.id,
2648
2815
  mutations: ctx.mutations,
@@ -2722,7 +2889,7 @@ function abortTransaction() {
2722
2889
  }
2723
2890
  }
2724
2891
  ctx.active = false;
2725
- ctx.committedAt = hlc.serialize(hlc.tick());
2892
+ ctx.committedAt = exports.hlc.serialize(exports.hlc.tick());
2726
2893
  const tx = {
2727
2894
  id: ctx.id,
2728
2895
  mutations: ctx.mutations,
@@ -2780,11 +2947,11 @@ __name(registerMutationInTransaction, "registerMutationInTransaction");
2780
2947
 
2781
2948
  // core/mutation/engine.ts
2782
2949
  function currentTimestamp() {
2783
- return hlc.serialize(hlc.tick());
2950
+ return exports.hlc.serialize(exports.hlc.tick());
2784
2951
  }
2785
2952
  __name(currentTimestamp, "currentTimestamp");
2786
2953
  function createMutation(path, operation, before2, after2, options) {
2787
- const now2 = hlc.tick();
2954
+ const now2 = exports.hlc.tick();
2788
2955
  const mutation = {
2789
2956
  id: generateMutationId(),
2790
2957
  path,
@@ -2792,7 +2959,7 @@ function createMutation(path, operation, before2, after2, options) {
2792
2959
  after: after2,
2793
2960
  before: before2,
2794
2961
  timestamp: now2.physical,
2795
- hlc: hlc.serialize(now2),
2962
+ hlc: exports.hlc.serialize(now2),
2796
2963
  context: options?.context || exports.internal.currentContext || void 0,
2797
2964
  source: options?.source,
2798
2965
  transactionId: options?.transactionId || (operation !== "length" ? tagForTransaction() : void 0),
@@ -4199,8 +4366,8 @@ function isAuditActive() {
4199
4366
  return _auditLogger !== null;
4200
4367
  }
4201
4368
  __name(isAuditActive, "isAuditActive");
4202
- function setAuditLogger(logger3) {
4203
- _auditLogger = logger3;
4369
+ function setAuditLogger(logger2) {
4370
+ _auditLogger = logger2;
4204
4371
  }
4205
4372
  __name(setAuditLogger, "setAuditLogger");
4206
4373
  function logAudit(entry) {
@@ -4443,6 +4610,9 @@ var logger = {
4443
4610
  exportLogs
4444
4611
  };
4445
4612
 
4613
+ // index.ts
4614
+ init_hlc();
4615
+
4446
4616
  // core/fractional.ts
4447
4617
  init_cjs_shims();
4448
4618
  function generateBetween(left, right, minChars = 2) {
@@ -4635,7 +4805,7 @@ init_internal();
4635
4805
 
4636
4806
  // package.json
4637
4807
  var package_default = {
4638
- version: "5.1.2"};
4808
+ version: "5.1.3"};
4639
4809
 
4640
4810
  // core/global.ts
4641
4811
  init_env();
@@ -4656,10 +4826,12 @@ __name(typed, "typed");
4656
4826
  init_cjs_shims();
4657
4827
  init_store();
4658
4828
  init_idb();
4829
+ init_hlc();
4659
4830
  init_env();
4660
4831
 
4661
4832
  // functions/memory/journal.ts
4662
4833
  init_cjs_shims();
4834
+ init_hlc();
4663
4835
  init_env();
4664
4836
  init_store();
4665
4837
  var g2 = globalThis;
@@ -4697,7 +4869,7 @@ var journal = {
4697
4869
  updatedAt: entry.updatedAt || Date.now(),
4698
4870
  version: entry.version || 1,
4699
4871
  sync: "pending",
4700
- hlc: entry.hlc || hlc.serialize(hlc.tick())
4872
+ hlc: entry.hlc || exports.hlc.serialize(exports.hlc.tick())
4701
4873
  };
4702
4874
  const key = `${STORE_PREFIX(ns)}${row.id}`;
4703
4875
  exports.store.set(key, row);
@@ -4719,9 +4891,9 @@ var journal = {
4719
4891
  }
4720
4892
  out.sort((a, b) => {
4721
4893
  if (a.hlc && b.hlc) {
4722
- const ha = hlc.parse(a.hlc);
4723
- const hb = hlc.parse(b.hlc);
4724
- if (ha && hb) return hlc.compare(ha, hb);
4894
+ const ha = exports.hlc.parse(a.hlc);
4895
+ const hb = exports.hlc.parse(b.hlc);
4896
+ if (ha && hb) return exports.hlc.compare(ha, hb);
4725
4897
  }
4726
4898
  return (a.updatedAt || 0) - (b.updatedAt || 0);
4727
4899
  });
@@ -4797,15 +4969,15 @@ var journal = {
4797
4969
  const remote = await provider.pull(since);
4798
4970
  for (const e of remote || []) {
4799
4971
  if (e.hlc) {
4800
- const parsed = hlc.parse(e.hlc);
4801
- if (parsed) hlc.receive(parsed);
4972
+ const parsed = exports.hlc.parse(e.hlc);
4973
+ if (parsed) exports.hlc.receive(parsed);
4802
4974
  }
4803
4975
  const localEntry = await this.get(e.id);
4804
4976
  if (localEntry && e.hlc && localEntry.hlc) {
4805
- const ha = hlc.parse(localEntry.hlc);
4806
- const hb = hlc.parse(e.hlc);
4977
+ const ha = exports.hlc.parse(localEntry.hlc);
4978
+ const hb = exports.hlc.parse(e.hlc);
4807
4979
  if (ha && hb) {
4808
- const cmp = hlc.compare(ha, hb);
4980
+ const cmp = exports.hlc.compare(ha, hb);
4809
4981
  if (cmp === 0) {
4810
4982
  const hasResolver = typeof provider.resolveConflict === "function";
4811
4983
  const resolution = hasResolver ? await provider.resolveConflict(localEntry, e) : "remote";
@@ -5147,7 +5319,7 @@ var memory = {
5147
5319
  version: existing ? existing.version ? existing.version + 1 : 1 : 1,
5148
5320
  sync: isSyncEnabled2() ? "pending" : void 0,
5149
5321
  supersededId: existing ? existing.id : null,
5150
- hlc: hlc.serialize(hlc.tick())
5322
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5151
5323
  };
5152
5324
  await saveToScope(entry);
5153
5325
  await recordJournal(entry, "remember");
@@ -5200,7 +5372,7 @@ var memory = {
5200
5372
  updatedAt: now(),
5201
5373
  version: 1,
5202
5374
  sync: isSyncEnabled2() ? "pending" : void 0,
5203
- hlc: hlc.serialize(hlc.tick())
5375
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5204
5376
  };
5205
5377
  await recordJournal(tombstone2, "delete");
5206
5378
  return;
@@ -5214,7 +5386,7 @@ var memory = {
5214
5386
  updatedAt: now(),
5215
5387
  version: (entry.version ? entry.version : 0) + 1,
5216
5388
  sync: isSyncEnabled2() ? "pending" : void 0,
5217
- hlc: hlc.serialize(hlc.tick())
5389
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5218
5390
  };
5219
5391
  await recordJournal(tombstone, "delete");
5220
5392
  dispatch.set("memorio:memory:forgotten", { key });
@@ -5243,7 +5415,7 @@ var memory = {
5243
5415
  updatedAt: now(),
5244
5416
  version: (existing.version ? existing.version : 0) + 1,
5245
5417
  sync: isSyncEnabled2() ? "pending" : void 0,
5246
- hlc: hlc.serialize(hlc.tick()),
5418
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
5247
5419
  ...opts.scope ? { scope: opts.scope } : {},
5248
5420
  ...opts.ttl !== void 0 ? { ttl: opts.ttl } : {},
5249
5421
  ...opts.type ? { type: opts.type } : {},
@@ -5326,7 +5498,7 @@ var memory = {
5326
5498
  lastConfirmedAt: now(),
5327
5499
  version: (entry.version ? entry.version : 0) + 1,
5328
5500
  sync: isSyncEnabled2() ? "pending" : void 0,
5329
- hlc: hlc.serialize(hlc.tick()),
5501
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
5330
5502
  patches,
5331
5503
  path: patches[0]?.path
5332
5504
  };
@@ -5572,6 +5744,7 @@ if (!("memorio" in globalThis)) {
5572
5744
  );
5573
5745
  memorio.memory = memory;
5574
5746
  memorio.encryption = exports.encryption;
5747
+ memorio.sqlite = exports.sqlite;
5575
5748
  initializePlatform();
5576
5749
  memorio.isBrowser = isBrowser;
5577
5750
  memorio.isNode = isNode;
@@ -5690,7 +5863,6 @@ exports.generateTransactionId = generateTransactionId;
5690
5863
  exports.getCapabilities = getCapabilities;
5691
5864
  exports.getContext = getContext;
5692
5865
  exports.help = help;
5693
- exports.hlc = hlc;
5694
5866
  exports.isBrowser = isBrowser;
5695
5867
  exports.isBun = isBun;
5696
5868
  exports.isDeno = isDeno;