@sdeck/plugin 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/bridge.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Live state for action components. The host provides a `HostBridge` around every slot; these
3
+ * hooks subscribe to exactly what they read and re-render when it changes.
4
+ */
5
+ import { compile, type Scope, sameValue, template } from "@sdeck/engine";
6
+ import {
7
+ createContext,
8
+ useCallback,
9
+ useContext,
10
+ useEffect,
11
+ useMemo,
12
+ useRef,
13
+ useState,
14
+ useSyncExternalStore,
15
+ } from "react";
16
+
17
+ export interface HostBridge {
18
+ /**
19
+ * Watches state keys and variables behind expression paths (`system.cpu`, `vars.mode`).
20
+ * Starts providers as needed. Returns a function that stops watching.
21
+ */
22
+ watch(paths: readonly string[], listener: () => void): () => void;
23
+ /** The current expression scope (state namespaces, `vars`, `self`…). */
24
+ scope(): Scope;
25
+ /** Runs a plugin action as a workflow step would (recorded in the history). */
26
+ run(plugin: string, action: string, settings?: Record<string, unknown>): Promise<unknown>;
27
+ /** Sets a global variable. */
28
+ setVariable(name: string, value: unknown): void;
29
+ /**
30
+ * What to draw for an image source (an icon reference, a URL or a `data:` URI), or
31
+ * `undefined` while it loads. `color` applies to icons.
32
+ */
33
+ image(src: string, color?: string): string | undefined;
34
+ /** Called when an image finishes loading. */
35
+ watchImages(listener: () => void): () => void;
36
+ }
37
+
38
+ export const HostBridgeContext = createContext<HostBridge | undefined>(undefined);
39
+
40
+ function useBridge(): HostBridge {
41
+ const bridge = useContext(HostBridgeContext);
42
+ if (!bridge)
43
+ throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
44
+ return bridge;
45
+ }
46
+
47
+ /** Re-renders every second while `on` (for `now()`/`time()` in templates). */
48
+ function useClock(on: boolean): number {
49
+ const [tick, setTick] = useState(0);
50
+ useEffect(() => {
51
+ if (!on) return;
52
+ const timer = setInterval(() => setTick((t) => t + 1), 1000);
53
+ return () => clearInterval(timer);
54
+ }, [on]);
55
+ return tick;
56
+ }
57
+
58
+ function useWatched<T>(paths: readonly string[], read: () => T): T {
59
+ const bridge = useBridge();
60
+ const key = paths.join("\n");
61
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `key` stands for `paths`.
62
+ const subscribe = useCallback(
63
+ (listener: () => void) => bridge.watch(paths, listener),
64
+ [bridge, key],
65
+ );
66
+ // Expressions can build fresh arrays/objects; keep the previous one while equal so React does
67
+ // not see a new snapshot on every read.
68
+ const last = useRef<{ value: T } | undefined>(undefined);
69
+ const snapshot = () => {
70
+ const value = read();
71
+ if (last.current && sameValue(last.current.value, value)) return last.current.value;
72
+ last.current = { value };
73
+ return value;
74
+ };
75
+ return useSyncExternalStore(subscribe, snapshot);
76
+ }
77
+
78
+ /** The value of an expression (`system.cpu > 80`, `vars.mode`), kept up to date. */
79
+ export function useExpression(source: string): unknown {
80
+ const bridge = useBridge();
81
+ const expression = useMemo(() => compile(source), [source]);
82
+ useClock(expression.timeDependent);
83
+ return useWatched(expression.paths, () => expression.evaluate(bridge.scope()));
84
+ }
85
+
86
+ /** A `{{template}}` rendered to text, kept up to date: `useTemplate("CPU {{system.cpu}}%")`. */
87
+ export function useTemplate(source: string): string {
88
+ const bridge = useBridge();
89
+ const compiled = useMemo(() => template(source), [source]);
90
+ useClock(compiled.timeDependent);
91
+ return useWatched(compiled.paths, () => compiled.render(bridge.scope()));
92
+ }
93
+
94
+ /** A live state value by key (`system.cpu`). */
95
+ export function useHostState(key: string): unknown {
96
+ const bridge = useBridge();
97
+ const paths = useMemo(() => [key], [key]);
98
+ return useWatched(paths, () => {
99
+ const dot = key.indexOf(".");
100
+ const ns = bridge.scope()[key.slice(0, dot)] as Record<string, unknown> | undefined;
101
+ return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;
102
+ });
103
+ }
104
+
105
+ /** A global variable and a setter for it. */
106
+ export function useVariable(name: string): [unknown, (value: unknown) => void] {
107
+ const bridge = useBridge();
108
+ const paths = useMemo(() => [`vars.${name}`], [name]);
109
+ const value = useWatched(paths, () => (bridge.scope().vars as Record<string, unknown>)[name]);
110
+ const set = useCallback((v: unknown) => bridge.setVariable(name, v), [bridge, name]);
111
+ return [value, set];
112
+ }
113
+
114
+ /** Runs another plugin's action from a component (`run("@sdeck/plugin-system", "open", {...})`). */
115
+ export function useRunAction(): HostBridge["run"] {
116
+ return useBridge().run;
117
+ }
118
+
119
+ /**
120
+ * An image ready to draw with `<img src>`: an icon (`icon:lucide/play`, `icon:si/SiDiscord`) in
121
+ * `color`, a URL or a `data:` URI. `undefined` until it has loaded.
122
+ */
123
+ export function useImage(src: string, color?: string): string | undefined {
124
+ const bridge = useBridge();
125
+ return useSyncExternalStore(bridge.watchImages, () =>
126
+ src ? bridge.image(src, color) : undefined,
127
+ );
128
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * A connection to another program or service, opened only while something needs it and reopened
3
+ * when it drops. Plugins hold it while their state is watched or a trigger listens, and borrow it
4
+ * to run actions.
5
+ */
6
+
7
+ export interface Link<C> {
8
+ /** What callers use. */
9
+ value: C;
10
+ close(): void;
11
+ }
12
+
13
+ /** Retrying cannot help (a wrong password, nothing configured) until something changes. */
14
+ export class PermanentError extends Error {}
15
+
16
+ export type ConnectionState = "connecting" | "connected" | "disconnected";
17
+
18
+ export interface ConnectionOptions<C> {
19
+ /**
20
+ * Opens the connection. Call `lost` if it drops later. `signal` aborts when nobody wants it
21
+ * any more.
22
+ */
23
+ open(lost: (error: Error) => void, signal: AbortSignal): Promise<Link<C>>;
24
+ onStatus?: (state: ConnectionState, error?: Error) => void;
25
+ /** How long it stays open after the last holder leaves (default 3000). */
26
+ lingerMs?: number;
27
+ /** First and longest pause between attempts (default 1000 and 30000). */
28
+ retry?: { minMs: number; maxMs: number };
29
+ }
30
+
31
+ interface Waiter<C> {
32
+ resolve: (value: C) => void;
33
+ reject: (error: Error) => void;
34
+ }
35
+
36
+ export class ManagedConnection<C> {
37
+ readonly #options: ConnectionOptions<C>;
38
+ readonly #waiters = new Set<Waiter<C>>();
39
+ #holders = 0;
40
+ #link: Link<C> | undefined;
41
+ #attempt: AbortController | undefined;
42
+ #retry: ReturnType<typeof setTimeout> | undefined;
43
+ #linger: ReturnType<typeof setTimeout> | undefined;
44
+ #delay: number;
45
+ /** Set by a {@link PermanentError}; cleared by {@link restart}. */
46
+ #failed: Error | undefined;
47
+
48
+ constructor(options: ConnectionOptions<C>) {
49
+ this.#options = options;
50
+ this.#delay = options.retry?.minMs ?? 1000;
51
+ }
52
+
53
+ /** The open connection, if there is one. */
54
+ get current(): C | undefined {
55
+ return this.#link?.value;
56
+ }
57
+
58
+ /** Keeps the connection wanted until the returned function is called. */
59
+ hold(): () => void {
60
+ this.#holders++;
61
+ clearTimeout(this.#linger);
62
+ this.#connect();
63
+ let released = false;
64
+ return () => {
65
+ if (released) return;
66
+ released = true;
67
+ this.#holders--;
68
+ if (this.#holders > 0) return;
69
+ this.#linger = setTimeout(() => this.#drop(), this.#options.lingerMs ?? 3000);
70
+ };
71
+ }
72
+
73
+ /** Runs `use` with the connection, opening it first if needed. */
74
+ async with<T>(use: (value: C) => T | Promise<T>, timeoutMs = 5000): Promise<T> {
75
+ const release = this.hold();
76
+ try {
77
+ return await use(await this.#ready(timeoutMs));
78
+ } finally {
79
+ release();
80
+ }
81
+ }
82
+
83
+ /** Starts over (the settings changed). */
84
+ restart(): void {
85
+ this.#failed = undefined;
86
+ this.#delay = this.#options.retry?.minMs ?? 1000;
87
+ this.#drop();
88
+ if (this.#holders > 0) this.#connect();
89
+ }
90
+
91
+ /** Closes it for good, whoever holds it. */
92
+ close(): void {
93
+ this.#holders = 0;
94
+ clearTimeout(this.#linger);
95
+ this.#drop();
96
+ this.#reject(new Error("the connection was closed"));
97
+ }
98
+
99
+ #ready(timeoutMs: number): Promise<C> {
100
+ if (this.#link) return Promise.resolve(this.#link.value);
101
+ if (this.#failed) return Promise.reject(this.#failed);
102
+ // Someone is waiting: no point sitting out the pause between attempts.
103
+ if (this.#retry) {
104
+ clearTimeout(this.#retry);
105
+ this.#retry = undefined;
106
+ this.#connect();
107
+ }
108
+ return new Promise<C>((resolve, reject) => {
109
+ let last: Error | undefined;
110
+ const waiter: Waiter<C> = {
111
+ resolve: (value) => {
112
+ clearTimeout(timer);
113
+ resolve(value);
114
+ },
115
+ reject: (error) => {
116
+ last = error;
117
+ clearTimeout(timer);
118
+ this.#waiters.delete(waiter);
119
+ reject(last);
120
+ },
121
+ };
122
+ const timer = setTimeout(
123
+ () => waiter.reject(new Error("could not connect in time")),
124
+ timeoutMs,
125
+ );
126
+ this.#waiters.add(waiter);
127
+ });
128
+ }
129
+
130
+ #connect(): void {
131
+ if (this.#link || this.#attempt || this.#retry || this.#failed) return;
132
+ const attempt = new AbortController();
133
+ this.#attempt = attempt;
134
+ this.#options.onStatus?.("connecting");
135
+ let lostEarly: Error | undefined;
136
+ let link: Link<C> | undefined;
137
+ const lost = (error: Error) => {
138
+ if (!link) {
139
+ lostEarly = error;
140
+ return;
141
+ }
142
+ if (this.#link !== link) return;
143
+ this.#link = undefined;
144
+ link.close();
145
+ this.#options.onStatus?.("disconnected", error);
146
+ this.#schedule(error);
147
+ };
148
+ const open = async () => {
149
+ const opened = await this.#options.open(lost, attempt.signal);
150
+ if (attempt.signal.aborted) {
151
+ opened.close();
152
+ return;
153
+ }
154
+ if (lostEarly) {
155
+ opened.close();
156
+ throw lostEarly;
157
+ }
158
+ link = opened;
159
+ this.#attempt = undefined;
160
+ this.#link = opened;
161
+ this.#delay = this.#options.retry?.minMs ?? 1000;
162
+ this.#options.onStatus?.("connected");
163
+ for (const waiter of this.#waiters) waiter.resolve(opened.value);
164
+ this.#waiters.clear();
165
+ };
166
+ open().catch((error: Error) => {
167
+ if (attempt.signal.aborted || this.#attempt !== attempt) return;
168
+ this.#attempt = undefined;
169
+ this.#options.onStatus?.("disconnected", error);
170
+ this.#reject(error);
171
+ this.#schedule(error);
172
+ });
173
+ }
174
+
175
+ #schedule(error: Error): void {
176
+ if (error instanceof PermanentError) {
177
+ this.#failed = error;
178
+ this.#reject(error);
179
+ return;
180
+ }
181
+ if (this.#holders <= 0) return;
182
+ clearTimeout(this.#retry);
183
+ this.#retry = setTimeout(() => {
184
+ this.#retry = undefined;
185
+ if (this.#holders > 0) this.#connect();
186
+ }, this.#delay);
187
+ this.#delay = Math.min(this.#delay * 2, this.#options.retry?.maxMs ?? 30_000);
188
+ }
189
+
190
+ #reject(error: Error): void {
191
+ for (const waiter of [...this.#waiters]) waiter.reject(error);
192
+ this.#waiters.clear();
193
+ }
194
+
195
+ #drop(): void {
196
+ clearTimeout(this.#retry);
197
+ this.#retry = undefined;
198
+ this.#attempt?.abort();
199
+ this.#attempt = undefined;
200
+ const link = this.#link;
201
+ this.#link = undefined;
202
+ if (!link) return;
203
+ link.close();
204
+ this.#options.onStatus?.("disconnected");
205
+ }
206
+ }
package/src/index.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * `@sdeck/plugin`: everything a plugin needs. Define actions that run headless (from keys,
3
+ * triggers and workflows) or draw themselves with React, publish live state, offer trigger types,
4
+ * and use the `@sdeck/app` hooks and components (re-exported here) for input and navigation.
5
+ */
6
+ export * from "@sdeck/app";
7
+ export {
8
+ type HostBridge,
9
+ HostBridgeContext,
10
+ useExpression,
11
+ useHostState,
12
+ useImage,
13
+ useRunAction,
14
+ useTemplate,
15
+ useVariable,
16
+ } from "./bridge.ts";
17
+ export {
18
+ type ConnectionOptions,
19
+ type ConnectionState,
20
+ type Link,
21
+ ManagedConnection,
22
+ PermanentError,
23
+ } from "./connection.ts";
24
+ export {
25
+ HOST_MODULES,
26
+ type ManifestResult,
27
+ PLUGIN_KEYWORD,
28
+ type PluginManifest,
29
+ parseManifest,
30
+ SUPPORTED_API_VERSIONS,
31
+ } from "./manifest.ts";
32
+ export {
33
+ type Action,
34
+ type ActionDef,
35
+ type ActionProps,
36
+ checkPlugin,
37
+ type Deactivate,
38
+ type DeckControls,
39
+ defineAction,
40
+ definePlugin,
41
+ defineTrigger,
42
+ type Onboarding,
43
+ type OnboardingStep,
44
+ type OptionSource,
45
+ PERMISSIONS,
46
+ type Permission,
47
+ PLUGIN_API_VERSION,
48
+ type PluginCommand,
49
+ type PluginContext,
50
+ type PluginDef,
51
+ pluginNamespace,
52
+ type RunContext,
53
+ type RunFn,
54
+ type RunOutcome,
55
+ type RunResult,
56
+ type SlotKind,
57
+ type StarterPage,
58
+ type StateDef,
59
+ type StatusLevel,
60
+ type Trigger,
61
+ type TriggerContext,
62
+ type TriggerDef,
63
+ } from "./plugin.ts";
64
+ export {
65
+ type BooleanField,
66
+ type ColorField,
67
+ checkSchema,
68
+ defaultValue,
69
+ type FieldValue,
70
+ type ImageField,
71
+ type InferSettings,
72
+ isFieldVisible,
73
+ type NumberField,
74
+ type PageField,
75
+ resolveSettings,
76
+ type SecretField,
77
+ type SelectField,
78
+ type SelectOption,
79
+ type SettingField,
80
+ type SettingsSchema,
81
+ type TextField,
82
+ } from "./settings.ts";
83
+ export { Shared } from "./shared.ts";
@@ -0,0 +1,85 @@
1
+ import { PLUGIN_API_VERSION } from "./plugin.ts";
2
+
3
+ /**
4
+ * What makes an npm package an sdeck plugin. In its `package.json`:
5
+ *
6
+ * ```json
7
+ * {
8
+ * "name": "sdeck-plugin-weather",
9
+ * "version": "1.0.0",
10
+ * "type": "module",
11
+ * "keywords": ["sdeck-plugin"],
12
+ * "sdeck": { "apiVersion": 2, "entry": "./dist/index.js" }
13
+ * }
14
+ * ```
15
+ *
16
+ * The entry's default export is the `definePlugin(...)` result. `react`, `@sdeck/plugin`,
17
+ * `@sdeck/app`, `@sdeck/core`, `@sdeck/engine` and `@sdeck/schema` are provided by the host: list them as peer dependencies and
18
+ * keep them out of the bundle.
19
+ */
20
+ export interface PluginManifest {
21
+ /** Package name; also the plugin id. */
22
+ name: string;
23
+ version: string;
24
+ description?: string;
25
+ /** Path of the module to import, relative to the package (default: `main`, else `index.js`). */
26
+ entry: string;
27
+ apiVersion: number;
28
+ }
29
+
30
+ /** The npm keyword that lists a package in the plugin registry. */
31
+ export const PLUGIN_KEYWORD = "sdeck-plugin";
32
+
33
+ /** Modules the host provides to plugins; plugins must not bundle their own copy. */
34
+ export const HOST_MODULES = [
35
+ "react",
36
+ "react/jsx-runtime",
37
+ "react/jsx-dev-runtime",
38
+ "@sdeck/plugin",
39
+ "@sdeck/app",
40
+ "@sdeck/core",
41
+ "@sdeck/engine",
42
+ "@sdeck/schema",
43
+ ] as const;
44
+
45
+ /**
46
+ * Plugin APIs this host loads. Version 1 plugins (actions that draw themselves) are a subset of
47
+ * version 2 and run unchanged.
48
+ */
49
+ export const SUPPORTED_API_VERSIONS: readonly number[] = [1, PLUGIN_API_VERSION];
50
+
51
+ export type ManifestResult = { ok: true; manifest: PluginManifest } | { ok: false; error: string };
52
+
53
+ /** Reads the plugin manifest out of a parsed `package.json`. */
54
+ export function parseManifest(pkg: unknown): ManifestResult {
55
+ if (!pkg || typeof pkg !== "object") return { ok: false, error: "package.json is not an object" };
56
+ const p = pkg as Record<string, unknown>;
57
+ const sdeck = p.sdeck as Record<string, unknown> | undefined;
58
+ if (typeof p.name !== "string") return { ok: false, error: "package.json has no name" };
59
+ if (!sdeck || typeof sdeck !== "object") {
60
+ return { ok: false, error: `${p.name} is not an sdeck plugin (no "sdeck" field)` };
61
+ }
62
+ const apiVersion = sdeck.apiVersion;
63
+ if (typeof apiVersion !== "number" || !SUPPORTED_API_VERSIONS.includes(apiVersion)) {
64
+ return {
65
+ ok: false,
66
+ error: `${p.name} targets plugin API ${String(apiVersion)}, this host supports ${SUPPORTED_API_VERSIONS.join(" and ")}`,
67
+ };
68
+ }
69
+ const entry =
70
+ typeof sdeck.entry === "string"
71
+ ? sdeck.entry
72
+ : typeof p.main === "string"
73
+ ? p.main
74
+ : "index.js";
75
+ return {
76
+ ok: true,
77
+ manifest: {
78
+ name: p.name,
79
+ version: typeof p.version === "string" ? p.version : "0.0.0",
80
+ ...(typeof p.description === "string" && { description: p.description }),
81
+ entry,
82
+ apiVersion,
83
+ },
84
+ };
85
+ }