@kiosko/sdk 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/src/schema.ts ADDED
@@ -0,0 +1,264 @@
1
+ /**
2
+ * A tiny, typed schema builder for plugin options.
3
+ *
4
+ * One declaration gives three things at once:
5
+ * - the TypeScript type of the options (`Infer<typeof schema>`),
6
+ * - the defaults and the validation the runtime applies to user config,
7
+ * - the form the editor renders (labels, hints, sliders, colour pickers…).
8
+ *
9
+ * `toJsonSchema` exports a standard JSON Schema (draft 2020-12) with `x-ui`
10
+ * hints, so tools that don't speak TypeScript can still validate a config.
11
+ */
12
+ import { localize, type Localized } from './i18n.ts';
13
+
14
+ /**
15
+ * What a value of a field lets Kiosko do as the user, so a config written by
16
+ * someone else (or by an AI) can be reviewed before it runs:
17
+ *
18
+ * - `exec`: runs a program or loads code (a command, an ssh host, a module);
19
+ * - `network`: contacts a host (a URL, an API host, a feed);
20
+ * - `path`: reads (or writes) a local file or folder.
21
+ *
22
+ * A list when it depends on the value, e.g. `['network', 'path']` for "a URL
23
+ * or a file": a value that looks like a URL counts as `network`, any other as
24
+ * the next one. Only free values need it; a switch that turns on a fixed tool
25
+ * (read git status) doesn't.
26
+ */
27
+ export type Risk = 'exec' | 'network' | 'path';
28
+
29
+ interface Common<T> {
30
+ /** Shown above the input in the editor. */
31
+ label?: Localized;
32
+ /** One line under the input. */
33
+ help?: Localized;
34
+ default: T;
35
+ /** Hide in the editor unless "advanced" is toggled. */
36
+ advanced?: boolean;
37
+ /** See `Risk`. Exported as `x-risk`; `kiosko config import` lists these values before applying a config. */
38
+ risk?: Risk | readonly Risk[];
39
+ }
40
+
41
+ export interface StringField extends Common<string> {
42
+ kind: 'string';
43
+ placeholder?: string;
44
+ multiline?: boolean;
45
+ /** Tokens, URLs with credentials…: masked in the editor and never logged. */
46
+ secret?: boolean;
47
+ /** Free text with a format hint: `url`, `path`, `time` (HH:MM), `date` (YYYY-MM-DD). */
48
+ format?: 'url' | 'path' | 'time' | 'date' | 'datetime';
49
+ maxLength?: number;
50
+ }
51
+ export interface NumberField extends Common<number> {
52
+ kind: 'number';
53
+ integer?: boolean;
54
+ min?: number;
55
+ max?: number;
56
+ step?: number;
57
+ /** Shown after the value: `ms`, `px`, `°C`, `%`… */
58
+ unit?: string;
59
+ /** Render as a slider when min and max are known. */
60
+ slider?: boolean;
61
+ }
62
+ export interface BooleanField extends Common<boolean> {
63
+ kind: 'boolean';
64
+ }
65
+ export interface EnumField<V extends string = string> extends Common<V> {
66
+ kind: 'enum';
67
+ values: readonly V[];
68
+ /** Label per value; the raw value otherwise. */
69
+ labels?: Partial<Record<V, Localized>>;
70
+ }
71
+ export interface ColorField extends Common<string> {
72
+ kind: 'color';
73
+ }
74
+ export interface ListField<I extends Field = Field> extends Common<Infer<I>[]> {
75
+ kind: 'list';
76
+ item: I;
77
+ max?: number;
78
+ /** Patterns for `matchFilter` (see `t.filter`): the editor edits them as one line, comma-separated. */
79
+ filter?: boolean;
80
+ }
81
+ export interface ObjectField<P extends Record<string, Field> = Record<string, Field>> extends Common<{ [K in keyof P]: Infer<P[K]> }> {
82
+ kind: 'object';
83
+ props: P;
84
+ }
85
+ /** A string → string map (aliases, renames…). */
86
+ export interface MapField extends Common<Record<string, string>> {
87
+ kind: 'map';
88
+ keyLabel?: Localized;
89
+ valueLabel?: Localized;
90
+ }
91
+
92
+ export type Field = StringField | NumberField | BooleanField | EnumField<string> | ColorField | ListField<any> | ObjectField<any> | MapField;
93
+
94
+ /** The TypeScript type a field validates to. */
95
+ export type Infer<F> = F extends ObjectField<infer P>
96
+ ? { [K in keyof P]: Infer<P[K]> }
97
+ : F extends ListField<infer I>
98
+ ? Infer<I>[]
99
+ : F extends EnumField<infer V>
100
+ ? V
101
+ : F extends Common<infer T>
102
+ ? T
103
+ : never;
104
+
105
+ type Opts<F extends { kind: string; default: unknown }, X extends string = never> = Omit<F, 'kind' | 'default' | X> & { default?: F['default'] };
106
+
107
+ export const t = {
108
+ string: (o: Opts<StringField> = {}): StringField => ({ kind: 'string', default: '', ...o }),
109
+ number: (o: Opts<NumberField> = {}): NumberField => ({ kind: 'number', default: o.min ?? 0, ...o }),
110
+ integer: (o: Opts<NumberField> = {}): NumberField => ({ kind: 'number', integer: true, default: o.min ?? 0, ...o }),
111
+ boolean: (o: Opts<BooleanField> = {}): BooleanField => ({ kind: 'boolean', default: false, ...o }),
112
+ enum: <const V extends string>(values: readonly V[], o: Opts<EnumField<V>, 'values'> = {}): EnumField<V> => ({ kind: 'enum', values, default: values[0]!, ...o }),
113
+ color: (o: Opts<ColorField> = {}): ColorField => ({ kind: 'color', default: '#ffffff', ...o }),
114
+ list: <I extends Field>(item: I, o: Opts<ListField<I>, 'item'> = {}): ListField<I> => ({ kind: 'list', item, default: [], ...o }),
115
+ object: <P extends Record<string, Field>>(props: P, o: Omit<Opts<ObjectField<P>, 'props'>, 'default'> = {}): ObjectField<P> =>
116
+ ({ kind: 'object', props, ...o, default: Object.fromEntries(Object.entries(props).map(([k, f]) => [k, clone(f.default)])) as ObjectField<P>['default'] }),
117
+ map: (o: Opts<MapField> = {}): MapField => ({ kind: 'map', default: {}, ...o }),
118
+ /** Duration in milliseconds, edited in seconds or minutes by the editor. */
119
+ duration: (o: Opts<NumberField> = {}): NumberField => ({ kind: 'number', integer: true, unit: 'ms', min: 0, default: 60_000, ...o }),
120
+ /**
121
+ * Which items to show, as patterns for `matchFilter`: `["web", "acme/*",
122
+ * "!*-old"]`. Empty = all. Name it after what it filters (`projects`,
123
+ * `repos`, `calendars`, `people`) and give it a `label`; the `help`
124
+ * explaining the patterns comes with it.
125
+ */
126
+ filter: (o: Opts<ListField<StringField>, 'item'> = {}): ListField<StringField> => ({
127
+ kind: 'list',
128
+ item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*' },
129
+ default: [],
130
+ filter: true,
131
+ help: FILTER_HELP,
132
+ ...o,
133
+ }),
134
+ };
135
+
136
+ /** The help every `t.filter()` field carries unless it brings its own. */
137
+ export const FILTER_HELP: Localized = {
138
+ en: 'Empty: all. Names or patterns, comma-separated: * matches anything, a leading ! leaves out (web, acme/*, !*-old).',
139
+ es: 'Vacío: todos. Nombres o patrones separados por comas: * vale por cualquier cosa y un ! delante excluye (web, acme/*, !*-old).',
140
+ };
141
+
142
+ function clone<T>(v: T): T {
143
+ return v === undefined ? v : (JSON.parse(JSON.stringify(v)) as T);
144
+ }
145
+
146
+ /** The defaults of a field, deep-copied (safe to mutate). */
147
+ export function defaultsOf<F extends Field>(f: F): Infer<F> {
148
+ return clone(f.default) as Infer<F>;
149
+ }
150
+
151
+ export interface ValidationIssue {
152
+ /** `events.2.date` */
153
+ path: string;
154
+ message: string;
155
+ }
156
+
157
+ /**
158
+ * Coerces `value` to the shape of `f`: unknown keys are kept (so a newer
159
+ * config survives an older plugin), wrong types fall back to the default
160
+ * and are reported. Never throws.
161
+ */
162
+ export function validate<F extends Field>(f: F, value: unknown, path = ''): { value: Infer<F>; issues: ValidationIssue[] } {
163
+ const issues: ValidationIssue[] = [];
164
+ const out = coerce(f, value, path, issues);
165
+ return { value: out as Infer<F>, issues };
166
+ }
167
+
168
+ function coerce(f: Field, v: unknown, path: string, issues: ValidationIssue[]): unknown {
169
+ const bad = (msg: string) => {
170
+ issues.push({ path: path || '(root)', message: msg });
171
+ return clone(f.default);
172
+ };
173
+ if (v === undefined || v === null) return clone(f.default);
174
+ switch (f.kind) {
175
+ case 'string':
176
+ if (typeof v === 'number') return String(v);
177
+ if (typeof v !== 'string') return bad('expected text');
178
+ return f.maxLength && v.length > f.maxLength ? v.slice(0, f.maxLength) : v;
179
+ case 'color':
180
+ if (typeof v !== 'string') return bad('expected a colour');
181
+ return v;
182
+ case 'number': {
183
+ const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
184
+ if (typeof n !== 'number' || !Number.isFinite(n)) return bad('expected a number');
185
+ let x = f.integer ? Math.round(n) : n;
186
+ if (f.min !== undefined && x < f.min) x = f.min;
187
+ if (f.max !== undefined && x > f.max) x = f.max;
188
+ return x;
189
+ }
190
+ case 'boolean':
191
+ if (typeof v === 'boolean') return v;
192
+ if (v === 'true' || v === 'false') return v === 'true';
193
+ return bad('expected true/false');
194
+ case 'enum':
195
+ if (typeof v === 'string' && (f.values as readonly string[]).includes(v)) return v;
196
+ return bad(`expected one of ${f.values.join(', ')}`);
197
+ case 'list': {
198
+ if (!Array.isArray(v)) return bad('expected a list');
199
+ const items = v.map((item, i) => coerce(f.item, item, path ? `${path}.${i}` : String(i), issues));
200
+ return f.max !== undefined ? items.slice(0, f.max) : items;
201
+ }
202
+ case 'map': {
203
+ if (typeof v !== 'object' || Array.isArray(v)) return bad('expected key/value pairs');
204
+ return Object.fromEntries(Object.entries(v as Record<string, unknown>).filter(([, x]) => typeof x === 'string' || typeof x === 'number').map(([k, x]) => [k, String(x)]));
205
+ }
206
+ case 'object': {
207
+ if (typeof v !== 'object' || Array.isArray(v)) return bad('expected an object');
208
+ const src = v as Record<string, unknown>;
209
+ const out: Record<string, unknown> = { ...src };
210
+ for (const [k, sub] of Object.entries(f.props as Record<string, Field>)) out[k] = coerce(sub, src[k], path ? `${path}.${k}` : k, issues);
211
+ return out;
212
+ }
213
+ }
214
+ }
215
+
216
+ /** Appended to the description of secret fields in the JSON Schema. */
217
+ export const SECRET_NOTE = 'Secret: leave it empty (or a placeholder such as "<token>"). Kiosko keeps the value it already has, or asks for it in the editor.';
218
+
219
+ /**
220
+ * Standard JSON Schema (draft 2020-12) with `x-ui` hints, for tools outside
221
+ * TypeScript: `title`/`description` in English, `x-secret` on secrets and
222
+ * `x-risk` (see `Risk`) on values that run programs, contact hosts or read
223
+ * paths. URLs carry no `format` keyword: an empty value or a placeholder is
224
+ * valid (a secret URL is filled in later), and editors would flag both.
225
+ */
226
+ export function toJsonSchema(f: Field): Record<string, unknown> {
227
+ const ui = { label: f.label, help: f.help, advanced: f.advanced };
228
+ const secret = f.kind === 'string' && !!f.secret;
229
+ const help = f.help === undefined ? undefined : localize(f.help, 'en');
230
+ const description = secret ? [help, SECRET_NOTE].filter(Boolean).join(' ') : help;
231
+ const base: Record<string, unknown> = {
232
+ ...(f.label === undefined ? {} : { title: localize(f.label, 'en') }),
233
+ ...(description ? { description } : {}),
234
+ default: f.default,
235
+ 'x-ui': ui,
236
+ ...(secret ? { 'x-secret': true } : {}),
237
+ ...(f.risk === undefined ? {} : { 'x-risk': typeof f.risk === 'string' ? f.risk : [...f.risk] }),
238
+ };
239
+ switch (f.kind) {
240
+ case 'string':
241
+ return { ...base, type: 'string', ...(f.format === 'date' ? { format: 'date' } : {}), ...(f.maxLength ? { maxLength: f.maxLength } : {}), 'x-ui': { ...ui, secret: f.secret, multiline: f.multiline, placeholder: f.placeholder, format: f.format } };
242
+ case 'color':
243
+ return { ...base, type: 'string', 'x-ui': { ...ui, widget: 'color' } };
244
+ case 'number':
245
+ return { ...base, type: f.integer ? 'integer' : 'number', minimum: f.min, maximum: f.max, 'x-ui': { ...ui, unit: f.unit, step: f.step, slider: f.slider } };
246
+ case 'boolean':
247
+ return { ...base, type: 'boolean' };
248
+ case 'enum':
249
+ return { ...base, type: 'string', enum: [...f.values], 'x-ui': { ...ui, labels: f.labels } };
250
+ case 'list':
251
+ return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter' }, 'x-filter': true } : {}) };
252
+ case 'map':
253
+ return { ...base, type: 'object', additionalProperties: { type: 'string' } };
254
+ case 'object':
255
+ return { ...base, type: 'object', properties: Object.fromEntries(Object.entries(f.props as Record<string, Field>).map(([k, sub]) => [k, toJsonSchema(sub)])) };
256
+ }
257
+ }
258
+
259
+ /** The risks of a field, as a list (empty when it has none). */
260
+ export function risksOf(f: { risk?: Risk | readonly Risk[] } | { 'x-risk'?: unknown }): Risk[] {
261
+ const r = 'risk' in f ? f.risk : (f as { 'x-risk'?: unknown })['x-risk'];
262
+ const list = typeof r === 'string' ? [r] : Array.isArray(r) ? r : [];
263
+ return list.filter((x): x is Risk => x === 'exec' || x === 'network' || x === 'path');
264
+ }
package/src/theme.ts ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Themes are design tokens, not CSS: every widget paints with `ctx.theme`, so
3
+ * switching the theme restyles the whole panel without touching a plugin.
4
+ *
5
+ * The default (`midnight`) is the art direction of the original aimonitor:
6
+ * the normal state is darkness, and colour is spent only on what claims you.
7
+ */
8
+ export interface ThemeColors {
9
+ /** Panel background. Kept near black: it's the backlight that wears out. */
10
+ bg: string;
11
+ /** Card background and its 1 px edge. */
12
+ surface: string;
13
+ surfaceEdge: string;
14
+ /** Text: primary, secondary and hints. */
15
+ ink: string;
16
+ inkDim: string;
17
+ inkFaint: string;
18
+ /** Brand/selection colour. */
19
+ accent: string;
20
+ /** Semaphore shared by every widget: needs you now / soon / informative / fine. */
21
+ alert: string;
22
+ warn: string;
23
+ info: string;
24
+ ok: string;
25
+ }
26
+
27
+ export interface ThemeFonts {
28
+ /** Condensed sans: titles, numbers. */
29
+ sans: string;
30
+ sansBold: string;
31
+ mono: string;
32
+ monoBold: string;
33
+ }
34
+
35
+ export interface Theme {
36
+ id: string;
37
+ name: string;
38
+ colors: ThemeColors;
39
+ fonts: ThemeFonts;
40
+ /** Card corner radius in px. */
41
+ radius: number;
42
+ /** Card title size in px (scaled for small panels by the compositor). */
43
+ titleSize: number;
44
+ }
45
+
46
+ /** Font families registered by the runtime (see core/fonts.ts). */
47
+ export const FONT_FAMILIES: ThemeFonts = {
48
+ sans: 'KioskoSans',
49
+ sansBold: 'KioskoSansBold',
50
+ mono: 'KioskoMono',
51
+ monoBold: 'KioskoMonoBold',
52
+ };
53
+
54
+ const base = { fonts: FONT_FAMILIES, radius: 12, titleSize: 30 };
55
+
56
+ export const THEMES: Theme[] = [
57
+ {
58
+ id: 'midnight',
59
+ name: 'Midnight',
60
+ ...base,
61
+ colors: { bg: '#05080D', surface: '#0D131A', surfaceEdge: '#1C2631', ink: '#D3DFEA', inkDim: '#627180', inkFaint: '#384450', accent: '#4DA3FF', alert: '#F5453D', warn: '#FFB020', info: '#4DA3FF', ok: '#3FCB7E' },
62
+ },
63
+ {
64
+ id: 'graphite',
65
+ name: 'Graphite',
66
+ ...base,
67
+ radius: 6,
68
+ colors: { bg: '#111214', surface: '#1A1C1F', surfaceEdge: '#2A2D31', ink: '#ECEDEE', inkDim: '#8B9096', inkFaint: '#4A4F55', accent: '#E8E8E8', alert: '#FF5F57', warn: '#FEBC2E', info: '#64B5F6', ok: '#28C840' },
69
+ },
70
+ {
71
+ id: 'aurora',
72
+ name: 'Aurora',
73
+ ...base,
74
+ radius: 16,
75
+ colors: { bg: '#0B0A1A', surface: '#15132B', surfaceEdge: '#2A2550', ink: '#EDE9FF', inkDim: '#8D86B8', inkFaint: '#4A4475', accent: '#9F7AEA', alert: '#FF4D8D', warn: '#FFC857', info: '#4CC9F0', ok: '#43E5A0' },
76
+ },
77
+ {
78
+ id: 'phosphor',
79
+ name: 'Phosphor',
80
+ ...base,
81
+ radius: 2,
82
+ fonts: { ...FONT_FAMILIES, sans: FONT_FAMILIES.mono, sansBold: FONT_FAMILIES.monoBold },
83
+ colors: { bg: '#020602', surface: '#061006', surfaceEdge: '#0F2A0F', ink: '#7CFF7C', inkDim: '#2F9E3A', inkFaint: '#165C1E', accent: '#7CFF7C', alert: '#FF5A3C', warn: '#FFD23C', info: '#5CE1E6', ok: '#7CFF7C' },
84
+ },
85
+ {
86
+ id: 'paper',
87
+ name: 'Paper',
88
+ ...base,
89
+ radius: 10,
90
+ colors: { bg: '#F2EFE8', surface: '#FFFFFF', surfaceEdge: '#DDD8CC', ink: '#1F2328', inkDim: '#6B6F76', inkFaint: '#B4B0A6', accent: '#2F6FEB', alert: '#D92D20', warn: '#C27803', info: '#2F6FEB', ok: '#1E8E3E' },
91
+ },
92
+ ];
93
+
94
+ export const DEFAULT_THEME = THEMES[0]!;
95
+
96
+ export function themeById(id: string | undefined): Theme {
97
+ return THEMES.find((t) => t.id === id) ?? DEFAULT_THEME;
98
+ }
package/src/workday.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The user's working week, set once in Settings and handed to every plugin
3
+ * as `ctx.workday`: which days, from when to when, how many hours are due,
4
+ * days with other hours (a short Friday) and days off. Plugins default to it
5
+ * instead of asking for their own start, end and holidays.
6
+ */
7
+
8
+ /** Other hours on one weekday. Unset fields are the week's. */
9
+ export interface DayHours {
10
+ start?: string;
11
+ end?: string;
12
+ hours?: number;
13
+ }
14
+
15
+ export interface Workday {
16
+ /** Working days, 0 = Sunday … 6 = Saturday. */
17
+ days: number[];
18
+ /** `HH:MM`, 24 h. */
19
+ start: string;
20
+ end: string;
21
+ /** Hours due on a working day (what a timesheet expects), not the span from start to end. */
22
+ hours: number;
23
+ /** Days off, `YYYY-MM-DD`: no work hours, nothing due. */
24
+ holidays: string[];
25
+ /** Days with other hours, by weekday (`"5"` = Friday): `{ "5": { "end": "15:00", "hours": 6 } }`. */
26
+ byDay: Partial<Record<string, DayHours>>;
27
+ }
28
+
29
+ export const DEFAULT_WORKDAY: Workday = { days: [1, 2, 3, 4, 5], start: '09:00', end: '17:00', hours: 8, holidays: [], byDay: {} };
30
+
31
+ /** `"09:30"` → 570. Anything unreadable is 0. */
32
+ export function minutesOf(hhmm: string | undefined): number {
33
+ const m = /^(\d{1,2}):(\d{2})/.exec(hhmm ?? '');
34
+ return m ? Number(m[1]) * 60 + Number(m[2]) : 0;
35
+ }
36
+
37
+ /** `YYYY-MM-DD` of the local day `at` falls in. */
38
+ export function dayKey(at: number | Date): string {
39
+ const d = new Date(at);
40
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
41
+ }
42
+
43
+ export interface DaySchedule {
44
+ /** A working day that is not a holiday. */
45
+ working: boolean;
46
+ holiday: boolean;
47
+ start: string;
48
+ end: string;
49
+ /** Minutes from local midnight. */
50
+ startMin: number;
51
+ endMin: number;
52
+ /** Hours due that day: 0 on days off. */
53
+ hours: number;
54
+ }
55
+
56
+ /** The schedule of the local day `at` falls in. */
57
+ export function scheduleOn(w: Workday, at: number | Date): DaySchedule {
58
+ const day = new Date(at).getDay();
59
+ const own = w.byDay?.[String(day)] ?? {};
60
+ const start = own.start || w.start;
61
+ const end = own.end || w.end;
62
+ const holiday = (w.holidays ?? []).includes(dayKey(at));
63
+ const working = w.days.includes(day) && !holiday;
64
+ return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? (own.hours ?? w.hours ?? 0) : 0 };
65
+ }
66
+
67
+ /** Inside work hours at `at`: a working day, not a holiday, between its start and end. */
68
+ export function isWorkingAt(w: Workday, at: number | Date): boolean {
69
+ const s = scheduleOn(w, at);
70
+ if (!s.working) return false;
71
+ const d = new Date(at);
72
+ const mins = d.getHours() * 60 + d.getMinutes();
73
+ return mins >= s.startMin && mins < s.endMin;
74
+ }
75
+
76
+ /** Hours due in a normal week (no holidays): the sum over the working days. */
77
+ export function weeklyHours(w: Workday): number {
78
+ return w.days.reduce((sum, d) => sum + (w.byDay?.[String(d)]?.hours ?? w.hours ?? 0), 0);
79
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.