@sdeck/plugin 0.1.0 → 0.2.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/plugin.ts CHANGED
@@ -2,6 +2,7 @@ import type { SlotInfo } from "@sdeck/app";
2
2
  import type { ExecSource, StateValueType } from "@sdeck/engine";
3
3
  import type { Look, NavigateTarget } from "@sdeck/schema";
4
4
  import type { ComponentType } from "react";
5
+ import { PERMISSIONS, type Permission } from "./permissions.ts";
5
6
  import {
6
7
  checkSchema,
7
8
  type InferSettings,
@@ -15,29 +16,6 @@ export const PLUGIN_API_VERSION = 2;
15
16
  /** Where an action can be placed. */
16
17
  export type SlotKind = "key" | "sensor" | "window";
17
18
 
18
- /**
19
- * What a plugin declares it does. Shown to the user before enabling it. Plugins run in the host
20
- * process, so this is information, not a sandbox.
21
- */
22
- export type Permission =
23
- | "shell"
24
- | "process"
25
- | "filesystem"
26
- | "network"
27
- | "input"
28
- | "audio"
29
- | "clipboard";
30
-
31
- export const PERMISSIONS: readonly Permission[] = [
32
- "shell",
33
- "process",
34
- "filesystem",
35
- "network",
36
- "input",
37
- "audio",
38
- "clipboard",
39
- ];
40
-
41
19
  /** Given to a plugin's `activate`, its actions, state providers and triggers. */
42
20
  export interface PluginContext {
43
21
  readonly pluginId: string;
@@ -61,11 +39,12 @@ export interface PluginContext {
61
39
  /** Live state: `set` publishes `<namespace>.<id>`, `get` reads any key (`system.cpu`). */
62
40
  readonly state: {
63
41
  set(id: string, value: unknown): void;
42
+ /** Keys of other plugins need the `state` permission. */
64
43
  get(key: string): unknown;
65
44
  };
66
45
  /** Emits `<namespace>:<event>` on the event bus (workflows can trigger on it). */
67
46
  emit(event: string, payload?: unknown): void;
68
- /** Global user variables. */
47
+ /** Global user variables. Needs the `variables` permission. */
69
48
  readonly vars: {
70
49
  get(name: string): unknown;
71
50
  set(name: string, value: unknown): void;
@@ -75,12 +54,17 @@ export interface PluginContext {
75
54
  /** How a plugin's status reads: fine, needing attention, or failing. */
76
55
  export type StatusLevel = "ok" | "info" | "error";
77
56
 
78
- /** Something the user can run from the plugin's page (sign in, reconnect). */
57
+ /** Something the user can run from the plugin's settings (sign in, reconnect). */
79
58
  export interface PluginCommand {
80
59
  /** Unique within the plugin. */
81
60
  id: string;
82
61
  name: string;
83
62
  description?: string;
63
+ /**
64
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
65
+ * Without them it is refused.
66
+ */
67
+ permissions?: readonly Permission[];
84
68
  /** What it returns, if a string, is opened in the user's browser. Throw to fail. */
85
69
  run(context: PluginContext): unknown | Promise<unknown>;
86
70
  }
@@ -200,9 +184,19 @@ export interface ActionDef<S extends SettingsSchema = SettingsSchema> {
200
184
  slots?: readonly SlotKind[];
201
185
  /** Settings shown in the UI, as a form. */
202
186
  settings?: S;
187
+ /**
188
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
189
+ * Without them it cannot run or draw itself.
190
+ */
191
+ permissions?: readonly Permission[];
192
+ /**
193
+ * It only shows something. It is offered for buttons, but not as a step of a workflow or
194
+ * gesture, and needs no `run`.
195
+ */
196
+ display?: boolean;
203
197
  /**
204
198
  * Does the work, without drawing anything: it can run from a key, a trigger or a workflow.
205
- * Throw to fail. An action needs `run`, `component`, or both.
199
+ * Throw to fail. An action needs `run`, `component`, or both, unless it is `display`.
206
200
  */
207
201
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `run` simply not return anything.
208
202
  run?(context: RunContext<S>): RunResult | void | Promise<RunResult | void>;
@@ -227,6 +221,8 @@ export interface Action {
227
221
  readonly icon?: string;
228
222
  readonly slots: readonly SlotKind[];
229
223
  readonly settings: SettingsSchema;
224
+ readonly permissions?: readonly Permission[];
225
+ readonly display?: boolean;
230
226
  readonly run?: RunFn;
231
227
  readonly component?: ComponentType<ActionProps>;
232
228
  readonly look?: (settings: Record<string, unknown>) => Look;
@@ -240,6 +236,11 @@ export interface StateDef {
240
236
  type: StateValueType;
241
237
  unit?: string;
242
238
  description?: string;
239
+ /**
240
+ * What reading it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
241
+ * Without them it has no value.
242
+ */
243
+ permissions?: readonly Permission[];
243
244
  /** Read every `everyMs` while something shows or waits on the value. */
244
245
  poll?: { everyMs: number; read(context: PluginContext): unknown | Promise<unknown> };
245
246
  /** Push updates while watched; return a stop function. */
@@ -261,6 +262,11 @@ export interface TriggerDef<S extends SettingsSchema = SettingsSchema> {
261
262
  name: string;
262
263
  description?: string;
263
264
  settings?: S;
265
+ /**
266
+ * What it needs, out of the plugin's `permissions` (default: all of them; `[]` for nothing).
267
+ * Without them it never fires.
268
+ */
269
+ permissions?: readonly Permission[];
264
270
  /** Starts watching; returns a function that stops. */
265
271
  // biome-ignore lint/suspicious/noConfusingVoidType: lets `subscribe` simply not return anything.
266
272
  subscribe(context: TriggerContext<S>): (() => void) | void;
@@ -271,6 +277,7 @@ export interface Trigger {
271
277
  readonly name: string;
272
278
  readonly description?: string;
273
279
  readonly settings: SettingsSchema;
280
+ readonly permissions?: readonly Permission[];
274
281
  readonly subscribe: (context: TriggerContext) => (() => void) | undefined;
275
282
  }
276
283
 
@@ -301,10 +308,14 @@ export interface PluginDef {
301
308
  state?: readonly StateDef[];
302
309
  triggers?: readonly Trigger[];
303
310
  optionSources?: Readonly<Record<string, OptionSource>>;
311
+ /**
312
+ * Everything the plugin asks to be allowed to do. The user decides about each one, and can
313
+ * change their mind at any time: handle being refused. What is not listed is never allowed.
314
+ */
304
315
  permissions?: readonly Permission[];
305
316
  /** The plugin's own settings (a server address, a token), shown on its page. */
306
317
  settings?: SettingsSchema;
307
- /** Buttons on the plugin's page. */
318
+ /** Buttons in the plugin's settings. */
308
319
  commands?: readonly PluginCommand[];
309
320
  /**
310
321
  * How to set the plugin up, step by step, shown after it is installed. Without it, Studio asks
@@ -370,6 +381,16 @@ export function definePlugin(def: PluginDef): PluginDef {
370
381
  return def;
371
382
  }
372
383
 
384
+ /** Problems with the `permissions` of one of a plugin's parts. */
385
+ function checkNeeds(part: string, needs: unknown, asked: unknown): string[] {
386
+ if (needs === undefined) return [];
387
+ if (!Array.isArray(needs)) return [`${part}: permissions must be an array`];
388
+ const missing = needs.filter((p) => !Array.isArray(asked) || !asked.includes(p));
389
+ return missing.map(
390
+ (p) => `${part}: permission "${String(p)}" is not in the plugin's permissions`,
391
+ );
392
+ }
393
+
373
394
  function checkLocalIds(
374
395
  kind: string,
375
396
  items: readonly { id?: unknown }[],
@@ -423,6 +444,7 @@ export function checkPlugin(value: unknown): string[] {
423
444
  const name = typeof c?.id === "string" ? c.id : "?";
424
445
  if (typeof c?.name !== "string") problems.push(`command "${name}": name is required`);
425
446
  if (typeof c?.run !== "function") problems.push(`command "${name}": run is required`);
447
+ problems.push(...checkNeeds(`command "${name}"`, c?.permissions, def.permissions));
426
448
  }
427
449
  }
428
450
  }
@@ -441,7 +463,10 @@ export function checkPlugin(value: unknown): string[] {
441
463
  const hasComponent =
442
464
  typeof action?.component === "function" || typeof action?.component === "object";
443
465
  const hasRun = typeof action?.run === "function";
444
- if (!hasComponent && !hasRun) problems.push(`action "${name}": needs run or component`);
466
+ if (!hasComponent && !hasRun && !action?.display) {
467
+ problems.push(`action "${name}": needs run or component`);
468
+ }
469
+ problems.push(...checkNeeds(`action "${name}"`, action?.permissions, def.permissions));
445
470
  if (action?.look !== undefined && typeof action.look !== "function") {
446
471
  problems.push(`action "${name}": look must be a function`);
447
472
  }
@@ -461,6 +486,9 @@ export function checkPlugin(value: unknown): string[] {
461
486
  if (field?.type === "secret") {
462
487
  problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
463
488
  }
489
+ if (field?.type === "groups") {
490
+ problems.push(`action "${name}": setting "${key}": groups belong in the plugin settings`);
491
+ }
464
492
  }
465
493
  }
466
494
 
@@ -474,6 +502,7 @@ export function checkPlugin(value: unknown): string[] {
474
502
  if (!["number", "string", "boolean", "json"].includes(s?.type as string)) {
475
503
  problems.push(`state "${name}": type must be number, string, boolean or json`);
476
504
  }
505
+ problems.push(...checkNeeds(`state "${name}"`, s?.permissions, def.permissions));
477
506
  if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
478
507
  problems.push(`state "${name}": poll needs read() and everyMs > 0`);
479
508
  }
@@ -494,6 +523,7 @@ export function checkPlugin(value: unknown): string[] {
494
523
  if (typeof t?.subscribe !== "function") {
495
524
  problems.push(`trigger "${name}": subscribe is required`);
496
525
  }
526
+ problems.push(...checkNeeds(`trigger "${name}"`, t?.permissions, def.permissions));
497
527
  for (const p of checkSchema(t?.settings ?? {}, sources)) {
498
528
  problems.push(`trigger "${name}": ${p}`);
499
529
  }
package/src/settings.ts CHANGED
@@ -10,6 +10,11 @@ interface FieldBase {
10
10
  label: string;
11
11
  /** Help text under the field. */
12
12
  description?: string;
13
+ /**
14
+ * It only changes how the button looks. It is asked for on a button, but not in a step of a
15
+ * workflow or gesture, where nothing is drawn.
16
+ */
17
+ appearance?: boolean;
13
18
  /**
14
19
  * Shown only while other fields have these values: `{ to: "page" }` or
15
20
  * `{ mode: ["a", "b"] }`. Hidden fields keep their value.
@@ -91,6 +96,25 @@ export interface ImageField extends FieldBase {
91
96
  default?: string;
92
97
  }
93
98
 
99
+ /** A named set the user made of options, from a `groups` field. */
100
+ export interface OptionGroup {
101
+ /** Stays the same when the group is renamed; refer to the group by it. */
102
+ id: string;
103
+ name: string;
104
+ /** The chosen options' values. */
105
+ members: readonly string[];
106
+ }
107
+
108
+ /** Named sets of options the user puts together (rooms of lights), only for a plugin's own settings. */
109
+ export interface GroupsField extends FieldBase {
110
+ type: "groups";
111
+ /** The plugin's `optionSources` entry that lists what a group can contain. */
112
+ source: string;
113
+ /** What a group contains, for the form, e.g. `lights` (default: `items`). */
114
+ noun?: string;
115
+ default?: readonly OptionGroup[];
116
+ }
117
+
94
118
  export type SettingField =
95
119
  | TextField
96
120
  | NumberField
@@ -99,6 +123,7 @@ export type SettingField =
99
123
  | SelectField
100
124
  | PageField
101
125
  | ImageField
126
+ | GroupsField
102
127
  | SecretField;
103
128
 
104
129
  export type SettingsSchema = Readonly<Record<string, SettingField>>;
@@ -108,11 +133,16 @@ export type FieldValue<F extends SettingField> = F extends NumberField
108
133
  ? number
109
134
  : F extends BooleanField
110
135
  ? boolean
111
- : F extends SelectField
112
- ? F extends { source: string }
113
- ? string
114
- : F["options"][number]["value"]
115
- : string;
136
+ : F extends GroupsField
137
+ ? readonly OptionGroup[]
138
+ : F extends SelectField
139
+ ? F extends { source: string }
140
+ ? string
141
+ : F["options"][number]["value"]
142
+ : string;
143
+
144
+ /** A value of any field. */
145
+ export type SettingValue = Primitive | readonly OptionGroup[];
116
146
 
117
147
  /** The settings object an action receives for a schema. */
118
148
  export type InferSettings<S extends SettingsSchema> = {
@@ -122,7 +152,7 @@ export type InferSettings<S extends SettingsSchema> = {
122
152
  const HEX = /^#[0-9a-f]{6}$/i;
123
153
 
124
154
  /** The value a field takes when nothing (valid) is stored. */
125
- export function defaultValue(field: SettingField): string | number | boolean {
155
+ export function defaultValue(field: SettingField): SettingValue {
126
156
  switch (field.type) {
127
157
  case "number":
128
158
  return field.default ?? field.min ?? 0;
@@ -130,6 +160,8 @@ export function defaultValue(field: SettingField): string | number | boolean {
130
160
  return field.default ?? false;
131
161
  case "color":
132
162
  return field.default ?? "#000000";
163
+ case "groups":
164
+ return field.default ?? [];
133
165
  case "select":
134
166
  return field.default ?? field.options[0]?.value ?? "";
135
167
  default:
@@ -137,7 +169,25 @@ export function defaultValue(field: SettingField): string | number | boolean {
137
169
  }
138
170
  }
139
171
 
140
- function coerce(field: SettingField, value: unknown): string | number | boolean {
172
+ /** The valid groups in a stored value, or `undefined` if it isn't a list. */
173
+ export function optionGroups(value: unknown): OptionGroup[] | undefined {
174
+ if (!Array.isArray(value)) return undefined;
175
+ const ids = new Set<string>();
176
+ return value.flatMap((group: Partial<OptionGroup> | null) => {
177
+ if (typeof group?.id !== "string" || !group.id || ids.has(group.id)) return [];
178
+ ids.add(group.id);
179
+ const members = Array.isArray(group.members) ? group.members : [];
180
+ return [
181
+ {
182
+ id: group.id,
183
+ name: typeof group.name === "string" ? group.name : "",
184
+ members: [...new Set(members.filter((m) => typeof m === "string"))],
185
+ },
186
+ ];
187
+ });
188
+ }
189
+
190
+ function coerce(field: SettingField, value: unknown): SettingValue {
141
191
  switch (field.type) {
142
192
  case "number": {
143
193
  const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
@@ -150,6 +200,8 @@ function coerce(field: SettingField, value: unknown): string | number | boolean
150
200
  return typeof value === "string" && HEX.test(value)
151
201
  ? value.toLowerCase()
152
202
  : defaultValue(field);
203
+ case "groups":
204
+ return optionGroups(value) ?? defaultValue(field);
153
205
  case "select":
154
206
  if (typeof value !== "string") return defaultValue(field);
155
207
  if (field.source !== undefined) return value;
@@ -172,6 +224,11 @@ export function resolveSettings<S extends SettingsSchema>(
172
224
  return out as InferSettings<S>;
173
225
  }
174
226
 
227
+ /** The fields that change what an action does, without those for how its button looks. */
228
+ export function behaviorFields(schema: SettingsSchema): SettingsSchema {
229
+ return Object.fromEntries(Object.entries(schema).filter(([, field]) => !field.appearance));
230
+ }
231
+
175
232
  /** Whether `field` is shown for these (resolved) settings. */
176
233
  export function isFieldVisible(
177
234
  field: SettingField,
@@ -201,6 +258,7 @@ export function checkSchema(
201
258
  "select",
202
259
  "page",
203
260
  "image",
261
+ "groups",
204
262
  "secret",
205
263
  ]);
206
264
  for (const [key, field] of Object.entries(schema)) {
@@ -210,6 +268,9 @@ export function checkSchema(
210
268
  }
211
269
  if (typeof field.label !== "string") problems.push(`setting "${key}" needs a label`);
212
270
  const source = "source" in field ? field.source : undefined;
271
+ if (field.type === "groups" && source === undefined) {
272
+ problems.push(`setting "${key}" needs a source`);
273
+ }
213
274
  if (source !== undefined && !(source in sources)) {
214
275
  problems.push(`setting "${key}" uses unknown option source "${source}"`);
215
276
  }
package/src/ui.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The parts that are plain data and functions, for UIs: no React, engine or runtime behind them. */
2
+ export * from "./permissions.ts";
3
+ export * from "./settings.ts";