@glazeen/mod-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/LICENSE +21 -0
- package/README.md +221 -2
- package/bin/bearbar-mod.js +3 -0
- package/client/bb.css +58 -0
- package/client/bb.js +157 -0
- package/dist/bb-JW737zq0.d.ts +266 -0
- package/dist/cli.js +457 -0
- package/dist/global.d.ts +19 -0
- package/dist/global.js +0 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +267 -0
- package/docs/api.md +229 -0
- package/docs/guide.md +200 -0
- package/docs/manifest.md +187 -0
- package/docs/runtime.md +144 -0
- package/docs/styling.md +118 -0
- package/package.json +66 -3
- package/schema/bearbar.mod.schema.json +276 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// src/bb.ts
|
|
2
|
+
/** CSS custom properties the dock sets on `<html>` of every mod page. */
|
|
3
|
+
const THEME_TOKENS = [
|
|
4
|
+
"--bb-text",
|
|
5
|
+
"--bb-text-dim",
|
|
6
|
+
"--bb-accent",
|
|
7
|
+
"--bb-accent-2",
|
|
8
|
+
"--bb-green",
|
|
9
|
+
"--bb-red",
|
|
10
|
+
"--bb-orange",
|
|
11
|
+
"--bb-surface",
|
|
12
|
+
"--bb-surface-hover",
|
|
13
|
+
"--bb-font",
|
|
14
|
+
"--bb-font-display",
|
|
15
|
+
"--bb-fs-xs",
|
|
16
|
+
"--bb-fs-sm",
|
|
17
|
+
"--bb-fs-lg",
|
|
18
|
+
"--bb-card-radius"
|
|
19
|
+
];
|
|
20
|
+
/** Size limit of `bb.storage`, per widget instance, measured as JSON text. */
|
|
21
|
+
const STORAGE_QUOTA = 262144;
|
|
22
|
+
// src/manifest.ts
|
|
23
|
+
/** Version of the mod API described by this package. See README, "API versions". */
|
|
24
|
+
const API_VERSION = 1;
|
|
25
|
+
const WIDGET_SIZES = [
|
|
26
|
+
"s",
|
|
27
|
+
"m",
|
|
28
|
+
"l"
|
|
29
|
+
];
|
|
30
|
+
const WIDGET_CATEGORIES = [
|
|
31
|
+
"Essentials",
|
|
32
|
+
"System",
|
|
33
|
+
"Productivity",
|
|
34
|
+
"Weather",
|
|
35
|
+
"Utilities",
|
|
36
|
+
"Mods"
|
|
37
|
+
];
|
|
38
|
+
/** Mod ids: 2-64 chars of letters, digits, ".", "_" or "-", starting with a letter or digit. */
|
|
39
|
+
const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{1,63}$/i;
|
|
40
|
+
/**
|
|
41
|
+
* Returns its argument unchanged, typed as a manifest with its literal values kept, so
|
|
42
|
+
* {@link InferConfig} can derive the config type. For mods that write bearbar.mod.json
|
|
43
|
+
* from TypeScript.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* const manifest = defineManifest({
|
|
47
|
+
* id: "weather", name: "Weather", version: "1.0.0", tile: "tile.html",
|
|
48
|
+
* settings: { unit: { type: "select", label: "Unit", default: "c",
|
|
49
|
+
* options: [{ value: "c", label: "Celsius" }, { value: "f", label: "Fahrenheit" }] } },
|
|
50
|
+
* });
|
|
51
|
+
* type Config = InferConfig<typeof manifest>; // { unit: "c" | "f" }
|
|
52
|
+
*/
|
|
53
|
+
function defineManifest(manifest) {
|
|
54
|
+
return manifest;
|
|
55
|
+
}
|
|
56
|
+
// src/validate.ts
|
|
57
|
+
/** "path: message", or just the message for the root. */
|
|
58
|
+
function formatIssue(issue) {
|
|
59
|
+
return issue.path ? `${issue.path}: ${issue.message}` : issue.message;
|
|
60
|
+
}
|
|
61
|
+
const PERMISSION_PATTERN = /^(system|open-url|net:(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*)$/i;
|
|
62
|
+
const SEMVER = /^\d+\.\d+\.\d+(-[0-9a-z.-]+)?(\+[0-9a-z.-]+)?$/i;
|
|
63
|
+
const MANIFEST_KEYS = [
|
|
64
|
+
"$schema",
|
|
65
|
+
"id",
|
|
66
|
+
"name",
|
|
67
|
+
"version",
|
|
68
|
+
"apiVersion",
|
|
69
|
+
"description",
|
|
70
|
+
"author",
|
|
71
|
+
"category",
|
|
72
|
+
"sizes",
|
|
73
|
+
"tile",
|
|
74
|
+
"panel",
|
|
75
|
+
"panelSize",
|
|
76
|
+
"permissions",
|
|
77
|
+
"settings"
|
|
78
|
+
];
|
|
79
|
+
const BASE_FIELD_KEYS = [
|
|
80
|
+
"type",
|
|
81
|
+
"label",
|
|
82
|
+
"description",
|
|
83
|
+
"visibleWhen",
|
|
84
|
+
"default"
|
|
85
|
+
];
|
|
86
|
+
const FIELD_KEYS = {
|
|
87
|
+
text: [...BASE_FIELD_KEYS, "placeholder"],
|
|
88
|
+
number: [
|
|
89
|
+
...BASE_FIELD_KEYS,
|
|
90
|
+
"min",
|
|
91
|
+
"max",
|
|
92
|
+
"step"
|
|
93
|
+
],
|
|
94
|
+
toggle: BASE_FIELD_KEYS,
|
|
95
|
+
select: [...BASE_FIELD_KEYS, "options"]
|
|
96
|
+
};
|
|
97
|
+
const FIELD_TYPES = Object.keys(FIELD_KEYS);
|
|
98
|
+
const DEFAULT_TYPE = {
|
|
99
|
+
text: "string",
|
|
100
|
+
select: "string",
|
|
101
|
+
number: "number",
|
|
102
|
+
toggle: "boolean"
|
|
103
|
+
};
|
|
104
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
105
|
+
const isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
106
|
+
const isPositive = (v) => isNum(v) && v > 0;
|
|
107
|
+
const json = (v) => JSON.stringify(v);
|
|
108
|
+
/** True for an .html file inside the mod folder: relative, no "..", no drive or scheme. */
|
|
109
|
+
function isPagePath(p) {
|
|
110
|
+
return typeof p === "string" && !/^([a-z][a-z0-9+.-]*:|[\\/])/i.test(p) && !p.split(/[\\/]/).includes("..") && /.\.html$/i.test(p);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Checks a parsed bearbar.mod.json and reports every problem, with a path to each.
|
|
114
|
+
*
|
|
115
|
+
* Stricter than the dock, which loads what it can and fills in defaults: use it in tooling
|
|
116
|
+
* and CI to catch mistakes early. It checks the manifest only; the `bearbar-mod validate`
|
|
117
|
+
* command also checks that the pages exist.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* const result = validateManifest(JSON.parse(text));
|
|
121
|
+
* if (!result.ok) for (const e of result.errors) console.error(formatIssue(e));
|
|
122
|
+
*/
|
|
123
|
+
function validateManifest(input) {
|
|
124
|
+
const errors = [];
|
|
125
|
+
const warnings = [];
|
|
126
|
+
const error = (path, message) => errors.push({
|
|
127
|
+
path,
|
|
128
|
+
message
|
|
129
|
+
});
|
|
130
|
+
const warn = (path, message) => warnings.push({
|
|
131
|
+
path,
|
|
132
|
+
message
|
|
133
|
+
});
|
|
134
|
+
if (!isObj(input)) return {
|
|
135
|
+
ok: false,
|
|
136
|
+
errors: [{
|
|
137
|
+
path: "",
|
|
138
|
+
message: "must be a JSON object"
|
|
139
|
+
}],
|
|
140
|
+
warnings
|
|
141
|
+
};
|
|
142
|
+
const m = input;
|
|
143
|
+
for (const key of Object.keys(m)) if (!MANIFEST_KEYS.includes(key)) warn(key, `unknown property${suggest(key, MANIFEST_KEYS)}`);
|
|
144
|
+
if (m.id === void 0) error("id", "is required");
|
|
145
|
+
else if (typeof m.id !== "string" || !MOD_ID_PATTERN.test(m.id)) error("id", "must be 2-64 letters, digits, \".\", \"_\" or \"-\", starting with a letter or digit");
|
|
146
|
+
if (m.name === void 0) error("name", "is required");
|
|
147
|
+
else if (typeof m.name !== "string" || m.name.trim() === "") error("name", "must be a non-empty string");
|
|
148
|
+
if (m.version === void 0) error("version", "is required");
|
|
149
|
+
else if (typeof m.version !== "string" || m.version.trim() === "") error("version", "must be a non-empty string");
|
|
150
|
+
else if (!SEMVER.test(m.version)) warn("version", `${json(m.version)} is not a semantic version like "1.0.0"`);
|
|
151
|
+
if (m.apiVersion !== void 0) {
|
|
152
|
+
if (typeof m.apiVersion !== "number" || !Number.isInteger(m.apiVersion) || m.apiVersion < 1) error("apiVersion", "must be a positive integer");
|
|
153
|
+
else if (m.apiVersion > 1) warn("apiVersion", `${m.apiVersion} is newer than this SDK supports (1)`);
|
|
154
|
+
}
|
|
155
|
+
for (const key of ["description", "author"]) if (m[key] !== void 0 && typeof m[key] !== "string") error(key, "must be a string");
|
|
156
|
+
if (m.category !== void 0) warn("category", "is ignored: mods are always listed under Mods");
|
|
157
|
+
if (m.tile === void 0) error("tile", "is required");
|
|
158
|
+
else if (!isPagePath(m.tile)) error("tile", "must be an .html file inside the mod folder");
|
|
159
|
+
if (m.panel !== void 0 && !isPagePath(m.panel)) error("panel", "must be an .html file inside the mod folder");
|
|
160
|
+
if (m.sizes !== void 0) {
|
|
161
|
+
if (!isObj(m.sizes) || Object.keys(m.sizes).length === 0) error("sizes", "must be an object with at least one of s, m, l");
|
|
162
|
+
else for (const [size, units] of Object.entries(m.sizes)) if (!WIDGET_SIZES.includes(size)) error(`sizes.${size}`, "unknown size (use s, m or l)");
|
|
163
|
+
else if (!isPositive(units)) error(`sizes.${size}`, "must be a positive number");
|
|
164
|
+
}
|
|
165
|
+
if (m.panelSize !== void 0) {
|
|
166
|
+
if (!isObj(m.panelSize) || !isPositive(m.panelSize.width) || !isPositive(m.panelSize.height)) error("panelSize", "must be { width, height } with positive numbers");
|
|
167
|
+
else for (const key of Object.keys(m.panelSize)) if (key !== "width" && key !== "height") error(`panelSize.${key}`, "unknown property");
|
|
168
|
+
if (m.panel === void 0) warn("panelSize", "is set but there is no panel");
|
|
169
|
+
}
|
|
170
|
+
if (m.permissions !== void 0) {
|
|
171
|
+
if (!Array.isArray(m.permissions)) error("permissions", "must be an array");
|
|
172
|
+
else {
|
|
173
|
+
const seen = /* @__PURE__ */ new Set();
|
|
174
|
+
m.permissions.forEach((p, i) => {
|
|
175
|
+
if (typeof p !== "string" || !PERMISSION_PATTERN.test(p)) error(`permissions[${i}]`, `unknown permission ${json(p)} (use "net:<host>", "system" or "open-url")`);
|
|
176
|
+
else if (seen.has(p.toLowerCase())) error(`permissions[${i}]`, `duplicate ${json(p)}`);
|
|
177
|
+
else seen.add(p.toLowerCase());
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (m.settings !== void 0) {
|
|
182
|
+
if (!isObj(m.settings)) error("settings", "must be an object");
|
|
183
|
+
else for (const [key, field] of Object.entries(m.settings)) validateField(`settings.${key}`, field, m.settings, error, warn);
|
|
184
|
+
}
|
|
185
|
+
return errors.length ? {
|
|
186
|
+
ok: false,
|
|
187
|
+
errors,
|
|
188
|
+
warnings
|
|
189
|
+
} : {
|
|
190
|
+
ok: true,
|
|
191
|
+
manifest: m,
|
|
192
|
+
errors: [],
|
|
193
|
+
warnings
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function validateField(path, f, all, error, warn) {
|
|
197
|
+
if (!isObj(f)) {
|
|
198
|
+
error(path, "must be an object");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const type = f.type;
|
|
202
|
+
if (!FIELD_TYPES.includes(type)) {
|
|
203
|
+
error(`${path}.type`, `must be one of ${FIELD_TYPES.join(", ")}`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
const allowed = FIELD_KEYS[type];
|
|
207
|
+
for (const key of Object.keys(f)) if (!allowed.includes(key)) error(`${path}.${key}`, `not allowed on a ${type} field${suggest(key, allowed)}`);
|
|
208
|
+
if (typeof f.label !== "string") error(`${path}.label`, "must be a string");
|
|
209
|
+
if (f.description !== void 0 && typeof f.description !== "string") error(`${path}.description`, "must be a string");
|
|
210
|
+
const vw = f.visibleWhen;
|
|
211
|
+
if (vw !== void 0) {
|
|
212
|
+
if (!isObj(vw) || typeof vw.field !== "string" || ![
|
|
213
|
+
"string",
|
|
214
|
+
"number",
|
|
215
|
+
"boolean"
|
|
216
|
+
].includes(typeof vw.equals) || Object.keys(vw).some((k) => k !== "field" && k !== "equals")) error(`${path}.visibleWhen`, "must be { field, equals }");
|
|
217
|
+
else if (!(vw.field in all) || `settings.${vw.field}` === path) error(`${path}.visibleWhen.field`, `${json(vw.field)} is not another setting`);
|
|
218
|
+
}
|
|
219
|
+
const def = f.default;
|
|
220
|
+
if (def !== void 0 && typeof def !== DEFAULT_TYPE[type]) error(`${path}.default`, `must be a ${DEFAULT_TYPE[type]}`);
|
|
221
|
+
if (type === "text" && f.placeholder !== void 0 && typeof f.placeholder !== "string") error(`${path}.placeholder`, "must be a string");
|
|
222
|
+
if (type === "number") {
|
|
223
|
+
for (const key of [
|
|
224
|
+
"min",
|
|
225
|
+
"max",
|
|
226
|
+
"step"
|
|
227
|
+
]) if (f[key] !== void 0 && !isNum(f[key])) error(`${path}.${key}`, "must be a number");
|
|
228
|
+
const { min, max, step } = f;
|
|
229
|
+
if (isNum(step) && step <= 0) error(`${path}.step`, "must be greater than 0");
|
|
230
|
+
if (isNum(min) && isNum(max) && min > max) error(`${path}.min`, "is greater than max");
|
|
231
|
+
if (isNum(def) && (isNum(min) && def < min || isNum(max) && def > max)) warn(`${path}.default`, "is outside min..max");
|
|
232
|
+
}
|
|
233
|
+
if (type === "select") {
|
|
234
|
+
const options = f.options;
|
|
235
|
+
if (!Array.isArray(options) || options.length === 0) error(`${path}.options`, "must be a non-empty array");
|
|
236
|
+
else {
|
|
237
|
+
const values = /* @__PURE__ */ new Set();
|
|
238
|
+
options.forEach((o, i) => {
|
|
239
|
+
if (!isObj(o) || typeof o.value !== "string" || typeof o.label !== "string" || Object.keys(o).some((k) => k !== "value" && k !== "label")) error(`${path}.options[${i}]`, "must be { value, label } strings");
|
|
240
|
+
else if (values.has(o.value)) error(`${path}.options[${i}].value`, `duplicate ${json(o.value)}`);
|
|
241
|
+
else values.add(o.value);
|
|
242
|
+
});
|
|
243
|
+
if (typeof def === "string" && values.size && !values.has(def)) error(`${path}.default`, `${json(def)} is not one of the option values`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** ' (did you mean "x"?)' when a known key is a likely typo of `key`. */
|
|
248
|
+
function suggest(key, known) {
|
|
249
|
+
let best = "";
|
|
250
|
+
let bestDist = 3;
|
|
251
|
+
for (const k of known) {
|
|
252
|
+
const d = distance(key.toLowerCase(), k.toLowerCase());
|
|
253
|
+
if (d < bestDist) [best, bestDist] = [k, d];
|
|
254
|
+
}
|
|
255
|
+
return best ? ` (did you mean ${json(best)}?)` : "";
|
|
256
|
+
}
|
|
257
|
+
/** Levenshtein distance. */
|
|
258
|
+
function distance(a, b) {
|
|
259
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
260
|
+
for (let i = 1; i <= a.length; i++) {
|
|
261
|
+
const cur = [i];
|
|
262
|
+
for (let j = 1; j <= b.length; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
263
|
+
prev = cur;
|
|
264
|
+
}
|
|
265
|
+
return prev[b.length];
|
|
266
|
+
}
|
|
267
|
+
export { API_VERSION, MOD_ID_PATTERN, STORAGE_QUOTA, THEME_TOKENS, WIDGET_CATEGORIES, WIDGET_SIZES, defineManifest, formatIssue, validateManifest };
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# `bb` API reference
|
|
2
|
+
|
|
3
|
+
The dock injects the `bb` runtime into every HTML page of a mod, before your own scripts, so
|
|
4
|
+
there is nothing to load. `bb` is a frozen global object; its state properties are read-only.
|
|
5
|
+
|
|
6
|
+
For editor completion in a plain-JS page:
|
|
7
|
+
|
|
8
|
+
```js
|
|
9
|
+
// @ts-check
|
|
10
|
+
/// <reference types="@glazeen/mod-sdk/global" />
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The type names below are exported from `@glazeen/mod-sdk`.
|
|
14
|
+
|
|
15
|
+
| Member | Kind | Needs |
|
|
16
|
+
| --------------------------------------------- | -------- | ------------ |
|
|
17
|
+
| [`bb.ready`](#bbready) | Promise | |
|
|
18
|
+
| [`bb.config`](#bbconfig) | property | |
|
|
19
|
+
| [`bb.size`](#bbsize) | property | |
|
|
20
|
+
| [`bb.surface`](#bbsurface) | property | |
|
|
21
|
+
| [`bb.preview`](#bbpreview) | property | |
|
|
22
|
+
| [`bb.on(event, listener)`](#bbonevent-listener) | method | |
|
|
23
|
+
| [`bb.fetch(url, init)`](#bbfetchurl-init) | method | `net:<host>` |
|
|
24
|
+
| [`bb.storage`](#bbstorage) | object | |
|
|
25
|
+
| [`bb.panel`](#bbpanel) | object | |
|
|
26
|
+
| [`bb.openUrl(url)`](#bbopenurlurl) | method | `open-url` |
|
|
27
|
+
| [`bb.openSettings()`](#bbopensettings) | method | |
|
|
28
|
+
|
|
29
|
+
## Errors
|
|
30
|
+
|
|
31
|
+
Methods return promises. When the dock refuses a call, the promise rejects with an `Error`
|
|
32
|
+
whose message starts with `bb: <method>:`, for example
|
|
33
|
+
`bb: openUrl: needs the "open-url" permission`. `bb.fetch` is the exception: a failed request
|
|
34
|
+
resolves with `ok: false`.
|
|
35
|
+
|
|
36
|
+
Invalid arguments throw a `TypeError` synchronously (`bb.on`) or reject (`bb.fetch`).
|
|
37
|
+
|
|
38
|
+
## State
|
|
39
|
+
|
|
40
|
+
### `bb.ready`
|
|
41
|
+
|
|
42
|
+
`Promise<Bb>`. Resolves once the dock has sent the config, size, surface and theme. Until then
|
|
43
|
+
`bb.config` is `{}` and `bb.size` is `"m"`. It resolves once and never rejects.
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
const { config, size, surface } = await bb.ready;
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### `bb.config`
|
|
50
|
+
|
|
51
|
+
The widget's settings: every field with a `default`, overridden by the user's values. Fields
|
|
52
|
+
without a default are missing until the user sets them. A new object replaces it on every
|
|
53
|
+
change; listen with `bb.on("config")`.
|
|
54
|
+
|
|
55
|
+
In TypeScript it is `Record<string, unknown>` unless you register a type; see
|
|
56
|
+
[typed config](../README.md#typed-config).
|
|
57
|
+
|
|
58
|
+
### `bb.size`
|
|
59
|
+
|
|
60
|
+
`"s" | "m" | "l"` (`WidgetSize`): the size the user picked for this tile, among the
|
|
61
|
+
[sizes](manifest.md#sizes) the manifest lists. The panel gets its tile's size.
|
|
62
|
+
|
|
63
|
+
### `bb.surface`
|
|
64
|
+
|
|
65
|
+
`"tile" | "panel"` (`Surface`): which page is running. Useful when the tile and panel share a
|
|
66
|
+
script.
|
|
67
|
+
|
|
68
|
+
### `bb.preview`
|
|
69
|
+
|
|
70
|
+
`true` inside the widget picker's preview. There, `bb.fetch` resolves with `ok: false`
|
|
71
|
+
(`error: "no network in preview"`), `bb.storage.set` resolves but stores nothing, and panels
|
|
72
|
+
and the widget menu don't open. Show sample data.
|
|
73
|
+
|
|
74
|
+
## Events
|
|
75
|
+
|
|
76
|
+
### `bb.on(event, listener)`
|
|
77
|
+
|
|
78
|
+
Adds a listener and returns a function that removes it.
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
const off = bb.on("config", (config) => render(config));
|
|
82
|
+
// later
|
|
83
|
+
off();
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
| Event | Value | When |
|
|
87
|
+
| -------- | ------------- | ----------------------------------------------------------- |
|
|
88
|
+
| `config` | config object | The user changed a setting. `bb.config` is already updated. |
|
|
89
|
+
| `size` | `WidgetSize` | The user changed the tile size. `bb.size` is updated. |
|
|
90
|
+
| `theme` | `Theme` | Theme, material or accent changed. Already applied. |
|
|
91
|
+
| `system` | `SystemStats` | Every 2 seconds. Needs the `system` permission. |
|
|
92
|
+
|
|
93
|
+
- Events don't fire for the initial state: read it after `bb.ready`.
|
|
94
|
+
- A listener that throws doesn't stop the others; the error is reported like an uncaught error.
|
|
95
|
+
- An unknown event name or a listener that isn't a function throws a `TypeError`.
|
|
96
|
+
- The first `system` listener asks the dock to start sending stats. Without the `system`
|
|
97
|
+
permission the request fails and is reported as an uncaught error; no stats arrive.
|
|
98
|
+
|
|
99
|
+
`SystemStats`:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
{
|
|
103
|
+
cpu: number; // CPU load, 0..1
|
|
104
|
+
ram: number; // memory in use, 0..1
|
|
105
|
+
ramUsedGb: number;
|
|
106
|
+
ramTotalGb: number;
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`Theme` is described in [styling](styling.md#the-theme-event).
|
|
111
|
+
|
|
112
|
+
## Network
|
|
113
|
+
|
|
114
|
+
### `bb.fetch(url, init?)`
|
|
115
|
+
|
|
116
|
+
Makes an HTTP request through the dock, which checks it against the mod's `net:` permissions.
|
|
117
|
+
|
|
118
|
+
```js
|
|
119
|
+
const res = await bb.fetch("https://api.example.com/v1/price?coin=btc", {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { "content-type": "application/json" },
|
|
122
|
+
body: JSON.stringify({ coin: "btc" }),
|
|
123
|
+
});
|
|
124
|
+
if (res.ok) {
|
|
125
|
+
const data = res.json();
|
|
126
|
+
} else {
|
|
127
|
+
console.warn(res.error ?? `HTTP ${res.status}`);
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**Arguments.**
|
|
132
|
+
|
|
133
|
+
| Name | Type | Notes |
|
|
134
|
+
| -------------- | ------------------------------------------ | ----------------------------------- |
|
|
135
|
+
| `url` | `string \| URL` | Must be `https:`. |
|
|
136
|
+
| `init.method` | `string` | Default `"GET"`. |
|
|
137
|
+
| `init.headers` | object, `Headers`, or `[name, value]` pairs | |
|
|
138
|
+
| `init.body` | `string` | Anything else rejects with a `TypeError`. |
|
|
139
|
+
|
|
140
|
+
**Result** (`BbResponse`):
|
|
141
|
+
|
|
142
|
+
| Property | Type | Notes |
|
|
143
|
+
| --------- | --------- | -------------------------------------------------------- |
|
|
144
|
+
| `ok` | `boolean` | `true` for a 2xx status. |
|
|
145
|
+
| `status` | `number` | HTTP status, or `0` when there was no response. |
|
|
146
|
+
| `text` | `string` | The body as UTF-8 text. |
|
|
147
|
+
| `error` | `string?` | Why the request failed, when `status` is `0`. |
|
|
148
|
+
| `json()` | function | `JSON.parse(text)`. Throws a `SyntaxError` on bad JSON. |
|
|
149
|
+
|
|
150
|
+
**Resolves with `ok: false` and `status: 0`** when:
|
|
151
|
+
|
|
152
|
+
- the host isn't declared (`permission "net:<host>" not declared`),
|
|
153
|
+
- the URL isn't https or isn't valid,
|
|
154
|
+
- the request fails or takes longer than 15 seconds (`timed out`),
|
|
155
|
+
- the response is larger than 2 MB (`response too large`),
|
|
156
|
+
- the page is a preview (`no network in preview`).
|
|
157
|
+
|
|
158
|
+
An HTTP error status (404, 500) resolves with that `status`, `ok: false` and the body.
|
|
159
|
+
|
|
160
|
+
**Limits.** Requests carry no cookies or credentials. Response headers aren't exposed. Bodies
|
|
161
|
+
are text only: binary responses (images, archives) aren't supported, so images from the web
|
|
162
|
+
can't be shown.
|
|
163
|
+
|
|
164
|
+
## Storage
|
|
165
|
+
|
|
166
|
+
### `bb.storage`
|
|
167
|
+
|
|
168
|
+
A key-value store for this widget instance. Two tiles of the same mod have separate stores; a
|
|
169
|
+
tile and its panel share one. It is saved with the dock's settings and survives restarts and
|
|
170
|
+
updates of the mod.
|
|
171
|
+
|
|
172
|
+
```js
|
|
173
|
+
await bb.storage.set("last", { price: 64250, at: Date.now() });
|
|
174
|
+
const last = await bb.storage.get("last"); // undefined if never set
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
| Method | Returns | Notes |
|
|
178
|
+
| ----------------- | -------------------------- | ----------------------------------------- |
|
|
179
|
+
| `get(key)` | `Promise<T \| undefined>` | |
|
|
180
|
+
| `set(key, value)` | `Promise<void>` | `value` must be JSON-serialisable. |
|
|
181
|
+
|
|
182
|
+
- Keys are strings (other values are converted with `String()`).
|
|
183
|
+
- The whole store is limited to 256 KB of JSON (`STORAGE_QUOTA`). A `set` that would exceed it
|
|
184
|
+
rejects with `storage is full` and changes nothing.
|
|
185
|
+
- Store plain JSON data: values are saved as JSON, so functions and `undefined` are dropped
|
|
186
|
+
and a `Date` comes back as a string after a restart.
|
|
187
|
+
- There is no `delete`; set the key to `null`.
|
|
188
|
+
- In preview, `set` resolves without storing.
|
|
189
|
+
|
|
190
|
+
## Dock actions
|
|
191
|
+
|
|
192
|
+
### `bb.panel`
|
|
193
|
+
|
|
194
|
+
| Method | Notes |
|
|
195
|
+
| --------- | ------------------------------------------------------------------------ |
|
|
196
|
+
| `open()` | Opens the mod's [panel](manifest.md#tile-and-panel) above the tile, or closes it if it is open (like clicking a built-in tile). Rejects when the mod has no panel, or when called from the panel itself. Does nothing in preview. |
|
|
197
|
+
| `close()` | Closes the panel. Works from the tile or the panel. |
|
|
198
|
+
|
|
199
|
+
Escape and clicking outside the panel also close it.
|
|
200
|
+
|
|
201
|
+
### `bb.openUrl(url)`
|
|
202
|
+
|
|
203
|
+
Opens an `http:` or `https:` link in the user's default browser. Needs the `open-url`
|
|
204
|
+
permission, or it rejects. Other schemes are ignored. Mod pages can't navigate or open windows
|
|
205
|
+
themselves, so links (`<a href>`) must go through this.
|
|
206
|
+
|
|
207
|
+
```js
|
|
208
|
+
link.addEventListener("click", (e) => {
|
|
209
|
+
e.preventDefault();
|
|
210
|
+
bb.openUrl(link.href);
|
|
211
|
+
});
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### `bb.openSettings()`
|
|
215
|
+
|
|
216
|
+
Opens this widget's settings popup, the one the user reaches from the widget menu. Useful for
|
|
217
|
+
a "Set up" button when a required setting is missing.
|
|
218
|
+
|
|
219
|
+
## Constants
|
|
220
|
+
|
|
221
|
+
Exported from `@glazeen/mod-sdk` for tooling:
|
|
222
|
+
|
|
223
|
+
| Name | Value |
|
|
224
|
+
| ---------------- | -------------------------------------------------------- |
|
|
225
|
+
| `API_VERSION` | `1`, the mod API this package describes. |
|
|
226
|
+
| `STORAGE_QUOTA` | `262144` (256 KB). |
|
|
227
|
+
| `THEME_TOKENS` | The CSS variables the dock sets. See [styling](styling.md). |
|
|
228
|
+
| `WIDGET_SIZES` | `["s", "m", "l"]`. |
|
|
229
|
+
| `MOD_ID_PATTERN` | The `RegExp` an `id` must match. |
|
package/docs/guide.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Writing a bearbar mod
|
|
2
|
+
|
|
3
|
+
A mod is a widget for the bearbar dock: a folder holding a manifest and one or two HTML pages.
|
|
4
|
+
It needs no build step and no package install. The dock serves the pages, injects the `bb`
|
|
5
|
+
runtime and a base stylesheet, and generates a settings popup from the manifest.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
my-mod/
|
|
9
|
+
bearbar.mod.json the manifest
|
|
10
|
+
tile.html the tile on the dock
|
|
11
|
+
panel.html optional popup, opened from the tile
|
|
12
|
+
anything.js/css/png/svg/woff2 ...
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Reference: [manifest](manifest.md) · [`bb` API](api.md) · [styling](styling.md) ·
|
|
16
|
+
[sandbox and runtime](runtime.md) · [CLI](../README.md#cli)
|
|
17
|
+
|
|
18
|
+
## 1. Create the mod
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npx @glazeen/mod-sdk init my-mod
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This writes `bearbar.mod.json`, `tile.html` and `tile.js` into `my-mod/` and never overwrites
|
|
25
|
+
existing files. You can also create the files by hand; the smallest mod is a manifest and a
|
|
26
|
+
page:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"$schema": "https://unpkg.com/@glazeen/mod-sdk/schema/bearbar.mod.schema.json",
|
|
31
|
+
"id": "my-mod",
|
|
32
|
+
"name": "My mod",
|
|
33
|
+
"version": "0.1.0",
|
|
34
|
+
"tile": "tile.html"
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```html
|
|
39
|
+
<!doctype html>
|
|
40
|
+
<html>
|
|
41
|
+
<body>
|
|
42
|
+
<div class="bb-tile"><span class="bb-value" id="v">…</span></div>
|
|
43
|
+
<script>
|
|
44
|
+
bb.ready.then(() => {
|
|
45
|
+
document.getElementById("v").textContent = "Hello";
|
|
46
|
+
});
|
|
47
|
+
</script>
|
|
48
|
+
</body>
|
|
49
|
+
</html>
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The `$schema` line gives you validation and hover docs in VS Code and other JSON editors.
|
|
53
|
+
|
|
54
|
+
## 2. Install it
|
|
55
|
+
|
|
56
|
+
The mods folder is `%APPDATA%\bearbar\mods`. To open it, right-click the dock, choose
|
|
57
|
+
**Add widget…**, then click **Mods folder**. Copy your folder there, or link it so you can keep
|
|
58
|
+
it elsewhere:
|
|
59
|
+
|
|
60
|
+
```bat
|
|
61
|
+
mklink /J "%APPDATA%\bearbar\mods\my-mod" "C:\path\to\my-mod"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The mod appears in **Add widget → Mods** within a second. Add it to the dock from there.
|
|
65
|
+
|
|
66
|
+
Edits reload live: save any file in the mod and every tile of that mod reloads. If the mod
|
|
67
|
+
can't load (invalid JSON, a missing page, an invalid id), its tile shows the reason.
|
|
68
|
+
|
|
69
|
+
A mod in the user folder replaces a bundled mod with the same `id`. A mod can't replace a
|
|
70
|
+
built-in widget.
|
|
71
|
+
|
|
72
|
+
## 3. Wait for `bb.ready`
|
|
73
|
+
|
|
74
|
+
`bb` exists as soon as your script runs, but its state arrives from the dock a moment later.
|
|
75
|
+
Read `bb.config`, `bb.size` and `bb.surface` after `bb.ready` resolves:
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
const { config, size } = await bb.ready;
|
|
79
|
+
render(config, size);
|
|
80
|
+
bb.on("config", (c) => render(c, bb.size));
|
|
81
|
+
bb.on("size", (s) => render(bb.config, s));
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
In a classic `<script>`, wrap this in an async function or use `bb.ready.then(...)`.
|
|
85
|
+
|
|
86
|
+
## 4. Add settings
|
|
87
|
+
|
|
88
|
+
Declare settings in the manifest. The dock generates the settings popup (right-click the tile >
|
|
89
|
+
Settings) and passes the values as `bb.config`, with defaults filled in:
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
"settings": {
|
|
93
|
+
"city": { "type": "text", "label": "City", "placeholder": "Milan" },
|
|
94
|
+
"unit": {
|
|
95
|
+
"type": "select", "label": "Unit", "default": "c",
|
|
96
|
+
"options": [{ "value": "c", "label": "Celsius" }, { "value": "f", "label": "Fahrenheit" }]
|
|
97
|
+
},
|
|
98
|
+
"decimals": { "type": "number", "label": "Decimals", "default": 1, "min": 0, "max": 3 },
|
|
99
|
+
"showFeelsLike": { "type": "toggle", "label": "Show feels-like", "default": false }
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Settings without a `default` are missing from `bb.config` until the user sets them, so handle
|
|
104
|
+
`undefined`. See [setting fields](manifest.md#settings) for every option, including
|
|
105
|
+
`visibleWhen`.
|
|
106
|
+
|
|
107
|
+
## 5. Fetch data
|
|
108
|
+
|
|
109
|
+
Pages can't make network requests themselves: the sandbox blocks `fetch`, images from the web
|
|
110
|
+
and remote scripts. Declare each host as a permission and go through `bb.fetch`:
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
"permissions": ["net:api.example.com"]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
```js
|
|
117
|
+
const res = await bb.fetch(`https://api.example.com/weather?city=${encodeURIComponent(city)}`);
|
|
118
|
+
if (res.ok) render(res.json());
|
|
119
|
+
else showError(res.error ?? `HTTP ${res.status}`);
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`bb.fetch` never rejects for a failed request: check `res.ok`. Only https is allowed. See
|
|
123
|
+
[`bb.fetch`](api.md#bbfetchurl-init) for the limits.
|
|
124
|
+
|
|
125
|
+
## 6. Handle the widget picker
|
|
126
|
+
|
|
127
|
+
The widget picker shows a live preview of your tile. There, `bb.preview` is `true`, `bb.fetch`
|
|
128
|
+
always fails and storage writes are dropped. Show sample data instead of an error:
|
|
129
|
+
|
|
130
|
+
```js
|
|
131
|
+
const data = bb.preview ? SAMPLE : await load();
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## 7. Remember things
|
|
135
|
+
|
|
136
|
+
`bb.storage` is a small key-value store per widget instance, kept with the dock's settings.
|
|
137
|
+
Use it to cache the last result so the tile shows something while it reloads:
|
|
138
|
+
|
|
139
|
+
```js
|
|
140
|
+
const last = await bb.storage.get("last");
|
|
141
|
+
if (last) render(last);
|
|
142
|
+
const fresh = await load();
|
|
143
|
+
await bb.storage.set("last", fresh);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Values must be JSON. The whole store is limited to 256 KB. `localStorage`, `IndexedDB` and
|
|
147
|
+
cookies don't work in the sandbox.
|
|
148
|
+
|
|
149
|
+
## 8. Add a panel
|
|
150
|
+
|
|
151
|
+
A panel is a popup above the tile, for detail that doesn't fit. Declare it and open it from the
|
|
152
|
+
tile:
|
|
153
|
+
|
|
154
|
+
```json
|
|
155
|
+
"panel": "panel.html",
|
|
156
|
+
"panelSize": { "width": 300, "height": 240 }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
document.getElementById("open").addEventListener("click", () => bb.panel.open());
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The panel page gets the same `bb`, with `bb.surface === "panel"`, the same config and the same
|
|
164
|
+
storage as its tile. `bb.panel.close()` closes it.
|
|
165
|
+
|
|
166
|
+
## 9. Style it
|
|
167
|
+
|
|
168
|
+
Your page inherits the dock's colours and fonts through CSS variables, and the base stylesheet
|
|
169
|
+
sets a transparent background, the dock font and helper classes like `bb-tile` and `bb-value`.
|
|
170
|
+
Style against `data-tone` to look right on light and dark surfaces. See [styling](styling.md).
|
|
171
|
+
|
|
172
|
+
## 10. Check it
|
|
173
|
+
|
|
174
|
+
```sh
|
|
175
|
+
npx @glazeen/mod-sdk validate my-mod
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
This checks the manifest, that the pages exist, and that they don't load anything remote. Add
|
|
179
|
+
`--strict` in CI to fail on warnings too.
|
|
180
|
+
|
|
181
|
+
## Debugging
|
|
182
|
+
|
|
183
|
+
- **The tile shows an error:** the manifest couldn't be loaded. Run `validate` for details.
|
|
184
|
+
- **"needs the … permission":** add the permission to `permissions` and save.
|
|
185
|
+
- **Nothing happens on right-click:** that's by design; the dock owns right-click and opens the
|
|
186
|
+
widget menu.
|
|
187
|
+
- **Console output and DevTools:** only development builds of bearbar have DevTools (run it
|
|
188
|
+
from source with `pnpm dev`, then right-click the dock > Open DevTools and choose the mod's
|
|
189
|
+
frame in the Console's JavaScript context dropdown). In a release build, show errors in the tile while
|
|
190
|
+
developing.
|
|
191
|
+
|
|
192
|
+
## Sharing a mod
|
|
193
|
+
|
|
194
|
+
Share the folder (for example as a zip or a git repository). Users copy it into their mods
|
|
195
|
+
folder. There is no mod store yet.
|
|
196
|
+
|
|
197
|
+
## Example
|
|
198
|
+
|
|
199
|
+
[`crypto-price`](https://github.com/glazeen/bearbar/tree/main/mods/crypto-price) ships with
|
|
200
|
+
bearbar: a tile and a panel, settings, storage, network and `open-url`.
|