@kiosko/sdk 0.2.1 → 0.2.2

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.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Helpers for plugin tests (Node only: they paint with @napi-rs/canvas).
3
+ *
4
+ * import { renderWidget, checkPlugin } from '@kiosko/sdk/testing';
5
+ *
6
+ * const r = renderWidget(forecast, { size: { w: 600, h: 300 }, locale: 'es' });
7
+ * assert.deepEqual(r.texts.slice(0, 2), ['13°', 'Parcialmente nublado']);
8
+ * assert.equal(r.outside, 0);
9
+ *
10
+ * assert.deepEqual(checkPlugin(plugin), []); // every widget, several sizes, themes and languages
11
+ *
12
+ * A widget is painted the way Kiosko paints it (same context, same drawing
13
+ * kit), with its `demo` data unless given other, and every text it draws
14
+ * through the kit is collected in order. It is painted with a margin around
15
+ * its box, so what it draws outside (which the panel would clip) is counted.
16
+ */
17
+ import { createCanvas, loadImage } from '@napi-rs/canvas';
18
+ import * as kit from '@loksly/lcd-canvas-kit';
19
+ import { createBaseContext } from "./context.js";
20
+ import { validate } from "./schema.js";
21
+ import { THEMES, themeById } from "./theme.js";
22
+ import { DEFAULT_WORKDAY } from "./workday.js";
23
+ const MARGIN = 24;
24
+ function resolve(w, o) {
25
+ const now = o.now ?? Date.UTC(2026, 10, 5, 9, 42);
26
+ const locale = o.locale ?? 'en';
27
+ const demoOpts = w.options ? validate(w.options, {}).value : {};
28
+ const demo = o.demo === false ? undefined : w.demo?.({ options: demoOpts, now, locale });
29
+ const options = w.options ? validate(w.options, o.options ?? demo?.options ?? {}).value : {};
30
+ const data = 'data' in o ? o.data : demo?.data;
31
+ const sources = o.sources ?? demo?.sources ?? {};
32
+ return { now, locale, options, data, sources };
33
+ }
34
+ /** Paints a widget alone and says what it drew. Never throws: a failing `render` is reported in `error`. */
35
+ export function renderWidget(w, o = {}) {
36
+ const { now, locale, options, data, sources } = resolve(w, o);
37
+ const size = o.size ?? w.size?.preferred ?? { w: 480, h: 300 };
38
+ const theme = typeof o.theme === 'object' ? o.theme : themeById(o.theme);
39
+ const texts = [];
40
+ const spy = { ...kit, drawTracked: (...a) => (texts.push(a[1]), kit.drawTracked(...a)) };
41
+ const canvas = createCanvas(size.w + 2 * MARGIN, size.h + 2 * MARGIN);
42
+ const g = canvas.getContext('2d');
43
+ const box = { x: MARGIN, y: MARGIN, w: size.w, h: size.h };
44
+ const ctx = {
45
+ ...createBaseContext({ now, locale, ...(o.timeFormat ? { timeFormat: o.timeFormat } : {}) }),
46
+ options,
47
+ data,
48
+ sources,
49
+ working: true,
50
+ box,
51
+ theme,
52
+ fonts: theme.fonts,
53
+ kit: spy,
54
+ canvas: { createCanvas, loadImage },
55
+ preview: !!o.preview,
56
+ };
57
+ const t0 = performance.now();
58
+ let error;
59
+ try {
60
+ w.render(g, ctx);
61
+ }
62
+ catch (err) {
63
+ error = err instanceof Error ? err.message : String(err);
64
+ }
65
+ const ms = performance.now() - t0;
66
+ const px = g.getImageData(0, 0, canvas.width, canvas.height).data;
67
+ let outside = 0;
68
+ for (let y = 0; y < canvas.height; y++) {
69
+ for (let x = 0; x < canvas.width; x++) {
70
+ if (x >= box.x && x < box.x + box.w && y >= box.y && y < box.y + box.h)
71
+ continue;
72
+ if (px[(y * canvas.width + x) * 4 + 3] > 24)
73
+ outside++;
74
+ }
75
+ }
76
+ return {
77
+ texts,
78
+ canvas,
79
+ box,
80
+ margin: MARGIN,
81
+ outside,
82
+ ms,
83
+ ...(error !== undefined ? { error } : {}),
84
+ png() {
85
+ const out = createCanvas(box.w, box.h);
86
+ out.getContext('2d').drawImage(canvas, -box.x, -box.y);
87
+ return out.toBuffer('image/png');
88
+ },
89
+ };
90
+ }
91
+ /** Asks a widget's `urgent`, `idle`, `empty` or `visible` with the same inputs `renderWidget` would use. */
92
+ export function widgetState(w, hook, o = {}) {
93
+ const fn = w[hook];
94
+ if (!fn)
95
+ return undefined;
96
+ const { now, options, data, sources } = resolve(w, o);
97
+ const ctx = { options, data, sources, now, working: true, workday: DEFAULT_WORKDAY };
98
+ return fn(ctx);
99
+ }
100
+ /**
101
+ * Paints every widget of a plugin with its demo data at its minimum and
102
+ * preferred sizes and a wide and a tall one, in every theme and in each
103
+ * language given, and lists what went wrong: a `render` that throws, one
104
+ * that paints nothing, paints outside its box, or takes longer than
105
+ * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
106
+ */
107
+ export function checkPlugin(p, o = {}) {
108
+ const issues = [];
109
+ const locales = o.locales ?? ['en', 'es'];
110
+ const themes = o.themes ?? THEMES.map((t) => t.id);
111
+ const slow = o.slowMs ?? 50;
112
+ for (const w of p.widgets ?? []) {
113
+ const type = `${p.id}/${w.id}`;
114
+ const pref = w.size?.preferred ?? { w: 480, h: 300 };
115
+ const min = w.size?.min ?? { w: Math.round(pref.w / 2), h: Math.round(pref.h / 2) };
116
+ const sizes = [min, pref, { w: Math.max(pref.w * 2, 900), h: Math.max(min.h, 120) }, { w: Math.max(min.w, 200), h: Math.max(pref.h * 2, 500) }, ...(o.extraSizes ?? [])];
117
+ for (const size of sizes) {
118
+ for (const theme of themes) {
119
+ for (const locale of locales) {
120
+ const where = `${size.w}x${size.h} ${theme} ${locale}`;
121
+ const r = renderWidget(w, { size, theme, locale });
122
+ if (r.error)
123
+ issues.push({ type, where, problem: `render threw: ${r.error}` });
124
+ else if (r.outside > 0)
125
+ issues.push({ type, where, problem: `painted ${r.outside} px outside its box` });
126
+ // The first paint pays for loading fonts and compiling code; on the panel a widget paints
127
+ // again and again. Slow means slow every time: the best of three.
128
+ if (r.ms > slow && !r.error) {
129
+ const ms = Math.min(r.ms, renderWidget(w, { size, theme, locale }).ms, renderWidget(w, { size, theme, locale }).ms);
130
+ if (ms > slow)
131
+ issues.push({ type, where, problem: `render took ${Math.round(ms)} ms` });
132
+ }
133
+ }
134
+ }
135
+ }
136
+ // Something must show with the demo data, at least at the preferred size.
137
+ const r = renderWidget(w, { size: pref });
138
+ if (!r.error) {
139
+ const px = r.canvas.getContext('2d').getImageData(r.box.x, r.box.y, r.box.w, r.box.h).data;
140
+ let inked = 0;
141
+ for (let i = 3; i < px.length; i += 4)
142
+ if (px[i] > 24)
143
+ inked++;
144
+ if (!inked)
145
+ issues.push({ type, where: `${pref.w}x${pref.h}`, problem: 'painted nothing with its demo data (add a `demo`)' });
146
+ }
147
+ }
148
+ return issues;
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiosko/sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Plugin SDK for Kiosko: define widgets, data sources and interludes for small always-on LCD panels.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,6 +19,11 @@
19
19
  "source": "./src/format.ts",
20
20
  "types": "./dist/format.d.ts",
21
21
  "default": "./dist/format.js"
22
+ },
23
+ "./testing": {
24
+ "source": "./src/testing.ts",
25
+ "types": "./dist/testing.d.ts",
26
+ "default": "./dist/testing.js"
22
27
  }
23
28
  },
24
29
  "files": [
package/src/http.ts ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * A small HTTP client for sources and fetches, so every plugin talks to
3
+ * APIs the same polite way:
4
+ *
5
+ * const http = createHttp({ agent: 'kiosko-plugin-weather/1.2.0' });
6
+ * const { data } = await http.json<Forecast>(url, { signal: ctx.signal });
7
+ *
8
+ * - Conditional requests: it remembers each URL's ETag / Last-Modified and
9
+ * body; a 304 gives the body it had, without downloading it again.
10
+ * - Rate limits: a 429 or 503 with `Retry-After` (or GitHub's
11
+ * `X-RateLimit-Reset`) throws an `HttpError` with `retryAt`, and until
12
+ * then calls to that host fail at once without contacting it.
13
+ * - The caller's `signal` (Kiosko aborts it after the source's timeout).
14
+ * - A User-Agent naming the plugin and Kiosko, never the person.
15
+ */
16
+
17
+ export class HttpError extends Error {
18
+ readonly status: number;
19
+ readonly url: string;
20
+ /** When the server says to come back (rate limits), epoch ms. */
21
+ readonly retryAt?: number;
22
+ constructor(message: string, o: { status: number; url: string; retryAt?: number }) {
23
+ super(message);
24
+ this.name = 'HttpError';
25
+ this.status = o.status;
26
+ this.url = o.url;
27
+ if (o.retryAt !== undefined) this.retryAt = o.retryAt;
28
+ }
29
+ }
30
+
31
+ export interface HttpRequest {
32
+ signal?: AbortSignal;
33
+ headers?: Record<string, string>;
34
+ method?: string;
35
+ body?: string;
36
+ /** Don't use or keep the conditional-request cache for this call. */
37
+ noCache?: boolean;
38
+ }
39
+
40
+ export interface HttpResponse<T> {
41
+ data: T;
42
+ status: number;
43
+ /** False when the server said "not modified" and the remembered body was returned. */
44
+ fresh: boolean;
45
+ headers: Headers;
46
+ }
47
+
48
+ export interface HttpClient {
49
+ json<T = unknown>(url: string, req?: HttpRequest): Promise<HttpResponse<T>>;
50
+ text(url: string, req?: HttpRequest): Promise<HttpResponse<string>>;
51
+ /** Until when a host is resting because it rate-limited us (epoch ms), if it is. */
52
+ resting(url: string): number | undefined;
53
+ }
54
+
55
+ /** How long to wait from the response's own words, if it says: `Retry-After` (seconds or a date) or `X-RateLimit-Reset` (epoch seconds). */
56
+ export function retryAtOf(headers: Headers, now: number): number | undefined {
57
+ const ra = headers.get('retry-after');
58
+ if (ra) {
59
+ const s = Number(ra);
60
+ if (Number.isFinite(s)) return now + Math.max(0, s) * 1000;
61
+ const at = Date.parse(ra);
62
+ if (Number.isFinite(at)) return at;
63
+ }
64
+ const reset = Number(headers.get('x-ratelimit-reset'));
65
+ if (headers.get('x-ratelimit-remaining') === '0' && Number.isFinite(reset) && reset > 0) return reset * 1000;
66
+ return undefined;
67
+ }
68
+
69
+ const hostOf = (url: string) => {
70
+ try {
71
+ return new URL(url).host;
72
+ } catch {
73
+ return url;
74
+ }
75
+ };
76
+
77
+ export function createHttp(o: { agent?: string; fetch?: typeof fetch; now?: () => number; maxCached?: number } = {}): HttpClient {
78
+ const doFetch = o.fetch ?? fetch;
79
+ const now = o.now ?? Date.now;
80
+ const agent = `${o.agent ? `${o.agent} ` : ''}Kiosko (+https://kioskolcd.dev)`;
81
+ const cache = new Map<string, { etag?: string; modified?: string; body: string }>();
82
+ const rest = new Map<string, number>();
83
+ const max = o.maxCached ?? 200;
84
+
85
+ async function request(url: string, req: HttpRequest = {}): Promise<HttpResponse<string>> {
86
+ const host = hostOf(url);
87
+ const until = rest.get(host);
88
+ if (until !== undefined) {
89
+ if (until > now()) throw new HttpError(`${host} asked to wait until ${new Date(until).toISOString()}`, { status: 429, url, retryAt: until });
90
+ rest.delete(host);
91
+ }
92
+ const method = req.method ?? 'GET';
93
+ const cacheable = method === 'GET' && !req.noCache;
94
+ const hit = cacheable ? cache.get(url) : undefined;
95
+ const headers: Record<string, string> = { 'User-Agent': agent, ...req.headers };
96
+ if (hit?.etag) headers['If-None-Match'] = hit.etag;
97
+ if (hit?.modified) headers['If-Modified-Since'] = hit.modified;
98
+ const res = await doFetch(url, { method, headers, ...(req.body !== undefined ? { body: req.body } : {}), ...(req.signal ? { signal: req.signal } : {}) });
99
+ if (res.status === 304 && hit) return { data: hit.body, status: 304, fresh: false, headers: res.headers };
100
+ const retryAt = retryAtOf(res.headers, now());
101
+ if (res.status === 429 || res.status === 503 || (res.status === 403 && retryAt !== undefined)) {
102
+ const at = retryAt ?? now() + 60_000;
103
+ rest.set(host, at);
104
+ throw new HttpError(`HTTP ${res.status} from ${host}: rate-limited until ${new Date(at).toISOString()}`, { status: res.status, url, retryAt: at });
105
+ }
106
+ if (!res.ok) throw new HttpError(`HTTP ${res.status} from ${host}`, { status: res.status, url });
107
+ const body = await res.text();
108
+ if (cacheable) {
109
+ const etag = res.headers.get('etag') ?? undefined;
110
+ const modified = res.headers.get('last-modified') ?? undefined;
111
+ if (etag || modified) {
112
+ cache.delete(url);
113
+ cache.set(url, { ...(etag ? { etag } : {}), ...(modified ? { modified } : {}), body });
114
+ // Oldest out first.
115
+ while (cache.size > max) cache.delete(cache.keys().next().value!);
116
+ }
117
+ }
118
+ return { data: body, status: res.status, fresh: true, headers: res.headers };
119
+ }
120
+
121
+ return {
122
+ text: request,
123
+ async json<T>(url: string, req?: HttpRequest) {
124
+ const r = await request(url, { ...req, headers: { Accept: 'application/json', ...req?.headers } });
125
+ try {
126
+ return { ...r, data: JSON.parse(r.data) as T };
127
+ } catch {
128
+ throw new HttpError(`not JSON from ${hostOf(url)}`, { status: r.status, url });
129
+ }
130
+ },
131
+ resting(url: string) {
132
+ const at = rest.get(hostOf(url));
133
+ return at !== undefined && at > now() ? at : undefined;
134
+ },
135
+ };
136
+ }
package/src/index.ts CHANGED
@@ -9,3 +9,5 @@ export * from './filter.ts';
9
9
  export * from './context.ts';
10
10
  export * from './location.ts';
11
11
  export * from './system.ts';
12
+ export * from './semver.ts';
13
+ export * from './http.ts';
package/src/plugin.ts CHANGED
@@ -361,6 +361,23 @@ export interface SourceDefinition<OF extends ObjectField<any> = ObjectField<any>
361
361
  */
362
362
  watch?: (ctx: SourceContext<Infer<OF>>, emit: (data: D) => void) => () => void;
363
363
  demo?: (ctx: { now: number; locale: string }) => D;
364
+ /**
365
+ * Named lists of values for the editor to offer in options, made from
366
+ * this source's latest data (or its demo data before there is any): the
367
+ * entities of a Home Assistant, the calendars read, the repos seen. A
368
+ * field asks for one with `choices: { source: 'plugin/source', list }`.
369
+ * Plain and quick: they run when the editor opens a form.
370
+ */
371
+ choices?: Record<string, (data: D, ctx: { locale: string; t: (text: Localized) => string }) => Choice[]>;
372
+ }
373
+
374
+ /** One value the editor offers for an option (see `SourceDefinition.choices`). */
375
+ export interface Choice {
376
+ value: string;
377
+ /** What the person sees, when it isn't the value itself (`Living room` for `sensor.living_room`). */
378
+ label?: string;
379
+ /** Heading to group it under (`Sensors`, `Lights`). */
380
+ group?: string;
364
381
  }
365
382
 
366
383
  export interface InterludePlayer {
@@ -396,6 +413,67 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
396
413
  skip?: (ctx: { sources: Record<string, unknown>; now: number; options: Infer<OF> }) => boolean;
397
414
  }
398
415
 
416
+ /**
417
+ * The version of the plugin API this Kiosko speaks. A plugin says which
418
+ * versions it was written for in `PluginDefinition.sdk` (and in its
419
+ * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
420
+ * it runs); the registry compares them with `satisfies`.
421
+ */
422
+ export const SDK_VERSION = '0.2.2';
423
+
424
+ /**
425
+ * What a plugin does on the machine, declared for the person who installs
426
+ * it: the Plugins page and the plugin store show it next to the plugin. It
427
+ * is a promise, not (yet) a fence: plugins run with the user's rights. Keep
428
+ * it honest and small; options with a `risk` (see `Risk`) are listed apart.
429
+ */
430
+ export interface Permissions {
431
+ /**
432
+ * Hosts it contacts on its own: exact names (`api.github.com`,
433
+ * `*.open-meteo.com`), `user` for the hosts the user types in its options
434
+ * (a feed, a Home Assistant), `lan` for the local network.
435
+ */
436
+ network?: string[];
437
+ /** Programs it runs (`nvidia-smi`, `pactl`, `ssh`); `user` for a command the user configures. */
438
+ exec?: string[];
439
+ /** Files or folders it reads or writes besides its own `dataDir`/`cacheDir` (`~/.aimonitor/sessions`); `user` for paths the user configures. */
440
+ files?: string[];
441
+ /** Hardware or system services it talks to: `usb`, `audio` (whether the microphone is in use), `mpris` (what is playing), `bluetooth`… */
442
+ devices?: string[];
443
+ }
444
+
445
+ /** One tile of a page template, in fractions of the page (0..1). */
446
+ export interface TemplateTile {
447
+ x: number;
448
+ y: number;
449
+ w: number;
450
+ h: number;
451
+ /** Widget types, stacked; a bare id (`clock`) is this plugin's own. With options: `['clock', { showDate: true }]`. */
452
+ widgets: (string | [string, Record<string, unknown>])[];
453
+ chrome?: 'card' | 'bare';
454
+ }
455
+
456
+ /**
457
+ * A starting layout the editor offers under "New page", made of this
458
+ * plugin's widgets (and others', if installed: tiles whose widgets are all
459
+ * missing are left out).
460
+ */
461
+ export interface PageTemplate {
462
+ /** Unique inside the plugin. */
463
+ id: string;
464
+ name: Localized;
465
+ /** An icon of the editor (Lucide name). */
466
+ icon?: string;
467
+ /** For strips and wide panels. */
468
+ wide: TemplateTile[];
469
+ /** For square-ish panels; defaults to `wide`. */
470
+ square?: TemplateTile[];
471
+ /** For portrait panels; defaults to `wide` turned a quarter (columns become bands). */
472
+ tall?: TemplateTile[];
473
+ }
474
+
475
+ export type Platform = 'linux' | 'darwin' | 'win32';
476
+
399
477
  export interface PluginDefinition {
400
478
  /** npm-like id: lowercase, digits and dashes. Stable: configs refer to it. */
401
479
  id: string;
@@ -404,11 +482,37 @@ export interface PluginDefinition {
404
482
  description?: Localized;
405
483
  author?: string;
406
484
  homepage?: string;
485
+ /** Where its code lives (a git URL): the store links to it. */
486
+ repository?: string;
407
487
  license?: string;
408
488
  icon?: string;
489
+ /**
490
+ * The plugin API versions it works with, as an npm range (`^0.2.0`).
491
+ * Without it, any Kiosko is assumed to fit. Put the same in package.json
492
+ * (`"kiosko": { "sdk": … }`) so an incompatible plugin is refused before
493
+ * its code runs.
494
+ */
495
+ sdk?: string;
496
+ /** What it does on the machine (see `Permissions`). */
497
+ permissions?: Permissions;
498
+ /**
499
+ * Sources or widgets of other plugins it needs (`agents/sessions`): the
500
+ * editor says which are missing and offers to install their plugins.
501
+ */
502
+ requires?: string[];
503
+ /**
504
+ * Sources or widgets of other plugins it uses when they are there, and
505
+ * does without otherwise (the weather in a corner): never asked for, only
506
+ * mentioned.
507
+ */
508
+ optional?: string[];
509
+ /** The operating systems it works on. Omitted: all. Also npm's `os` in package.json. */
510
+ platforms?: Platform[];
409
511
  widgets?: WidgetDefinition<any, any>[];
410
512
  sources?: SourceDefinition<any, any>[];
411
513
  interludes?: InterludeDefinition<any>[];
514
+ /** Page layouts the editor offers, built from its widgets (see `PageTemplate`). */
515
+ templates?: PageTemplate[];
412
516
  }
413
517
 
414
518
  /* Identity helpers: they only exist so TypeScript infers option and data types. */
package/src/schema.ts CHANGED
@@ -38,9 +38,24 @@ interface Common<T> {
38
38
  risk?: Risk | readonly Risk[];
39
39
  }
40
40
 
41
+ /**
42
+ * Where the editor finds values to offer for a text field: a named list of
43
+ * a source (see `SourceDefinition.choices`), computed from its live data,
44
+ * e.g. the entities of the user's Home Assistant. The field stays free
45
+ * text: a value that isn't in the list is kept.
46
+ */
47
+ export interface ChoicesRef {
48
+ /** `plugin/source`. */
49
+ source: string;
50
+ /** The name of the list in that source's `choices`. */
51
+ list: string;
52
+ }
53
+
41
54
  export interface StringField extends Common<string> {
42
55
  kind: 'string';
43
56
  placeholder?: string;
57
+ /** Values to offer, from a source's live data (see `ChoicesRef`). */
58
+ choices?: ChoicesRef;
44
59
  multiline?: boolean;
45
60
  /** Tokens, URLs with credentials…: masked in the editor and never logged. */
46
61
  secret?: boolean;
@@ -123,9 +138,9 @@ export const t = {
123
138
  * `repos`, `calendars`, `people`) and give it a `label`; the `help`
124
139
  * explaining the patterns comes with it.
125
140
  */
126
- filter: (o: Opts<ListField<StringField>, 'item'> = {}): ListField<StringField> => ({
141
+ filter: ({ choices, ...o }: Opts<ListField<StringField>, 'item'> & { choices?: ChoicesRef } = {}): ListField<StringField> => ({
127
142
  kind: 'list',
128
- item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*' },
143
+ item: { kind: 'string', default: '', placeholder: 'name, group/*, !old-*', ...(choices ? { choices } : {}) },
129
144
  default: [],
130
145
  filter: true,
131
146
  help: FILTER_HELP,
@@ -238,7 +253,7 @@ export function toJsonSchema(f: Field): Record<string, unknown> {
238
253
  };
239
254
  switch (f.kind) {
240
255
  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 } };
256
+ 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, choices: f.choices } };
242
257
  case 'color':
243
258
  return { ...base, type: 'string', 'x-ui': { ...ui, widget: 'color' } };
244
259
  case 'number':
@@ -248,7 +263,7 @@ export function toJsonSchema(f: Field): Record<string, unknown> {
248
263
  case 'enum':
249
264
  return { ...base, type: 'string', enum: [...f.values], 'x-ui': { ...ui, labels: f.labels } };
250
265
  case 'list':
251
- return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter' }, 'x-filter': true } : {}) };
266
+ return { ...base, type: 'array', items: toJsonSchema(f.item), maxItems: f.max, ...(f.filter ? { 'x-ui': { ...ui, widget: 'filter', choices: f.item.kind === 'string' ? f.item.choices : undefined }, 'x-filter': true } : {}) };
252
267
  case 'map':
253
268
  return { ...base, type: 'object', additionalProperties: { type: 'string' } };
254
269
  case 'object':
package/src/semver.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Just enough semver to say whether a plugin fits this Kiosko: versions
3
+ * `1.2.3` (a pre-release such as `1.2.3-beta.1` sorts before its release),
4
+ * and ranges as npm writes them in package.json:
5
+ *
6
+ * ^0.2.0 >=0.2.0 <0.3.0 (caret: the left-most non-zero part is fixed)
7
+ * ~0.2.1 >=0.2.1 <0.3.0
8
+ * 0.2 · 0.2.x · * wildcards
9
+ * >=0.2.0 <1 comparators, space-separated (all must hold)
10
+ * ^0.2 || ^1 alternatives
11
+ *
12
+ * No dependencies, so the registry can check a plugin before running it.
13
+ */
14
+
15
+ type V = [number, number, number, string];
16
+
17
+ /** `1.2.3` → its parts; null when it isn't a version. */
18
+ export function parseVersion(s: string): V | null {
19
+ const m = /^\s*v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?\s*$/.exec(s);
20
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ?? ''] : null;
21
+ }
22
+
23
+ /** -1, 0 or 1. A pre-release sorts before the release of the same numbers. */
24
+ export function compareVersions(a: string, b: string): number {
25
+ const x = parseVersion(a), y = parseVersion(b);
26
+ if (!x || !y) return 0;
27
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return (x[i] as number) < (y[i] as number) ? -1 : 1;
28
+ if (x[3] === y[3]) return 0;
29
+ if (!x[3]) return 1;
30
+ if (!y[3]) return -1;
31
+ return x[3] < y[3] ? -1 : 1;
32
+ }
33
+
34
+ type Cmp = { op: '>=' | '>' | '<=' | '<' | '='; v: string };
35
+
36
+ /** A partial version (`1`, `1.2`, `1.x`) as its parts, `undefined` for the missing or wild ones. */
37
+ function partial(s: string): [number | undefined, number | undefined, number | undefined, string] | null {
38
+ const m = /^\s*v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?\s*$/.exec(s);
39
+ if (!m) return null;
40
+ const n = (p: string | undefined) => (p === undefined || /^[xX*]$/.test(p) ? undefined : Number(p));
41
+ return [n(m[1]), n(m[2]), n(m[3]), m[4] ?? ''];
42
+ }
43
+
44
+ const ver = (a: number, b: number, c: number, pre = '') => `${a}.${b}.${c}${pre ? `-${pre}` : ''}`;
45
+
46
+ /** One space-separated set of comparators → plain `op version` pairs. */
47
+ function comparators(set: string): Cmp[] | null {
48
+ const out: Cmp[] = [];
49
+ const tokens = set.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter(Boolean);
50
+ if (!tokens.length) return [{ op: '>=', v: '0.0.0' }];
51
+ for (const tk of tokens) {
52
+ const m = /^(>=|<=|>|<|=|\^|~)?(.*)$/.exec(tk)!;
53
+ const op = m[1] ?? '';
54
+ const p = partial(m[2]!);
55
+ if (!p) return null;
56
+ const [ma, mi, pa, pre] = p;
57
+ if (ma === undefined) {
58
+ out.push({ op: '>=', v: '0.0.0' });
59
+ continue;
60
+ }
61
+ if (op === '^') {
62
+ const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
63
+ const hi = ma > 0 || mi === undefined ? ver(ma + 1, 0, 0) : mi > 0 || pa === undefined ? ver(0, mi + 1, 0) : ver(0, 0, pa + 1);
64
+ out.push({ op: '>=', v: lo }, { op: '<', v: `${hi}-0` });
65
+ } else if (op === '~') {
66
+ const lo = ver(ma, mi ?? 0, pa ?? 0, pre);
67
+ const hi = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
68
+ out.push({ op: '>=', v: lo }, { op: '<', v: `${hi}-0` });
69
+ } else if (op === '' || op === '=') {
70
+ if (mi === undefined) out.push({ op: '>=', v: ver(ma, 0, 0) }, { op: '<', v: `${ver(ma + 1, 0, 0)}-0` });
71
+ else if (pa === undefined) out.push({ op: '>=', v: ver(ma, mi, 0) }, { op: '<', v: `${ver(ma, mi + 1, 0)}-0` });
72
+ else out.push({ op: '=', v: ver(ma, mi, pa, pre) });
73
+ } else {
74
+ // >1.2 means >=1.3.0; <=1.2 means <1.3.0.
75
+ if (pa === undefined && (op === '>' || op === '<=')) {
76
+ const next = mi === undefined ? ver(ma + 1, 0, 0) : ver(ma, mi + 1, 0);
77
+ out.push(op === '>' ? { op: '>=', v: next } : { op: '<', v: `${next}-0` });
78
+ } else out.push({ op: op as Cmp['op'], v: ver(ma, mi ?? 0, pa ?? 0, pre) });
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * Whether `version` is in `range`. A pre-release only matches a range that
86
+ * names a pre-release of the same numbers (npm's rule), so `0.3.0-beta` does
87
+ * not quietly satisfy `^0.2`. An unreadable range or version is `false`.
88
+ */
89
+ export function satisfies(version: string, range: string): boolean {
90
+ const v = parseVersion(version);
91
+ if (!v) return false;
92
+ return range.split('||').some((set) => {
93
+ const cs = comparators(set);
94
+ if (!cs) return false;
95
+ const ok = cs.every(({ op, v: w }) => {
96
+ const c = compareVersions(version, w);
97
+ return op === '>=' ? c >= 0 : op === '>' ? c > 0 : op === '<=' ? c <= 0 : op === '<' ? c < 0 : c === 0;
98
+ });
99
+ if (!ok || !v[3]) return ok;
100
+ return cs.some(({ v: w }) => {
101
+ const x = parseVersion(w);
102
+ return !!x && !!x[3] && x[3] !== '0' && x[0] === v[0] && x[1] === v[1] && x[2] === v[2];
103
+ });
104
+ });
105
+ }