@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,161 @@
|
|
|
1
|
+
// Service runtime (ADR-004, ADR-023, ADR-032, ADR-040): per-instance state, secrets in the vault, the auth-aware fetch, OAuth PKCE.
|
|
2
|
+
|
|
3
|
+
import type { ServiceContext, ServiceImpl } from '@tacoshell/sdk';
|
|
4
|
+
import { serviceKey, type AuthMode, type FieldDecl, type Registry, type RegistryService } from '../types.ts';
|
|
5
|
+
import { allowedBy } from './hosts.ts';
|
|
6
|
+
import * as log from './log.ts';
|
|
7
|
+
import { createStore } from './prefs.ts';
|
|
8
|
+
import * as store from './storage.ts';
|
|
9
|
+
import * as vault from './vault.ts';
|
|
10
|
+
|
|
11
|
+
const STATE_KEY = 'taco.services';
|
|
12
|
+
export interface ServiceState { enabled: boolean; mode: AuthMode; config: Record<string, string>; /** Current Session services appear in the header's Sessions menu unless the user hides them. */ hideFromSessions?: boolean; lastTest?: { ok: boolean; at: number; detail: string } }
|
|
13
|
+
|
|
14
|
+
let registry: Registry | undefined;
|
|
15
|
+
let impls: Record<string, ServiceImpl> = {};
|
|
16
|
+
export const states = createStore<Record<string, ServiceState>>({});
|
|
17
|
+
|
|
18
|
+
export async function init(reg: Registry, implementations: Record<string, ServiceImpl>) {
|
|
19
|
+
registry = reg;
|
|
20
|
+
impls = implementations;
|
|
21
|
+
states.set((await store.get<Record<string, ServiceState>>('local', STATE_KEY)) ?? {});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const find = (type: string, name: string) => registry?.services.find((s) => s.type === type && s.name === name);
|
|
25
|
+
export const stateOf = (s: RegistryService): ServiceState => states.get()[serviceKey(s)] ?? { enabled: true, mode: s.auth[0], config: {} };
|
|
26
|
+
|
|
27
|
+
export async function update(s: RegistryService, patch: Partial<ServiceState>) {
|
|
28
|
+
const next = { ...states.get(), [serviceKey(s)]: { ...stateOf(s), ...patch } };
|
|
29
|
+
states.set(next);
|
|
30
|
+
await store.set('local', STATE_KEY, next);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const secretId = (s: RegistryService, field: string) => `${s.type}/${s.name}.${field}`;
|
|
34
|
+
|
|
35
|
+
/** Declared fields for the auth mode, plus the ones each mode implies when the service didn't declare them. */
|
|
36
|
+
export function fieldsFor(s: RegistryService, mode: AuthMode): FieldDecl[] {
|
|
37
|
+
const declared = (s.fields ?? []).filter((f) => !f.modes || f.modes.includes(mode));
|
|
38
|
+
const implied: Record<AuthMode, FieldDecl[]> = {
|
|
39
|
+
session: [],
|
|
40
|
+
apikey: [{ key: 'apiKey', label: 'API key', secret: true }],
|
|
41
|
+
basic: [{ key: 'username', label: 'Username' }, { key: 'password', label: 'Password or token', secret: true }],
|
|
42
|
+
oauth: [{ key: 'clientId', label: 'OAuth client ID' }],
|
|
43
|
+
};
|
|
44
|
+
const out = [...declared];
|
|
45
|
+
for (const f of implied[mode]) if (!out.some((d) => d.key === f.key)) out.push(f);
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function isConfigured(s: RegistryService): boolean {
|
|
50
|
+
const st = stateOf(s);
|
|
51
|
+
const ok = fieldsFor(s, st.mode).every((f) => f.required === false || (f.secret ? vault.has(secretId(s, f.key)) : !!st.config[f.key]?.trim()));
|
|
52
|
+
return ok && (st.mode !== 'oauth' || vault.has(secretId(s, 'accessToken')));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function isUsable(type: string, name: string) {
|
|
56
|
+
const s = find(type, name);
|
|
57
|
+
return !!s && stateOf(s).enabled && isConfigured(s);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const fill = (template: string, config: Record<string, string>) => template.replace(/\{(\w+)\}/g, (_, k: string) => encodeURIComponent(config[k] ?? ''));
|
|
61
|
+
|
|
62
|
+
export function contextFor(s: RegistryService): ServiceContext {
|
|
63
|
+
const st = stateOf(s);
|
|
64
|
+
const source = `${s.label} (${serviceKey(s)})`;
|
|
65
|
+
const slog = log.logger(source);
|
|
66
|
+
const secret = async (field: string) => {
|
|
67
|
+
const v = await vault.get(secretId(s, field));
|
|
68
|
+
if (v === undefined) throw new Error(`${s.label}: "${field}" isn't set (Settings → Services → ${s.label}).`);
|
|
69
|
+
return v;
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
instance: { module: s.module, type: s.type, name: s.name },
|
|
73
|
+
config: { ...st.config },
|
|
74
|
+
authMode: st.mode,
|
|
75
|
+
secret,
|
|
76
|
+
log: slog,
|
|
77
|
+
async fetch(url, init = {}) {
|
|
78
|
+
if (!url.startsWith('https://')) throw new Error(`${s.label}: only https:// URLs are allowed (${url}).`);
|
|
79
|
+
if (!allowedBy(url, s.hosts)) throw new Error(`${s.label}: ${new URL(url).host} isn't one of this service's declared hosts.`);
|
|
80
|
+
const headers = new Headers(init.headers);
|
|
81
|
+
let body = init.body;
|
|
82
|
+
if (init.json !== undefined) { headers.set('Content-Type', 'application/json'); body = JSON.stringify(init.json); }
|
|
83
|
+
if (st.mode === 'apikey') headers.set(s.apiKey?.header ?? 'Authorization', `${s.apiKey?.prefix ?? 'Bearer '}${await secret('apiKey')}`);
|
|
84
|
+
if (st.mode === 'basic') headers.set('Authorization', `Basic ${btoa(`${st.config.username ?? ''}:${await secret('password')}`)}`);
|
|
85
|
+
if (st.mode === 'oauth') headers.set('Authorization', `Bearer ${await oauthToken(s)}`);
|
|
86
|
+
const method = (init.method ?? 'GET').toUpperCase();
|
|
87
|
+
try {
|
|
88
|
+
const res = await fetch(url, { ...init, body, headers, credentials: st.mode === 'session' ? 'include' : 'omit' });
|
|
89
|
+
log.add('debug', `${method} ${url} → ${res.status}`, init.json === undefined ? undefined : { payload: init.json }, source, 'api');
|
|
90
|
+
return res;
|
|
91
|
+
} catch (e) {
|
|
92
|
+
log.add('debug', `${method} ${url} → no response (${(e as Error).message})`, undefined, source, 'api');
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function test(s: RegistryService): Promise<{ ok: boolean; detail: string }> {
|
|
100
|
+
const impl = impls[serviceKey(s)];
|
|
101
|
+
let result: { ok: boolean; detail: string };
|
|
102
|
+
try {
|
|
103
|
+
const r = impl?.test ? await impl.test(contextFor(s)) : undefined;
|
|
104
|
+
result = { ok: true, detail: r && r.who ? `Connected as ${r.who}` : impl?.test ? 'Test passed' : 'No test defined by this service' };
|
|
105
|
+
} catch (e) {
|
|
106
|
+
result = { ok: false, detail: (e as Error).message };
|
|
107
|
+
}
|
|
108
|
+
await update(s, { lastTest: { ...result, at: Date.now() } });
|
|
109
|
+
log.add(result.ok ? 'info' : 'warn', `${s.label} (${serviceKey(s)}) test: ${result.detail}`, undefined, 'Settings › Services');
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const implFor = (s: RegistryService) => impls[serviceKey(s)];
|
|
114
|
+
|
|
115
|
+
// ── OAuth PKCE (ADR-004): redirect https://<id>.chromiumapp.org/oauth/<type>/<name>; random single-use state ────────
|
|
116
|
+
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
117
|
+
export const redirectUrl = (s: RegistryService, extensionId: string) =>
|
|
118
|
+
typeof chrome !== 'undefined' && chrome.identity?.getRedirectURL ? chrome.identity.getRedirectURL(`oauth/${s.type}/${s.name}`) : `https://${extensionId}.chromiumapp.org/oauth/${s.type}/${s.name}`;
|
|
119
|
+
|
|
120
|
+
export async function connectOAuth(s: RegistryService) {
|
|
121
|
+
if (!s.oauth) throw new Error(`${s.label} doesn't declare oauth.authorizeUrl / tokenUrl in its module.`);
|
|
122
|
+
if (!chrome?.identity?.launchWebAuthFlow) throw new Error('OAuth sign-in needs the extension (chrome.identity).');
|
|
123
|
+
const st = stateOf(s);
|
|
124
|
+
if (!st.config.clientId) throw new Error('Enter the OAuth client ID first.');
|
|
125
|
+
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
126
|
+
const challenge = b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
|
|
127
|
+
const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
|
|
128
|
+
const redirect = redirectUrl(s, registry!.app.extensionId);
|
|
129
|
+
const auth = new URL(fill(s.oauth.authorizeUrl, st.config));
|
|
130
|
+
auth.search = new URLSearchParams({ response_type: 'code', client_id: st.config.clientId, redirect_uri: redirect, code_challenge: challenge, code_challenge_method: 'S256', state, ...(s.oauth.scopes?.length ? { scope: s.oauth.scopes.join(' ') } : {}) }).toString();
|
|
131
|
+
const back = await chrome.identity.launchWebAuthFlow({ url: auth.toString(), interactive: true });
|
|
132
|
+
const q = new URL(back ?? '').searchParams;
|
|
133
|
+
if (q.get('state') !== state) throw new Error('OAuth state mismatch: sign-in refused.');
|
|
134
|
+
if (!q.get('code')) throw new Error(`Sign-in didn't return a code (${q.get('error') ?? 'no error given'}).`);
|
|
135
|
+
await exchange(s, { grant_type: 'authorization_code', code: q.get('code')!, redirect_uri: redirect, code_verifier: verifier, client_id: st.config.clientId });
|
|
136
|
+
log.add('info', `${s.label} (${serviceKey(s)}) connected with OAuth`, undefined, 'Settings › Services');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function exchange(s: RegistryService, params: Record<string, string>) {
|
|
140
|
+
const res = await fetch(fill(s.oauth!.tokenUrl, stateOf(s).config), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(params), credentials: 'omit' });
|
|
141
|
+
if (!res.ok) throw new Error(`Token request failed (${res.status}).`);
|
|
142
|
+
const t = await res.json();
|
|
143
|
+
await vault.put(secretId(s, 'accessToken'), t.access_token);
|
|
144
|
+
if (t.refresh_token) await vault.put(secretId(s, 'refreshToken'), t.refresh_token);
|
|
145
|
+
await vault.put(secretId(s, 'expiresAt'), String(t.expires_in ? Date.now() + t.expires_in * 1000 : 0));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const refreshing = new Map<string, Promise<void>>();
|
|
149
|
+
async function oauthToken(s: RegistryService): Promise<string> {
|
|
150
|
+
const expiresAt = Number((await vault.get(secretId(s, 'expiresAt'))) ?? 0);
|
|
151
|
+
const refreshToken = await vault.get(secretId(s, 'refreshToken'));
|
|
152
|
+
if (expiresAt && Date.now() > expiresAt - 60_000 && refreshToken) {
|
|
153
|
+
// Providers that rotate refresh tokens break if two refreshes race, so one refresh per service at a time.
|
|
154
|
+
const key = serviceKey(s);
|
|
155
|
+
if (!refreshing.has(key)) refreshing.set(key, exchange(s, { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: stateOf(s).config.clientId ?? '' }).finally(() => refreshing.delete(key)));
|
|
156
|
+
await refreshing.get(key);
|
|
157
|
+
}
|
|
158
|
+
const token = await vault.get(secretId(s, 'accessToken'));
|
|
159
|
+
if (!token) throw new Error(`${s.label} isn't connected (Settings → Services → ${s.label} → Connect).`);
|
|
160
|
+
return token;
|
|
161
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Sessions: services signed in with "Current Session" (the user's own browser session) report whether that session is there.
|
|
2
|
+
// The header's Sessions icon is yellow only while a shown service has no active session; its menu lists every such service (green = detected and active, yellow = missing).
|
|
3
|
+
|
|
4
|
+
import type { Registry, RegistryService } from '../types.ts';
|
|
5
|
+
import { serviceKey } from '../types.ts';
|
|
6
|
+
import * as log from './log.ts';
|
|
7
|
+
import { createStore } from './prefs.ts';
|
|
8
|
+
import * as services from './services.ts';
|
|
9
|
+
|
|
10
|
+
export type SessionState = 'active' | 'missing' | 'checking';
|
|
11
|
+
export interface SessionStatus { state: SessionState; who?: string; detail?: string; at?: number }
|
|
12
|
+
|
|
13
|
+
export const statuses = createStore<Record<string, SessionStatus>>({});
|
|
14
|
+
|
|
15
|
+
/** Services currently signed in with Current Session and not turned off. */
|
|
16
|
+
export const sessionServices = (reg: Registry): RegistryService[] =>
|
|
17
|
+
reg.services.filter((s) => s.auth.includes('session') && services.stateOf(s).mode === 'session' && services.stateOf(s).enabled);
|
|
18
|
+
|
|
19
|
+
/** The ones the menu shows: a user may hide a connected, active service from it (default: shown). */
|
|
20
|
+
export const shown = (reg: Registry) => sessionServices(reg).filter((s) => !services.stateOf(s).hideFromSessions);
|
|
21
|
+
|
|
22
|
+
export const statusOf = (s: RegistryService): SessionStatus | undefined => statuses.get()[serviceKey(s)];
|
|
23
|
+
|
|
24
|
+
/** How bad is "no session" for this service? Set by the service's `sessionRequirement`: required → danger, recommended → warning, optional → fine. */
|
|
25
|
+
export type Level = 'ok' | 'warn' | 'bad';
|
|
26
|
+
export const REQUIREMENT_LABEL = { required: 'Required', recommended: 'Recommended', optional: 'Optional' } as const;
|
|
27
|
+
const RANK: Record<Level, number> = { ok: 0, warn: 1, bad: 2 };
|
|
28
|
+
|
|
29
|
+
/** The color of one service's session: green when active (or missing but optional), yellow when missing and recommended, red when missing and required. undefined until it has been checked. */
|
|
30
|
+
export function levelOf(s: RegistryService, st: SessionStatus | undefined): Level | undefined {
|
|
31
|
+
if (!st || st.state === 'checking') return undefined;
|
|
32
|
+
if (st.state === 'active') return 'ok';
|
|
33
|
+
return s.sessionRequirement === 'required' ? 'bad' : s.sessionRequirement === 'optional' ? 'ok' : 'warn';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The header icon's one color: the worst level across every shown service (2 green + 1 red = red). undefined while nothing has been checked yet. */
|
|
37
|
+
export function worst(reg: Registry, all = statuses.get()): Level | undefined {
|
|
38
|
+
let out: Level | undefined;
|
|
39
|
+
for (const s of shown(reg)) {
|
|
40
|
+
const l = levelOf(s, all[serviceKey(s)]);
|
|
41
|
+
if (l && (!out || RANK[l] > RANK[out])) out = l;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const put = (s: RegistryService, st: SessionStatus) => statuses.set({ ...statuses.get(), [serviceKey(s)]: st });
|
|
47
|
+
|
|
48
|
+
/** Asks the service: its `session()` if it has one, else whether its `test()` passes. */
|
|
49
|
+
export async function check(s: RegistryService, run?: (s: RegistryService) => Promise<{ active: boolean; who?: string; detail?: string }>): Promise<SessionStatus> {
|
|
50
|
+
const before = statusOf(s);
|
|
51
|
+
put(s, { ...before, state: before?.state ?? 'checking' }); // keep the last known answer while re-checking: no flicker
|
|
52
|
+
let result: SessionStatus;
|
|
53
|
+
try {
|
|
54
|
+
const r = await (run ?? defaultRun)(s);
|
|
55
|
+
result = r.active ? { state: 'active', who: r.who, at: Date.now() } : { state: 'missing', detail: r.detail ?? 'No signed-in session detected', at: Date.now() };
|
|
56
|
+
} catch (e) {
|
|
57
|
+
result = { state: 'missing', detail: (e as Error).message, at: Date.now() };
|
|
58
|
+
}
|
|
59
|
+
if (before?.state !== result.state) log.add(result.state === 'active' ? 'info' : 'warn', `${s.label} session: ${result.state === 'active' ? `active${result.who ? ` (${result.who})` : ''}` : `missing (${result.detail})`}`, undefined, 'Sessions');
|
|
60
|
+
put(s, result);
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function defaultRun(s: RegistryService) {
|
|
65
|
+
const impl = services.implFor(s);
|
|
66
|
+
const ctx = services.contextFor(s);
|
|
67
|
+
if (impl?.session) return impl.session(ctx);
|
|
68
|
+
if (impl?.test) { const r = await impl.test(ctx); return { active: true, who: r?.who }; }
|
|
69
|
+
return { active: true, detail: 'No session check defined by this service' };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const checkAll = (reg: Registry) => Promise.all(sessionServices(reg).map((s) => check(s)));
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// The page the app opens on (ADR-064). The developer sets a default in taco.json (`settings.startPage`); the user can override it in
|
|
2
|
+
// Settings → Configuration → Start page. Values: "auto" (the first Featured action, else Home) · "home" · "reports" · a view key "<module>/<view>".
|
|
3
|
+
// Getting Started always comes first until a vault exists (ADR-047), and anything that no longer exists falls back to "auto".
|
|
4
|
+
|
|
5
|
+
import type { Registry, RegistryView } from '../types.ts';
|
|
6
|
+
import { viewKey } from '../types.ts';
|
|
7
|
+
import { href } from './router.ts';
|
|
8
|
+
|
|
9
|
+
export const START_AUTO = 'auto';
|
|
10
|
+
|
|
11
|
+
/** Does the app have Reports views (so "reports" is a possible start page)? */
|
|
12
|
+
const hasReportViews = (reg: Registry) => reg.views.some((v) => (v.nav.section ?? 'home') === 'reports');
|
|
13
|
+
|
|
14
|
+
/** The hash the app opens on. `firstFeatured` is the rail's first Featured action (`nav.home.featured[0]`). */
|
|
15
|
+
export function startHash(reg: Registry, firstFeatured: RegistryView | undefined, choice?: string | null, appDefault?: string): string {
|
|
16
|
+
const auto = () => (firstFeatured ? href.view(firstFeatured.module, firstFeatured.name) : '#/home');
|
|
17
|
+
for (const pick of [choice, appDefault]) {
|
|
18
|
+
if (!pick || pick === START_AUTO) { if (pick === START_AUTO) return auto(); continue; }
|
|
19
|
+
if (pick === 'home') return '#/home';
|
|
20
|
+
if (pick === 'reports') { if (hasReportViews(reg)) return '#/reports'; continue; }
|
|
21
|
+
const v = reg.views.find((x) => viewKey(x) === pick);
|
|
22
|
+
if (v) return href.view(v.module, v.name); // a view that was removed (or a module taken out of the app) falls through to the next choice
|
|
23
|
+
}
|
|
24
|
+
return auto();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The app default as the developer set it (for the "App default" line in Settings). */
|
|
28
|
+
export const appDefaultOf = (reg: Registry) => reg.settings.startPage ?? START_AUTO;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// chrome.storage with an in-memory fallback, so core logic runs in tests and in a plain browser tab.
|
|
2
|
+
// `local` = settings, ciphertext, service config (ADR-003). `session` = memory-only, cleared when the browser closes (the vault key).
|
|
3
|
+
|
|
4
|
+
export type Area = 'local' | 'session';
|
|
5
|
+
type Listener = (value: unknown) => void;
|
|
6
|
+
|
|
7
|
+
const memory: Record<Area, Map<string, unknown>> = { local: new Map(), session: new Map() };
|
|
8
|
+
const memoryListeners = new Map<string, Set<Listener>>();
|
|
9
|
+
const hasChrome = () => typeof chrome !== 'undefined' && !!chrome.storage?.local;
|
|
10
|
+
|
|
11
|
+
export async function get<T>(area: Area, key: string): Promise<T | undefined> {
|
|
12
|
+
if (!hasChrome()) return structuredClone(memory[area].get(key)) as T | undefined;
|
|
13
|
+
const got = await chrome.storage[area].get(key);
|
|
14
|
+
return got[key] as T | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function set(area: Area, key: string, value: unknown): Promise<void> {
|
|
18
|
+
if (!hasChrome()) {
|
|
19
|
+
memory[area].set(key, structuredClone(value));
|
|
20
|
+
for (const fn of memoryListeners.get(`${area}:${key}`) ?? []) fn(value);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
await chrome.storage[area].set({ [key]: value });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function remove(area: Area, key: string): Promise<void> {
|
|
27
|
+
if (!hasChrome()) {
|
|
28
|
+
memory[area].delete(key);
|
|
29
|
+
for (const fn of memoryListeners.get(`${area}:${key}`) ?? []) fn(undefined);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
await chrome.storage[area].remove(key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Calls `fn(newValue)` whenever `key` changes in `area` (from any page or the service worker). */
|
|
36
|
+
export function onChange(area: Area, key: string, fn: Listener): () => void {
|
|
37
|
+
if (!hasChrome()) {
|
|
38
|
+
const k = `${area}:${key}`;
|
|
39
|
+
if (!memoryListeners.has(k)) memoryListeners.set(k, new Set());
|
|
40
|
+
memoryListeners.get(k)!.add(fn);
|
|
41
|
+
return () => memoryListeners.get(k)?.delete(fn);
|
|
42
|
+
}
|
|
43
|
+
const listener = (changes: Record<string, chrome.storage.StorageChange>, changedArea: string) => {
|
|
44
|
+
if (changedArea === area && key in changes) fn(changes[key].newValue);
|
|
45
|
+
};
|
|
46
|
+
chrome.storage.onChanged.addListener(listener);
|
|
47
|
+
return () => chrome.storage.onChanged.removeListener(listener);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Test helper: forget everything stored in memory. */
|
|
51
|
+
export function resetMemory() {
|
|
52
|
+
memory.local.clear();
|
|
53
|
+
memory.session.clear();
|
|
54
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// System tools (ADR-054): framework-provided Tools-menu entries a view switches on by listing them in its manifest:
|
|
2
|
+
// "tools": { "system": ["copy-chart", "copy-report"], "selector": "div.card" } (selector: which DIVs Copy Chart may pick; default: every div)
|
|
3
|
+
// Ported from CommunityOS v2 (lib/chartcopy.js, FR-TOOLS-1).
|
|
4
|
+
|
|
5
|
+
import type { Tool } from '@tacoshell/sdk';
|
|
6
|
+
import { blockToPng, paneToPng } from './domshot.ts';
|
|
7
|
+
import * as log from './log.ts';
|
|
8
|
+
import { toast } from './toasts.ts';
|
|
9
|
+
|
|
10
|
+
export const SYSTEM_TOOLS = ['copy-chart', 'copy-report'] as const;
|
|
11
|
+
export type SystemTool = (typeof SYSTEM_TOOLS)[number];
|
|
12
|
+
|
|
13
|
+
/** The view's content pane: what Copy Chart picks inside and what Copy Report pictures (without the 3rd-level bar, Log and Help). */
|
|
14
|
+
const pane = () => document.querySelector<HTMLElement>('main.content');
|
|
15
|
+
const isChrome = (el: Element) => el.matches('.subbar, .taco-pick');
|
|
16
|
+
|
|
17
|
+
async function toClipboard(blob: Blob, what: string) {
|
|
18
|
+
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
|
|
19
|
+
log.add('info', `${what} copied to the clipboard (${Math.round(blob.size / 1024)} KB PNG)`, undefined, 'Tools');
|
|
20
|
+
toast(`${what} copied. Paste it where you need it.`);
|
|
21
|
+
}
|
|
22
|
+
const nextFrame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
|
23
|
+
|
|
24
|
+
let cancelPick: (() => void) | null = null;
|
|
25
|
+
|
|
26
|
+
/** Copy Chart: hover outlines the nearest matching block, a click copies it as a PNG, Esc (or pressing it again) cancels. */
|
|
27
|
+
export function copyChart(selector = 'div') {
|
|
28
|
+
if (cancelPick) { cancelPick(); return; }
|
|
29
|
+
const scope = pane();
|
|
30
|
+
if (!scope) return toast('Nothing to copy on this page.', 'error');
|
|
31
|
+
const frame = Object.assign(document.createElement('div'), { className: 'taco-pick taco-pick-frame' });
|
|
32
|
+
const banner = Object.assign(document.createElement('div'), { className: 'taco-pick taco-pick-banner', textContent: 'Click a block to copy it as a picture · Esc to cancel' });
|
|
33
|
+
banner.setAttribute('role', 'status');
|
|
34
|
+
document.body.append(frame, banner);
|
|
35
|
+
const blockAt = (t: EventTarget | null) => {
|
|
36
|
+
if (!(t instanceof Element) || !scope.contains(t) || t.closest('.subbar')) return null;
|
|
37
|
+
const b = t.closest(selector);
|
|
38
|
+
return b && scope.contains(b) && b !== scope ? b : null;
|
|
39
|
+
};
|
|
40
|
+
const move = (e: MouseEvent) => {
|
|
41
|
+
const b = blockAt(e.target);
|
|
42
|
+
if (!b) { frame.style.display = 'none'; return; }
|
|
43
|
+
const r = b.getBoundingClientRect();
|
|
44
|
+
Object.assign(frame.style, { display: 'block', left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
|
45
|
+
};
|
|
46
|
+
const stop = () => {
|
|
47
|
+
document.removeEventListener('mousemove', move, true);
|
|
48
|
+
document.removeEventListener('click', click, true);
|
|
49
|
+
document.removeEventListener('keydown', key, true);
|
|
50
|
+
frame.remove(); banner.remove(); document.body.style.cursor = ''; cancelPick = null;
|
|
51
|
+
};
|
|
52
|
+
const key = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); stop(); toast('Copy Chart cancelled.'); } };
|
|
53
|
+
async function click(e: MouseEvent) {
|
|
54
|
+
const b = blockAt(e.target);
|
|
55
|
+
if (!b) return;
|
|
56
|
+
e.preventDefault(); e.stopPropagation();
|
|
57
|
+
stop(); // the outline and banner must not be in the picture
|
|
58
|
+
await nextFrame();
|
|
59
|
+
try { await toClipboard(await blockToPng(b), 'Chart'); } catch (err) { log.add('error', `Copy Chart failed: ${(err as Error).message}`, undefined, 'Tools'); toast(`Couldn't copy the chart: ${(err as Error).message}`, 'error'); }
|
|
60
|
+
}
|
|
61
|
+
document.addEventListener('mousemove', move, true);
|
|
62
|
+
document.addEventListener('click', click, true);
|
|
63
|
+
document.addEventListener('keydown', key, true);
|
|
64
|
+
document.body.style.cursor = 'crosshair';
|
|
65
|
+
cancelPick = stop;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Copy Report: the whole view pane (title and all content, full height) as one PNG. */
|
|
69
|
+
export async function copyReport() {
|
|
70
|
+
const p = pane();
|
|
71
|
+
if (!p) return toast('Nothing to copy on this page.', 'error');
|
|
72
|
+
toast('Copying the page…');
|
|
73
|
+
await nextFrame();
|
|
74
|
+
try { await toClipboard(await paneToPng(p, { skip: isChrome }), 'Page'); } catch (err) { log.add('error', `Copy Report failed: ${(err as Error).message}`, undefined, 'Tools'); toast(`Couldn't copy the page: ${(err as Error).message}`, 'error'); }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The Tools-menu entries for a view's `tools` declaration. Unknown names are ignored (the CLI rejects them at build time). */
|
|
78
|
+
export function systemToolsFor(decl: { system?: string[]; selector?: string } | undefined): Tool[] {
|
|
79
|
+
const out: Tool[] = [];
|
|
80
|
+
for (const name of decl?.system ?? []) {
|
|
81
|
+
if (name === 'copy-chart') out.push({ id: 'taco:copy-chart', label: 'Copy Chart', icon: 'fa-solid fa-camera', run: () => copyChart(decl?.selector || 'div') });
|
|
82
|
+
if (name === 'copy-report') out.push({ id: 'taco:copy-report', label: 'Copy Report', icon: 'fa-solid fa-images', run: () => copyReport() });
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Which 3rd-level tabs show and which go to "More" (pure, so it is unit-tested; the DOM measuring is in ui/TabBar.tsx).
|
|
2
|
+
|
|
3
|
+
/** Space kept clear between the tabs and the action buttons (Refresh …) on their right. Tabs that would reach into it move to "More". */
|
|
4
|
+
export const TAB_GUTTER = 64;
|
|
5
|
+
export const TAB_GAP = 4;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Which tabs show: the current one always (room is reserved for it first), then as many others, in order, as fit beside a More button.
|
|
9
|
+
* When even the current tab plus More won't fit, nothing shows but More (labelled with the current page), so the gutter is never entered.
|
|
10
|
+
*/
|
|
11
|
+
export function fit(widths: number[], moreWidth: number, avail: number, active: number): { shown: number[]; hidden: number[] } {
|
|
12
|
+
const all = widths.map((_, i) => i);
|
|
13
|
+
const total = widths.reduce((s, w) => s + w, 0) + TAB_GAP * Math.max(0, widths.length - 1);
|
|
14
|
+
if (total <= avail) return { shown: all, hidden: [] };
|
|
15
|
+
let used = moreWidth;
|
|
16
|
+
const chosen = new Set<number>();
|
|
17
|
+
if (active >= 0) {
|
|
18
|
+
used += widths[active] + TAB_GAP;
|
|
19
|
+
if (used > avail) return { shown: [], hidden: all };
|
|
20
|
+
chosen.add(active);
|
|
21
|
+
}
|
|
22
|
+
for (const i of all) {
|
|
23
|
+
if (i === active) continue;
|
|
24
|
+
if (used + widths[i] + TAB_GAP > avail) break;
|
|
25
|
+
used += widths[i] + TAB_GAP;
|
|
26
|
+
chosen.add(i);
|
|
27
|
+
}
|
|
28
|
+
const shown = all.filter((i) => chosen.has(i));
|
|
29
|
+
return { shown, hidden: all.filter((i) => !chosen.has(i)) };
|
|
30
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Templates (from CommunityOS v2 lib/templates.js): developer-shipped text the user may reword but not create. The shipped value is the default and the
|
|
2
|
+
// source of truth for which ${tokens} may be used (the module declares them). A user's edit is stored in the vault (item `template.<module>/<name>`).
|
|
3
|
+
// await templates.render(t, { alias: 'ada' }) → string; throws if a token has no value, so a blank never goes out in an email.
|
|
4
|
+
|
|
5
|
+
import type { RegistryTemplate } from '../types.ts';
|
|
6
|
+
import * as vault from './vault.ts';
|
|
7
|
+
|
|
8
|
+
const TOKEN = /\$\{\s*([A-Za-z_]\w*)\s*\}/g;
|
|
9
|
+
export const idOf = (t: { module: string; name: string }) => `${t.module}/${t.name}`;
|
|
10
|
+
const itemOf = (t: { module: string; name: string }) => `template.${idOf(t)}`;
|
|
11
|
+
|
|
12
|
+
export const tokensOf = (text: string) => [...new Set([...String(text).matchAll(TOKEN)].map((m) => m[1]))];
|
|
13
|
+
|
|
14
|
+
/** null when the edit is valid; otherwise a message naming the tokens the module didn't declare. */
|
|
15
|
+
export function validateEdit(t: Pick<RegistryTemplate, 'tokens'>, edited: string): string | null {
|
|
16
|
+
const bad = tokensOf(edited).filter((k) => !t.tokens.includes(k));
|
|
17
|
+
if (!bad.length) return null;
|
|
18
|
+
return `Unknown token${bad.length > 1 ? 's' : ''}: ${bad.map((k) => '${' + k + '}').join(', ')}. Allowed: ${t.tokens.map((k) => '${' + k + '}').join(', ') || 'none'}.`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface Resolved { value: string; edited: boolean; updatedAt?: number }
|
|
22
|
+
|
|
23
|
+
/** The effective text: the user's edit, unless it is stale (uses a token the module has since removed), then the shipped default. */
|
|
24
|
+
export async function get(t: RegistryTemplate): Promise<Resolved> {
|
|
25
|
+
let edit: { value?: unknown; updatedAt?: number } | null = null;
|
|
26
|
+
try { edit = JSON.parse((await vault.get(itemOf(t))) || 'null'); } catch { /* unreadable edit: use the default */ }
|
|
27
|
+
const usable = !!edit && typeof edit.value === 'string' && !validateEdit(t, edit.value);
|
|
28
|
+
return usable ? { value: edit!.value as string, edited: true, updatedAt: edit!.updatedAt } : { value: t.value, edited: false };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function save(t: RegistryTemplate, value: string) {
|
|
32
|
+
const err = validateEdit(t, value);
|
|
33
|
+
if (err) throw new Error(err);
|
|
34
|
+
if (value === t.value) return reset(t);
|
|
35
|
+
await vault.put(itemOf(t), JSON.stringify({ value, updatedAt: Date.now() }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const reset = (t: RegistryTemplate) => vault.remove(itemOf(t));
|
|
39
|
+
|
|
40
|
+
/** Fills ${tokens} from `vars`; a token with no value throws. */
|
|
41
|
+
export function fill(text: string, vars: Record<string, unknown>, name = 'template'): string {
|
|
42
|
+
return text.replace(TOKEN, (_, k: string) => {
|
|
43
|
+
if (vars[k] == null) throw new Error(`Template “${name}” needs a value for \${${k}}.`);
|
|
44
|
+
return String(vars[k]);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function render(t: RegistryTemplate, vars: Record<string, unknown>) { return fill((await get(t)).value, vars, t.name); }
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// In-app toasts (bottom-right; errors stay until dismissed, others go after 4 s: UX.md).
|
|
2
|
+
import { createStore } from './prefs.ts';
|
|
3
|
+
|
|
4
|
+
export interface Toast { id: number; text: string; kind: 'info' | 'error'; title?: string }
|
|
5
|
+
export const toasts = createStore<Toast[]>([]);
|
|
6
|
+
let next = 1;
|
|
7
|
+
|
|
8
|
+
export function toast(text: string, kind: Toast['kind'] = 'info', title?: string) {
|
|
9
|
+
const t = { id: next++, text, kind, title };
|
|
10
|
+
toasts.set([...toasts.get(), t]);
|
|
11
|
+
if (kind !== 'error') setTimeout(() => dismiss(t.id), 4000);
|
|
12
|
+
}
|
|
13
|
+
export const dismiss = (id: number) => toasts.set(toasts.get().filter((t) => t.id !== id));
|