@glazeen/mod-sdk 0.0.0-stage → 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/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 +474 -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 +284 -0
- package/docs/api.md +238 -0
- package/docs/guide.md +200 -0
- package/docs/manifest.md +198 -0
- package/docs/runtime.md +150 -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,284 @@
|
|
|
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
|
+
/**
|
|
63
|
+
* Hosts bearbar refuses whatever the manifest says (it checks the same at runtime): IP addresses,
|
|
64
|
+
* localhost and other names that only mean something on this PC or the LAN, and wildcards over a
|
|
65
|
+
* whole top-level domain.
|
|
66
|
+
*/
|
|
67
|
+
function netHostProblem(pattern) {
|
|
68
|
+
const wild = pattern.startsWith("*.");
|
|
69
|
+
const host = (wild ? pattern.slice(2) : pattern).toLowerCase();
|
|
70
|
+
if (/^[\d.]+$/.test(host)) return "IP addresses are not allowed, use a host name";
|
|
71
|
+
if (/(^|\.)(localhost|local|internal|home\.arpa)$/.test(host)) return "local network names are not allowed";
|
|
72
|
+
if (!host.includes(".")) return wild ? "a wildcard must cover a domain, not a top-level domain" : "use a full host name";
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const SEMVER = /^\d+\.\d+\.\d+(-[0-9a-z.-]+)?(\+[0-9a-z.-]+)?$/i;
|
|
76
|
+
const MANIFEST_KEYS = [
|
|
77
|
+
"$schema",
|
|
78
|
+
"id",
|
|
79
|
+
"name",
|
|
80
|
+
"version",
|
|
81
|
+
"apiVersion",
|
|
82
|
+
"description",
|
|
83
|
+
"author",
|
|
84
|
+
"category",
|
|
85
|
+
"sizes",
|
|
86
|
+
"tile",
|
|
87
|
+
"panel",
|
|
88
|
+
"panelSize",
|
|
89
|
+
"permissions",
|
|
90
|
+
"settings"
|
|
91
|
+
];
|
|
92
|
+
const BASE_FIELD_KEYS = [
|
|
93
|
+
"type",
|
|
94
|
+
"label",
|
|
95
|
+
"description",
|
|
96
|
+
"visibleWhen",
|
|
97
|
+
"default"
|
|
98
|
+
];
|
|
99
|
+
const FIELD_KEYS = {
|
|
100
|
+
text: [...BASE_FIELD_KEYS, "placeholder"],
|
|
101
|
+
number: [
|
|
102
|
+
...BASE_FIELD_KEYS,
|
|
103
|
+
"min",
|
|
104
|
+
"max",
|
|
105
|
+
"step"
|
|
106
|
+
],
|
|
107
|
+
toggle: BASE_FIELD_KEYS,
|
|
108
|
+
select: [...BASE_FIELD_KEYS, "options"]
|
|
109
|
+
};
|
|
110
|
+
const FIELD_TYPES = Object.keys(FIELD_KEYS);
|
|
111
|
+
const DEFAULT_TYPE = {
|
|
112
|
+
text: "string",
|
|
113
|
+
select: "string",
|
|
114
|
+
number: "number",
|
|
115
|
+
toggle: "boolean"
|
|
116
|
+
};
|
|
117
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
118
|
+
const isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
119
|
+
const isPositive = (v) => isNum(v) && v > 0;
|
|
120
|
+
const json = (v) => JSON.stringify(v);
|
|
121
|
+
/** True for an .html file inside the mod folder: relative, no "..", no drive or scheme. */
|
|
122
|
+
function isPagePath(p) {
|
|
123
|
+
return typeof p === "string" && !/^([a-z][a-z0-9+.-]*:|[\\/])/i.test(p) && !p.split(/[\\/]/).includes("..") && /.\.html$/i.test(p);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Checks a parsed bearbar.mod.json and reports every problem, with a path to each.
|
|
127
|
+
*
|
|
128
|
+
* Stricter than the dock, which loads what it can and fills in defaults: use it in tooling
|
|
129
|
+
* and CI to catch mistakes early. It checks the manifest only; the `bearbar-mod validate`
|
|
130
|
+
* command also checks that the pages exist.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* const result = validateManifest(JSON.parse(text));
|
|
134
|
+
* if (!result.ok) for (const e of result.errors) console.error(formatIssue(e));
|
|
135
|
+
*/
|
|
136
|
+
function validateManifest(input) {
|
|
137
|
+
const errors = [];
|
|
138
|
+
const warnings = [];
|
|
139
|
+
const error = (path, message) => errors.push({
|
|
140
|
+
path,
|
|
141
|
+
message
|
|
142
|
+
});
|
|
143
|
+
const warn = (path, message) => warnings.push({
|
|
144
|
+
path,
|
|
145
|
+
message
|
|
146
|
+
});
|
|
147
|
+
if (!isObj(input)) return {
|
|
148
|
+
ok: false,
|
|
149
|
+
errors: [{
|
|
150
|
+
path: "",
|
|
151
|
+
message: "must be a JSON object"
|
|
152
|
+
}],
|
|
153
|
+
warnings
|
|
154
|
+
};
|
|
155
|
+
const m = input;
|
|
156
|
+
for (const key of Object.keys(m)) if (!MANIFEST_KEYS.includes(key)) warn(key, `unknown property${suggest(key, MANIFEST_KEYS)}`);
|
|
157
|
+
if (m.id === void 0) error("id", "is required");
|
|
158
|
+
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");
|
|
159
|
+
if (m.name === void 0) error("name", "is required");
|
|
160
|
+
else if (typeof m.name !== "string" || m.name.trim() === "") error("name", "must be a non-empty string");
|
|
161
|
+
if (m.version === void 0) error("version", "is required");
|
|
162
|
+
else if (typeof m.version !== "string" || m.version.trim() === "") error("version", "must be a non-empty string");
|
|
163
|
+
else if (!SEMVER.test(m.version)) warn("version", `${json(m.version)} is not a semantic version like "1.0.0"`);
|
|
164
|
+
if (m.apiVersion !== void 0) {
|
|
165
|
+
if (typeof m.apiVersion !== "number" || !Number.isInteger(m.apiVersion) || m.apiVersion < 1) error("apiVersion", "must be a positive integer");
|
|
166
|
+
else if (m.apiVersion > 1) warn("apiVersion", `${m.apiVersion} is newer than this SDK supports (1)`);
|
|
167
|
+
}
|
|
168
|
+
for (const key of ["description", "author"]) if (m[key] !== void 0 && typeof m[key] !== "string") error(key, "must be a string");
|
|
169
|
+
if (m.category !== void 0) warn("category", "is ignored: mods are always listed under Mods");
|
|
170
|
+
if (m.tile === void 0) error("tile", "is required");
|
|
171
|
+
else if (!isPagePath(m.tile)) error("tile", "must be an .html file inside the mod folder");
|
|
172
|
+
if (m.panel !== void 0 && !isPagePath(m.panel)) error("panel", "must be an .html file inside the mod folder");
|
|
173
|
+
if (m.sizes !== void 0) {
|
|
174
|
+
if (!isObj(m.sizes) || Object.keys(m.sizes).length === 0) error("sizes", "must be an object with at least one of s, m, l");
|
|
175
|
+
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)");
|
|
176
|
+
else if (!isPositive(units)) error(`sizes.${size}`, "must be a positive number");
|
|
177
|
+
}
|
|
178
|
+
if (m.panelSize !== void 0) {
|
|
179
|
+
if (!isObj(m.panelSize) || !isPositive(m.panelSize.width) || !isPositive(m.panelSize.height)) error("panelSize", "must be { width, height } with positive numbers");
|
|
180
|
+
else for (const key of Object.keys(m.panelSize)) if (key !== "width" && key !== "height") error(`panelSize.${key}`, "unknown property");
|
|
181
|
+
if (m.panel === void 0) warn("panelSize", "is set but there is no panel");
|
|
182
|
+
}
|
|
183
|
+
if (m.permissions !== void 0) {
|
|
184
|
+
if (!Array.isArray(m.permissions)) error("permissions", "must be an array");
|
|
185
|
+
else {
|
|
186
|
+
const seen = /* @__PURE__ */ new Set();
|
|
187
|
+
m.permissions.forEach((p, i) => {
|
|
188
|
+
if (typeof p !== "string" || !PERMISSION_PATTERN.test(p)) error(`permissions[${i}]`, `unknown permission ${json(p)} (use "net:<host>", "system" or "open-url")`);
|
|
189
|
+
else if (seen.has(p.toLowerCase())) error(`permissions[${i}]`, `duplicate ${json(p)}`);
|
|
190
|
+
else {
|
|
191
|
+
seen.add(p.toLowerCase());
|
|
192
|
+
const problem = p.toLowerCase().startsWith("net:") ? netHostProblem(p.slice(4)) : null;
|
|
193
|
+
if (problem) error(`permissions[${i}]`, `${json(p)}: ${problem}`);
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (m.settings !== void 0) {
|
|
199
|
+
if (!isObj(m.settings)) error("settings", "must be an object");
|
|
200
|
+
else for (const [key, field] of Object.entries(m.settings)) validateField(`settings.${key}`, field, m.settings, error, warn);
|
|
201
|
+
}
|
|
202
|
+
return errors.length ? {
|
|
203
|
+
ok: false,
|
|
204
|
+
errors,
|
|
205
|
+
warnings
|
|
206
|
+
} : {
|
|
207
|
+
ok: true,
|
|
208
|
+
manifest: m,
|
|
209
|
+
errors: [],
|
|
210
|
+
warnings
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function validateField(path, f, all, error, warn) {
|
|
214
|
+
if (!isObj(f)) {
|
|
215
|
+
error(path, "must be an object");
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const type = f.type;
|
|
219
|
+
if (!FIELD_TYPES.includes(type)) {
|
|
220
|
+
error(`${path}.type`, `must be one of ${FIELD_TYPES.join(", ")}`);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const allowed = FIELD_KEYS[type];
|
|
224
|
+
for (const key of Object.keys(f)) if (!allowed.includes(key)) error(`${path}.${key}`, `not allowed on a ${type} field${suggest(key, allowed)}`);
|
|
225
|
+
if (typeof f.label !== "string") error(`${path}.label`, "must be a string");
|
|
226
|
+
if (f.description !== void 0 && typeof f.description !== "string") error(`${path}.description`, "must be a string");
|
|
227
|
+
const vw = f.visibleWhen;
|
|
228
|
+
if (vw !== void 0) {
|
|
229
|
+
if (!isObj(vw) || typeof vw.field !== "string" || ![
|
|
230
|
+
"string",
|
|
231
|
+
"number",
|
|
232
|
+
"boolean"
|
|
233
|
+
].includes(typeof vw.equals) || Object.keys(vw).some((k) => k !== "field" && k !== "equals")) error(`${path}.visibleWhen`, "must be { field, equals }");
|
|
234
|
+
else if (!(vw.field in all) || `settings.${vw.field}` === path) error(`${path}.visibleWhen.field`, `${json(vw.field)} is not another setting`);
|
|
235
|
+
}
|
|
236
|
+
const def = f.default;
|
|
237
|
+
if (def !== void 0 && typeof def !== DEFAULT_TYPE[type]) error(`${path}.default`, `must be a ${DEFAULT_TYPE[type]}`);
|
|
238
|
+
if (type === "text" && f.placeholder !== void 0 && typeof f.placeholder !== "string") error(`${path}.placeholder`, "must be a string");
|
|
239
|
+
if (type === "number") {
|
|
240
|
+
for (const key of [
|
|
241
|
+
"min",
|
|
242
|
+
"max",
|
|
243
|
+
"step"
|
|
244
|
+
]) if (f[key] !== void 0 && !isNum(f[key])) error(`${path}.${key}`, "must be a number");
|
|
245
|
+
const { min, max, step } = f;
|
|
246
|
+
if (isNum(step) && step <= 0) error(`${path}.step`, "must be greater than 0");
|
|
247
|
+
if (isNum(min) && isNum(max) && min > max) error(`${path}.min`, "is greater than max");
|
|
248
|
+
if (isNum(def) && (isNum(min) && def < min || isNum(max) && def > max)) warn(`${path}.default`, "is outside min..max");
|
|
249
|
+
}
|
|
250
|
+
if (type === "select") {
|
|
251
|
+
const options = f.options;
|
|
252
|
+
if (!Array.isArray(options) || options.length === 0) error(`${path}.options`, "must be a non-empty array");
|
|
253
|
+
else {
|
|
254
|
+
const values = /* @__PURE__ */ new Set();
|
|
255
|
+
options.forEach((o, i) => {
|
|
256
|
+
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");
|
|
257
|
+
else if (values.has(o.value)) error(`${path}.options[${i}].value`, `duplicate ${json(o.value)}`);
|
|
258
|
+
else values.add(o.value);
|
|
259
|
+
});
|
|
260
|
+
if (typeof def === "string" && values.size && !values.has(def)) error(`${path}.default`, `${json(def)} is not one of the option values`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** ' (did you mean "x"?)' when a known key is a likely typo of `key`. */
|
|
265
|
+
function suggest(key, known) {
|
|
266
|
+
let best = "";
|
|
267
|
+
let bestDist = 3;
|
|
268
|
+
for (const k of known) {
|
|
269
|
+
const d = distance(key.toLowerCase(), k.toLowerCase());
|
|
270
|
+
if (d < bestDist) [best, bestDist] = [k, d];
|
|
271
|
+
}
|
|
272
|
+
return best ? ` (did you mean ${json(best)}?)` : "";
|
|
273
|
+
}
|
|
274
|
+
/** Levenshtein distance. */
|
|
275
|
+
function distance(a, b) {
|
|
276
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
277
|
+
for (let i = 1; i <= a.length; i++) {
|
|
278
|
+
const cur = [i];
|
|
279
|
+
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));
|
|
280
|
+
prev = cur;
|
|
281
|
+
}
|
|
282
|
+
return prev[b.length];
|
|
283
|
+
}
|
|
284
|
+
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,238 @@
|
|
|
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 host is an IP address, `localhost` or another local name (`host <name> is not allowed`),
|
|
155
|
+
- a redirect leads somewhere the first URL couldn't go: plain http, a host the mod didn't
|
|
156
|
+
declare, a local name (`redirect refused: ...`), or there are more than 5 redirects
|
|
157
|
+
(`too many redirects`),
|
|
158
|
+
- the request fails or takes longer than 15 seconds (`timed out`),
|
|
159
|
+
- the response is larger than 2 MB (`response too large`),
|
|
160
|
+
- the page is a preview (`no network in preview`).
|
|
161
|
+
|
|
162
|
+
An HTTP error status (404, 500) resolves with that `status`, `ok: false` and the body.
|
|
163
|
+
|
|
164
|
+
**Redirects** are followed only when the target passes the same checks as the first URL, so a
|
|
165
|
+
mod with `net:api.example.com` can't be redirected to another host, to the local network or to
|
|
166
|
+
http.
|
|
167
|
+
|
|
168
|
+
**Limits.** Requests carry no cookies or credentials. Response headers aren't exposed. Bodies
|
|
169
|
+
are text only: binary responses (images, archives) aren't supported, so images from the web
|
|
170
|
+
can't be shown.
|
|
171
|
+
|
|
172
|
+
## Storage
|
|
173
|
+
|
|
174
|
+
### `bb.storage`
|
|
175
|
+
|
|
176
|
+
A key-value store for this widget instance. Two tiles of the same mod have separate stores; a
|
|
177
|
+
tile and its panel share one. It is saved with the dock's settings and survives restarts and
|
|
178
|
+
updates of the mod.
|
|
179
|
+
|
|
180
|
+
```js
|
|
181
|
+
await bb.storage.set("last", { price: 64250, at: Date.now() });
|
|
182
|
+
const last = await bb.storage.get("last"); // undefined if never set
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
| Method | Returns | Notes |
|
|
186
|
+
| ----------------- | -------------------------- | ----------------------------------------- |
|
|
187
|
+
| `get(key)` | `Promise<T \| undefined>` | |
|
|
188
|
+
| `set(key, value)` | `Promise<void>` | `value` must be JSON-serialisable. |
|
|
189
|
+
|
|
190
|
+
- Keys are strings (other values are converted with `String()`).
|
|
191
|
+
- The whole store is limited to 256 KB of JSON (`STORAGE_QUOTA`). A `set` that would exceed it
|
|
192
|
+
rejects with `storage is full` and changes nothing.
|
|
193
|
+
- Store plain JSON data: values are saved as JSON, so functions and `undefined` are dropped
|
|
194
|
+
and a `Date` comes back as a string after a restart.
|
|
195
|
+
- There is no `delete`; set the key to `null`.
|
|
196
|
+
- In preview, `set` resolves without storing.
|
|
197
|
+
|
|
198
|
+
## Dock actions
|
|
199
|
+
|
|
200
|
+
### `bb.panel`
|
|
201
|
+
|
|
202
|
+
| Method | Notes |
|
|
203
|
+
| --------- | ------------------------------------------------------------------------ |
|
|
204
|
+
| `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. |
|
|
205
|
+
| `close()` | Closes the panel. Works from the tile or the panel. |
|
|
206
|
+
|
|
207
|
+
Escape and clicking outside the panel also close it.
|
|
208
|
+
|
|
209
|
+
### `bb.openUrl(url)`
|
|
210
|
+
|
|
211
|
+
Opens an `http:` or `https:` link in the user's default browser. Needs the `open-url`
|
|
212
|
+
permission, or it rejects. Other schemes are ignored. Mod pages can't navigate or open windows
|
|
213
|
+
themselves, so links (`<a href>`) must go through this. Call it from a click: the dock opens at
|
|
214
|
+
most one link every 2 seconds and 5 a minute per mod, and quietly drops the rest.
|
|
215
|
+
|
|
216
|
+
```js
|
|
217
|
+
link.addEventListener("click", (e) => {
|
|
218
|
+
e.preventDefault();
|
|
219
|
+
bb.openUrl(link.href);
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### `bb.openSettings()`
|
|
224
|
+
|
|
225
|
+
Opens this widget's settings popup, the one the user reaches from the widget menu. Useful for
|
|
226
|
+
a "Set up" button when a required setting is missing.
|
|
227
|
+
|
|
228
|
+
## Constants
|
|
229
|
+
|
|
230
|
+
Exported from `@glazeen/mod-sdk` for tooling:
|
|
231
|
+
|
|
232
|
+
| Name | Value |
|
|
233
|
+
| ---------------- | -------------------------------------------------------- |
|
|
234
|
+
| `API_VERSION` | `1`, the mod API this package describes. |
|
|
235
|
+
| `STORAGE_QUOTA` | `262144` (256 KB). |
|
|
236
|
+
| `THEME_TOKENS` | The CSS variables the dock sets. See [styling](styling.md). |
|
|
237
|
+
| `WIDGET_SIZES` | `["s", "m", "l"]`. |
|
|
238
|
+
| `MOD_ID_PATTERN` | The `RegExp` an `id` must match. |
|