@tacoshell/shell 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +6 -2
  3. package/package.json +40 -4
  4. package/src/background.ts +41 -0
  5. package/src/core/bus.ts +210 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/contrib.ts +70 -0
  8. package/src/core/cron.ts +63 -0
  9. package/src/core/cronfriendly.ts +70 -0
  10. package/src/core/csv.ts +36 -0
  11. package/src/core/csvfeature.ts +57 -0
  12. package/src/core/datasets.ts +367 -0
  13. package/src/core/domshot.ts +81 -0
  14. package/src/core/guards.ts +36 -0
  15. package/src/core/hosts.ts +15 -0
  16. package/src/core/hotkeys.ts +44 -0
  17. package/src/core/indicators.ts +62 -0
  18. package/src/core/jobs.ts +37 -0
  19. package/src/core/localdata.ts +88 -0
  20. package/src/core/log.ts +91 -0
  21. package/src/core/markdown.ts +57 -0
  22. package/src/core/nav.ts +105 -0
  23. package/src/core/notifyrules.ts +31 -0
  24. package/src/core/page.ts +91 -0
  25. package/src/core/prefs.ts +119 -0
  26. package/src/core/router.ts +78 -0
  27. package/src/core/search.ts +65 -0
  28. package/src/core/services.ts +178 -0
  29. package/src/core/sessions.ts +93 -0
  30. package/src/core/startpage.ts +28 -0
  31. package/src/core/storage.ts +54 -0
  32. package/src/core/systemtools.ts +85 -0
  33. package/src/core/tabfit.ts +30 -0
  34. package/src/core/templates.ts +48 -0
  35. package/src/core/text.ts +6 -0
  36. package/src/core/toasts.ts +13 -0
  37. package/src/core/vault.ts +208 -0
  38. package/src/env.d.ts +2 -0
  39. package/src/index.ts +58 -0
  40. package/src/styles.css +391 -0
  41. package/src/types.ts +133 -0
  42. package/src/ui/ActionModal.tsx +22 -0
  43. package/src/ui/App.tsx +241 -0
  44. package/src/ui/ClearableInput.tsx +23 -0
  45. package/src/ui/CsvFeature.tsx +151 -0
  46. package/src/ui/Icon.tsx +8 -0
  47. package/src/ui/ItemFeature.tsx +39 -0
  48. package/src/ui/Markdown.tsx +24 -0
  49. package/src/ui/Rail.tsx +135 -0
  50. package/src/ui/RelatedMenu.tsx +57 -0
  51. package/src/ui/Search.tsx +111 -0
  52. package/src/ui/Sessions.tsx +76 -0
  53. package/src/ui/SidePanel.tsx +150 -0
  54. package/src/ui/TabBar.tsx +56 -0
  55. package/src/ui/ViewHost.tsx +142 -0
  56. package/src/ui/hooks.ts +28 -0
  57. package/src/ui/settings/Datasets.tsx +172 -0
  58. package/src/ui/settings/ReleaseNotes.tsx +96 -0
  59. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  60. package/src/ui/settings/Settings.tsx +339 -0
  61. package/src/ui/settings/SettingsTabs.tsx +63 -0
  62. package/src/ui/settings/Templates.tsx +52 -0
  63. package/src/ui/useContrib.ts +36 -0
@@ -0,0 +1,57 @@
1
+ // CSV feature type: template, upload parsing, per-column value filters and row results. Pure, so it is unit-tested (the UI is ui/CsvFeature.tsx).
2
+
3
+ import type { CsvColumn, CsvFeatureDef, RowResult, RowStatus } from '@tacoshell/sdk';
4
+ import { parseCsv, stringifyCsv } from './csv.ts';
5
+
6
+ export type CsvRow = Record<string, string>;
7
+ export const BLANK = '(blank)';
8
+ export const labelOf = (c: CsvColumn) => c.label ?? c.key;
9
+ export const shownColumns = (def: Pick<CsvFeatureDef, 'columns'>) => def.columns.filter((c) => c.show !== false);
10
+
11
+ /** The template CSV: the feature's `template.rows`, else one row built from each column's `sample`. */
12
+ export function templateCsv(def: Pick<CsvFeatureDef, 'columns' | 'template'>): string {
13
+ const keys = def.columns.map((c) => c.key);
14
+ const rows = def.template?.rows?.length ? def.template.rows : [Object.fromEntries(def.columns.map((c) => [c.key, c.sample ?? '']))];
15
+ return stringifyCsv(keys, rows);
16
+ }
17
+ export const templateName = (def: Pick<CsvFeatureDef, 'template'>, view: string) => def.template?.filename ?? `${view}-template.csv`;
18
+
19
+ export interface Parsed { rows: CsvRow[]; headers: string[]; problems: string[]; skipped: string[] }
20
+
21
+ /** Header → objects (extra columns are kept, so the processor gets the full row). `line` is the row's line in the file (the header is line 1). */
22
+ export function parseUpload(text: string, def: Pick<CsvFeatureDef, 'columns' | 'validateRow' | 'skipRow'>): Parsed {
23
+ const table = parseCsv(text);
24
+ const out: Parsed = { rows: [], headers: [], problems: [], skipped: [] };
25
+ if (!table.length) { out.problems.push('The file is empty.'); return out; }
26
+ out.headers = table[0].map((h) => h.trim());
27
+ const missing = def.columns.filter((c) => c.required && !out.headers.includes(c.key)).map((c) => c.key);
28
+ if (missing.length) { out.problems.push(`Missing column${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}. Start from the template and keep its header.`); return out; }
29
+ table.slice(1).forEach((cells, i) => {
30
+ const line = i + 2;
31
+ const row: CsvRow = Object.fromEntries(out.headers.map((h, c) => [h, (cells[c] ?? '').trim()]));
32
+ const why = def.skipRow?.(row, line);
33
+ if (why) { out.skipped.push(`Line ${line}: ${why}`); return; }
34
+ const bad = def.validateRow?.(row, line);
35
+ if (bad) out.problems.push(`Line ${line}: ${bad}`);
36
+ out.rows.push(row);
37
+ });
38
+ if (!out.problems.length && !out.rows.length) out.problems.push(out.skipped.length ? 'Every row was removed.' : 'The file has no data rows.');
39
+ return out;
40
+ }
41
+
42
+ /** Distinct values of a column, sorted (blank last): what its filter dropdown lists. */
43
+ export function distinct(rows: CsvRow[], key: string): string[] {
44
+ const set = new Set(rows.map((r) => (r[key] ?? '') || BLANK));
45
+ return [...set].sort((a, b) => (a === BLANK ? 1 : b === BLANK ? -1 : a.localeCompare(b, undefined, { numeric: true })));
46
+ }
47
+
48
+ /** `excluded[col]` = values the user unticked. Default (nothing excluded) shows every row. Returns indexes into `rows`. */
49
+ export function visibleIndexes(rows: CsvRow[], excluded: Record<string, ReadonlySet<string>>): number[] {
50
+ const cols = Object.entries(excluded).filter(([, set]) => set.size);
51
+ return rows.flatMap((r, i) => (cols.every(([k, set]) => !set.has((r[k] ?? '') || BLANK)) ? [i] : []));
52
+ }
53
+
54
+ export const normalizeResult = (r: RowStatus | RowResult | void | undefined): RowResult => (typeof r === 'string' ? { status: r } : r && (r as RowResult).status ? (r as RowResult) : { status: 'ok' });
55
+ export const ICON: Record<RowStatus, string> = { ok: '✅', warn: '⚠️', error: '❌' };
56
+
57
+ export const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
@@ -0,0 +1,367 @@
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 { DatasetInfo, Framework, Routine, Store } 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 choice for an incremental dataset: what the next refresh does. */ load?: 'full' | 'incremental';
19
+ /** The user's schedule (Settings → Datasets → Schedule); wins over the developer's default in the manifest. `cron: null` = manual only. */
20
+ schedule?: { cron: string | null }; scheduleSetAt?: number; lastAttemptAt?: number }
21
+
22
+ const META_KEY = 'taco.datasets';
23
+ let registry: Registry | undefined;
24
+ let routines: Record<string, Routine> = {};
25
+ export const states = createStore<Record<string, DatasetState>>({});
26
+ const cache = new Map<string, Row[]>();
27
+ let changed: (d: RegistryDataset) => void = () => {};
28
+ /** The bus publishes each dataset's `changed` event; set by the bus to avoid an import cycle. */
29
+ export const onChanged = (fn: typeof changed) => { changed = fn; };
30
+
31
+ export const idOf = (d: { module: string; name: string }) => `${d.module}/${d.name}`;
32
+ export const list = () => registry?.datasets ?? [];
33
+ export const find = (module: string, name: string) => list().find((d) => d.module === module && d.name === name);
34
+ export const stateOf = (d: RegistryDataset): DatasetState => states.get()[idOf(d)] ?? { rows: 0, columns: [], durations: [] };
35
+ export const hasRoutine = (d: RegistryDataset) => !!routines[idOf(d)];
36
+
37
+ export async function init(reg: Registry, rs: Record<string, Routine>) {
38
+ registry = reg;
39
+ routines = rs;
40
+ states.set((await store.get<Record<string, DatasetState>>('local', META_KEY)) ?? {});
41
+ // Decrypted rows never outlive an unlock (v2 ADR-033).
42
+ vault.subscribe((s) => { if (s !== 'unlocked') cache.clear(); });
43
+ }
44
+
45
+ async function setState(d: RegistryDataset, patch: Partial<DatasetState>) {
46
+ const next = { ...states.get(), [idOf(d)]: { ...stateOf(d), ...patch } };
47
+ states.set(next);
48
+ await store.set('local', META_KEY, next);
49
+ }
50
+
51
+ export class LockedError extends Error { constructor() { super('The vault is locked: datasets are only readable while it is unlocked.'); } }
52
+
53
+ // ── Types on read (v2 ADR-029): string · integer · number · boolean · date · timestamp · list · json; "#N/A" and "" → null ──────
54
+ export function typedValue(type: string | undefined, v: unknown): unknown {
55
+ if (v === null || v === undefined) return null;
56
+ if (typeof v !== 'string') return v;
57
+ const s = v.trim();
58
+ if (s === '' || s === '#N/A') return null;
59
+ switch ((type ?? 'string').replace(/\?$/, '')) {
60
+ case 'integer': { const n = Number.parseInt(s.replace(/,/g, ''), 10); return Number.isFinite(n) ? n : null; }
61
+ case 'number': { const n = Number(s.replace(/,/g, '')); return Number.isFinite(n) ? n : null; }
62
+ case 'boolean': return /^(true|yes|y|1)$/i.test(s) ? true : /^(false|no|n|0)$/i.test(s) ? false : null;
63
+ 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); }
64
+ case 'timestamp': { const t = new Date(s); return Number.isNaN(t.getTime()) ? null : t.toISOString(); }
65
+ case 'list': { if (s.startsWith('[')) { try { return JSON.parse(s); } catch { /* fall through */ } } return s.split(/[;|]/).map((x) => x.trim()).filter(Boolean); }
66
+ case 'json': try { return JSON.parse(s); } catch { return null; }
67
+ default: return v;
68
+ }
69
+ }
70
+ const typedRow = (d: RegistryDataset, raw: Row): Row => Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, typedValue(d.schema?.[k], v)]));
71
+
72
+ export async function rows(d: RegistryDataset): Promise<Row[]> {
73
+ if (vault.status() !== 'unlocked') throw new LockedError();
74
+ const id = idOf(d);
75
+ if (cache.has(id)) return cache.get(id)!;
76
+ const text = await vault.getData(`dataset/${id}`);
77
+ const out = text ? (JSON.parse(text) as Row[]) : [];
78
+ cache.set(id, out);
79
+ return out;
80
+ }
81
+
82
+ /** 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). */
83
+ async function write(d: RegistryDataset, next: Row[], source: DatasetState['source'], columns?: string[]) {
84
+ await vault.putData(`dataset/${idOf(d)}`, JSON.stringify(next));
85
+ cache.set(idOf(d), next);
86
+ await setState(d, { rows: next.length, columns: columns ?? Object.keys(d.schema ?? next[0] ?? {}), updatedAt: new Date().toISOString(), source, lastError: undefined });
87
+ changed(d);
88
+ }
89
+
90
+ export interface CsvAnalysis {
91
+ /** Data rows in the file (before duplicate keys are merged). */
92
+ fileRows: number;
93
+ /** Rows that would be stored. */
94
+ rows: Row[];
95
+ columns: string[];
96
+ missing: string[];
97
+ extra: string[];
98
+ /** Rows whose key repeated an earlier one (the last wins). */
99
+ dupes: number;
100
+ /** Rows with an empty key value. */
101
+ emptyKeys: number;
102
+ warnings: string[];
103
+ }
104
+
105
+ /** 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. */
106
+ export function analyzeCsv(d: RegistryDataset, text: string): CsvAnalysis {
107
+ const table = parseCsv(text);
108
+ if (!table.length) throw new Error('The file is empty.');
109
+ const header = table[0].map((h) => h.trim());
110
+ const warnings: string[] = [];
111
+ const declared = Object.keys(d.schema ?? {});
112
+ const missing = declared.filter((c) => !header.includes(c));
113
+ const extra = declared.length ? header.filter((c) => !declared.includes(c)) : [];
114
+ if (d.key && !header.includes(d.key)) throw new Error(`The CSV has no "${d.key}" column (this dataset's key).`);
115
+ if (missing.length) warnings.push(`Missing column(s): ${missing.join(', ')} (left empty).`);
116
+ if (extra.length) warnings.push(`Column(s) not in the schema were imported as text: ${extra.join(', ')}.`);
117
+ const fileRows = table.length - 1;
118
+ let out = table.slice(1).map((cells) => typedRow(d, Object.fromEntries(header.map((h, i) => [h, cells[i] ?? '']))));
119
+ let dupes = 0, emptyKeys = 0;
120
+ if (d.key) {
121
+ const byKey = new Map<unknown, Row>();
122
+ 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); }
123
+ if (dupes) warnings.push(`${dupes} row(s) repeated a "${d.key}"; the last one was kept.`);
124
+ out = [...byKey.values()];
125
+ }
126
+ return { fileRows, rows: out, columns: [...new Set([...declared, ...header])], missing, extra, dupes, emptyKeys, warnings };
127
+ }
128
+
129
+ /** CSV import replaces every row (a Full Load). Returns warnings (unknown/missing columns, duplicate keys). */
130
+ export async function importCsv(d: RegistryDataset, text: string): Promise<{ rows: number; warnings: string[] }> {
131
+ const a = analyzeCsv(d, text);
132
+ await write(d, a.rows, 'csv', a.columns);
133
+ log.add('info', `Imported ${a.rows.length} row(s) into ${d.label} from CSV`, a.warnings.length ? { warnings: a.warnings } : undefined, 'Datasets');
134
+ return { rows: a.rows.length, warnings: a.warnings };
135
+ }
136
+
137
+ export async function exportCsv(d: RegistryDataset): Promise<string> {
138
+ const r = await rows(d);
139
+ return stringifyCsv(stateOf(d).columns.length ? stateOf(d).columns : Object.keys(d.schema ?? r[0] ?? {}), r);
140
+ }
141
+
142
+ export async function clear(d: RegistryDataset) {
143
+ await vault.removeData(`dataset/${idOf(d)}`);
144
+ cache.delete(idOf(d));
145
+ await setState(d, { rows: 0, updatedAt: undefined, source: undefined });
146
+ changed(d);
147
+ log.add('info', `Cleared ${d.label}`, undefined, 'Datasets');
148
+ }
149
+
150
+ /** 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. */
151
+ /** Datasets refreshing right now (ids). The header's database icon shows while this is non-empty. */
152
+ export const refreshingNow = createStore<string[]>([]);
153
+ const queued = new Set<string>();
154
+ let chain: Promise<unknown> = Promise.resolve();
155
+
156
+ /**
157
+ * Refreshes one dataset. The framework serializes every refresh (scheduled or manual) so two datasets never run on top of each other:
158
+ * a request made while another runs waits its turn. Asking for a dataset that is already running or waiting is refused.
159
+ */
160
+ export function refresh(d: RegistryDataset, framework: Framework, opts: { load?: 'full' | 'incremental' } = {}): Promise<number> {
161
+ const id = idOf(d);
162
+ if (queued.has(id)) return Promise.reject(new Error(`${d.label} is already refreshing.`));
163
+ queued.add(id);
164
+ const run = chain.then(async () => {
165
+ refreshingNow.set([...refreshingNow.get(), id]);
166
+ try { return await runRefresh(d, framework, opts.load); }
167
+ finally { refreshingNow.set(refreshingNow.get().filter((x) => x !== id)); progressNow.set(without(progressNow.get(), id)); controllers.delete(id); }
168
+ }).finally(() => queued.delete(id));
169
+ chain = run.catch(() => {});
170
+ return run;
171
+ }
172
+
173
+ /** What each running refresh says it is doing, and whether the user asked it to stop. */
174
+ export const progressNow = createStore<Record<string, { text?: string; cancelling: boolean }>>({});
175
+ const controllers = new Map<string, AbortController>();
176
+ const without = <T,>(o: Record<string, T>, k: string) => { const { [k]: _gone, ...rest } = o; return rest; };
177
+
178
+ /** The load the next refresh will do: incremental only for a dataset that declares it, once it has data, unless the user chose Full. */
179
+ export function loadOf(d: RegistryDataset, ask?: 'full' | 'incremental'): 'full' | 'incremental' {
180
+ if (!d.incremental || !stateOf(d).rows) return 'full';
181
+ return (ask ?? stateOf(d).load ?? 'incremental') === 'full' ? 'full' : 'incremental';
182
+ }
183
+ export const setLoad = (d: RegistryDataset, load: 'full' | 'incremental') => setState(d, { load });
184
+
185
+ /** Asks the running refresh of a dataset to stop. Its routine sees `ctx.signal`; whatever it returns afterwards is discarded. */
186
+ export function cancel(d: RegistryDataset) {
187
+ const c = controllers.get(idOf(d));
188
+ if (!c || c.signal.aborted) return;
189
+ c.abort();
190
+ progressNow.set({ ...progressNow.get(), [idOf(d)]: { ...progressNow.get()[idOf(d)], cancelling: true } });
191
+ log.add('info', `Cancelling the refresh of ${d.label}…`, undefined, 'Datasets');
192
+ }
193
+
194
+ async function runRefresh(d: RegistryDataset, framework: Framework, ask?: 'full' | 'incremental'): Promise<number> {
195
+ const routine = routines[idOf(d)];
196
+ if (d.kind !== 'refreshable' || !routine) throw new Error(`${d.label} is import-only: import a CSV in Settings → Datasets.`);
197
+ if (stateOf(d).refreshing) throw new Error(`${d.label} is already refreshing.`);
198
+ const started = Date.now();
199
+ await setState(d, { refreshing: true, lastAttemptAt: started });
200
+ const dlog = log.logger(`Datasets › ${d.label}`);
201
+ const id = idOf(d);
202
+ const controller = new AbortController();
203
+ controllers.set(id, controller);
204
+ progressNow.set({ ...progressNow.get(), [id]: { cancelling: false } });
205
+ const load = loadOf(d, ask);
206
+ try {
207
+ const result = await routine.run({
208
+ framework, log: dlog, previous: { rows: stateOf(d).rows, updatedAt: stateOf(d).updatedAt }, load, signal: controller.signal,
209
+ progress: (text) => { progressNow.set({ ...progressNow.get(), [id]: { ...progressNow.get()[id], text, cancelling: controller.signal.aborted } }); dlog.debug(text); },
210
+ });
211
+ if (controller.signal.aborted) throw new Error('Cancelled');
212
+ const next = result.rows.map((r) => typedRow(d, r));
213
+ const mode = load === 'full' ? 'replace' : result.mode ?? 'upsert'; // an incremental load that doesn't say how to merge upserts when there is a key, else appends
214
+ let stored = next, total = next.length;
215
+ if (mode !== 'replace') {
216
+ const existing = await rows(d);
217
+ if (mode === 'upsert' && d.key) {
218
+ const byKey = new Map(existing.map((r) => [r[d.key!], r]));
219
+ for (const r of next) byKey.set(r[d.key], { ...(byKey.get(r[d.key]) ?? {}), ...r });
220
+ stored = [...byKey.values()];
221
+ } else stored = [...existing, ...next];
222
+ total = stored.length;
223
+ }
224
+ await write(d, stored, 'routine', result.columns);
225
+ await setState(d, { refreshing: false, durations: [...stateOf(d).durations, Date.now() - started].slice(-3) });
226
+ dlog.info(`${load === 'incremental' ? `Incremental load (${mode})` : 'Refreshed'}: ${next.length} row(s) loaded, ${total} total, in ${Math.round((Date.now() - started) / 100) / 10} s`);
227
+ return next.length;
228
+ } catch (e) {
229
+ const cancelled = controller.signal.aborted;
230
+ await setState(d, { refreshing: false, lastError: cancelled ? undefined : (e as Error).message });
231
+ if (cancelled) dlog.warn('Refresh cancelled; the data is unchanged.'); else dlog.error(`Refresh failed: ${(e as Error).message}`);
232
+ throw cancelled ? new Error('Cancelled') : e;
233
+ }
234
+ }
235
+ // ── Schedules: the developer ships a default (manifest `schedule.cron`), the user chooses when and how often ─────────────
236
+ /** The crontab in force: the user's saved choice (null = manual), else the developer's default, else manual. */
237
+ export const cronOf = (d: RegistryDataset): string | null => { const s = stateOf(d).schedule; return s ? s.cron : d.schedule?.cron ?? null; };
238
+ export const describeSchedule = (d: RegistryDataset) => describeCron(cronOf(d));
239
+
240
+ export async function setSchedule(d: RegistryDataset, cron: string | null) {
241
+ if (cron && !isValidCron(cron)) throw new Error(`"${cron}" isn't a valid crontab.`);
242
+ await setState(d, { schedule: { cron }, scheduleSetAt: Date.now() });
243
+ log.add('info', `${d.label} schedule: ${describeCron(cron)}`, cron ? { cron } : undefined, 'Datasets');
244
+ }
245
+
246
+ /** The next time the dataset is due (ms), counted from its last attempt or from when its schedule was first seen; null for manual. */
247
+ export function nextDue(d: RegistryDataset): number | null {
248
+ const cron = cronOf(d), st = stateOf(d), base = Math.max(st.lastAttemptAt ?? 0, st.scheduleSetAt ?? 0);
249
+ if (!cron || !base || !isValidCron(cron)) return null;
250
+ return cronNext(cron, base);
251
+ }
252
+ export const isDue = (d: RegistryDataset, now = Date.now()) => { const n = nextDue(d); return n !== null && n <= now; };
253
+
254
+ /** Up to date for its schedule? { scheduled: false } when manual; else ok = no scheduled time has passed since the last update (refresh or import). */
255
+ export function compliance(d: RegistryDataset, now = Date.now()): { scheduled: boolean; ok: boolean } {
256
+ const cron = cronOf(d), at = stateOf(d).updatedAt ? new Date(stateOf(d).updatedAt!).getTime() : 0;
257
+ if (!cron || !isValidCron(cron)) return { scheduled: false, ok: true };
258
+ if (!at) return { scheduled: true, ok: false };
259
+ const next = cronNext(cron, at);
260
+ return { scheduled: true, ok: next === null || next > now };
261
+ }
262
+
263
+ /**
264
+ * 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
265
+ * (a slot missed while locked runs once it is unlocked). A manual "Refresh now" is never held back by this.
266
+ */
267
+ export function startScheduler(framework: (module: string) => Framework, everyMs = 30_000): () => void {
268
+ let running = false;
269
+ const tick = async () => {
270
+ if (running || vault.status() !== 'unlocked') return;
271
+ // A schedule counts from when it was first seen, so a never-refreshed dataset waits for its first slot instead of running at once.
272
+ for (const d of list()) if (d.kind === 'refreshable' && !stateOf(d).scheduleSetAt && cronOf(d)) await setState(d, { scheduleSetAt: Date.now() });
273
+ const due = list().filter((d) => d.kind === 'refreshable' && hasRoutine(d) && !stateOf(d).refreshing && isDue(d))
274
+ .sort((a, b) => (nextDue(a) ?? 0) - (nextDue(b) ?? 0));
275
+ if (!due.length) return;
276
+ running = true;
277
+ try {
278
+ for (const d of due) {
279
+ if (vault.status() !== 'unlocked') break;
280
+ log.add('info', `Scheduled refresh of ${d.label} (${describeSchedule(d)})`, undefined, 'Datasets');
281
+ try { await refresh(d, framework(d.module)); } catch { /* refresh() already logged the failure and kept the old rows */ }
282
+ }
283
+ } finally { running = false; }
284
+ };
285
+ const timer = setInterval(() => void tick(), everyMs);
286
+ const off = vault.subscribe((s) => { if (s === 'unlocked') void tick(); });
287
+ void tick();
288
+ return () => { clearInterval(timer); off(); };
289
+ }
290
+
291
+ export const estimateMs = (d: RegistryDataset) => { const ds = stateOf(d).durations; return ds.length ? ds.reduce((a, b) => a + b, 0) / ds.length : undefined; };
292
+
293
+ // ── Standard topics (ADR-026): query · get · set · delete · meta ─────────────────────────────────────────────────────
294
+ export interface Query { filters?: Record<string, unknown>; sort?: string[]; limit?: number }
295
+
296
+ function matches(v: unknown, cond: unknown): boolean {
297
+ if (cond && typeof cond === 'object' && !Array.isArray(cond)) {
298
+ const c = cond as Record<string, unknown>;
299
+ if ('contains' in c && !String(v ?? '').toLowerCase().includes(String(c.contains).toLowerCase())) return false;
300
+ if ('in' in c && !(c.in as unknown[]).includes(v)) return false;
301
+ if ('gt' in c && !((v as number) > (c.gt as number))) return false;
302
+ if ('gte' in c && !((v as number) >= (c.gte as number))) return false;
303
+ if ('lt' in c && !((v as number) < (c.lt as number))) return false;
304
+ if ('lte' in c && !((v as number) <= (c.lte as number))) return false;
305
+ return true;
306
+ }
307
+ return v === cond;
308
+ }
309
+
310
+ /** filters: { col: value } (equal) or { col: { contains | in | gt | gte | lt | lte } }; sort: ["col", "-col"]; limit. */
311
+ export function query(all: Row[], q: Query = {}): Row[] {
312
+ let out = all.filter((r) => Object.entries(q.filters ?? {}).every(([k, cond]) => matches(r[k], cond)));
313
+ for (const s of [...(q.sort ?? [])].reverse()) {
314
+ const desc = s.startsWith('-'), k = desc ? s.slice(1) : s;
315
+ 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; });
316
+ }
317
+ return q.limit ? out.slice(0, q.limit) : out;
318
+ }
319
+
320
+ export const getById = (all: Row[], d: RegistryDataset, id: unknown) => (d.key ? all.find((r) => r[d.key!] === id) ?? null : null);
321
+
322
+ export async function upsert(d: RegistryDataset, incoming: Row[]): Promise<number> {
323
+ if (!d.key) throw new Error(`${d.label} has no key, so rows can't be set one by one.`);
324
+ const byKey = new Map((await rows(d)).map((r) => [r[d.key!], r]));
325
+ for (const r of incoming.map((x) => typedRow(d, x))) byKey.set(r[d.key], { ...(byKey.get(r[d.key]) ?? {}), ...r });
326
+ await write(d, [...byKey.values()], 'set', stateOf(d).columns.length ? stateOf(d).columns : undefined);
327
+ return incoming.length;
328
+ }
329
+
330
+ export async function remove(d: RegistryDataset, ids: unknown[]): Promise<number> {
331
+ if (!d.key) throw new Error(`${d.label} has no key, so rows can't be deleted one by one.`);
332
+ const all = await rows(d);
333
+ const keep = all.filter((r) => !ids.includes(r[d.key!]));
334
+ await write(d, keep, 'set', stateOf(d).columns);
335
+ return all.length - keep.length;
336
+ }
337
+
338
+ const planOf = (d: RegistryDataset) => loadOf(d);
339
+ /** This module's datasets as the framework hands them to a Settings tab: live (rows, refreshing, progress) as states change. Snapshots are cached so React can compare them. */
340
+ export function infoOf(d: RegistryDataset): DatasetInfo {
341
+ const st = stateOf(d), id = idOf(d), p = progressNow.get()[id];
342
+ return {
343
+ name: d.name, label: d.label, kind: d.kind, key: d.key, rows: st.rows, columns: st.columns, updatedAt: st.updatedAt, source: st.source,
344
+ refreshing: refreshingNow.get().includes(id), progress: p?.text, cancelling: !!p?.cancelling, schedule: describeSchedule(d), lastError: st.lastError,
345
+ incremental: !!d.incremental, load: planOf(d),
346
+ };
347
+ }
348
+ let sourceVersion = 0;
349
+ for (const src of [states, refreshingNow, progressNow]) src.subscribe(() => { sourceVersion++; });
350
+ const infoCache = new Map<string, { version: number; list: DatasetInfo[] }>();
351
+ export function infoStore(module: string): Store<DatasetInfo[]> {
352
+ return {
353
+ get() {
354
+ const c = infoCache.get(module);
355
+ if (c && c.version === sourceVersion) return c.list;
356
+ const list = (registry?.datasets ?? []).filter((d) => d.module === module).map(infoOf);
357
+ infoCache.set(module, { version: sourceVersion, list });
358
+ return list;
359
+ },
360
+ subscribe(fn) { const offs = [states, refreshingNow, progressNow].map((s) => s.subscribe(fn)); return () => offs.forEach((o) => o()); },
361
+ };
362
+ }
363
+
364
+ export const meta = (d: RegistryDataset) => {
365
+ const st = stateOf(d);
366
+ return { rows: st.rows, refreshing: refreshingNow.get().includes(idOf(d)), progress: progressNow.get()[idOf(d)]?.text, incremental: !!d.incremental, load: planOf(d), 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 };
367
+ };
@@ -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);