You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

21 lines
2.5 KiB

// storage-bridge.js - двухслойный клиент памяти dsh-memory
var LK="dsm_state",TK="dshmem-bridge-token",BU="http://127.0.0.1:8766";
function empty() {return {version:1,updatedAt:new Date().toISOString(),memories:{},skills:[]};}
function loadLocal() {return new Promise(function(res){chrome.storage.local.get([LK],function(o){res(o[LK] || empty())})})};
function saveLocal(s) {return new Promise(function(res){chrome.storage.local.set({dsm_state:s},function(){res(true)})})};
function authHeaders() {return new Promise(function(res){chrome.storage.local.get([TK],function(o){var h={};h["Content-Type"]="application/json";if(o[TK])h.Authorization="Bearer "+o[TK];res(h)})})};
function fetchRemote() {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"GET",headers:h})}).then(function(r){if(!r.ok)throw new Error("GET "+r.status);return r.json()}).then(function(j){if(!j||!j.ok)throw new Error("bad payload");return j.data||empty()})};
function putRemote(s) {return authHeaders().then(function(h){return fetch(BU+"/"+"memory/state",{method:"PUT",headers:h,body:JSON.stringify(s)})}).then(function(r){if(!r.ok)throw new Error("PUT "+r.status);return r.json()}).then(function(j){return j&&j.ok})};
function newer(a,b) {return (a&&a.updatedAt?a.updatedAt:"") >= (b&&b.updatedAt?b.updatedAt:"")};
function isEmpty(s) {return !s || ((s.memories ? Object.keys(s.memories).length : 0) + (s.skills ? s.skills.length : 0) === 0)};
function sync() {return Promise.all([loadLocal(),fetchRemote().catch(function(){return null})]).then(function(arr){var loc=arr[0],rem=arr[1];if(!rem)return loc;var le=isEmpty(loc),re=isEmpty(rem);if(le!==re){if(le){return saveLocal(rem).then(function(){return rem})}putRemote(loc).catch(function(){});return loc};if(newer(loc,rem)){putRemote(loc).catch(function(){});return loc};return saveLocal(rem).then(function(){return rem})})};
function getState() {return sync()};
function putState(s) {var v={version:1,updatedAt:new Date().toISOString(),memories:s.memories||{},skills:s.skills||[]};return saveLocal(v).then(function(){return putRemote(v).catch(function(){return false})}).then(function(){return v})};
var API={empty:empty,loadLocal:loadLocal,saveLocal:saveLocal,authHeaders:authHeaders,fetchRemote:fetchRemote,putRemote:putRemote,sync:sync,getState:getState,putState:putState,LK:LK,TK:TK,BU:BU};
if(typeof module!=="undefined"&&module.exports){module.exports=API};
if(typeof globalThis!=="undefined"){globalThis.STORAGE_BRIDGE=API};