@black-studio/plugin 0.0.0-stage → 1.0.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.
Files changed (5) hide show
  1. package/README.md +807 -2
  2. package/build.mjs +118 -0
  3. package/cli.mjs +28 -0
  4. package/index.d.ts +911 -0
  5. package/package.json +18 -4
package/README.md CHANGED
@@ -1,3 +1,808 @@
1
- # Temporary Holding Version
1
+ # Writing a plugin for Bläck Studio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A plugin is a folder with a `manifest.json` and a script. Bläck Studio finds
4
+ plugins in its plugins folder:
5
+
6
+ | System | Folder |
7
+ | ------- | ---------------------------------------------- |
8
+ | Linux | `~/.local/share/black-studio/plugins/` (or `$XDG_DATA_HOME/black-studio/plugins`) |
9
+ | macOS | `~/Library/Application Support/black-studio/plugins/` |
10
+ | Windows | `%APPDATA%\black-studio\plugins\` |
11
+
12
+ Settings → Plugins opens this folder and turns plugins on and off.
13
+
14
+ ## Starting one
15
+
16
+ The SDK is the npm package `@black-studio/plugin`. Start a plugin with:
17
+
18
+ ```bash
19
+ npm create @black-studio/plugin my-plugin # in the window, with React
20
+ npm create @black-studio/plugin my-plugin --sandboxed
21
+ npm create @black-studio/plugin my-plugin --computer # sandboxed, with files and a program
22
+ cd my-plugin
23
+ npm install
24
+ npm run dev
25
+ ```
26
+
27
+ There are three starting points:
28
+ - **In the window:** a command with a hotkey, and an inspector tab drawn
29
+ with React.
30
+ - **`--sandboxed`:** a command, marks in the text, and text in the status
31
+ bar, all running in a separate worker.
32
+ - **`--computer`:** a sandboxed plugin with `files:write` and `exec:pandoc`.
33
+ It saves the scene the writer is in as a Word file. Pandoc makes the file
34
+ in the plugin's temporary folder, and the plugin then saves it in a folder
35
+ the writer chooses. It remembers that folder for next time. The template
36
+ shows how to ask for a folder, run a program, and tell the writer plainly
37
+ when the program isn't installed. To run another program, name it in the
38
+ manifest and in the code.
39
+
40
+ `npm run dev` builds the plugin into the plugins folder every time you save,
41
+ and Bläck Studio reloads it as soon as it lands. Turn it on once under
42
+ Settings → Plugins. `npm run build` makes `dist/<id>/` to share, and a zip
43
+ with its SHA-256 for the plugin list.
44
+
45
+ A plugin in plain JavaScript needs no build at all. A `main.js` like this,
46
+ next to the manifest, is a complete plugin. A plain script asks for the SDK by
47
+ its older name, `@black/plugin`, which every version of Bläck Studio knows.
48
+ The build does the same for you.
49
+
50
+ ```js
51
+ var __blackPlugin = class extends __black.require('@black/plugin').Plugin {
52
+ onload() {
53
+ this.addCommand({ id: 'hello', name: 'Say hello', run: () => this.app.ui.notify('Hello') })
54
+ }
55
+ }
56
+ ```
57
+
58
+ ## The manifest
59
+
60
+ ```json
61
+ {
62
+ "id": "word-of-the-day",
63
+ "name": "Word of the day",
64
+ "version": "1.0.0",
65
+ "description": "A word to use today, every morning.",
66
+ "author": "You",
67
+ "apiVersion": 1,
68
+ "main": "main.js",
69
+ "sandboxed": false,
70
+ "permissions": ["project:write", "network:api.example.com", "files:read", "exec:pandoc"],
71
+ "permissionReasons": {
72
+ "network:api.example.com": "fetch today's word from Example (api.example.com)"
73
+ },
74
+ "category": "writing",
75
+ "locales": {
76
+ "sv": { "name": "Dagens ord", "description": "Ett ord att använda i dag, varje morgon." }
77
+ }
78
+ }
79
+ ```
80
+
81
+ - **`id`:** lower-case letters, digits and dashes. It's also the folder name.
82
+ - **`apiVersion`:** the plugin API version the plugin needs. It defaults to 1.
83
+ Set it to the version that added the newest feature you use:
84
+ - 2: the dashboard and the library
85
+ - 3: the microphone
86
+ - 4: `app.speech`
87
+ - 5: dictation drafts, pauses and microphone choice
88
+ - 6: actions on marks
89
+ - 7: book importers
90
+ - 8: `permissionReasons` and `category` in the manifest. A plugin that uses
91
+ only these two doesn't need version 8, because older versions of the app
92
+ ignore them.
93
+ - 9: quiet marks
94
+ - 10: `app.folder` and `project:folder`, `network:ask`,
95
+ `app.net.streamBytes`, `during`, `addVersionHistory`, `project.flush` and
96
+ `project.getProjectData`
97
+ - **`sandboxed`:** runs the plugin in a separate worker, apart from the
98
+ window (see below).
99
+ - **`locales`:** the plugin's name and description in other languages, by
100
+ language code. Settings → Plugins, the plugin list and the permission
101
+ questions show them in the writer's language. You choose the plugin's other
102
+ strings (commands, settings, notices) yourself, using `this.app.language`.
103
+ When the writer changes the language, Bläck Studio reloads the plugin, so
104
+ `onload` runs again in the new language.
105
+ - **`permissions`:** what the plugin needs beyond reading the book.
106
+ - `project:write` lets the plugin change the book.
107
+ - `project:folder` lets the plugin read and change every file in the open
108
+ project's folder, and nothing outside it (see The project's folder). It
109
+ needs `"apiVersion": 10`.
110
+ - `library:read` lets the plugin see the writer's recent books and their
111
+ series (`app.library`), for example to build the welcome screen's
112
+ dashboard. It needs `"apiVersion": 2`.
113
+ - `microphone` lets a plugin in the window record, with
114
+ `navigator.mediaDevices.getUserMedia({ audio: true })`. Bläck Studio gives
115
+ the page access to the microphone only while a plugin with this
116
+ permission is on, and never gives it a camera. It needs
117
+ `"apiVersion": 3`. Release the stream as soon as you're done, so the
118
+ system stops showing that it's listening.
119
+ With `"apiVersion": 4` the plugin also gets `app.speech`, which turns
120
+ what the writer says into text on the device itself. Nothing is sent
121
+ anywhere. On a computer this uses Whisper, and Bläck Studio downloads its
122
+ model once, after asking the writer. On a phone or tablet it uses the
123
+ system's own recogniser, which gives you the words as they come. Call
124
+ `status(language)` first. If it isn't `ready`, `prepare(language)` gets
125
+ what's missing. Then call `listen()` and keep listening until `stop()`.
126
+ `onLevel` reports how loud the sound is, so you can show that the plugin
127
+ is hearing something. The session can also `pause()` and `resume()`.
128
+ Older versions of Bläck Studio have neither of these, so check that
129
+ they exist.
130
+ - `network:<host>` lets the plugin reach a host. `network:*.<host>` also
131
+ covers that host's subdomains, and `network:*` lets the plugin reach
132
+ anywhere on the internet. It doesn't cover this computer or the network
133
+ it's on (a router, a NAS). The plugin can reach those only by name, for
134
+ example `network:127.0.0.1`.
135
+ - `files:read` and `files:write` let the plugin use files and folders that
136
+ the writer chooses for it in the system's own dialog
137
+ (`app.files.pickFolder`, `pickFile`). It never gets the whole disk.
138
+ - `exec:<program>` lets the plugin run that one program. The program is
139
+ found by name on the PATH, gets its arguments as you give them, and runs
140
+ with no shell. `exec:pandoc` runs Pandoc and nothing else.
141
+
142
+ Bläck Studio marks `network:*` and every `exec:` permission as reaching
143
+ beyond the app, with a warning. A shell, Python or Node gets a stronger
144
+ warning.
145
+
146
+ The writer is asked to allow these permissions when they turn the plugin
147
+ on. If a new version asks for more, it stays off until the writer allows
148
+ that too.
149
+
150
+ Running in Bläck Studio's window (without `sandboxed`) is also a permission
151
+ the writer is asked to allow, and it's shown as unrestricted: a plugin there
152
+ can do anything the window can.
153
+ - **`optionalPermissions`:** permissions the plugin may ask for later with
154
+ `app.permissions.request`. Use it when the writer chooses something that
155
+ needs a permission (a service to send to, say), instead of asking when the
156
+ plugin is turned on. It takes the same kinds as `permissions`, and needs
157
+ `"apiVersion": 5`.
158
+ - **`permissionReasons`:** why the plugin asks, by permission. Bläck Studio
159
+ shows each reason to the writer when it asks them to allow the permission,
160
+ with its own description of what the permission allows underneath. Say what
161
+ is sent where and what for, so that your text completes the sentence "it
162
+ needs to …". It can be one text, or one text per language code:
163
+
164
+ ```json
165
+ "permissionReasons": {
166
+ "network:api.example.com": {
167
+ "en": "fetch today's word from Example (api.example.com)",
168
+ "sv": "hämta dagens ord från Example (api.example.com)"
169
+ }
170
+ }
171
+ ```
172
+
173
+ Each reason belongs to a permission in `permissions` or
174
+ `optionalPermissions`, and can be up to 300 characters. Bläck Studio reads
175
+ it from plugin API 8 on. Older versions leave it out, so your plugin doesn't
176
+ need to ask for API 8 to include it.
177
+ - **`category`:** where Manage Plugins lists the plugin: `writing`,
178
+ `planning`, `welcome` (the welcome screen), `import-export` or `other`.
179
+ Bläck Studio reads it from plugin API 8 on, and older versions leave it
180
+ out, just like `permissionReasons`.
181
+
182
+ ## What a plugin can do
183
+
184
+ Everything is in [`index.d.ts`](index.d.ts). The plugins on Bläck Studio's
185
+ list are written this way too, and each shows a part of the API:
186
+
187
+ | Plugin | Shows |
188
+ | --- | --- |
189
+ | `filter-words` | sandboxed: marks in the text, settings, a status bar item, events |
190
+ | `markdown-export` | sandboxed: a format in Compile |
191
+ | `name-generator` | in the window: a view, an inspector tab, a menu entry, a TipTap shortcut, changing the book |
192
+ | `pomodoro` | in the window: React in the status bar, a hotkey |
193
+ | `cast-suggest` | sandboxed: suggestions as you type, kept up to date as the binder changes |
194
+ | `pandoc-export` | sandboxed: running a program in its temporary folder, with formats that follow its settings |
195
+ | `continue-writing`, `today`, `book-progress`, `writing-calendar`, `series-overview`, `recent-activity` | in the window: cards on the welcome screen's dashboard, built from the writer's library; starting a sprint |
196
+ | `dictation` | in the window: the microphone, speech turned into text on the device (`app.speech`), a toolbar button, a hotkey, a secret setting, a request to a service using the writer's own key |
197
+
198
+ In short:
199
+
200
+ | Method | Adds |
201
+ | --- | --- |
202
+ | `addCommand` | a command in the palette (Ctrl+K) and the Plugins menu, with a hotkey if you like |
203
+ | `addView` | a view beside the corkboard and outliner (window only) |
204
+ | `addInspectorTab` | a tab in the inspector, for the items you choose (window only) |
205
+ | `addStatusBarItem` | an item in the status bar, drawn with React or as text you change |
206
+ | `addEditorMenuItem` | an entry in the text's right-click menu |
207
+ | `addBinderMenuItem` | an entry in the binder's right-click menu |
208
+ | `addExporter` | a format in Compile |
209
+ | `addHighlighter` | marks in the text, found one paragraph at a time and never saved |
210
+ | `registerEditorExtension` | TipTap extensions: marks, nodes, input rules, shortcuts (window only) |
211
+ | `addSidebarPanel` | a tab beside the binder (window only) |
212
+ | `addToolbarButton` | a button in the editor's toolbar |
213
+ | `addSuggester` | suggestions under the caret after a trigger: `@` for characters, `#` for tags… |
214
+ | `addImporter` | a kind of file for File → Import Documents |
215
+ | `addBookImporter` | a whole book from another app's file or folder, in File → Import and on the welcome screen (API 7) |
216
+ | `addSettings` | settings that Bläck Studio draws for you in Settings → Plugins |
217
+ | `addSettingsPanel` | settings that you draw yourself (window only) |
218
+ | `on` | `project-open`, `project-close`, `selection-change`, `doc-change`, `nodes-change` |
219
+ | `loadData`, `saveData` | your plugin's data, stored on this computer |
220
+
221
+ You read settings declared with `addSettings` from `this.settings`. Bläck
222
+ Studio keeps only the values the writer changed. So if a new version of your
223
+ plugin has a better default, everyone who hadn't changed that setting gets it.
224
+ `updateSettings({ key: undefined })` puts a setting back to its default.
225
+
226
+ `this.app` gives you the rest, each part described below:
227
+ - **[`app.project`](#the-book):** the book.
228
+ - **[`app.editor`](#the-editor):** the selection, comments on it, typing at
229
+ the caret, and, in the window, the editor itself.
230
+ - **[`app.ui`](#dialogs):** notices and dialogs.
231
+ - **[`app.net`](#the-network):** the internet, limited to the hosts you asked
232
+ for.
233
+ - **[`app.files`](#files-and-folders):** files and folders the writer chose.
234
+ - **[`app.exec`](#programs):** the programs you named.
235
+
236
+ If your plugin has a `styles.css` next to its manifest, Bläck Studio loads it
237
+ with the plugin.
238
+
239
+ In the window, `react`, `react/jsx-runtime`, `@tiptap/core` and
240
+ `@tiptap/pm/*` are Bläck Studio's copies. The build leaves them out of your
241
+ script. Your interface follows the theme if you use Bläck Studio's classes:
242
+ `btn`, `input`, `insp-section`, `sb-btn` and so on.
243
+
244
+ ## The book
245
+
246
+ `this.app.project` reads the open book and, with `project:write`, changes it.
247
+ Every method returns a promise. You refer to items by id. You get ids from
248
+ `nodes()`, `manuscript()` and `selected()`.
249
+
250
+ ```ts
251
+ const p = this.app.project
252
+ for (const id of await p.manuscript()) { // the scenes, in reading order
253
+ const text = await p.readText(id) // or read(id) for its HTML
254
+ const meta = await p.meta(id) // synopsis, notes, keywords, fields, when, words
255
+ if (meta && text.length > 20_000) await p.setMeta(id, { keywords: [...meta.keywords, 'long'] })
256
+ }
257
+ ```
258
+
259
+ These methods read the book: `info()`, `nodes()`, `node(id)`, `manuscript()`,
260
+ `selected()`, `read`, `readText`, `meta`, `labels()`, `statuses()`,
261
+ `comments(id)`, `snapshots(id)`, `search(query, { wholeWord, caseSensitive,
262
+ regex })` (which works like Find in project) and `series()`.
263
+
264
+ With `project:write`, these methods change the book:
265
+ - **Text:** `write(id, html)`.
266
+ - **The binder:** `create(type, title, parentId?)`, `rename`,
267
+ `move(id, folderId, index?)`, and `trash`, which moves an item to the
268
+ trash and never deletes it for good.
269
+ - **Cards and comments:** `setMeta(id, patch)` (synopsis, notes, keywords,
270
+ fields, when), `setLabel`, `setStatus` (by id; `''` for none), and
271
+ `resolveComment`.
272
+
273
+ Some things are always safe:
274
+ - **Snapshots:** before a plugin first rewrites a document, Bläck Studio
275
+ keeps a snapshot of it under the plugin's name. `snapshot(id, label)` keeps
276
+ one yourself, and needs no permission.
277
+ - **Undo:** every change is saved, can be undone, and is committed like the
278
+ writer's own changes.
279
+ - **Settings → Plugins** lists what each plugin changed recently.
280
+ - **Ids:** a method that takes an item's id throws if the book has no such
281
+ item. An id therefore always refers to an item in the book.
282
+
283
+ `getData()` and `setData(value)` keep your plugin's data in the book, saved
284
+ with it. Data that belongs to the plugin rather than to one book goes in
285
+ `loadData` and `saveData`.
286
+
287
+ To find out when the binder changes (an item is created, renamed, moved or
288
+ trashed), listen for `nodes-change`: `this.on('nodes-change', () => …)`.
289
+
290
+ ## The editor
291
+
292
+ `this.app.editor` works with the editor the writer is in:
293
+ - `selection()` gives the selected text and where it is.
294
+ - `insertText(text)` types at the caret, replacing the selection.
295
+ - `comment(text)` puts a margin comment on the selection.
296
+
297
+ The last two need `project:write`. In the window, `active()` gives you the
298
+ TipTap editor itself, for anything else you need. In a sandboxed plugin it
299
+ returns `null`.
300
+
301
+ To change how the editor works (new marks or nodes, input rules, keyboard
302
+ shortcuts), register a TipTap extension with `registerEditorExtension`
303
+ (window only). If a mark only shows something, like a word to look at again,
304
+ a highlighter (`addHighlighter`) is a better fit. Bläck Studio draws
305
+ highlights and never saves them, and they work in sandboxed plugins too.
306
+
307
+ ## Dialogs
308
+
309
+ `this.app.ui` asks the writer questions in dialogs that Bläck Studio draws:
310
+
311
+ ```ts
312
+ const name = await this.app.ui.prompt({ title: 'Name the scene', label: 'Title', value: 'Untitled' })
313
+ if (name === null) return // cancelled
314
+
315
+ const kind = await this.app.ui.choose({
316
+ title: 'Export as',
317
+ options: [
318
+ { value: 'odt', label: 'OpenDocument', detail: '.odt' },
319
+ { value: 'tex', label: 'LaTeX', detail: '.tex' },
320
+ ],
321
+ })
322
+
323
+ if (await this.app.ui.confirm('Replace every em dash?', 'In every scene.', 'Replace')) { … }
324
+ ```
325
+
326
+ - **`prompt` and `choose`** resolve with the writer's answer, or with `null`
327
+ if the writer cancels.
328
+ - **`confirm`** asks a yes or no question and resolves with `true` or
329
+ `false`. The dialog says that your plugin is asking.
330
+ - **`notify(message, action?)`** shows a notice, with a button if you pass
331
+ an action.
332
+
333
+ All of these work in sandboxed plugins too, except that a sandboxed plugin's
334
+ notice can't have a button.
335
+
336
+ `openModal({ title, render, wide?, onClose? })` shows a dialog that you draw
337
+ yourself (window only). Bläck Studio passes `render` a `close` function, and
338
+ `openModal` returns one too. `onClose` tells you why the dialog went away:
339
+ `'closed'` if the writer closed it (Escape, ✕) or you called `close`, or
340
+ `'replaced'` if another dialog opened over it.
341
+
342
+ ```tsx
343
+ const close = this.app.ui.openModal({
344
+ title: 'Word of the day',
345
+ render: (close) => (
346
+ <div>
347
+ <p className="insp-hint">{word}</p>
348
+ <button className="btn primary" onClick={close}>Thanks</button>
349
+ </div>
350
+ ),
351
+ })
352
+ ```
353
+
354
+ ## Suggestions as you type
355
+
356
+ `addSuggester` shows a list of suggestions under the caret. The list appears
357
+ when the writer types a trigger character at the start of a word: `@` for
358
+ people, `#` for tags, `:` for emoji…
359
+
360
+ ```ts
361
+ this.addSuggester({
362
+ id: 'tags',
363
+ trigger: '#',
364
+ find: (query) =>
365
+ this.tags
366
+ .filter((tag) => tag.startsWith(query.toLowerCase()))
367
+ .map((tag) => ({ label: tag, insert: `#${tag}`, detail: 'tag' })),
368
+ })
369
+ ```
370
+
371
+ This is how it behaves:
372
+ - **What `find` gets:** the text typed after the trigger so far. Bläck Studio
373
+ calls `find` again as the writer types, after a 60 ms pause. Keep it quick,
374
+ and prepare whatever it searches beforehand. `find` may be async. If its
375
+ answer arrives after the writer has typed more, Bläck Studio drops it.
376
+ - **What it returns:** suggestions, each with a `label`, an optional `detail`
377
+ shown beside it, and an optional `insert`. When the writer picks a
378
+ suggestion, its `insert` (or its `label`, if there is no `insert`) replaces
379
+ the trigger and everything typed after it.
380
+ - **The keys:** up and down choose a suggestion, Enter or Tab takes it, and
381
+ Escape hides the list until the writer moves on.
382
+ - **Limits:** Bläck Studio shows at most 12 suggestions, counting every
383
+ suggester with the same trigger. A trigger in the middle of a word
384
+ (`e@mail`) offers nothing.
385
+
386
+ Suggesters work in sandboxed plugins too.
387
+
388
+ ## More of the interface
389
+
390
+ - **`addSidebarPanel({ id, name, render })`:** a tab beside the binder,
391
+ drawn with React (window only).
392
+ - **`addToolbarButton({ id, title, icon, active?, run })`:** a button in the
393
+ editor's toolbar. In the window the icon is a component. In either mode it
394
+ can also be a few characters (`'★'`). `active` shows the button as pressed.
395
+ - **`addImporter({ id, name, extensions, import })`:** a kind of file for
396
+ File → Import Documents. Bläck Studio offers it in the file dialog and
397
+ passes `import` the file (`name`, `ext`, `data` as bytes, `text`). You
398
+ return the documents to create: `[{ title, html }]`.
399
+ - **`addBookImporter({ id, name, from?, extensions, folder?, import })`:**
400
+ imports a whole book from another app's file or folder. Use `folder: true`
401
+ for a folder, as with a Scrivener project's .scriv. On a phone, the writer
402
+ chooses a zip of it. The importer appears in File → Import as `name`, and on
403
+ the welcome screen as "Import from `from`". Bläck Studio asks the writer for
404
+ the file and passes it to `import`. For a file, that's `name`, `ext`,
405
+ `data` and `text`. For a folder, it's `files` (every file in the folder,
406
+ by its path there), plus `read(path)` and `readText(path)` to read one of
407
+ them. You return the book:
408
+ - its `title`, labels, statuses and storylines;
409
+ - the items in each part of the binder (`manuscript`, `characters`,
410
+ `places`, `notes`, `research`, `trash`), each with its text as HTML,
411
+ synopsis, notes, keywords, label and status;
412
+ - beats on the storylines.
413
+
414
+ Items refer to each other (a scene's cast and place, a beat's scene) by ids
415
+ that you make up for the import. Bläck Studio shows the writer what it
416
+ created, and either makes it a new book or adds it to the open one. To say
417
+ why a file can't be read, throw an Error. Book importers need no
418
+ permission and work in sandboxed plugins. They need `"apiVersion": 7`. The
419
+ Scrivener and Plottr imports on the list are built this way.
420
+ - **`styles.css`:** if it's next to the manifest, Bläck Studio loads it with
421
+ the plugin and removes it when the plugin is removed. Put your plugin's id
422
+ in your class names, so they don't clash with Bläck Studio's or another
423
+ plugin's.
424
+
425
+ ## The dashboard
426
+
427
+ When no book is open, the welcome screen is the writer's dashboard. It shows
428
+ cards from plugins instead of its quote. If a plugin is turned off, its card
429
+ goes away, and when no plugin has a card, the quote comes back. This needs
430
+ `"apiVersion": 2`. A Bläck Studio that supports only API 1 tells the writer
431
+ that the plugin needs a newer version.
432
+
433
+ ```tsx
434
+ export default class WordsToday extends Plugin {
435
+ onload() {
436
+ this.addDashboardWidget({ id: 'today', name: 'Today', size: 'half', order: 20, render: () => <Today app={this.app} /> })
437
+ }
438
+ }
439
+ ```
440
+
441
+ - **`addDashboardWidget({ id, name, size?, order?, render })`:** adds a card.
442
+ `size` is `'half'` (half the dashboard's width, the default) or `'full'`.
443
+ Cards are sorted by `order`, lowest first (100 if you don't give one), and
444
+ then by name. Window only. These values only set where a card starts. The
445
+ writer can drag it elsewhere and make it wider or narrower, and Bläck Studio
446
+ remembers that. A card the writer hasn't placed yet (one just turned on)
447
+ goes after the others.
448
+ - **`app.library`**, with the `library:read` permission:
449
+ - `books()`: the books on the recent list and every book in their series.
450
+ Each book is summarised from its files: title, words, goal and deadline,
451
+ the daily goal, the words written each day (`history`), scenes by status,
452
+ its series and its place in it, and the scene written in most recently,
453
+ with the end of its text. Every card asks for this as the screen needs it, but
454
+ Bläck Studio reads the files only once for all of them.
455
+ - `activity()`: the latest saved versions (git), zip backups, and each
456
+ book's last push of its history, whether it failed or not.
457
+ - `open(path, { select? })`: opens one of these books, at one of its
458
+ documents.
459
+ - **`app.ui.startSprint(minutes)`**: starts a writing sprint in the open book.
460
+
461
+ Draw cards with Bläck Studio's classes, so they look like the rest of the
462
+ dashboard:
463
+ - `dash-big`: a large number.
464
+ - `dash-muted`: a quiet line.
465
+ - `dash-rows` and `dash-row`: a list of rows, with a name at the start and a
466
+ number at the end.
467
+ - `dash-bar`: progress, with a `<span style="width: 40%">` inside it. Add
468
+ `done` to make it green.
469
+ - `dash-quote`: a passage of the book.
470
+ - `dash-warn`: a warning.
471
+ - `btn`, `btn primary` and `btn ghost sm` for buttons.
472
+
473
+ ## Settings that are secrets
474
+
475
+ A setting with `type: 'secret'` is text shown as dots, for an API key, say.
476
+ Bläck Studio keeps it apart from the plugin's other settings, sealed with the
477
+ system's keychain on a computer and in its keystore on a phone. On a computer
478
+ with no keychain (Linux without one), it stays in a file only the writer can read (API 3).
479
+
480
+ ## The project's folder
481
+
482
+ A plugin that asks for `"project:folder"` can read and change every file in the open
483
+ project's folder, including hidden ones such as a version history, and nothing
484
+ outside it. The writer is told exactly that when asked to allow it. It works the
485
+ same on a computer and a phone, sandboxed or in the window, and needs `"apiVersion": 10`.
486
+
487
+ ```ts
488
+ const here = await this.app.folder.current() // { key, name, book: 'books/<id>' }, or null
489
+ const bytes = await this.app.folder.read(here.key, 'project.json') // null if it isn't there
490
+ await this.app.folder.write(here.key, 'notes/today.txt', 'Hello')
491
+ ```
492
+
493
+ - Paths are relative to the project's folder and use `/` as the separator. A path is refused if
494
+ it's absolute, contains `..`, goes through a symbolic link, or names `.sync` (at any level) or
495
+ `.git` (below the top level).
496
+ - Each call names the project by its key, not by a path, so work started on one project can't end
497
+ up in the next one opened. A key stops working two minutes after its project closes.
498
+ - `folder.arrived(key, paths)` tells the app that files were changed from outside it: they're
499
+ marked as downloaded, and the open book reloads them. `folder.create(title, name)` asks the
500
+ writer where to create a new project, for a plugin that brings one in from elsewhere, and
501
+ `project.open(key)` opens it.
502
+
503
+ ## Versions, and the moments the app waits for
504
+
505
+ A plugin can keep versions of the project. The app draws the list, so this works in a sandboxed
506
+ plugin too:
507
+
508
+ ```ts
509
+ this.addVersionHistory({
510
+ id: 'versions',
511
+ list: async (file) => [{ id: 'v2', label: 'Chapter one done', at: '2026-11-07T10:00:00Z' }],
512
+ read: async (version, file) => '<p>The text then.</p>',
513
+ save: async (message) => true, // false if nothing has changed since the last one
514
+ status: async () => ({ text: 'The last backup failed.', problem: true }), // or null
515
+ })
516
+ this.versionsChanged() // the app reloads the list
517
+ ```
518
+
519
+ The list shows in Book → Versions & Backups and in a document's history. `file` is a path in the project's folder. There's no
520
+ call for restoring. The writer restores a document from the list, and the app reads its text with
521
+ `read`, keeps a snapshot of the document first, and then replaces it.
522
+
523
+ `this.during(event, handler)` registers a handler for a moment when the app waits for plugins, up
524
+ to a time limit:
525
+ - `'copy-due'`: the writing timer is due and something has changed, or a new book was created
526
+ (`info.reason` says which). 30 seconds.
527
+ - `'project-closing'`: a book is closing, or the app is quitting (then `info.quitting` is set).
528
+ 30 seconds.
529
+ - `'session-end'`: a writing session ended, after 30 minutes without writing or because the book is
530
+ closing. 10 seconds.
531
+
532
+ The handler receives `{ words, changed }`. After the limit the app carries on, so a plugin can't
533
+ stop anything from closing. A plugin has one handler per event: calling `during` again for the
534
+ same event replaces it. `app.project.flush()` resolves once the project's files are all saved, and
535
+ `app.project.getProjectData()` and `setProjectData(value)` store data with the project, on this device.
536
+
537
+ ## On a phone or tablet
538
+
539
+ Bläck Studio for Android runs plugins too, from the same lists and under the
540
+ same rules. There are two differences:
541
+ - A plugin can't ask the writer to choose files, and can't run programs.
542
+ `files:*` and `exec:*` aren't granted there. A plugin that asks for them
543
+ stays off, and the writer is told it works on a desktop.
544
+ - `app.net.stream` and `app.net.streamBytes` give the whole answer as one piece.
545
+
546
+ Everything else works as it does on a desktop, sandboxed or in the window.
547
+
548
+ ## The network
549
+
550
+ A plugin reaches the internet only through `this.app.net`, and only the hosts
551
+ that its manifest names (`network:api.example.com`) and the writer allowed.
552
+ Requests go over https. Plain http is allowed only to this computer
553
+ (`localhost`, `127.0.0.1`), so you can try a plugin against a server you run
554
+ yourself. Redirects aren't followed.
555
+
556
+ **`app.net.fetch(url, init?)`** gets the whole answer, up to 20 MB, within 30
557
+ seconds:
558
+
559
+ ```ts
560
+ const res = await this.app.net.fetch('https://api.example.com/words', {
561
+ method: 'POST',
562
+ headers: { 'Content-Type': 'application/json' },
563
+ body: JSON.stringify({ text }),
564
+ })
565
+ if (res.ok) console.log(res.json()) // also res.text(), res.bytes(), res.status, res.headers
566
+ ```
567
+
568
+ **`app.net.stream(url, init, onChunk)`** passes the answer on as it arrives,
569
+ giving each piece to `onChunk` as text. This suits an AI's reply, word by
570
+ word. When the answer is complete, `stream` resolves with its status and
571
+ headers. It can run for up to ten minutes and receive up to 200 MB.
572
+
573
+ **`app.net.streamBytes(url, init, onChunk)`** does the same with each piece as bytes, for
574
+ what isn't text (API 10).
575
+
576
+ **An address the writer enters**, such as a repository's, can't be named in the manifest. List
577
+ `"network:ask"` in `optionalPermissions`, and ask for the exact address when it's needed:
578
+ `await this.app.permissions.request('address:https://git.example.com/me/books')`. The writer
579
+ is asked about that address, in Bläck Studio's own window. The plugin can then reach that address
580
+ and what's under it, and no other (API 10).
581
+
582
+ ```ts
583
+ const status = this.addStatusBarItem({ id: 'reply', text: '' })
584
+ let reply = ''
585
+ const res = await this.app.net.stream(
586
+ 'https://api.example.com/v1/chat',
587
+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, stream: true }) },
588
+ (text) => {
589
+ reply += text
590
+ status.setText(reply.slice(-40))
591
+ },
592
+ )
593
+ if (!res.ok) this.app.ui.notify(`The service answered ${res.status}`)
594
+ ```
595
+
596
+ Each piece is the text as it arrived, not a whole line or message. The
597
+ `data:` lines of an event stream can be split across pieces, so collect them
598
+ before you read them.
599
+
600
+ There is one catch with a `text/plain` answer. Unless it has the header
601
+ `X-Content-Type-Options: nosniff`, the first 512 bytes may arrive as one
602
+ piece, because Chromium reads that much to guess the type of the answer.
603
+ Event streams (`text/event-stream`, which AI services send) and JSON arrive as
604
+ they're sent.
605
+
606
+ Both work the same way in a sandboxed plugin. A plugin can't open a
607
+ WebSocket.
608
+
609
+ ## Files and folders
610
+
611
+ With `files:read` or `files:write`, a plugin can use what the writer chooses
612
+ for it in the system's own dialog (its title starts with the plugin's name),
613
+ and nothing else:
614
+
615
+ ```ts
616
+ const folder = await this.app.files.pickFolder({ write: true, title: 'Where should the notes go?' })
617
+ if (!folder) return // cancelled
618
+ await this.app.files.write(`${folder}/notes.md`, '# Notes\n')
619
+ for (const entry of await this.app.files.list(folder)) console.log(entry.name, entry.folder, entry.size)
620
+
621
+ const file = await this.app.files.pickFile({ extensions: ['csv'] }) // one file, to read
622
+ const target = await this.app.files.pickFile({ save: true, name: 'cast.csv' }) // where to save one
623
+ ```
624
+
625
+ Choosing:
626
+ - **`pickFolder`** gives the plugin a folder and everything in it.
627
+ `write: true` lets the plugin change what's there, if it has
628
+ `files:write`. With only `files:read`, it can read what's there and nothing
629
+ more.
630
+ - **`pickFile`** gives the plugin one file, to read it or, with
631
+ `save: true`, to write it.
632
+
633
+ Reading and writing (paths are full paths):
634
+ - **`read`** returns bytes, up to 100 MB. **`readText`** returns text.
635
+ - **`write(path, text or bytes)`** creates any missing folders on the way.
636
+ - **`list`**, **`stat`** and **`mkdir`** do what their names say.
637
+ - **`trash`** moves a file to the system's trash, where the writer can get it
638
+ back.
639
+
640
+ Bläck Studio checks every path in the main process, including any links. A
641
+ link inside a chosen folder that leads outside it leads nowhere. Bläck Studio
642
+ remembers what the writer chose until they take it back in Settings →
643
+ Plugins, or turn the plugin off. `granted()` lists these choices.
644
+
645
+ `temp()` gives the plugin a private folder among Bläck Studio's data, which
646
+ only the writer's account can open. The plugin can always use it, with any
647
+ `files:` or `exec:` permission, for passing files to a program.
648
+
649
+ ## Programs
650
+
651
+ With `exec:<program>` in its manifest, a plugin can run that program and no
652
+ other:
653
+
654
+ ```ts
655
+ const dir = await this.app.files.temp()
656
+ await this.app.files.write(`${dir}/book.html`, book.html)
657
+ const res = await this.app.exec.run('pandoc', ['book.html', '-o', 'book.odt'], { cwd: dir, timeout: 120_000 })
658
+ if (res.code !== 0) throw new Error(res.stderr || 'Pandoc failed')
659
+ const odt = await this.app.files.read(`${dir}/book.odt`)
660
+ ```
661
+
662
+ This is how it runs:
663
+ - **The program:** Bläck Studio finds it by name on the PATH, as the system
664
+ would. A path isn't accepted. If the program isn't installed, you get an
665
+ error that says so.
666
+ - **Arguments:** they go to the program as you give them, with no shell.
667
+ `$HOME`, `;`, `|` and `*` are just characters.
668
+ - **`input`:** goes to the program's standard input.
669
+ - **`cwd`:** a folder the writer chose for the plugin, or the plugin's
670
+ temporary folder (the default).
671
+ - **Time and output:** Bläck Studio stops the program after `timeout` (a
672
+ minute unless you set it, ten at most; `timedOut` tells you this happened),
673
+ and at 50 MB of output. Anything the program started is stopped with it.
674
+ - **Its environment:** only what a program needs to find its way: `PATH`,
675
+ `HOME`, the language and the like. It doesn't get Bläck Studio's own
676
+ environment, which may hold keys and tokens.
677
+ - **The result:** `code`, `stdout` as bytes (`text()` for text), `stderr` and
678
+ `timedOut`.
679
+
680
+ When the writer allows a program, they trust the plugin with whatever that
681
+ program can be made to do with the arguments the plugin gives it. Pandoc
682
+ converts documents, but it also runs Lua filters it's given, and git runs
683
+ hooks. That's why every `exec:` permission comes with a warning, and a shell,
684
+ Python or Node with a stronger one. Ask only for the programs you need, and
685
+ say in your description what you run them for.
686
+
687
+ ## In the window, or sandboxed
688
+
689
+ A plugin **in the window** runs in Bläck Studio's page. It can draw its own
690
+ interface and use the editor directly.
691
+
692
+ A **sandboxed** plugin runs in a separate worker:
693
+ - **No page:** it can't reach the page, the editor or other plugins.
694
+ - **No network access of its own:** it has no `fetch` and no way to load
695
+ code.
696
+ - **Everything through Bläck Studio:** it asks for what it needs through
697
+ `this.app`, and Bläck Studio answers according to the plugin's permissions.
698
+ - **The same methods:** it has everything described above, except what draws
699
+ an interface, `editor.active()`, `editor.anchor()` and `app.speech`. Its status bar items are text, and its menu entries use
700
+ `show` to say whether they're for a selection.
701
+
702
+ The plugin list shows when a plugin is sandboxed. If your plugin doesn't need
703
+ to draw anything, make it sandboxed.
704
+
705
+ ## What protects the writer
706
+
707
+ - **The disk:** plugins reach the books only through Bläck Studio, and can't
708
+ reach the disk at all. Bläck Studio's main process works only in the books
709
+ and series the writer chose in the app's own dialogs, whatever the page
710
+ asks. It copies into a book only files the writer picked or dropped.
711
+ - **Plugins' changes:** they go through Bläck Studio's own actions, so they
712
+ can be undone, and they are saved like the writer's own
713
+ changes. Bläck Studio snapshots a document under the plugin's name before
714
+ the plugin first rewrites it.
715
+ - **Deleting:** nothing a plugin does deletes for good. `trash` moves an item
716
+ to the trash.
717
+ - **The network:** the page and its plugins can't send requests themselves.
718
+ `app.net.fetch` goes through Bläck Studio, which allows only https, only to
719
+ the hosts in the manifest or addresses the writer entered, and only to those the writer
720
+ allowed. The page also can't open an address in the browser.
721
+ - **The project's folder:** a plugin with `project:folder` reaches that folder and nothing outside
722
+ it. The checks on each path are in the main process, including any links.
723
+ - **Files:** a plugin reads and changes only what the writer chose for it.
724
+ The main process checks this, including any links. Settings → Plugins lists
725
+ what each plugin was given, so the writer can take it back. "Deleting" a
726
+ file moves it to the system's trash.
727
+ - **Programs:** a plugin can run only the programs named in its manifest, by
728
+ name, without a shell, and Bläck Studio stops them after a time limit.
729
+ - **Permissions:** the writer allows permissions in a small Bläck Studio
730
+ window, in the app's theme, that opens over the main one. No plugin runs
731
+ there, and the main process takes an answer only from that window, so
732
+ nothing in the page can answer for the writer. Cancel has the focus, and
733
+ Allow becomes active after a short delay, so a key pressed just as the
734
+ window appears allows nothing. Bläck Studio asks the same way before
735
+ uninstalling a plugin and before adding a list.
736
+ - **Separate tokens:** each plugin's calls carry its own token. Bläck Studio
737
+ makes the tokens from a secret that it gives the page's plugin host once,
738
+ before any plugin loads, and it takes the means of making tokens away
739
+ before any plugin runs. So a sandboxed plugin can't use what another plugin
740
+ was allowed.
741
+ - **What still depends on trust:** a plugin in the window shares the page with Bläck
742
+ Studio. In principle it could interfere with the app or with other plugins,
743
+ as in Obsidian. It could change the books that are open, or get at what
744
+ another plugin in the page was allowed. It still can't reach the rest of
745
+ the disk, or the network beyond what plugins were allowed. A sandboxed
746
+ plugin can do none of this.
747
+ - **A crash:** when a plugin throws, Bläck Studio shows the error where it
748
+ happened and in Settings → Plugins, and the rest of the app carries on.
749
+ - **Safe mode:** Plugins → Restart Without Plugins starts Bläck Studio
750
+ without plugins. `--safe-mode` on the command line does the same.
751
+
752
+ ## The plugin list
753
+
754
+ Settings → Plugins → Find plugins reads a list from
755
+ `https://blackstudio.app/plugins/plugins.json`
756
+ (set `BLACK_PLUGIN_INDEX` to use another):
757
+
758
+ ```json
759
+ {
760
+ "plugins": [
761
+ {
762
+ "id": "word-of-the-day",
763
+ "name": "Word of the day",
764
+ "description": "A word to use today, every morning.",
765
+ "author": "You",
766
+ "version": "1.0.0",
767
+ "apiVersion": 1,
768
+ "sandboxed": true,
769
+ "permissions": ["network:api.example.com"],
770
+ "download": "https://example.com/word-of-the-day-1.0.0.zip",
771
+ "sha256": "…the SHA-256 that npm run build prints…",
772
+ "homepage": "https://example.com/word-of-the-day"
773
+ }
774
+ ]
775
+ }
776
+ ```
777
+
778
+ Bläck Studio installs plugins only from a list:
779
+ - **The download:** it fetches the zip that the list names, and refuses it
780
+ unless the zip's SHA-256 matches the one in the list.
781
+ - **The contents:** before unpacking, it checks that the zip holds the plugin
782
+ the list names, with nothing outside the plugin's folder.
783
+
784
+ To add a plugin, add its entry to the list's repository.
785
+
786
+ ### Lists of your own
787
+
788
+ Anyone can keep a list: a `plugins.json` like the one above, at an https
789
+ address. A list can name itself with `"name"` next to `"plugins"`.
790
+
791
+ Bläck Studio also offers a community list by default, next to the official
792
+ one: `https://raw.githubusercontent.com/black-community/plugins/main/plugins.json`.
793
+ Its plugins are marked as not official. The writer can remove the list.
794
+
795
+ The writer adds a list under Settings → Plugins → Find plugins → Plugin
796
+ lists, by its address:
797
+ - **Asked first:** Bläck Studio reads the list, then asks in its own window
798
+ whether to add it. The window says that the list's plugins aren't Bläck
799
+ Studio's.
800
+ - **Marked as unofficial:** its plugins appear next to the official ones,
801
+ each labelled with the list it's from.
802
+ - **Checked the same way:** Bläck Studio checks a download against its list
803
+ exactly as it does for the official list.
804
+ - **Updates:** a plugin installed from a list is updated only from that list.
805
+ Bläck Studio won't replace a plugin from one list with one from another
806
+ list, and won't replace one you're writing in the plugins folder.
807
+ - **Removing a list:** its plugins stay installed. They just aren't offered
808
+ any more.