@tacoshell/shell 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/README.md +6 -2
- package/package.json +40 -4
- package/src/background.ts +41 -0
- package/src/core/bus.ts +186 -0
- package/src/core/cards.ts +33 -0
- package/src/core/cron.ts +63 -0
- package/src/core/cronfriendly.ts +70 -0
- package/src/core/csv.ts +36 -0
- package/src/core/datasets.ts +276 -0
- package/src/core/domshot.ts +81 -0
- package/src/core/guards.ts +36 -0
- package/src/core/hosts.ts +15 -0
- package/src/core/hotkeys.ts +44 -0
- package/src/core/localdata.ts +88 -0
- package/src/core/log.ts +91 -0
- package/src/core/markdown.ts +57 -0
- package/src/core/nav.ts +102 -0
- package/src/core/notifyrules.ts +31 -0
- package/src/core/page.ts +81 -0
- package/src/core/prefs.ts +114 -0
- package/src/core/router.ts +78 -0
- package/src/core/search.ts +65 -0
- package/src/core/services.ts +161 -0
- package/src/core/sessions.ts +72 -0
- package/src/core/startpage.ts +28 -0
- package/src/core/storage.ts +54 -0
- package/src/core/systemtools.ts +85 -0
- package/src/core/tabfit.ts +30 -0
- package/src/core/templates.ts +48 -0
- package/src/core/toasts.ts +13 -0
- package/src/core/vault.ts +208 -0
- package/src/env.d.ts +2 -0
- package/src/index.ts +56 -0
- package/src/styles.css +288 -0
- package/src/types.ts +113 -0
- package/src/ui/App.tsx +229 -0
- package/src/ui/ClearableInput.tsx +23 -0
- package/src/ui/Icon.tsx +8 -0
- package/src/ui/Markdown.tsx +24 -0
- package/src/ui/Rail.tsx +89 -0
- package/src/ui/Search.tsx +111 -0
- package/src/ui/Sessions.tsx +72 -0
- package/src/ui/SidePanel.tsx +148 -0
- package/src/ui/TabBar.tsx +56 -0
- package/src/ui/ViewHost.tsx +122 -0
- package/src/ui/hooks.ts +21 -0
- package/src/ui/settings/Datasets.tsx +162 -0
- package/src/ui/settings/ReleaseNotes.tsx +19 -0
- package/src/ui/settings/ScheduleEditor.tsx +57 -0
- package/src/ui/settings/Settings.tsx +328 -0
- package/src/ui/settings/Templates.tsx +52 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Datasets (ADR-043; from CommunityOS v2 ADR-028/029/033/067). A dataset is declared by a module:
|
|
2
|
+
// "datasets": { "greeters": { "label": "…", "kind": "importOnly", "key": "slug", "schema": { "slug": "string", "joined": "date" }, "instructions": "docs/…md" } }
|
|
3
|
+
// kind importOnly = CSV import only; refreshable = a module routine produces the rows (CSV import still works). Rows are stored ONLY in the vault
|
|
4
|
+
// (one encrypted, gzipped blob per dataset), typed on read from the schema, cached in memory while unlocked, and dropped from memory on lock.
|
|
5
|
+
|
|
6
|
+
import type { Framework, Routine } from '@tacoshell/sdk';
|
|
7
|
+
import type { Registry, RegistryDataset } from '../types.ts';
|
|
8
|
+
import { parseCsv, stringifyCsv } from './csv.ts';
|
|
9
|
+
import * as log from './log.ts';
|
|
10
|
+
import { cronNext, isValidCron } from './cron.ts';
|
|
11
|
+
import { describeCron } from './cronfriendly.ts';
|
|
12
|
+
import { createStore } from './prefs.ts';
|
|
13
|
+
import * as store from './storage.ts';
|
|
14
|
+
import * as vault from './vault.ts';
|
|
15
|
+
|
|
16
|
+
export type Row = Record<string, unknown>;
|
|
17
|
+
export interface DatasetState { rows: number; columns: string[]; updatedAt?: string; source?: 'csv' | 'routine' | 'set'; durations: number[]; refreshing?: boolean; lastError?: string;
|
|
18
|
+
/** The user's schedule (Settings → Datasets → Schedule); wins over the developer's default in the manifest. `cron: null` = manual only. */
|
|
19
|
+
schedule?: { cron: string | null }; scheduleSetAt?: number; lastAttemptAt?: number }
|
|
20
|
+
|
|
21
|
+
const META_KEY = 'taco.datasets';
|
|
22
|
+
let registry: Registry | undefined;
|
|
23
|
+
let routines: Record<string, Routine> = {};
|
|
24
|
+
export const states = createStore<Record<string, DatasetState>>({});
|
|
25
|
+
const cache = new Map<string, Row[]>();
|
|
26
|
+
let changed: (d: RegistryDataset) => void = () => {};
|
|
27
|
+
/** The bus publishes each dataset's `changed` event; set by the bus to avoid an import cycle. */
|
|
28
|
+
export const onChanged = (fn: typeof changed) => { changed = fn; };
|
|
29
|
+
|
|
30
|
+
export const idOf = (d: { module: string; name: string }) => `${d.module}/${d.name}`;
|
|
31
|
+
export const list = () => registry?.datasets ?? [];
|
|
32
|
+
export const find = (module: string, name: string) => list().find((d) => d.module === module && d.name === name);
|
|
33
|
+
export const stateOf = (d: RegistryDataset): DatasetState => states.get()[idOf(d)] ?? { rows: 0, columns: [], durations: [] };
|
|
34
|
+
export const hasRoutine = (d: RegistryDataset) => !!routines[idOf(d)];
|
|
35
|
+
|
|
36
|
+
export async function init(reg: Registry, rs: Record<string, Routine>) {
|
|
37
|
+
registry = reg;
|
|
38
|
+
routines = rs;
|
|
39
|
+
states.set((await store.get<Record<string, DatasetState>>('local', META_KEY)) ?? {});
|
|
40
|
+
// Decrypted rows never outlive an unlock (v2 ADR-033).
|
|
41
|
+
vault.subscribe((s) => { if (s !== 'unlocked') cache.clear(); });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function setState(d: RegistryDataset, patch: Partial<DatasetState>) {
|
|
45
|
+
const next = { ...states.get(), [idOf(d)]: { ...stateOf(d), ...patch } };
|
|
46
|
+
states.set(next);
|
|
47
|
+
await store.set('local', META_KEY, next);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class LockedError extends Error { constructor() { super('The vault is locked: datasets are only readable while it is unlocked.'); } }
|
|
51
|
+
|
|
52
|
+
// ── Types on read (v2 ADR-029): string · integer · number · boolean · date · timestamp · list · json; "#N/A" and "" → null ──────
|
|
53
|
+
export function typedValue(type: string | undefined, v: unknown): unknown {
|
|
54
|
+
if (v === null || v === undefined) return null;
|
|
55
|
+
if (typeof v !== 'string') return v;
|
|
56
|
+
const s = v.trim();
|
|
57
|
+
if (s === '' || s === '#N/A') return null;
|
|
58
|
+
switch ((type ?? 'string').replace(/\?$/, '')) {
|
|
59
|
+
case 'integer': { const n = Number.parseInt(s.replace(/,/g, ''), 10); return Number.isFinite(n) ? n : null; }
|
|
60
|
+
case 'number': { const n = Number(s.replace(/,/g, '')); return Number.isFinite(n) ? n : null; }
|
|
61
|
+
case 'boolean': return /^(true|yes|y|1)$/i.test(s) ? true : /^(false|no|n|0)$/i.test(s) ? false : null;
|
|
62
|
+
case 'date': { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s); if (m) return `${m[1]}-${m[2]}-${m[3]}`; const t = new Date(s); return Number.isNaN(t.getTime()) ? null : t.toISOString().slice(0, 10); }
|
|
63
|
+
case 'timestamp': { const t = new Date(s); return Number.isNaN(t.getTime()) ? null : t.toISOString(); }
|
|
64
|
+
case 'list': { if (s.startsWith('[')) { try { return JSON.parse(s); } catch { /* fall through */ } } return s.split(/[;|]/).map((x) => x.trim()).filter(Boolean); }
|
|
65
|
+
case 'json': try { return JSON.parse(s); } catch { return null; }
|
|
66
|
+
default: return v;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const typedRow = (d: RegistryDataset, raw: Row): Row => Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, typedValue(d.schema?.[k], v)]));
|
|
70
|
+
|
|
71
|
+
export async function rows(d: RegistryDataset): Promise<Row[]> {
|
|
72
|
+
if (vault.status() !== 'unlocked') throw new LockedError();
|
|
73
|
+
const id = idOf(d);
|
|
74
|
+
if (cache.has(id)) return cache.get(id)!;
|
|
75
|
+
const text = await vault.getData(`dataset/${id}`);
|
|
76
|
+
const out = text ? (JSON.parse(text) as Row[]) : [];
|
|
77
|
+
cache.set(id, out);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Stores a full set of rows. The old data stays readable until the new rows are stored (v2's swap lock: only this step swaps). */
|
|
82
|
+
async function write(d: RegistryDataset, next: Row[], source: DatasetState['source'], columns?: string[]) {
|
|
83
|
+
await vault.putData(`dataset/${idOf(d)}`, JSON.stringify(next));
|
|
84
|
+
cache.set(idOf(d), next);
|
|
85
|
+
await setState(d, { rows: next.length, columns: columns ?? Object.keys(d.schema ?? next[0] ?? {}), updatedAt: new Date().toISOString(), source, lastError: undefined });
|
|
86
|
+
changed(d);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface CsvAnalysis {
|
|
90
|
+
/** Data rows in the file (before duplicate keys are merged). */
|
|
91
|
+
fileRows: number;
|
|
92
|
+
/** Rows that would be stored. */
|
|
93
|
+
rows: Row[];
|
|
94
|
+
columns: string[];
|
|
95
|
+
missing: string[];
|
|
96
|
+
extra: string[];
|
|
97
|
+
/** Rows whose key repeated an earlier one (the last wins). */
|
|
98
|
+
dupes: number;
|
|
99
|
+
/** Rows with an empty key value. */
|
|
100
|
+
emptyKeys: number;
|
|
101
|
+
warnings: string[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Reads a CSV against the dataset's schema without storing anything: what an import would do. Throws when the file can't be imported at all. */
|
|
105
|
+
export function analyzeCsv(d: RegistryDataset, text: string): CsvAnalysis {
|
|
106
|
+
const table = parseCsv(text);
|
|
107
|
+
if (!table.length) throw new Error('The file is empty.');
|
|
108
|
+
const header = table[0].map((h) => h.trim());
|
|
109
|
+
const warnings: string[] = [];
|
|
110
|
+
const declared = Object.keys(d.schema ?? {});
|
|
111
|
+
const missing = declared.filter((c) => !header.includes(c));
|
|
112
|
+
const extra = declared.length ? header.filter((c) => !declared.includes(c)) : [];
|
|
113
|
+
if (d.key && !header.includes(d.key)) throw new Error(`The CSV has no "${d.key}" column (this dataset's key).`);
|
|
114
|
+
if (missing.length) warnings.push(`Missing column(s): ${missing.join(', ')} (left empty).`);
|
|
115
|
+
if (extra.length) warnings.push(`Column(s) not in the schema were imported as text: ${extra.join(', ')}.`);
|
|
116
|
+
const fileRows = table.length - 1;
|
|
117
|
+
let out = table.slice(1).map((cells) => typedRow(d, Object.fromEntries(header.map((h, i) => [h, cells[i] ?? '']))));
|
|
118
|
+
let dupes = 0, emptyKeys = 0;
|
|
119
|
+
if (d.key) {
|
|
120
|
+
const byKey = new Map<unknown, Row>();
|
|
121
|
+
for (const r of out) { if (r[d.key] == null || r[d.key] === '') emptyKeys++; if (byKey.has(r[d.key])) dupes++; byKey.set(r[d.key], r); }
|
|
122
|
+
if (dupes) warnings.push(`${dupes} row(s) repeated a "${d.key}"; the last one was kept.`);
|
|
123
|
+
out = [...byKey.values()];
|
|
124
|
+
}
|
|
125
|
+
return { fileRows, rows: out, columns: [...new Set([...declared, ...header])], missing, extra, dupes, emptyKeys, warnings };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** CSV import replaces every row (a Full Load). Returns warnings (unknown/missing columns, duplicate keys). */
|
|
129
|
+
export async function importCsv(d: RegistryDataset, text: string): Promise<{ rows: number; warnings: string[] }> {
|
|
130
|
+
const a = analyzeCsv(d, text);
|
|
131
|
+
await write(d, a.rows, 'csv', a.columns);
|
|
132
|
+
log.add('info', `Imported ${a.rows.length} row(s) into ${d.label} from CSV`, a.warnings.length ? { warnings: a.warnings } : undefined, 'Datasets');
|
|
133
|
+
return { rows: a.rows.length, warnings: a.warnings };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function exportCsv(d: RegistryDataset): Promise<string> {
|
|
137
|
+
const r = await rows(d);
|
|
138
|
+
return stringifyCsv(stateOf(d).columns.length ? stateOf(d).columns : Object.keys(d.schema ?? r[0] ?? {}), r);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function clear(d: RegistryDataset) {
|
|
142
|
+
await vault.removeData(`dataset/${idOf(d)}`);
|
|
143
|
+
cache.delete(idOf(d));
|
|
144
|
+
await setState(d, { rows: 0, updatedAt: undefined, source: undefined });
|
|
145
|
+
changed(d);
|
|
146
|
+
log.add('info', `Cleared ${d.label}`, undefined, 'Datasets');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Refreshable datasets: runs the module's routine (a Full Load) and records how long it took; the estimate is the average of the last 3. */
|
|
150
|
+
export async function refresh(d: RegistryDataset, framework: Framework): Promise<number> {
|
|
151
|
+
const routine = routines[idOf(d)];
|
|
152
|
+
if (d.kind !== 'refreshable' || !routine) throw new Error(`${d.label} is import-only: import a CSV in Settings → Datasets.`);
|
|
153
|
+
if (stateOf(d).refreshing) throw new Error(`${d.label} is already refreshing.`);
|
|
154
|
+
const started = Date.now();
|
|
155
|
+
await setState(d, { refreshing: true, lastAttemptAt: started });
|
|
156
|
+
const dlog = log.logger(`Datasets › ${d.label}`);
|
|
157
|
+
try {
|
|
158
|
+
const result = await routine.run({ framework, log: dlog, previous: { rows: stateOf(d).rows, updatedAt: stateOf(d).updatedAt } });
|
|
159
|
+
const next = result.rows.map((r) => typedRow(d, r));
|
|
160
|
+
await write(d, next, 'routine', result.columns);
|
|
161
|
+
await setState(d, { refreshing: false, durations: [...stateOf(d).durations, Date.now() - started].slice(-3) });
|
|
162
|
+
dlog.info(`Refreshed: ${next.length} row(s) in ${Math.round((Date.now() - started) / 100) / 10} s`);
|
|
163
|
+
return next.length;
|
|
164
|
+
} catch (e) {
|
|
165
|
+
await setState(d, { refreshing: false, lastError: (e as Error).message });
|
|
166
|
+
dlog.error(`Refresh failed: ${(e as Error).message}`);
|
|
167
|
+
throw e;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// ── Schedules: the developer ships a default (manifest `schedule.cron`), the user chooses when and how often ─────────────
|
|
171
|
+
/** The crontab in force: the user's saved choice (null = manual), else the developer's default, else manual. */
|
|
172
|
+
export const cronOf = (d: RegistryDataset): string | null => { const s = stateOf(d).schedule; return s ? s.cron : d.schedule?.cron ?? null; };
|
|
173
|
+
export const describeSchedule = (d: RegistryDataset) => describeCron(cronOf(d));
|
|
174
|
+
|
|
175
|
+
export async function setSchedule(d: RegistryDataset, cron: string | null) {
|
|
176
|
+
if (cron && !isValidCron(cron)) throw new Error(`"${cron}" isn't a valid crontab.`);
|
|
177
|
+
await setState(d, { schedule: { cron }, scheduleSetAt: Date.now() });
|
|
178
|
+
log.add('info', `${d.label} schedule: ${describeCron(cron)}`, cron ? { cron } : undefined, 'Datasets');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The next time the dataset is due (ms), counted from its last attempt or from when its schedule was first seen; null for manual. */
|
|
182
|
+
export function nextDue(d: RegistryDataset): number | null {
|
|
183
|
+
const cron = cronOf(d), st = stateOf(d), base = Math.max(st.lastAttemptAt ?? 0, st.scheduleSetAt ?? 0);
|
|
184
|
+
if (!cron || !base || !isValidCron(cron)) return null;
|
|
185
|
+
return cronNext(cron, base);
|
|
186
|
+
}
|
|
187
|
+
export const isDue = (d: RegistryDataset, now = Date.now()) => { const n = nextDue(d); return n !== null && n <= now; };
|
|
188
|
+
|
|
189
|
+
/** Up to date for its schedule? { scheduled: false } when manual; else ok = no scheduled time has passed since the last update (refresh or import). */
|
|
190
|
+
export function compliance(d: RegistryDataset, now = Date.now()): { scheduled: boolean; ok: boolean } {
|
|
191
|
+
const cron = cronOf(d), at = stateOf(d).updatedAt ? new Date(stateOf(d).updatedAt!).getTime() : 0;
|
|
192
|
+
if (!cron || !isValidCron(cron)) return { scheduled: false, ok: true };
|
|
193
|
+
if (!at) return { scheduled: true, ok: false };
|
|
194
|
+
const next = cronNext(cron, at);
|
|
195
|
+
return { scheduled: true, ok: next === null || next > now };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Runs due refreshable datasets by themselves, one at a time, the longest-delayed first. Only while the app is open and the vault is unlocked
|
|
200
|
+
* (a slot missed while locked runs once it is unlocked). A manual "Refresh now" is never held back by this.
|
|
201
|
+
*/
|
|
202
|
+
export function startScheduler(framework: (module: string) => Framework, everyMs = 30_000): () => void {
|
|
203
|
+
let running = false;
|
|
204
|
+
const tick = async () => {
|
|
205
|
+
if (running || vault.status() !== 'unlocked') return;
|
|
206
|
+
// A schedule counts from when it was first seen, so a never-refreshed dataset waits for its first slot instead of running at once.
|
|
207
|
+
for (const d of list()) if (d.kind === 'refreshable' && !stateOf(d).scheduleSetAt && cronOf(d)) await setState(d, { scheduleSetAt: Date.now() });
|
|
208
|
+
const due = list().filter((d) => d.kind === 'refreshable' && hasRoutine(d) && !stateOf(d).refreshing && isDue(d))
|
|
209
|
+
.sort((a, b) => (nextDue(a) ?? 0) - (nextDue(b) ?? 0));
|
|
210
|
+
if (!due.length) return;
|
|
211
|
+
running = true;
|
|
212
|
+
try {
|
|
213
|
+
for (const d of due) {
|
|
214
|
+
if (vault.status() !== 'unlocked') break;
|
|
215
|
+
log.add('info', `Scheduled refresh of ${d.label} (${describeSchedule(d)})`, undefined, 'Datasets');
|
|
216
|
+
try { await refresh(d, framework(d.module)); } catch { /* refresh() already logged the failure and kept the old rows */ }
|
|
217
|
+
}
|
|
218
|
+
} finally { running = false; }
|
|
219
|
+
};
|
|
220
|
+
const timer = setInterval(() => void tick(), everyMs);
|
|
221
|
+
const off = vault.subscribe((s) => { if (s === 'unlocked') void tick(); });
|
|
222
|
+
void tick();
|
|
223
|
+
return () => { clearInterval(timer); off(); };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export const estimateMs = (d: RegistryDataset) => { const ds = stateOf(d).durations; return ds.length ? ds.reduce((a, b) => a + b, 0) / ds.length : undefined; };
|
|
227
|
+
|
|
228
|
+
// ── Standard topics (ADR-026): query · get · set · delete · meta ─────────────────────────────────────────────────────
|
|
229
|
+
export interface Query { filters?: Record<string, unknown>; sort?: string[]; limit?: number }
|
|
230
|
+
|
|
231
|
+
function matches(v: unknown, cond: unknown): boolean {
|
|
232
|
+
if (cond && typeof cond === 'object' && !Array.isArray(cond)) {
|
|
233
|
+
const c = cond as Record<string, unknown>;
|
|
234
|
+
if ('contains' in c && !String(v ?? '').toLowerCase().includes(String(c.contains).toLowerCase())) return false;
|
|
235
|
+
if ('in' in c && !(c.in as unknown[]).includes(v)) return false;
|
|
236
|
+
if ('gt' in c && !((v as number) > (c.gt as number))) return false;
|
|
237
|
+
if ('gte' in c && !((v as number) >= (c.gte as number))) return false;
|
|
238
|
+
if ('lt' in c && !((v as number) < (c.lt as number))) return false;
|
|
239
|
+
if ('lte' in c && !((v as number) <= (c.lte as number))) return false;
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
return v === cond;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** filters: { col: value } (equal) or { col: { contains | in | gt | gte | lt | lte } }; sort: ["col", "-col"]; limit. */
|
|
246
|
+
export function query(all: Row[], q: Query = {}): Row[] {
|
|
247
|
+
let out = all.filter((r) => Object.entries(q.filters ?? {}).every(([k, cond]) => matches(r[k], cond)));
|
|
248
|
+
for (const s of [...(q.sort ?? [])].reverse()) {
|
|
249
|
+
const desc = s.startsWith('-'), k = desc ? s.slice(1) : s;
|
|
250
|
+
out = [...out].sort((a, b) => { const x = a[k] as never, y = b[k] as never; const c = x == null ? 1 : y == null ? -1 : x < y ? -1 : x > y ? 1 : 0; return desc ? -c : c; });
|
|
251
|
+
}
|
|
252
|
+
return q.limit ? out.slice(0, q.limit) : out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export const getById = (all: Row[], d: RegistryDataset, id: unknown) => (d.key ? all.find((r) => r[d.key!] === id) ?? null : null);
|
|
256
|
+
|
|
257
|
+
export async function upsert(d: RegistryDataset, incoming: Row[]): Promise<number> {
|
|
258
|
+
if (!d.key) throw new Error(`${d.label} has no key, so rows can't be set one by one.`);
|
|
259
|
+
const byKey = new Map((await rows(d)).map((r) => [r[d.key!], r]));
|
|
260
|
+
for (const r of incoming.map((x) => typedRow(d, x))) byKey.set(r[d.key], { ...(byKey.get(r[d.key]) ?? {}), ...r });
|
|
261
|
+
await write(d, [...byKey.values()], 'set', stateOf(d).columns.length ? stateOf(d).columns : undefined);
|
|
262
|
+
return incoming.length;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export async function remove(d: RegistryDataset, ids: unknown[]): Promise<number> {
|
|
266
|
+
if (!d.key) throw new Error(`${d.label} has no key, so rows can't be deleted one by one.`);
|
|
267
|
+
const all = await rows(d);
|
|
268
|
+
const keep = all.filter((r) => !ids.includes(r[d.key!]));
|
|
269
|
+
await write(d, keep, 'set', stateOf(d).columns);
|
|
270
|
+
return all.length - keep.length;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export const meta = (d: RegistryDataset) => {
|
|
274
|
+
const st = stateOf(d);
|
|
275
|
+
return { rows: st.rows, key: d.key, kind: d.kind, lastRefreshed: st.updatedAt, source: st.source, schema: d.schema, columns: st.columns, estimateMs: estimateMs(d), schedule: describeSchedule(d), nextRefresh: nextDue(d) ? new Date(nextDue(d)!).toISOString() : undefined };
|
|
276
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// A picture of a DOM block without a library (ADR-045; ported from CommunityOS v2 lib/domshot.js): the block is cloned with every element's computed style
|
|
2
|
+
// written inline, canvases (charts) become images, the clone is wrapped in an SVG <foreignObject>, drawn onto a canvas at 2× and returned as a PNG Blob.
|
|
3
|
+
// <img> pictures (https) are fetched and embedded, because the SVG image loads nothing from the network; ::before / ::after content is not captured.
|
|
4
|
+
|
|
5
|
+
const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT']);
|
|
6
|
+
// Chrome's getComputedStyle().cssText is empty, so the style is copied property by property.
|
|
7
|
+
const styleText = (cs: CSSStyleDeclaration) => { let t = ''; for (let i = 0; i < cs.length; i++) t += `${cs[i]}:${cs.getPropertyValue(cs[i])};`; return t; };
|
|
8
|
+
|
|
9
|
+
const IMGS = new Map<string, string>(); // image URL → data: URI
|
|
10
|
+
async function inlineImages(el: Element) {
|
|
11
|
+
const urls = new Set([...el.querySelectorAll('img')].map((i) => i.currentSrc || i.src).filter((s) => /^https:/i.test(s) && !IMGS.has(s)));
|
|
12
|
+
await Promise.all([...urls].map(async (u) => {
|
|
13
|
+
try {
|
|
14
|
+
const blob = await (await fetch(u, { credentials: 'omit' })).blob();
|
|
15
|
+
IMGS.set(u, await new Promise<string>((ok, no) => { const r = new FileReader(); r.onload = () => ok(String(r.result)); r.onerror = no; r.readAsDataURL(blob); }));
|
|
16
|
+
} catch { /* host not allowed or offline: the image is left out */ }
|
|
17
|
+
}));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function clone(src: Node, skip?: (el: Element) => boolean): Node | null {
|
|
21
|
+
if (src.nodeType === Node.TEXT_NODE) return src.cloneNode(false);
|
|
22
|
+
if (!(src instanceof Element) || SKIP.has(src.tagName) || skip?.(src)) return null;
|
|
23
|
+
const cs = getComputedStyle(src);
|
|
24
|
+
if (cs.display === 'none') return null;
|
|
25
|
+
let dst: Element;
|
|
26
|
+
if (src instanceof HTMLCanvasElement) {
|
|
27
|
+
dst = document.createElement('img');
|
|
28
|
+
try { dst.setAttribute('src', src.toDataURL('image/png')); } catch { /* tainted canvas: left blank */ }
|
|
29
|
+
dst.setAttribute('width', String(src.clientWidth));
|
|
30
|
+
dst.setAttribute('height', String(src.clientHeight));
|
|
31
|
+
} else {
|
|
32
|
+
dst = src.cloneNode(false) as Element;
|
|
33
|
+
if (src instanceof HTMLImageElement) { const u = src.currentSrc || src.src; if (IMGS.has(u)) { dst.setAttribute('src', IMGS.get(u)!); dst.removeAttribute('srcset'); } }
|
|
34
|
+
if (src instanceof HTMLInputElement || src instanceof HTMLSelectElement) dst.setAttribute('value', src.value);
|
|
35
|
+
if (src instanceof HTMLTextAreaElement) dst.textContent = src.value;
|
|
36
|
+
}
|
|
37
|
+
dst.setAttribute('style', styleText(cs));
|
|
38
|
+
if (!(src instanceof HTMLCanvasElement)) for (const c of src.childNodes) { const k = clone(c, skip); if (k) dst.appendChild(k); }
|
|
39
|
+
return dst;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The first non-transparent background up the tree, so a card on the page background still looks right. */
|
|
43
|
+
function backdrop(el: Element): string {
|
|
44
|
+
for (let n: Element | null = el; n; n = n.parentElement) {
|
|
45
|
+
const c = getComputedStyle(n).backgroundColor;
|
|
46
|
+
if (c && !/rgba?\(\s*0,\s*0,\s*0,\s*0\s*\)|transparent/.test(c)) return c;
|
|
47
|
+
}
|
|
48
|
+
return getComputedStyle(document.body).backgroundColor || '#fff';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function toPng(root: HTMLElement, w: number, h: number, scale: number): Promise<Blob> {
|
|
52
|
+
root.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
|
|
53
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><foreignObject x="0" y="0" width="100%" height="100%">${new XMLSerializer().serializeToString(root)}</foreignObject></svg>`;
|
|
54
|
+
const img = new Image();
|
|
55
|
+
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
56
|
+
await img.decode();
|
|
57
|
+
const k = Math.min(scale, 16000 / Math.max(w, h)); // keep a very tall page within the browser's canvas limit
|
|
58
|
+
const canvas = Object.assign(document.createElement('canvas'), { width: Math.round(w * k), height: Math.round(h * k) });
|
|
59
|
+
const ctx = canvas.getContext('2d')!;
|
|
60
|
+
ctx.scale(k, k);
|
|
61
|
+
ctx.drawImage(img, 0, 0, w, h);
|
|
62
|
+
return new Promise((ok, no) => canvas.toBlob((b) => (b ? ok(b) : no(new Error("Couldn't make the picture"))), 'image/png'));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** PNG of `el` as it looks now. */
|
|
66
|
+
export async function blockToPng(el: Element, { scale = 2 } = {}): Promise<Blob> {
|
|
67
|
+
const r = el.getBoundingClientRect(), w = Math.ceil(r.width), h = Math.ceil(r.height);
|
|
68
|
+
await inlineImages(el);
|
|
69
|
+
const root = clone(el) as HTMLElement;
|
|
70
|
+
Object.assign(root.style, { margin: '0', width: `${w}px`, height: `${h}px`, backgroundColor: backdrop(el) });
|
|
71
|
+
return toPng(root, w, h, scale);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** PNG of a whole scrolling pane, full height (not just what is on screen); `skip(el)` leaves elements out. */
|
|
75
|
+
export async function paneToPng(pane: HTMLElement, { skip, scale = 2 }: { skip?: (el: Element) => boolean; scale?: number } = {}): Promise<Blob> {
|
|
76
|
+
const w = Math.ceil(pane.getBoundingClientRect().width), h = Math.ceil(pane.scrollHeight);
|
|
77
|
+
await inlineImages(pane);
|
|
78
|
+
const root = clone(pane, skip) as HTMLElement;
|
|
79
|
+
Object.assign(root.style, { width: `${w}px`, height: `${h}px`, overflow: 'visible', maxHeight: 'none', margin: '0', backgroundColor: backdrop(pane) });
|
|
80
|
+
return toPng(root, w, h, scale);
|
|
81
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Navigation guards (ADR-036, from v2 ADR-041). The router asks them before EVERY navigation.
|
|
2
|
+
// A blocking guard refuses (a running bulk operation can't be abandoned by accident); an unsaved guard asks Stay / Leave.
|
|
3
|
+
|
|
4
|
+
type Guard = { kind: 'block'; reason: string } | { kind: 'unsaved'; isDirty: () => boolean };
|
|
5
|
+
const guards = new Set<Guard>();
|
|
6
|
+
|
|
7
|
+
export function block(reason: string): () => void {
|
|
8
|
+
const g: Guard = { kind: 'block', reason };
|
|
9
|
+
guards.add(g);
|
|
10
|
+
return () => { guards.delete(g); };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function unsaved(isDirty: () => boolean): () => void {
|
|
14
|
+
const g: Guard = { kind: 'unsaved', isDirty };
|
|
15
|
+
guards.add(g);
|
|
16
|
+
return () => { guards.delete(g); };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type Verdict = { ok: true } | { ok: false; reason: string };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `confirm` asks the user (Stay / Leave); `refused` is told why navigation was blocked.
|
|
23
|
+
* Returns true when navigation may proceed.
|
|
24
|
+
*/
|
|
25
|
+
export function ask(confirm: (question: string) => boolean, refused: (reason: string) => void): boolean {
|
|
26
|
+
const blocking = [...guards].find((g) => g.kind === 'block') as Extract<Guard, { kind: 'block' }> | undefined;
|
|
27
|
+
if (blocking) { refused(blocking.reason); return false; }
|
|
28
|
+
const dirty = [...guards].some((g) => g.kind === 'unsaved' && g.isDirty());
|
|
29
|
+
return dirty ? confirm('You have unsaved changes on this page. Leave anyway?') : true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Guards die with the view that registered them; the shell calls this when a view unmounts. */
|
|
33
|
+
export function clearAll() { guards.clear(); }
|
|
34
|
+
|
|
35
|
+
/** For `beforeunload`: anything that should make the browser ask before closing or reloading. */
|
|
36
|
+
export const anyActive = () => [...guards].some((g) => g.kind === 'block' || g.isDirty());
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Chrome match patterns (`https://*.zendesk.com/*`) for checking that a service only calls the hosts it declared (ADR-023).
|
|
2
|
+
|
|
3
|
+
export function patternToRegExp(pattern: string): RegExp {
|
|
4
|
+
const m = /^(https):\/\/(\*|\*\.[^/*]+|[^/*]+)(\/.*)$/.exec(pattern);
|
|
5
|
+
if (!m) throw new Error(`Not a valid host pattern: ${pattern}`);
|
|
6
|
+
const [, scheme, host, path] = m;
|
|
7
|
+
const esc = (s: string) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
|
|
8
|
+
const hostRe = host === '*' ? '[^/]+' : host.startsWith('*.') ? `(?:[^/]+\\.)?${esc(host.slice(2))}` : esc(host);
|
|
9
|
+
const pathRe = path.split('*').map(esc).join('.*');
|
|
10
|
+
return new RegExp(`^${scheme}://${hostRe}(?::\\d+)?${pathRe}$`, 'i');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function allowedBy(url: string, patterns: string[]): boolean {
|
|
14
|
+
return patterns.some((p) => { try { return patternToRegExp(p).test(url); } catch { return false; } });
|
|
15
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// HotKeys (ADR-046, from v2 config/hotkeys.js). A combo is modifiers + key joined by "+": Mod (⌘ on a Mac, Ctrl elsewhere; either works),
|
|
2
|
+
// Shift, Alt, then the key ("D", ".", "/", "ArrowUp"). "" = no shortcut. The user's choices live in settings.hotkeys.map; unset = the default.
|
|
3
|
+
|
|
4
|
+
export interface HotkeyDef { id: string; label: string; default: string }
|
|
5
|
+
|
|
6
|
+
/** Framework hotkeys. Module-declared hotkeys (with build-time clash checks) come later (ADR-046). */
|
|
7
|
+
export const FRAMEWORK_HOTKEYS: HotkeyDef[] = [
|
|
8
|
+
{ id: 'log', label: 'Show / hide the Activity Log', default: 'Mod+.' },
|
|
9
|
+
{ id: 'help', label: 'Show / hide Help', default: 'Mod+Shift+/' },
|
|
10
|
+
{ id: 'favorite', label: 'Add / remove this page from Favorites', default: 'Mod+D' },
|
|
11
|
+
{ id: 'search', label: 'Jump to the search box', default: 'Mod+K' },
|
|
12
|
+
{ id: 'navFilter', label: 'Jump to the navigation filter', default: 'Mod+/' },
|
|
13
|
+
{ id: 'lock', label: 'Lock the vault', default: 'Mod+Shift+L' },
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
const isMac = () => typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform || navigator.userAgent);
|
|
17
|
+
|
|
18
|
+
/** The combo a key event represents, or '' for a bare modifier press. */
|
|
19
|
+
export function comboOf(e: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'altKey' | 'shiftKey' | 'code'>): string {
|
|
20
|
+
if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return '';
|
|
21
|
+
// Shift+/ reports "?"; Alt changes letters on a Mac: use the physical key for those.
|
|
22
|
+
let key = e.key;
|
|
23
|
+
if (e.code === 'Slash') key = '/';
|
|
24
|
+
else if (e.code === 'Period') key = '.';
|
|
25
|
+
else if (/^Key[A-Z]$/.test(e.code)) key = e.code.slice(3);
|
|
26
|
+
else if (/^Digit\d$/.test(e.code)) key = e.code.slice(5);
|
|
27
|
+
else if (key.length === 1) key = key.toUpperCase();
|
|
28
|
+
return [e.metaKey || e.ctrlKey ? 'Mod' : '', e.shiftKey ? 'Shift' : '', e.altKey ? 'Alt' : '', key].filter(Boolean).join('+');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const effective = (def: HotkeyDef, map: Record<string, string>) => (def.id in map ? map[def.id] : def.default);
|
|
32
|
+
|
|
33
|
+
/** "Mod+Shift+/" → "⌘⇧/" on a Mac, "Ctrl+Shift+/" elsewhere. */
|
|
34
|
+
export function formatCombo(combo: string): string {
|
|
35
|
+
if (!combo) return '—';
|
|
36
|
+
const mac = isMac();
|
|
37
|
+
return combo.split('+').map((p) => (p === 'Mod' ? (mac ? '⌘' : 'Ctrl') : p === 'Shift' ? (mac ? '⇧' : 'Shift') : p === 'Alt' ? (mac ? '⌥' : 'Alt') : p.replace('Arrow', ''))).join(mac ? '' : '+');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Which hotkey a combo triggers (or undefined). */
|
|
41
|
+
export const match = (combo: string, map: Record<string, string>) => (combo ? FRAMEWORK_HOTKEYS.find((d) => effective(d, map) === combo) : undefined);
|
|
42
|
+
|
|
43
|
+
/** Another hotkey already using `combo`, if any (the remap UI refuses duplicates). */
|
|
44
|
+
export const clash = (id: string, combo: string, map: Record<string, string>) => (combo ? FRAMEWORK_HOTKEYS.find((d) => d.id !== id && effective(d, map) === combo) : undefined);
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Local data management (from v2 config/localdata.js + Settings › Manage Local Data / Clear All Local Data / Share setup).
|
|
2
|
+
// Everything the app keeps in this browser, what each collection is, and how to clear it, plus export / import of NON-secret configuration.
|
|
3
|
+
|
|
4
|
+
import * as log from './log.ts';
|
|
5
|
+
import { favorites, settings, SETTINGS_KEY, updateSettings, type UserSettings } from './prefs.ts';
|
|
6
|
+
import * as services from './services.ts';
|
|
7
|
+
import * as store from './storage.ts';
|
|
8
|
+
import * as vault from './vault.ts';
|
|
9
|
+
import type { Registry } from '../types.ts';
|
|
10
|
+
|
|
11
|
+
export interface Collection { id: string; label: string; description: string; caution?: boolean; clear(): Promise<void> }
|
|
12
|
+
|
|
13
|
+
const uiPrefKeys = () => (typeof localStorage === 'undefined' ? [] : Object.keys(localStorage).filter((k) => k.startsWith('taco.') && k !== 'taco.favorites'));
|
|
14
|
+
|
|
15
|
+
export const collections: Collection[] = [
|
|
16
|
+
{ id: 'favorites', label: 'Favorites', description: 'Your starred pages and their order. Clearing removes every favorite.',
|
|
17
|
+
async clear() { favorites.set([]); localStorage.removeItem('taco.favorites'); } },
|
|
18
|
+
{ id: 'ui', label: 'Layout preferences', description: 'Panel widths, which panel is open, collapsed groups and filters. Clearing restores the defaults.',
|
|
19
|
+
async clear() { for (const k of uiPrefKeys()) localStorage.removeItem(k); } },
|
|
20
|
+
{ id: 'settings', label: 'Configuration', description: 'Theme, notification and HotKey choices, the idle lock and the Activity Log levels. Clearing restores the defaults.',
|
|
21
|
+
async clear() { await store.remove('local', SETTINGS_KEY); } },
|
|
22
|
+
{ id: 'log', label: 'Activity Log', description: 'The saved Activity Log entries (the last 500).',
|
|
23
|
+
async clear() { log.clear(); await store.remove('local', 'taco.log'); } },
|
|
24
|
+
{ id: 'services', label: 'Service settings (advanced)', description: 'Non-secret service details: on/off, sign-in mode, fields such as site names, last test results. Secrets in the vault are kept, but you will re-enter the details.', caution: true,
|
|
25
|
+
async clear() { await store.remove('local', 'taco.services'); } },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** Clear All Local Data: every collection AND the vault (secrets, module data). The page reloads afterwards. */
|
|
29
|
+
export async function clearAll() {
|
|
30
|
+
for (const c of collections) await c.clear();
|
|
31
|
+
await vault.destroy();
|
|
32
|
+
for (const k of ['taco.lastActivity', 'taco.lockReason', 'taco.notifyOpen']) await store.remove('session', k);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ── Share setup: export / import (never secrets) ──────────────────────────────────────────────────────────────────
|
|
36
|
+
|
|
37
|
+
export interface SetupFile { format: 'taco-setup'; version: 1; app: string; settings: Omit<UserSettings, 'notifications'> & { notifications: Omit<UserSettings['notifications'], 'items'> & { items: Record<string, boolean> } }; services: Record<string, { enabled: boolean; mode: string; config: Record<string, string> }> }
|
|
38
|
+
|
|
39
|
+
export function exportSetup(reg: Registry): SetupFile {
|
|
40
|
+
const svc: SetupFile['services'] = {};
|
|
41
|
+
for (const s of reg.services) {
|
|
42
|
+
const st = services.stateOf(s);
|
|
43
|
+
// Only fields the service declares as non-secret: a secret can't leak even if someone typed it into the wrong box.
|
|
44
|
+
const allowed = new Set(services.fieldsFor(s, st.mode).filter((f) => !f.secret).map((f) => f.key));
|
|
45
|
+
svc[`${s.type}/${s.name}`] = { enabled: st.enabled, mode: st.mode, config: Object.fromEntries(Object.entries(st.config).filter(([k]) => allowed.has(k))) };
|
|
46
|
+
}
|
|
47
|
+
return { format: 'taco-setup', version: 1, app: reg.app.name, settings: settings.get(), services: svc };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Applies an exported setup. Unknown services and fields are ignored; nothing in it can reach the vault. Returns what was applied. */
|
|
51
|
+
export async function importSetup(reg: Registry, raw: unknown): Promise<string[]> {
|
|
52
|
+
const f = raw as Partial<SetupFile>;
|
|
53
|
+
if (!f || f.format !== 'taco-setup' || f.version !== 1) throw new Error('This is not a Taco setup file.');
|
|
54
|
+
const applied: string[] = [];
|
|
55
|
+
for (const [key, v] of Object.entries(f.services ?? {})) {
|
|
56
|
+
const [type, name] = key.split('/');
|
|
57
|
+
const s = services.find(type, name);
|
|
58
|
+
if (!s || typeof v !== 'object' || !v) continue;
|
|
59
|
+
const mode = s.auth.includes(v.mode as never) ? (v.mode as typeof s.auth[number]) : services.stateOf(s).mode;
|
|
60
|
+
const allowed = new Set(services.fieldsFor(s, mode).filter((x) => !x.secret).map((x) => x.key));
|
|
61
|
+
const config = Object.fromEntries(Object.entries(v.config ?? {}).filter(([k, val]) => allowed.has(k) && typeof val === 'string'));
|
|
62
|
+
await services.update(s, { enabled: v.enabled !== false, mode, config: { ...services.stateOf(s).config, ...config } });
|
|
63
|
+
applied.push(`${s.label} (${key})`);
|
|
64
|
+
}
|
|
65
|
+
if (f.settings) {
|
|
66
|
+
const cur = settings.get();
|
|
67
|
+
const next: UserSettings = {
|
|
68
|
+
theme: ['dark', 'light', 'system'].includes(f.settings.theme) ? f.settings.theme : cur.theme,
|
|
69
|
+
idleLockMinutes: Number.isFinite(f.settings.idleLockMinutes) ? f.settings.idleLockMinutes : cur.idleLockMinutes,
|
|
70
|
+
visibleLevels: Array.isArray(f.settings.visibleLevels) ? f.settings.visibleLevels.filter((l) => typeof l === 'string') : cur.visibleLevels,
|
|
71
|
+
notifications: { ...cur.notifications, ...(f.settings.notifications ?? {}) },
|
|
72
|
+
confirmLock: typeof f.settings.confirmLock === 'boolean' ? f.settings.confirmLock : cur.confirmLock,
|
|
73
|
+
startPage: f.settings.startPage === null || typeof f.settings.startPage === 'string' ? f.settings.startPage : cur.startPage,
|
|
74
|
+
hotkeys: { enabled: f.settings.hotkeys?.enabled ?? cur.hotkeys.enabled, map: { ...(f.settings.hotkeys?.map ?? cur.hotkeys.map) } },
|
|
75
|
+
};
|
|
76
|
+
await updateSettings(next);
|
|
77
|
+
applied.push('Configuration');
|
|
78
|
+
}
|
|
79
|
+
log.add('info', `Imported setup from ${f.app ?? 'another install'}: ${applied.join(', ') || 'nothing matched this app'}`, undefined, 'Settings');
|
|
80
|
+
return applied;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Saves a file to Downloads (an <a download> click; no extra permission). Objects are written as JSON. */
|
|
84
|
+
export function download(name: string, data: unknown, type = 'application/json') {
|
|
85
|
+
const url = URL.createObjectURL(new Blob([typeof data === 'string' ? data : JSON.stringify(data, null, 2)], { type }));
|
|
86
|
+
Object.assign(document.createElement('a'), { href: url, download: name }).click();
|
|
87
|
+
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
|
88
|
+
}
|
package/src/core/log.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Activity Log store (ADR-027, ADR-040). Adding an entry is synchronous and never waits for rendering or storage;
|
|
2
|
+
// subscribers are told in a microtask and entries are persisted in the background.
|
|
3
|
+
|
|
4
|
+
import type { LogLevel, Logger } from '@tacoshell/sdk';
|
|
5
|
+
import * as store from './storage.ts';
|
|
6
|
+
|
|
7
|
+
export const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
|
|
8
|
+
const SEVERITY = (l: LogLevel) => LEVELS.indexOf(l);
|
|
9
|
+
/** The indicator reacts to info and above; trace and debug never color the Log button. */
|
|
10
|
+
const INDICATOR_MIN = SEVERITY('info');
|
|
11
|
+
const STORE_KEY = 'taco.log';
|
|
12
|
+
const KEEP = 500;
|
|
13
|
+
|
|
14
|
+
export interface Entry { id: number; at: number; level: LogLevel; message: string; data?: unknown; source?: string; tag?: 'notification' | 'api' }
|
|
15
|
+
|
|
16
|
+
let entries: Entry[] = [];
|
|
17
|
+
let nextId = 1;
|
|
18
|
+
let unseen = -1;
|
|
19
|
+
let panelOpen = false;
|
|
20
|
+
let version = 0;
|
|
21
|
+
const listeners = new Set<() => void>();
|
|
22
|
+
let notifyQueued = false;
|
|
23
|
+
let persistTimer: ReturnType<typeof setTimeout> | undefined;
|
|
24
|
+
|
|
25
|
+
function changed() {
|
|
26
|
+
version++;
|
|
27
|
+
if (notifyQueued) return;
|
|
28
|
+
notifyQueued = true;
|
|
29
|
+
queueMicrotask(() => { notifyQueued = false; for (const fn of listeners) fn(); });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const SECRET_KEY = /pass(word)?|secret|token|authorization|cookie|api[-_]?key|session|credential/i;
|
|
33
|
+
const SECRET_VALUE = /^(bearer|basic)\s+\S+/i;
|
|
34
|
+
/** Masks values under secret-looking keys and auth-looking strings; never throws (ADR-040). */
|
|
35
|
+
export function redact(data: unknown, depth = 0): unknown {
|
|
36
|
+
if (depth > 6) return '…';
|
|
37
|
+
if (typeof data === 'string') return SECRET_VALUE.test(data) ? '••••' : data.length > 2000 ? data.slice(0, 2000) + '…' : data;
|
|
38
|
+
if (Array.isArray(data)) return data.slice(0, 50).map((v) => redact(v, depth + 1));
|
|
39
|
+
if (data && typeof data === 'object') {
|
|
40
|
+
const out: Record<string, unknown> = {};
|
|
41
|
+
for (const [k, v] of Object.entries(data)) out[k] = SECRET_KEY.test(k) ? '••••' : redact(v, depth + 1);
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
return data;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function add(level: LogLevel, message: string, data?: unknown, source?: string, tag?: Entry['tag']) {
|
|
48
|
+
const entry: Entry = { id: nextId++, at: Date.now(), level, message, source, tag };
|
|
49
|
+
if (data !== undefined) entry.data = redact(data);
|
|
50
|
+
entries.push(entry);
|
|
51
|
+
if (entries.length > 2000) entries = entries.slice(-2000);
|
|
52
|
+
if (!panelOpen && SEVERITY(level) >= INDICATOR_MIN) unseen = Math.max(unseen, SEVERITY(level));
|
|
53
|
+
changed();
|
|
54
|
+
clearTimeout(persistTimer);
|
|
55
|
+
persistTimer = setTimeout(persist, 250);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const logger = (source?: string): Logger =>
|
|
59
|
+
Object.fromEntries(LEVELS.map((l) => [l, (message: string, data?: unknown) => add(l, message, data, source)])) as Logger;
|
|
60
|
+
|
|
61
|
+
/** Highest severity received since the log was last viewed, or null (ADR-027: the color "sticks" until viewed). */
|
|
62
|
+
export const indicator = (): LogLevel | null => (unseen >= INDICATOR_MIN ? LEVELS[unseen] : null);
|
|
63
|
+
|
|
64
|
+
export function setPanelOpen(open: boolean) {
|
|
65
|
+
panelOpen = open;
|
|
66
|
+
if (open) unseen = -1;
|
|
67
|
+
changed();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const all = () => entries;
|
|
71
|
+
export const getVersion = () => version;
|
|
72
|
+
export function clear() { entries = []; unseen = -1; changed(); void persist(); }
|
|
73
|
+
export const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
|
|
74
|
+
|
|
75
|
+
async function persist() {
|
|
76
|
+
try { await store.set('local', STORE_KEY, entries.slice(-KEEP)); } catch { /* storage full or closing: the in-memory log is still complete */ }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Loads entries saved by earlier sessions and saves on the way out. */
|
|
80
|
+
export async function init() {
|
|
81
|
+
const saved = await store.get<Entry[]>('local', STORE_KEY);
|
|
82
|
+
if (saved?.length) {
|
|
83
|
+
entries = [...saved, ...entries];
|
|
84
|
+
nextId = Math.max(nextId, ...entries.map((e) => e.id + 1));
|
|
85
|
+
changed();
|
|
86
|
+
}
|
|
87
|
+
if (typeof addEventListener === 'function') addEventListener('pagehide', () => { void persist(); });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Test helper. */
|
|
91
|
+
export function resetForTests() { entries = []; nextId = 1; unseen = -1; panelOpen = false; listeners.clear(); }
|