diff --git a/package.json b/package.json index 170ec09..76a926d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "life-os", - "version": "1.19.0", + "version": "1.20.0", "private": true, "type": "module", "scripts": { diff --git a/public/addons.js b/public/addons.js index ca1019b..2ba43db 100644 --- a/public/addons.js +++ b/public/addons.js @@ -3,7 +3,7 @@ const DRAFT_KEY = 'lifeos_today_draft_v1'; const localDay = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }; const escapeHtml = value => String(value || '').replace(/[&<>]/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char])); - const APP_VERSION = '1.19.0'; + const APP_VERSION = '1.20.0'; window.LifeOSVersion = APP_VERSION; const appIds = ['today', 'timeline', 'museum', 'insights', 'profile', 'tasks', 'calendar', 'system', 'browser', 'terminal', 'database']; const t = (key, values) => LifeI18n.t(key, values); diff --git a/public/backup.js b/public/backup.js new file mode 100644 index 0000000..bc17dad --- /dev/null +++ b/public/backup.js @@ -0,0 +1,96 @@ +/* Portable Life OS backup format. Schema v3 carries every device-local app record. */ +(() => { + const BACKUP_SCHEMA = 3; + const SAFETY_KEY = 'lifeos_restore_safety_v1'; + const excluded = /^(lifeos_(?:cloud_|precloud_|sync_conflict_|storage_mode_|local_cache_revision_|restore_safety_))/; + const portableKey = key => typeof key === 'string' && key.startsWith('lifeos_') && !excluded.test(key); + const records = () => Object.fromEntries( + Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) + .filter(portableKey) + .sort() + .map(key => [key, localStorage.getItem(key)]) + ); + const canonical = value => JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)))); + const sha256 = async value => { + const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); + return Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join(''); + }; + const json = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key) || 'null') ?? fallback; } catch { return fallback; } }; + const safeDay = () => new Date().toISOString().slice(0, 10); + + async function createBackup() { + const stored = records(); + return { + app: 'Life OS', + version: window.LifeOSVersion || '1.20.0', + schemaVersion: BACKUP_SCHEMA, + exportedAt: new Date().toISOString(), + profile: json('lifeos_profile', {}), + memories: json('lifeos_memories', []), + museum: json('lifeos_museum', []), + settings: json('lifeos_settings', {}), + system: json('lifeos_system', { schemaVersion: 2 }), + desktopLayout: json('lifeos_window_layout_v1', null), + widgetLayout: json('lifeos_widget_layout_v1', null), + records: stored, + recordCount: Object.keys(stored).length, + checksum: { algorithm: 'SHA-256', value: await sha256(canonical(stored)) } + }; + } + + function download(data, filename) { + const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })); + const link = document.createElement('a'); + link.href = url; link.download = filename; link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + + async function valid(data) { + if (!data || data.app !== 'Life OS' || ![1, 2, 3].includes(data.schemaVersion) || !Array.isArray(data.memories) || !Array.isArray(data.museum)) return false; + if (data.schemaVersion < BACKUP_SCHEMA) return true; + if (!data.records || Array.isArray(data.records) || typeof data.records !== 'object') return false; + const entries = Object.entries(data.records); + if (entries.some(([key, value]) => !portableKey(key) || typeof value !== 'string')) return false; + if (data.recordCount !== entries.length || data.checksum?.algorithm !== 'SHA-256' || !/^[a-f0-9]{64}$/.test(data.checksum?.value || '')) return false; + return (await sha256(canonical(data.records))) === data.checksum.value; + } + + window.exportData = async () => { + const state = settings(); state.lastBackup = new Date().toISOString(); save('lifeos_settings', state); + download(await createBackup(), `life-os-backup-${safeDay()}.json`); + window.renderAll?.(); window.toast?.('feedback.backup'); + }; + + window.readImport = async input => { + const file = input.files?.[0]; + input.value = ''; + if (!file || file.size > 32 * 1024 * 1024) return window.toast?.('feedback.invalid'); + try { + const data = JSON.parse(await file.text()); + if (!(await valid(data))) throw new Error('invalid backup'); + importData = data; + window.importPreview(); + } catch { + window.toast?.('feedback.invalid'); + } + }; + + const previousApplyImport = window.applyImport; + window.applyImport = async mode => { + const data = importData; + if (mode !== 'replace' || data?.schemaVersion !== BACKUP_SCHEMA) return previousApplyImport(mode); + const safety = await createBackup(); + localStorage.setItem(SAFETY_KEY, JSON.stringify(safety)); + download(safety, `life-os-before-restore-${safeDay()}.json`); + for (const key of Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)).filter(portableKey)) localStorage.removeItem(key); + for (const [key, value] of Object.entries(data.records)) localStorage.setItem(key, value); + document.querySelector('#modal').innerHTML = ''; + window.toast?.('feedback.restoring'); + setTimeout(() => { + window.renderIcons?.(); window.renderAll?.(); window.applyLanguage?.(); window.applyDesktopPreferences?.(); + window.LifeOSLocalDB?.refresh?.(); window.toast?.('feedback.restored'); + }, 500); + }; + + window.LifeOSBackup = { schemaVersion: BACKUP_SCHEMA, create: createBackup, validate: valid, portableKey }; +})(); diff --git a/public/index.html b/public/index.html index 56e1f34..0119caf 100644 --- a/public/index.html +++ b/public/index.html @@ -23,6 +23,6 @@ function museumApp(c){let a=museum(),ms=mems();c.innerHTML=`
m.date===d.toISOString().slice(0,10))){s++;d.setDate(d.getDate()-1)}return s}function longest(a){let ds=a.map(x=>x.date).sort(),best=0,run=0,last='';ds.forEach(d=>{run=last&&((new Date(d)-new Date(last))/864e5===1)?run+1:1;best=Math.max(best,run);last=d});return best}function insights(c){let a=mems(),last=a.filter(m=>(Date.now()-new Date(m.date+'T12:00:00'))<2592e6),cnt={clear:0,light:0,cloudy:0,rain:0,storm:0};last.forEach(x=>cnt[x.mood]++);let avg=a.length?(a.reduce((s,x)=>s+x.energy,0)/a.length).toFixed(1):'—',days={};a.forEach(x=>{let d=new Date(x.date+'T12:00:00').toLocaleDateString('en-US',{weekday:'long'});days[d]=(days[d]||0)+1});let active=Object.entries(days).sort((x,y)=>y[1]-x[1])[0]?.[0]||'—';c.innerHTML=`
LAST 30 DAYS

Insights, quietly.

WEATHER
${Object.entries(cnt).map(([k,v])=>`
${cap(k)} ${v} DAYS
`).join('')}
AVERAGE ENERGY
${avg} / 5
${a.slice(0,10).reverse().map(x=>``).join('')||'No entries yet'}
MOST ACTIVE DAY
${active}
CURRENT STREAK
${streak(a)} DAYS
Longest streak: ${longest(a)} days
`} function profileApp(c){let p=profile(),a=mems(),common=Object.entries(a.reduce((o,m)=>(o[m.mood]=(o[m.mood]||0)+1,o),{})).sort((x,y)=>y[1]-x[1])[0]?.[0]||'—',avg=a.length?(a.reduce((x,m)=>x+m.energy,0)/a.length).toFixed(1):'—',started=Math.max(1,Math.floor((Date.now()-new Date(p.startDate))/864e5));c.innerHTML=`
SYSTEM PROFILE

${p.name?esc(p.name)+' · ':''}LIFE OS ONLINE

${started}DAYS ONLINE
${a.length}MEMORIES
${museum().length}MUSEUM ITEMS
${streak(a)}CURRENT STREAK
${longest(a)}LONGEST STREAK
${cap(common)}COMMON WEATHER
PERSONAL SYSTEM
AVERAGE ENERGY ${avg} / 5
`}function saveProfile(){save('lifeos_profile',{name:pname.value,birthday:pbday.value,startDate:pstart.value||day(),motto:pmotto.value});renderAll();toast('PROFILE SAVED')} function today(c){let m=mems().find(x=>x.date===day());if(todayDraft===null){selectedMood=m?.mood||'cloudy';selectedEnergy=m?.energy||3}let f=m||filmFor(selectedMood,selectedEnergy),text=todayDraft===null?(m?.text||''):todayDraft,cWeek=new Date().toLocaleDateString(LifeI18n.locale(),{weekday:'long'}).toUpperCase();c.innerHTML=`
${cWeek}

${fmtDate(day()).replace(/^[^,]+, /,'')}

${i18n('How was your day?')}

`}function rerenderToday(){let old=document.querySelector('#entry');todayDraft=old?old.value:todayDraft||'';window.today(document.querySelector('#content-today'));let entry=document.querySelector('#entry');entry?.focus();entry?.setSelectionRange(entry.value.length,entry.value.length)} -function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS

System, local and yours.

APPEARANCE
${['dark','light','auto'].map(x=>``).join('')}
LANGUAGE
DATA
STORAGE

Local Storage
${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB

DATA STORAGE

Your data is stored locally in this browser.
Create regular backups to prevent data loss.

${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'
BACKUP RECOMMENDED':''}

VERSION

Life OS
Version ${window.LifeOSVersion||'1.18.1'} · Schema v2

`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=``}function replaceConfirm(){modal.innerHTML=``}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=``}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)} +function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS

System, local and yours.

APPEARANCE
${['dark','light','auto'].map(x=>``).join('')}
LANGUAGE
DATA
STORAGE

Local Storage
${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB

DATA STORAGE

Your data is stored locally in this browser.
Create regular backups to prevent data loss.

${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'
BACKUP RECOMMENDED':''}

VERSION

Life OS
Version ${window.LifeOSVersion||'1.18.1'} · Schema v2

`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2,3].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=``}function replaceConfirm(){modal.innerHTML=``}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=``}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)} window.renderIcons=renderIcons;window.renderAll=renderAll;window.toast=toast; - + diff --git a/public/local-db-worker.js b/public/local-db-worker.js index cfbadab..4f76ba3 100644 --- a/public/local-db-worker.js +++ b/public/local-db-worker.js @@ -70,6 +70,11 @@ async function status() { return { ready: true, engine: 'SQLite', sqliteVersion: db.selectValue('SELECT sqlite_version()'), records: Number(rows[0]?.count || 0), size }; } +async function exportDatabase() { + db.exec('PRAGMA optimize'); + return await pool.exportFile(DB_FILE); +} + self.onmessage = async event => { const { id, action, payload = {} } = event.data || {}; try { @@ -79,6 +84,7 @@ self.onmessage = async event => { if (action === 'write') return reply(id, write(payload)); if (action === 'remove') return reply(id, remove(payload)); if (action === 'status') return reply(id, await status()); + if (action === 'exportDatabase') return reply(id, await exportDatabase()); throw new Error(`Unknown local database action: ${action}`); } catch (error) { reply(id, null, error); diff --git a/public/local-db.js b/public/local-db.js index dd947c9..7dc668b 100644 --- a/public/local-db.js +++ b/public/local-db.js @@ -22,6 +22,16 @@ es: { title:'ALMACENAMIENTO DEL DISPOSITIVO', local:'SOLO LOCAL', cloud:'SINCRONIZACIÓN EN LA NUBE', location:'Este dispositivo · Este navegador · Almacenamiento privado de Life OS', database:'Base de datos', persistent:'Almacenamiento persistente', granted:'Protegido', bestEffort:'Conservación estándar', ready:'Lista', unavailable:'No disponible', preparing:'Preparando', size:'Tamaño de la base', warning:'Cambiar de navegador o dispositivo no traslada estos datos. Exporta una copia antes de migrar.', choose:'Elige cómo guarda Life OS tus datos', chooseBody:'El modo local funciona sin iniciar sesión y guarda los datos en este dispositivo. La nube requiere iniciar sesión.', useLocal:'USAR SOLO LOCAL', useCloud:'INICIAR SESIÓN Y SINCRONIZAR', localSaved:'Modo local activado', cloudSaved:'Sincronización en la nube activada' }, ja: { title:'デバイスストレージ', local:'ローカルのみ', cloud:'クラウド同期', location:'このデバイス · このブラウザ · Life OS 専用ストレージ', database:'データベース', persistent:'永続ストレージ', granted:'保護済み', bestEffort:'標準保持', ready:'利用可能', unavailable:'利用不可', preparing:'準備中', size:'データベース容量', warning:'ブラウザや端末を変更してもデータは自動移行されません。先にバックアップを書き出してください。', choose:'Life OS の保存方法を選択', chooseBody:'ローカルのみならログイン不要で、この端末だけに保存します。クラウド同期にはログインが必要です。', useLocal:'ローカルのみで使用', useCloud:'ログインして同期', localSaved:'ローカルモードを有効にしました', cloudSaved:'クラウド同期を有効にしました' } }; + Object.assign(translations.en, { sqliteCopy: 'DOWNLOAD SQLITE COPY' }); + Object.assign(translations['zh-CN'], { sqliteCopy: '下载 SQLite 副本' }); + Object.assign(translations['zh-HK'], { sqliteCopy: '下載 SQLite 副本' }); + Object.assign(translations['zh-MO'], { sqliteCopy: '下載 SQLite 副本' }); + Object.assign(translations['zh-TW'], { sqliteCopy: '下載 SQLite 副本' }); + Object.assign(translations.ar, { sqliteCopy: 'تنزيل نسخة SQLITE' }); + Object.assign(translations.fr, { sqliteCopy: 'TÉLÉCHARGER UNE COPIE SQLITE' }); + Object.assign(translations.ru, { sqliteCopy: 'СКАЧАТЬ КОПИЮ SQLITE' }); + Object.assign(translations.es, { sqliteCopy: 'DESCARGAR COPIA SQLITE' }); + Object.assign(translations.ja, { sqliteCopy: 'SQLITE コピーを保存' }); const text = () => translations[window.LifeI18n?.language?.()] || translations.en; const isManagedKey = key => typeof key === 'string' && key.startsWith(PREFIX) && key !== REVISION_KEY; @@ -92,9 +102,23 @@ window.renderAll?.(); } + async function downloadDatabase() { + if (!worker || !status.ready) return window.toast?.(text().unavailable); + try { + const bytes = await call('exportDatabase'); + const url = URL.createObjectURL(new Blob([bytes], { type: 'application/vnd.sqlite3' })); + const link = document.createElement('a'); + link.href = url; link.download = `lifeos-${new Date().toISOString().slice(0, 10)}.sqlite`; link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } catch (error) { + console.warn('Life OS SQLite export failed:', error); + window.toast?.(text().unavailable); + } + } + function settingsMarkup() { const t = text(), current = mode(), state = status.ready ? t.ready : status.supported ? t.preparing : t.unavailable; - return `
${t.title}
${t.database}
OPFS:/lifeos.sqlite · ${state}
${t.size}
${formatBytes(status.size || 0)}
${t.persistent}
${status.persisted ? t.granted : t.bestEffort}

${t.location}

${t.warning}

`; + return `
${t.title}
${t.database}
OPFS:/lifeos.sqlite · ${state}
${t.size}
${formatBytes(status.size || 0)}
${t.persistent}
${status.persisted ? t.granted : t.bestEffort}

${t.location}

${t.warning}

`; } function promptForMode() { @@ -130,11 +154,12 @@ document.addEventListener('click', event => { const button = event.target.closest('[data-storage-mode]'); if (button) setMode(button.dataset.storageMode); + if (event.target.closest('[data-download-sqlite]')) downloadDatabase(); }); const style = document.createElement('style'); - style.textContent = `.local-storage-card dl{display:grid;gap:7px;margin:15px 0}.local-storage-card dl div{display:flex;justify-content:space-between;gap:18px}.local-storage-card dt{color:var(--muted)}.local-storage-card dd{margin:0;text-align:end;overflow-wrap:anywhere}.local-storage-card p{margin:8px 0}.local-storage-warning{padding-top:10px;border-top:1px solid var(--line)}.local-storage-modes{display:flex;gap:7px;flex-wrap:wrap}#lifeos-storage-choice{position:fixed;inset:0;z-index:9200;display:grid;place-items:center;padding:20px;background:#071008d9}.lifeos-storage-choice-card{width:min(500px,100%);padding:26px;border:1px solid var(--line);border-radius:16px;background:var(--panel);box-shadow:var(--shadow)}.lifeos-storage-choice-card h2{margin:10px 0;font-size:25px;letter-spacing:-.04em}.lifeos-storage-choice-card p{color:var(--muted);line-height:1.65}.lifeos-storage-choice-card .actions{flex-wrap:wrap}`; + style.textContent = `.local-storage-card dl{display:grid;gap:7px;margin:15px 0}.local-storage-card dl div{display:flex;justify-content:space-between;gap:18px}.local-storage-card dt{color:var(--muted)}.local-storage-card dd{margin:0;text-align:end;overflow-wrap:anywhere}.local-storage-card p{margin:8px 0}.local-storage-actions{margin:12px 0}.local-storage-actions button:disabled{opacity:.5}.local-storage-warning{padding-top:10px;border-top:1px solid var(--line)}.local-storage-modes{display:flex;gap:7px;flex-wrap:wrap}#lifeos-storage-choice{position:fixed;inset:0;z-index:9200;display:grid;place-items:center;padding:20px;background:#071008d9}.lifeos-storage-choice-card{width:min(500px,100%);padding:26px;border:1px solid var(--line);border-radius:16px;background:var(--panel);box-shadow:var(--shadow)}.lifeos-storage-choice-card h2{margin:10px 0;font-size:25px;letter-spacing:-.04em}.lifeos-storage-choice-card p{color:var(--muted);line-height:1.65}.lifeos-storage-choice-card .actions{flex-wrap:wrap}`; document.head.append(style); const ready = initialize(); - window.LifeOSLocalDB = { ready, mode, setMode, status: () => ({ ...status }), settingsMarkup, promptForMode, refresh: async () => { if (worker && status.ready) status = { ...status, ...(await call('status')), persisted: await navigator.storage?.persisted?.() || status.persisted }; return { ...status }; } }; + window.LifeOSLocalDB = { ready, mode, setMode, downloadDatabase, status: () => ({ ...status }), settingsMarkup, promptForMode, refresh: async () => { if (worker && status.ready) status = { ...status, ...(await call('status')), persisted: await navigator.storage?.persisted?.() || status.persisted }; return { ...status }; } }; })(); diff --git a/public/service-worker.js b/public/service-worker.js index ca6b073..c04f8ba 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -1,4 +1,4 @@ -const CACHE = 'life-os-shell-v1.19.0'; +const CACHE = 'life-os-shell-v1.20.0'; const SHELL = [ '/', '/index.html', '/manifest.webmanifest', '/life-os-icon.svg', '/local-db-worker.js', '/sqlite3.mjs', '/sqlite3.wasm' diff --git a/public/system-navigation.js b/public/system-navigation.js index 36db6c9..39989b1 100644 --- a/public/system-navigation.js +++ b/public/system-navigation.js @@ -27,7 +27,7 @@ shell.innerHTML = `
${t('settings')}

${t(active)}

${active === 'home' ? `

${t('homeHint')}

` : ''}
`; const view = shell.querySelector('.system-settings-view'); if (active === 'home') { - view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.19.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; + view.innerHTML = `
${t('device')}

${t('deviceHint')}

${t('version', { version: window.LifeOSVersion || '1.20.0' })}
${t('quickSettings')}
${['appearance', 'notifications', 'language', 'data'].map(id => `
${navigationButton(id, true)}

${t(`${id}Hint`)}

`).join('')}
`; } else { const group = document.createElement('div'); group.className = 'settings system-settings-group'; diff --git a/public/terminal-app.js b/public/terminal-app.js index b4af90e..b3cc913 100644 --- a/public/terminal-app.js +++ b/public/terminal-app.js @@ -150,7 +150,7 @@ return { message: new Intl.DateTimeFormat(LifeI18n.locale(), options).format(new Date()) }; } if (kind === 'uptime') { if (verb) throw new Error('usage'); const seconds = Math.floor((Date.now() - startedAt) / 1000); return { message: t('uptime', { minutes: Math.floor(seconds / 60), seconds: seconds % 60 }) }; } - if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.19.0'}` }; } + if (kind === 'version') { if (verb) throw new Error('usage'); return { message: `Life OS v${window.LifeOSVersion || '1.20.0'}` }; } if (kind === 'status') { if (verb) throw new Error('usage'); const data = board(); return { message: t('status', { memories: mems().length, goals: data.goals.length, tasks: data.tasks.length }) }; } if (kind === 'apps') { if (verb) throw new Error('usage'); return { message: Object.keys(APPS).map(id => `${id} — ${LifeI18n.t(`app.${id}`)}`).join('\n') }; } if (kind === 'history') { if (verb) throw new Error('usage'); return { message: history.slice(-20).map((entry,index) => `${index + 1}. ${entry}`).join('\n') || t('empty') }; } @@ -235,7 +235,7 @@ }; window.terminalApp = node => { if (node.querySelector('.terminal-shell') && node.dataset.terminalLocale === lang()) { output(node); return; } - if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.19.0' }), kind: 'system' }); welcomed = true; } + if (!welcomed) { lines.unshift({ value: t('welcome', { version: window.LifeOSVersion || '1.20.0' }), kind: 'system' }); welcomed = true; } node.dataset.terminalLocale = lang(); node.innerHTML = `
Life OS / ${t('title')}${t('hint')}
`; output(node); composer(node, Boolean(compose)); diff --git a/scripts/build.mjs b/scripts/build.mjs index ea53e8b..32a34a2 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -7,13 +7,13 @@ const meta = new URL("../dist/.openai/", import.meta.url); await rm(dist, { recursive: true, force: true }); await Promise.all([mkdir(server, { recursive: true }), mkdir(meta, { recursive: true })]); -const [rawIndexHtml, addonsJs, bootGuardJs, localDbJs, localDbWorkerJs, sqliteModuleJs, sqliteWasm, i18nJs, tasksJs, calendarJs, notificationsJs, i18nRenderersJs, desktopPersonalizationJs, desktopWidgetsJs, systemNavigationJs, browserAppJs, dataActionsJs, terminalAppJs, dbAdminJs, manifest, serviceWorker, icon, localeEn, localeZh] = await Promise.all([ - text("index.html"), text("addons.js"), text("boot-guard.js"), text("local-db.js"), text("local-db-worker.js"), +const [rawIndexHtml, addonsJs, backupJs, bootGuardJs, localDbJs, localDbWorkerJs, sqliteModuleJs, sqliteWasm, i18nJs, tasksJs, calendarJs, notificationsJs, i18nRenderersJs, desktopPersonalizationJs, desktopWidgetsJs, systemNavigationJs, browserAppJs, dataActionsJs, terminalAppJs, dbAdminJs, manifest, serviceWorker, icon, localeEn, localeZh] = await Promise.all([ + text("index.html"), text("addons.js"), text("backup.js"), text("boot-guard.js"), text("local-db.js"), text("local-db-worker.js"), readFile(new URL("../node_modules/@sqlite.org/sqlite-wasm/dist/index.mjs", import.meta.url), "utf8"), readFile(new URL("../node_modules/@sqlite.org/sqlite-wasm/dist/sqlite3.wasm", import.meta.url)), text("i18n.js"), text("tasks.js"), text("calendar.js"), text("notifications.js"), text("i18n-renderers.js"), text("desktop-personalization.js"), text("desktop-widgets.js"), text("system-navigation.js"), text("browser-app.js"), text("data-actions.js"), text("terminal-app.js"), text("db-admin.js"), text("manifest.webmanifest"), text("service-worker.js"), text("life-os-icon.svg"), readFile(new URL("../public/locales/en.json", import.meta.url), "utf8"), readFile(new URL("../public/locales/zh-CN.json", import.meta.url), "utf8") ]); -const release = "1.19.0"; +const release = "1.20.0"; const localeEnJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales.en=${localeEn};`; const localeZhJs = `window.LifeOSLocales=window.LifeOSLocales||{};window.LifeOSLocales['zh-CN']=${localeZh};`; const extraLocaleCodes = ['zh-HK', 'zh-MO', 'zh-TW', 'ar', 'fr', 'ru', 'es', 'ja']; @@ -24,13 +24,13 @@ let indexHtml = rawIndexHtml.replace('src="addons.js"', `src="addons.js?v=${rele for (const [src, code] of [ ['boot-guard.js', bootGuardJs], ['local-db.js', localDbJs], ['locales/en.js', localeEnJs], ['locales/zh-CN.js', localeZhJs], ...extraLocaleCodes.map(code => [`locales/${code}.js`, localeScripts[code]]), ['i18n.js', i18nJs], ['tasks.js', tasksJs], ['calendar.js', calendarJs], - ['addons.js', addonsJs], ['notifications.js', notificationsJs], ['i18n-renderers.js', i18nRenderersJs], ['desktop-personalization.js', desktopPersonalizationJs], ['desktop-widgets.js', desktopWidgetsJs], ['system-navigation.js', systemNavigationJs], ['browser-app.js', browserAppJs], ['data-actions.js', dataActionsJs], ['terminal-app.js', terminalAppJs], ['db-admin.js', dbAdminJs] + ['addons.js', addonsJs], ['notifications.js', notificationsJs], ['i18n-renderers.js', i18nRenderersJs], ['backup.js', backupJs], ['desktop-personalization.js', desktopPersonalizationJs], ['desktop-widgets.js', desktopWidgetsJs], ['system-navigation.js', systemNavigationJs], ['browser-app.js', browserAppJs], ['data-actions.js', dataActionsJs], ['terminal-app.js', terminalAppJs], ['db-admin.js', dbAdminJs] ]) { const tag = ``; if (!indexHtml.includes(tag)) throw new Error(`Missing Life OS script: ${src}`); indexHtml = indexHtml.replace(tag, ``); } -await writeFile(new URL("assets.js", server), `export const indexHtml=${JSON.stringify(indexHtml)};\nexport const addonsJs=${JSON.stringify(addonsJs)};\nexport const bootGuardJs=${JSON.stringify(bootGuardJs)};\nexport const i18nJs=${JSON.stringify(i18nJs)};\nexport const localeEn=JSON.parse(${JSON.stringify(localeEn)});\nexport const localeZh=JSON.parse(${JSON.stringify(localeZh)});\nexport const localeEnJs=${JSON.stringify(localeEnJs)};\nexport const localeZhJs=${JSON.stringify(localeZhJs)};\nexport const localeScripts=${JSON.stringify(localeScripts)};\nexport const localeData=${JSON.stringify(localeData)};\nexport const tasksJs=${JSON.stringify(tasksJs)};\nexport const calendarJs=${JSON.stringify(calendarJs)};\nexport const notificationsJs=${JSON.stringify(notificationsJs)};\nexport const i18nRenderersJs=${JSON.stringify(i18nRenderersJs)};\nexport const desktopPersonalizationJs=${JSON.stringify(desktopPersonalizationJs)};\nexport const desktopWidgetsJs=${JSON.stringify(desktopWidgetsJs)};\nexport const systemNavigationJs=${JSON.stringify(systemNavigationJs)};\nexport const browserAppJs=${JSON.stringify(browserAppJs)};\nexport const dataActionsJs=${JSON.stringify(dataActionsJs)};\nexport const terminalAppJs=${JSON.stringify(terminalAppJs)};\nexport const dbAdminJs=${JSON.stringify(dbAdminJs)};\nexport const manifest=${JSON.stringify(manifest)};\nexport const serviceWorker=${JSON.stringify(serviceWorker)};\nexport const icon=${JSON.stringify(icon)};\n`); +await writeFile(new URL("assets.js", server), `export const indexHtml=${JSON.stringify(indexHtml)};\nexport const addonsJs=${JSON.stringify(addonsJs)};\nexport const backupJs=${JSON.stringify(backupJs)};\nexport const bootGuardJs=${JSON.stringify(bootGuardJs)};\nexport const i18nJs=${JSON.stringify(i18nJs)};\nexport const localeEn=JSON.parse(${JSON.stringify(localeEn)});\nexport const localeZh=JSON.parse(${JSON.stringify(localeZh)});\nexport const localeEnJs=${JSON.stringify(localeEnJs)};\nexport const localeZhJs=${JSON.stringify(localeZhJs)};\nexport const localeScripts=${JSON.stringify(localeScripts)};\nexport const localeData=${JSON.stringify(localeData)};\nexport const tasksJs=${JSON.stringify(tasksJs)};\nexport const calendarJs=${JSON.stringify(calendarJs)};\nexport const notificationsJs=${JSON.stringify(notificationsJs)};\nexport const i18nRenderersJs=${JSON.stringify(i18nRenderersJs)};\nexport const desktopPersonalizationJs=${JSON.stringify(desktopPersonalizationJs)};\nexport const desktopWidgetsJs=${JSON.stringify(desktopWidgetsJs)};\nexport const systemNavigationJs=${JSON.stringify(systemNavigationJs)};\nexport const browserAppJs=${JSON.stringify(browserAppJs)};\nexport const dataActionsJs=${JSON.stringify(dataActionsJs)};\nexport const terminalAppJs=${JSON.stringify(terminalAppJs)};\nexport const dbAdminJs=${JSON.stringify(dbAdminJs)};\nexport const manifest=${JSON.stringify(manifest)};\nexport const serviceWorker=${JSON.stringify(serviceWorker)};\nexport const icon=${JSON.stringify(icon)};\n`); await writeFile(new URL("local-assets.js", server), `export const localDbWorkerJs=${JSON.stringify(localDbWorkerJs)};\nexport const sqliteModuleJs=${JSON.stringify(sqliteModuleJs)};\nexport const sqliteWasmBase64=${JSON.stringify(sqliteWasm.toString('base64'))};\n`); await copyFile(new URL("../worker/index.js", import.meta.url), new URL("index.js", server)); await copyFile(new URL("../worker/cloud-state.js", import.meta.url), new URL("cloud-state.js", server)); diff --git a/scripts/validate.mjs b/scripts/validate.mjs index c64d8a6..08af939 100644 --- a/scripts/validate.mjs +++ b/scripts/validate.mjs @@ -5,10 +5,13 @@ const worker = await import(new URL("../dist/server/index.js", import.meta.url)) assert.equal(typeof worker.default?.fetch, "function"); const assets = await import(new URL("../dist/server/assets.js", import.meta.url)); const source = await readFile(new URL("../public/index.html", import.meta.url), "utf8"); -assert.match(assets.indexHtml, /!\[1,2\]\.includes\(d\.schemaVersion\)/); +assert.match(assets.indexHtml, /!\[1,2,3\]\.includes\(d\.schemaVersion\)/); assert.doesNotMatch(assets.indexHtml, /localizeDynamicText|createTreeWalker|NodeFilter\.SHOW_TEXT|const ZH=/); assert.match(assets.indexHtml, /window\.LifeOSLocales\.en=/); assert.match(assets.addonsJs, /window\.exportData = exportData/); +assert.match(assets.backupJs, /schemaVersion: BACKUP_SCHEMA/); +assert.match(assets.backupJs, /checksum: \{ algorithm: 'SHA-256'/); +assert.match(assets.backupJs, /life-os-before-restore/); assert.match(assets.addonsJs, /schemaVersion: 2/); assert.match(assets.addonsJs, /settings: settings\(\), system: sys\(\)/); assert.match(assets.addonsJs, /widgetLayout/); @@ -65,14 +68,14 @@ assert.doesNotMatch(assets.indexHtml, /setTimeout\(applyLanguage\s*,/); assert.doesNotMatch(assets.addonsJs, /(?([\s\S]*?)<\/script>/g)].map(match => match[1]); -assert.equal(shippedScripts.length, 27, "the complete desktop script chain is present in the served HTML"); +assert.equal(shippedScripts.length, 28, "the complete desktop script chain is present in the served HTML"); assert.match(assets.indexHtml, /LifeOSLocalDB/); assert.match(assets.indexHtml, /OPFS:\/lifeos\.sqlite/); assert.match(assets.serviceWorker, /sqlite3\.wasm/); assert.doesNotMatch(assets.indexHtml, / 8); assert.ok(command('time').message.includes(':')); assert.ok(command('datetime').message.length > 12); assert.equal(command('uptime').message, 'terminal.uptime'); -assert.equal(command('version').message, 'Life OS v1.19.0'); +assert.equal(command('version').message, 'Life OS v1.20.0'); assert.equal(command('status').message, 'terminal.status'); assert.match(command('apps').message, /calendar/); assert.equal(command('echo "hello Life OS"').message, 'hello Life OS'); @@ -293,6 +296,29 @@ const makeStorage = initial => { const values = new Map(Object.entries(initial || {})); return { getItem: key => values.get(key) ?? null, setItem: (key,value) => values.set(key,String(value)), values }; }; +const backupStorage = makeStorage({ + lifeos_memories: '[]', lifeos_museum: '[]', lifeos_profile: '{}', lifeos_settings: '{}', lifeos_system: '{"schemaVersion":2}', + lifeos_notifications_v1: '{"memory":{"enabled":true}}', lifeos_storage_mode_v1: 'local', lifeos_cloud_baseline_v3: '{"internal":true}' +}); +Object.defineProperties(backupStorage, { length: { get: () => backupStorage.values.size } }); +backupStorage.key = index => [...backupStorage.values.keys()][index] ?? null; +backupStorage.removeItem = key => backupStorage.values.delete(key); +const backupContext = vm.createContext({ + localStorage: backupStorage, crypto: globalThis.crypto, TextEncoder, Blob, URL, + document: { createElement: () => ({ click() {} }), querySelector: () => ({ innerHTML: '' }) }, + settings: () => ({}), save: (key, value) => backupStorage.setItem(key, JSON.stringify(value)), + applyImport() {}, importData: null, setTimeout() {} +}); +backupContext.window = backupContext; +vm.runInContext(assets.backupJs, backupContext); +const portableBackup = await backupContext.LifeOSBackup.create(); +assert.equal(portableBackup.schemaVersion, 3); +assert.equal(portableBackup.records.lifeos_notifications_v1, '{"memory":{"enabled":true}}'); +assert.equal(portableBackup.records.lifeos_storage_mode_v1, undefined, 'device storage choice does not migrate'); +assert.equal(portableBackup.records.lifeos_cloud_baseline_v3, undefined, 'cloud internals do not migrate'); +assert.equal(await backupContext.LifeOSBackup.validate(portableBackup), true); +portableBackup.records.lifeos_notifications_v1 = '{}'; +assert.equal(await backupContext.LifeOSBackup.validate(portableBackup), false, 'checksum rejects a modified backup'); let legacySettings = { language: "auto", languageMode: "auto" }; const calls = { icons: 0, render: 0, apply: 0, toast: 0 }; const localStorage = makeStorage(); @@ -376,7 +402,7 @@ const uiContext = vm.createContext({ ...Object.fromEntries(["icons", "tasks", "launcher", "calendar", "desktop", "boot", "modal"].map(id => [id, uiNodes.get(`#${id}`)])) }); uiContext.window = uiContext; -for (const index of [0, ...Array.from({ length: 10 }, (_, i) => i + 3), 13, 14, 19, 20]) vm.runInContext(shippedScripts[index], uiContext); +for (const index of [0, ...Array.from({ length: 10 }, (_, i) => i + 3), 13, 14, 19, 21]) vm.runInContext(shippedScripts[index], uiContext); vm.runInContext("windows.system={classList:{contains(){return false}}}", uiContext); uiContext.setLanguage("zh"); assert.equal(uiContext.LifeI18n.language(), "zh-CN");