@nesso-how/plugin 0.6.0 → 0.8.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/README.md CHANGED
@@ -4,21 +4,34 @@ Build Nesso plugins with TypeScript: **actions** read and edit graphs, **vocabul
4
4
 
5
5
  ## Install
6
6
 
7
- With Node.js and npm installed, add the SDK to your TypeScript project:
7
+ Use Node.js 24. To add the SDK to an existing TypeScript project:
8
8
 
9
9
  ```sh
10
10
  npm install --save-dev @nesso-how/plugin
11
11
  ```
12
12
 
13
- This installs the development SDK, not a plugin in Nesso. If you are starting a new plugin, use the example below for TypeScript and bundler configuration, including React UI support. To install and try your built plugin in the desktop app, follow the [local testing instructions](example/README.md#test-an-unpublished-build).
13
+ For a new project, start with the [standalone example](example/), which includes TypeScript, Vite, and React configuration. Plugins can be installed locally through MCP without publishing to npm.
14
14
 
15
15
  ## Create a plugin
16
16
 
17
- Copy the [standalone action example](example/) into a separate project. It includes the SDK, TypeScript configuration, and bundler setup:
17
+ ### With an agent
18
+
19
+ Use an agent such as Claude Code or Codex that can create files and run commands on your computer. Nesso's internal chat cannot build or install plugins.
20
+
21
+ 1. In the desktop app, open Settings → AI → MCP and start the server. If `plugins` and `propose_plugin` are not available, update Nesso.
22
+ 2. In your agent's MCP configuration, connect to the URL shown in Nesso using Streamable HTTP and an `Authorization: Bearer <token>` header. Copy the token from Settings into the client's configuration, not into a chat message, source file, or repository. Keep Nesso open.
23
+ 3. Describe the plugin you want, or use this prompt:
24
+
25
+ > Build a Nesso plugin that [describe the behavior]. Call `read_docs` for `plugin` and `plugin-example` through Nesso MCP and follow the documented workflow, then propose a local installation for my approval in Nesso.
26
+
27
+ The agent should work in a separate project, choose a unique package name, and request only the permissions the plugin needs. For a panel, also read `read_docs` with `{"topic":"ui"}`. Follow [Build and test](#build-and-test), then [Install or update through MCP](#install-or-update-through-mcp). Nesso reads the finished package; it never installs dependencies or runs build scripts.
28
+
29
+ ### By hand
30
+
31
+ Copy the [standalone example](example/) into a separate project and install its dependencies:
18
32
 
19
33
  ```sh
20
34
  npm install
21
- npm run build
22
35
  ```
23
36
 
24
37
  Choose your own package name and action ID, then edit `src/index.ts`:
@@ -49,13 +62,7 @@ export const create = (): readonly ActionContribution[] => {
49
62
  }
50
63
  ```
51
64
 
52
- This changes labels in the invoked view in one undoable batch. Shared concepts change in every view containing them.
53
-
54
- How the example works:
55
-
56
- - `create()` defines the actions. Nesso supplies the execution context to `run`, where graph data is always available.
57
- - `applyOperations` takes an array of edits. Here, `.map()` creates one `concept.label` edit per concept, with its ID and new label.
58
- - Writes automatically check that the snapshot you read is still current. If it changed, the entire batch is rejected rather than overwriting newer edits.
65
+ `create()` defines the action; Nesso calls `run` when the user invokes it. This action uppercases every concept label in that view with one undoable batch. Shared concepts change in every view containing them.
59
66
 
60
67
  ### Package metadata and permissions
61
68
 
@@ -67,7 +74,7 @@ Keep the example's build configuration and set these fields in `package.json`:
67
74
  "version": "1.0.0",
68
75
  "keywords": ["nesso-plugin"],
69
76
  "nesso": {
70
- "apiVersion": 1,
77
+ "apiVersion": 3,
71
78
  "kind": "actions",
72
79
  "entry": "dist/index.js",
73
80
  "writes": ["concept.label"],
@@ -83,19 +90,65 @@ Keep the example's build configuration and set these fields in `package.json`:
83
90
  }
84
91
  ```
85
92
 
86
- Declare the operations your action uses in `writes`. The optional permissions listed in `capabilities` are `files`, `notifications`, `storage`, and `ui`. The first three authorize their APIs; `ui` authorizes interactive UI contributions. All fields shown under `nesso` and `i18n.metadata` are required. Add the `nesso-plugin` keyword for discovery in Settings → Plugins.
93
+ Declare the operations your action uses in `writes`. Available capabilities are `files`, `images`, `notifications`, `storage`, and `ui`: the first four grant access to their APIs; `ui` allows interactive panels. Declare only what you use. All fields shown under `nesso` and `i18n.metadata` are required. The `nesso-plugin` keyword makes published packages discoverable in Settings → Plugins.
94
+
95
+ `nesso.apiVersion` identifies the plugin API, not the SDK version or your package's version.
87
96
 
88
97
  `i18n.metadata.name` names the plugin in Settings. Each action defines its own `label` for menus, independently of the plugin name. Labels and metadata use `{ en: string, it?: string, 'zh-CN'?: string }`, with English required as the fallback.
89
98
 
90
99
  ### Build and test
91
100
 
92
- Run `npm run build`, then follow the example's [local testing instructions](example/README.md#test-an-unpublished-build).
101
+ Run `npm run build` to typecheck and build the example. Use `npm run check` to typecheck without building.
102
+
103
+ Test calculations, graph edit generation, and storage transformations separately from React and host APIs. Node.js 24 can run pure TypeScript tests with `node --test "src/**/*.test.ts"`, using `node:test` and `node:assert/strict`. These tests need `.ts` imports and cannot load JSX or DOM-dependent modules. Add `@types/node` and `node` to your test TypeScript configuration's `types` if needed.
104
+
105
+ An action package ships one browser ES module. Bundle its dependencies except `react`, `react/*`, `react-dom`, and `react-dom/*`; Nesso supplies React 19 in the sandbox. The example's Vite configuration handles this.
106
+
107
+ Before installing, validate the built package with `preparePluginPackage`. Save this as `validate.ts` in the project root and run `node validate.ts` after building:
108
+
109
+ ```ts
110
+ import { readFile } from 'node:fs/promises'
111
+ import { preparePluginPackage } from '@nesso-how/plugin/package'
112
+ import { parsePluginManifest } from '@nesso-how/plugin/runtime'
113
+
114
+ const manifest = JSON.parse(await readFile('package.json', 'utf8'))
115
+ const nesso = parsePluginManifest(manifest.nesso)
116
+ const entry = new Uint8Array(await readFile(nesso.entry))
117
+ const files = [{ path: nesso.entry, bytes: entry }]
118
+
119
+ const prepared = await preparePluginPackage({ manifest, files })
120
+ console.log(prepared.name, prepared.version, prepared.contentId)
121
+ ```
122
+
123
+ This checks metadata, permission declarations, file sizes, UTF-8, and theme/vocabulary definitions without running action code. Validation failures throw `PluginError` with details in `issues`. It does not call `create()` or test behavior; those still need testing in Nesso.
124
+
125
+ ### Install or update through MCP
126
+
127
+ Connect to the [desktop MCP server](#with-an-agent) and call `plugins` to check installed names and local builds. Then call `propose_plugin` with the absolute package root, containing `package.json` and the built entry:
128
+
129
+ ```json
130
+ { "directory": "/absolute/path/to/nesso-plugin-my-action" }
131
+ ```
132
+
133
+ Pass the package root, not `dist`, an archive, or inline JavaScript. Nesso reads only `package.json` and the `nesso.entry` file. Relative paths, files outside the directory (including through symlinks), and oversized files are rejected.
134
+
135
+ Tell the user to switch to Nesso before proposing. Every install or replacement needs approval within the **120-second** request timeout, which includes processing time. The result is one of:
136
+
137
+ - `installed`: includes `name`, `version`, and `contentId`.
138
+ - `cancelled`: the proposal was not approved. Do not automatically propose again.
139
+ - `failed`: includes `{ path, message }[]` issues to fix before a new proposal.
93
140
 
94
- Actions ship one browser ES module with dependencies bundled except React and React DOM, which Nesso supplies inside the sandbox. Keep `react`, `react/*`, `react-dom`, and `react-dom/*` external in your bundler; the example's build handles this. The runtime supports React 19. Test and install external plugins in the desktop app.
141
+ If the client times out or disconnects, call `plugins` to check whether installation completed. Do not retry automatically or report success without confirmation.
142
+
143
+ Local plugins stay installed across restarts and appear in Settings → Plugins with a **Local** badge. They are not verified by npm or checked for npm updates. Rebuilding your project does not update the installed copy.
144
+
145
+ To update a local plugin the user has asked to replace, call `plugins`, find its entry with `local: true`, and pass its current `contentId` as `replacing` alongside `directory`. MCP cannot replace or shadow npm-installed or bundled plugins; use a different package name for your local copy.
146
+
147
+ Try the installed action from a view's actions menu, or choose the theme/vocabulary in Settings. Check that the plugin handles cancellation and stale-state errors, closes cleanly, and restores saved data after restarting Nesso.
95
148
 
96
149
  ## Action API
97
150
 
98
- Nesso passes `{ document, storage, files, notifications, signal, viewId }` to `run` as `ActionContext`. `document` exposes the shared graph, view membership, and transient selection; `storage` holds the plugin's private data for that document.
151
+ Nesso passes `{ document, storage, files, images, notifications, signal, viewId }` to `run` as `ActionContext`. `document` exposes the shared graph, view membership, and transient selection; `storage` holds the plugin's private data for that document.
99
152
 
100
153
  `create()` receives no arguments and returns an array of actions with unique lowercase kebab-case IDs, localized labels, optional icons, and either a `run(context)` handler or a React component in `ui`. The two forms are mutually exclusive. Use `ActionIconName` for supported icons.
101
154
 
@@ -135,7 +188,9 @@ Nesso supplies React, the `@nesso-how/ui` component stylesheet, and theme CSS va
135
188
 
136
189
  #### Lifecycle
137
190
 
138
- Use React effects to clean up subscriptions and resources. Panels have no action execution timeout, but initialization and API requests have deadlines. Uncaught errors or rejected promises fail the session; handle expected errors in your UI. Nesso provides the title, close control, and loading/failure screens. Changing the active view revokes the current panel instance and mounts the same action in a new instance for the selected view, including All. Closing or replacing a panel discards its React state: save progress through `storage` during use, not during cleanup, which is best effort.
191
+ Nesso provides the panel title, close control, and loading/error screens. Opening a panel or changing the active view starts a new React instance and invalidates the previous context. Closing it, changing documents, replacing/removing the plugin, or a runtime failure ends the session.
192
+
193
+ Keep mutable state inside the component and clean up subscriptions in React effects. Save progress through `storage` as it changes; cleanup may not finish. Panels have no action execution timeout, but initialization and API requests have deadlines. Handle expected errors in the UI; uncaught errors or rejected promises fail the session.
139
194
 
140
195
  ### Action badges
141
196
 
@@ -193,55 +248,70 @@ Call helpers on `document` and declare their operation kinds in `nesso.writes`:
193
248
 
194
249
  `addConcept` returns the new IRI. New concepts join the active saved view and link to the single selected concept, if any. These links and `connect` use the vocabulary's default relation type. `createRelationType` creates and assigns a type to the given relation.
195
250
 
196
- For related edits, use `document.applyOperations(operations)` as in the quickstart. The entire batch succeeds or changes nothing. Separate calls are separate transactions. Raw `concept.add` operations require an explicit new absolute IRI.
251
+ For related edits, use `document.applyOperations(operations)` as in the quickstart. The entire batch succeeds or changes nothing. Editing, reconnecting, retyping, or removing an unknown concept or relation rejects the batch, as does reconnecting or retyping onto an existing relation; removing an item already removed earlier in the same batch, such as a relation of a removed concept, is allowed. Separate calls are separate transactions. Raw `concept.add` operations require an explicit new absolute IRI.
197
252
 
198
253
  Every write checks against the last snapshot you read, or the initial snapshot if you haven't read one. Successful writes advance that baseline, so awaited sequential writes work normally. Incoming updates alone do not advance it. A conflict rejects with `stale-state`; let the failure propagate so Nesso can ask the user to run the action again. Never retry mutations automatically or read a new snapshot just to submit edits calculated from old data.
199
254
 
200
255
  The invoked view is **not a write sandbox**: permitted writes can affect the whole document. Only the operations listed above are available to plugins.
201
256
 
202
- ### Files, notifications, and failures
257
+ ### Files, images, notifications, and failures
203
258
 
204
259
  | API | Required capability | Result |
205
260
  | ------------------------------------------------------------------------------------------------------ | ------------------- | -------------------------------------------------------------------------------- |
206
261
  | `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
207
262
  | `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
263
+ | `files.save({ name: 'graph.png', mediaType: 'image/png', base64 })` | `files` | `{ saved: boolean }`; the host decodes canonical base64 before saving. |
264
+ | `images.renderView({ format: 'png', scale: 2 })` | `images` | `{ mediaType: 'image/png', base64 }` for the invoked view. |
208
265
  | `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
209
266
 
210
- Files use UTF-8 text and host-managed dialogs or browser downloads; `files` grants no unrestricted filesystem access. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
267
+ File saves accept exactly one of UTF-8 `text` or canonical `base64` (without a data URL prefix), with a 16 MiB decoded byte limit. File opening remains UTF-8 text only. Host-managed dialogs or browser downloads grant no unrestricted filesystem access. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
268
+
269
+ `images.renderView` captures the invoked view with the current theme and fonts, without selection or canvas controls. Scale defaults to `2`, or accepts `4`. Empty or oversized images fail rather than silently downscaling (8192 pixels per side, 16,777,216 pixels total, 16 MiB PNG). Save the result separately with `files.save({ name: 'view.png', ...image })`; this also requires `files`.
211
270
 
212
271
  Failures throw `PluginError` with `code` and `{ path, message }[]` issues. Let them propagate instead of reporting success. Files and notifications cannot be rolled back with graph edits.
213
272
 
214
273
  ### Private persistent storage
215
274
 
216
- Declare `storage` to read, write, or delete your plugin's private data. Nesso derives the namespace from the authorized npm package name and current document, never from plugin-provided identity fields. Different versions and action instances of the same package share data; different packages and documents do not.
275
+ Declare `storage` to read, write, or delete private data. Storage is separate for each package name, installation source (local or npm), and document. Versions and action instances of the same package share data; a local install and an npm install never do, even with the same name. Plugins cannot choose another package's namespace.
217
276
 
218
277
  ```ts
219
278
  const records = await storage.list()
220
279
 
221
- await storage.set('progress', { attempts: 1, answers: ['good'] }, concept.id)
280
+ await storage.set(
281
+ 'progress',
282
+ { attempts: 1, answers: ['good'] },
283
+ { kind: 'concept', id: concept.id },
284
+ )
222
285
  await storage.set('settings', { enabled: true })
223
- await storage.delete('progress', concept.id)
286
+ if (viewId !== null)
287
+ await storage.set('notes', { text: 'Project ideas' }, { kind: 'view', id: viewId })
288
+ await storage.delete('progress', { kind: 'concept', id: concept.id })
224
289
  ```
225
290
 
226
- `storage.list()` returns all records as an array. Each record has a `key`, a JSON `value`, and optionally a `conceptId`:
291
+ `storage.list()` returns all records as an array, including records associated with deleted concepts or views. Each record has a `key`, a JSON `value`, and an optional `scope`:
292
+
293
+ - Without `scope`, the record belongs to the document, for example plugin configuration or notes for Overview (`viewId === null`).
294
+ - With `{ kind: 'concept', id }`, it belongs to that concept. Its data is shared across all views containing the concept.
295
+ - With `{ kind: 'view', id }`, it belongs to that saved view, independently of its name or membership. Use a non-null `viewId`.
296
+ - Scopes identify records within the same plugin/document namespace; they do not create separate namespaces or revision baselines. The same key can be used at document scope and for different concepts and views, including a concept and view with the same ID.
297
+ - Your plugin owns the payload format and any migrations. Version it independently of the SDK and package version; Nesso does not interpret its fields.
227
298
 
228
- - Without `conceptId`, the record belongs to the document, for example plugin configuration.
229
- - With `conceptId`, it belongs to that concept in the document. The same key can be used for different concepts and for document-level data.
230
- - Views do not create storage namespaces. A concept's data is shared across all views containing it.
231
- - Payloads belong to the plugin: the host does not interpret their fields or implement domain logic.
299
+ `storage.set(key, value, scope?)` saves one record and `storage.delete(key, scope?)` removes one. Each call is a single transaction returning `true` if data changed, or `false` if nothing changed, such as saving an identical value or deleting a missing record. Failed writes throw.
232
300
 
233
- `storage.set(key, value, conceptId?)` saves one record and `storage.delete(key, conceptId?)` removes one. Each call is a single transaction returning `true` when storage changed and `false` for valid net-no-op writes, such as saving an identical value or deleting a missing record. Failed writes throw instead of returning `false`.
301
+ Setting a scoped record requires the concept or saved view to exist. Concept IDs must be absolute IRIs; view IDs are opaque identifiers. Deleting a record also accepts references to deleted entities.
234
302
 
235
- The SDK tracks storage revisions internally. Every mutation checks against the last listed snapshot or the preceding successful mutation. If you haven't listed storage, the first mutation reads its baseline automatically. Concurrent changes reject stale writes with `stale-state`, without refreshing the baseline or retrying automatically. List storage again before recomputing edits; never refresh just to resubmit edits calculated from old data. Document reads do not refresh the storage baseline, and storage writes do not invalidate the document snapshot. Document edits and private storage calls are separate transactions.
303
+ Each write checks the storage revision from your last `storage.list()` or successful write. If you have not listed storage, the SDK reads the initial revision for you. Concurrent changes reject the write with `stale-state`; the SDK does not retry or refresh the revision. List storage again and recompute your changes rather than resubmitting old data.
236
304
 
237
- Await all storage calls before the action returns. Success means the validated change was committed in memory, not that a disk write has finished. Nesso autosaves through its shared persistence API, reports failures in its persistence banner, and waits for saving before desktop close, update installation, and data-folder transfers. Unreadable records are protected until explicit recovery; in-memory editing can continue but may remain unsaved.
305
+ Document and storage revisions are independent: reading one does not refresh the other. Graph edits and storage calls are separate transactions.
306
+
307
+ Await all storage calls before the action returns. Success means the change is in memory, not necessarily on disk. Nesso autosaves, reports save failures in its persistence banner, and waits for saving before closing the desktop app. Unreadable records require user recovery and are not overwritten automatically.
238
308
 
239
309
  #### Data lifecycle
240
310
 
241
311
  - A document has a persistent identity outside graph JSON-LD. Resetting it creates a new identity and empty plugin storage; a mismatched saved identity is reported and protected, never silently attached to another document.
242
- - Removing a view or changing membership does not delete concept data.
243
- - Deleting a concept retains its records, including across restart and backup restoration. Document Undo/Redo can recover the concept during the current app session; private storage changes themselves do not enter graph history.
244
- - Use concept-associated records to identify a concept's data, including its logs. Plugins may explicitly delete records no longer needed; IDs embedded in arbitrary payloads remain opaque to the host.
312
+ - Renaming a view or changing membership does not affect scoped records. Removing a view does not delete concept data.
313
+ - Deleting a concept or saved view retains its records, including across restart and backup restoration. Document Undo/Redo can recover the entity during the current app session, reconnecting its records by the same ID; private storage changes themselves do not enter graph history. Creating a different entity with the same name does not reconnect old records.
314
+ - Use scopes for concept or view data, including logs. Nesso does not interpret IDs embedded in keys or payloads and does not automatically delete orphaned records; your plugin must clean them up explicitly.
245
315
  - Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data.
246
316
 
247
317
  #### Limits
@@ -258,7 +328,7 @@ Storage accepts finite JSON primitives, dense arrays, and plain objects, includi
258
328
  | Record nesting | 24 levels |
259
329
  | Record key | 1–128 characters |
260
330
 
261
- Concept IDs must be absolute IRIs and refer to an existing document concept when writing. Deletes may remove retained orphan records. Keys are logical identifiers, not paths. Normal action channel request, deadline, rate, and cancellation limits also apply.
331
+ Keys are logical identifiers, not file paths. Action channel size, deadline, rate, and cancellation limits also apply.
262
332
 
263
333
  ## Vocabularies
264
334
 
@@ -289,10 +359,11 @@ Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use em
289
359
  - `id`: a lowercase kebab-case contribution ID.
290
360
  - `colors`: every required token, using `#RRGGBB` or `#RRGGBBAA`. Start with [Paper's palette](../../plugins/paper-theme/src/index.ts) or [Kernel's](../../plugins/kernel-theme/src/index.ts).
291
361
  - `metrics`: `radius-control` and `radius-object` in pixels, and `duration-state` in milliseconds.
292
- - `fonts`: `sans` and `mono`, each with a `faces` array. Use `[]` for system fallbacks, or include local WOFF2 files with package-relative `path`, `weight: [min, max]`, and `style: "normal"` or `"italic"`.
293
362
 
294
- Only light themes are supported. Use readable text contrast; arbitrary CSS and remote fonts are unsupported.
363
+ Only light themes are supported. Use readable text contrast; arbitrary CSS and plugin fonts are unsupported. Theme packages ship only their JSON entry. Nesso owns `--font-sans` (Geist) and `--font-mono` (IBM Plex Mono), with system fallbacks for other scripts. Switching themes does not change typography.
364
+
365
+ ## API reference
295
366
 
296
- The SDK exposes shared graph and operation types from the internal [`@nesso-how/core`](../core/) package. Trusted renderers use its synchronous store contract; plugins use only the permission-limited asynchronous `ActionContext` above. The published SDK bundles these shared contracts and helpers, so plugin projects need no separate core dependency.
367
+ Import graph and operation types from `@nesso-how/plugin`; no separate `@nesso-how/core` dependency is needed.
297
368
 
298
369
  For the full API and validation rules, see [action types](src/runtime.ts), [graph operations](../core/src/types.ts), and [theme/vocabulary schemas](src/definitions.ts).
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as ThemeDefinition, C as PluginStorage, F as PluginError, G as SavedView, K as Selection, L as LocalizedText, T as PluginStorageRecord, U as GraphSnapshot, W as NessoOperation, a as ActionDescriptor, c as PluginI18n, i as ActionContribution, l as PluginManifest, n as ActionBadgeResult, o as ActionIconName, q as VocabDefinition, r as ActionContext, s as ActionState, t as ActionBadgeInput, u as actionIconNames, w as PluginStorageKey } from "./runtime-BxtTAcko.js";
2
- export { type ActionBadgeInput, type ActionBadgeResult, type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type LocalizedText, type NessoOperation, PluginError, type PluginI18n, type PluginManifest, type PluginStorage, type PluginStorageKey, type PluginStorageRecord, type SavedView, type Selection, type ThemeDefinition, type VocabDefinition, actionIconNames };
1
+ import { C as PluginStorageKey, F as ImageRenderOptions, G as GraphSnapshot, H as ThemeDefinition, I as RenderedImage, J as Selection, K as NessoOperation, L as PluginError, S as PluginStorage, T as PluginStorageScope, Y as VocabDefinition, a as ActionDescriptor, c as PluginI18n, i as ActionContribution, l as PluginManifest, n as ActionBadgeResult, o as ActionIconName, q as SavedView, r as ActionContext, s as ActionState, t as ActionBadgeInput, u as actionIconNames, w as PluginStorageRecord, z as LocalizedText } from "./runtime-DCyJA620.js";
2
+ export { type ActionBadgeInput, type ActionBadgeResult, type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type ImageRenderOptions, type LocalizedText, type NessoOperation, PluginError, type PluginI18n, type PluginManifest, type PluginStorage, type PluginStorageKey, type PluginStorageRecord, type PluginStorageScope, type RenderedImage, type SavedView, type Selection, type ThemeDefinition, type VocabDefinition, actionIconNames };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { C as PluginError, t as actionIconNames } from "./runtime-BM45o1qi.js";
1
+ export { S as PluginError, t as actionIconNames } from "./runtime-uvKgm2yV.js";
package/dist/node/data.js CHANGED
@@ -1,21 +1,32 @@
1
1
  import { PluginError } from './errors.js';
2
2
  export function checkMessageSize(value, limit, maximumDepth = 32) {
3
+ const exceeded = () => new PluginError('invalid-input', [{ path: 'message', message: 'Message limit exceeded' }]);
4
+ let size = 0;
3
5
  const visit = (value, depth) => {
4
6
  if (depth > maximumDepth)
5
7
  throw new PluginError('invalid-input', [
6
8
  { path: 'message', message: 'Nesting limit exceeded' },
7
9
  ]);
10
+ if (value === undefined)
11
+ return;
12
+ size += typeof value === 'string' ? value.length + 1 : 1;
13
+ if (size > limit)
14
+ throw exceeded();
8
15
  if (value === null)
9
16
  return;
10
17
  if (typeof value === 'object') {
11
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype)
18
+ const array = Array.isArray(value);
19
+ if (!array && Object.getPrototypeOf(value) !== Object.prototype)
12
20
  throw new PluginError('invalid-input', [
13
21
  { path: 'message', message: 'Expected plain data' },
14
22
  ]);
15
- for (const item of Object.values(value))
23
+ for (const [key, item] of Object.entries(value)) {
24
+ if (!array && item !== undefined)
25
+ size += key.length;
16
26
  visit(item, depth + 1);
27
+ }
17
28
  }
18
- else if (!['string', 'number', 'boolean', 'undefined'].includes(typeof value) ||
29
+ else if (!['string', 'number', 'boolean'].includes(typeof value) ||
19
30
  (typeof value === 'number' && !Number.isFinite(value))) {
20
31
  throw new PluginError('invalid-input', [
21
32
  { path: 'message', message: 'Expected serializable data' },
@@ -24,5 +35,5 @@ export function checkMessageSize(value, limit, maximumDepth = 32) {
24
35
  };
25
36
  visit(value, 0);
26
37
  if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit)
27
- throw new PluginError('invalid-input', [{ path: 'message', message: 'Message limit exceeded' }]);
38
+ throw exceeded();
28
39
  }
@@ -27,30 +27,6 @@ declare const themeDefinition: z.ZodObject<{
27
27
  'radius-object': z.ZodNumber;
28
28
  'duration-state': z.ZodNumber;
29
29
  }, z.core.$strict>;
30
- fonts: z.ZodObject<{
31
- sans: z.ZodObject<{
32
- faces: z.ZodArray<z.ZodObject<{
33
- path: z.ZodString;
34
- weight: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>;
35
- style: z.ZodEnum<{
36
- italic: "italic";
37
- normal: "normal";
38
- }>;
39
- unicodeRange: z.ZodOptional<z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>>;
40
- }, z.core.$strict>>;
41
- }, z.core.$strict>;
42
- mono: z.ZodObject<{
43
- faces: z.ZodArray<z.ZodObject<{
44
- path: z.ZodString;
45
- weight: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>;
46
- style: z.ZodEnum<{
47
- italic: "italic";
48
- normal: "normal";
49
- }>;
50
- unicodeRange: z.ZodOptional<z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>>;
51
- }, z.core.$strict>>;
52
- }, z.core.$strict>;
53
- }, z.core.$strict>;
54
30
  }, z.core.$strict>;
55
31
  export declare const vocabRelationType: z.ZodObject<{
56
32
  id: z.ZodString;
@@ -25,24 +25,6 @@ const contributionId = z
25
25
  .max(64)
26
26
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
27
27
  const color = z.string().regex(/^#[\da-fA-F]{6}([\da-fA-F]{2})?$/);
28
- const fontFace = z.strictObject({
29
- path: z
30
- .string()
31
- .max(240)
32
- .regex(/^(?:[\w-]+\/)*[\w-]+\.woff2$/),
33
- weight: z
34
- .tuple([z.number().int().min(1).max(1000), z.number().int().min(1).max(1000)])
35
- .refine(([min, max]) => min <= max),
36
- style: z.enum(['normal', 'italic']),
37
- unicodeRange: z
38
- .array(z
39
- .tuple([z.number().int().min(0).max(0x10ffff), z.number().int().min(0).max(0x10ffff)])
40
- .refine(([min, max]) => min <= max))
41
- .min(1)
42
- .max(64)
43
- .optional(),
44
- });
45
- const font = z.strictObject({ faces: z.array(fontFace).max(32) });
46
28
  const luminance = (value) => {
47
29
  const channels = [1, 3, 5].map((offset) => parseInt(value.slice(offset, offset + 2), 16) / 255);
48
30
  const linear = channels.map((value) => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
@@ -60,9 +42,8 @@ const themeDefinition = z
60
42
  'radius-object': z.number().min(0).max(16),
61
43
  'duration-state': z.number().int().min(0).max(300),
62
44
  }),
63
- fonts: z.strictObject({ sans: font, mono: font }),
64
45
  })
65
- .superRefine(({ colors, fonts }, context) => {
46
+ .superRefine(({ colors }, context) => {
66
47
  for (const key of ['background', 'canvas', 'sidebar']) {
67
48
  if (!opaque(colors[key]) || luminance(colors[key]) < 0.8)
68
49
  context.addIssue({
@@ -85,8 +66,6 @@ const themeDefinition = z
85
66
  path: ['colors', 'primary-foreground'],
86
67
  message: 'Insufficient primary contrast',
87
68
  });
88
- if (fonts.sans.faces.length + fonts.mono.faces.length > 32)
89
- context.addIssue({ code: 'custom', path: ['fonts'], message: 'Font face limit exceeded' });
90
69
  });
91
70
  export const vocabRelationType = z.strictObject({
92
71
  id: z.string().min(1).max(2048),
@@ -1,6 +1,8 @@
1
1
  import { NessoError, type ErrorIssue } from '@nesso-how/errors';
2
2
  import type { ZodType } from 'zod';
3
3
  import type { LocalizedText } from './i18n.ts';
4
+ export declare const pluginErrorCodes: readonly ['invalid-input', 'denied', 'stale-state', 'stale-context', 'unavailable', 'cancelled', 'timeout', 'closed', 'failed'];
5
+ export declare function pluginErrorCode(error: unknown): "cancelled" | "closed" | "denied" | "failed" | "invalid-input" | "stale-context" | "stale-state" | "timeout" | "unavailable";
4
6
  export declare class PluginError extends NessoError {
5
7
  name: string;
6
8
  readonly code: string;
@@ -11,6 +11,21 @@ const boundText = (text, limit) => {
11
11
  }
12
12
  return result;
13
13
  };
14
+ export const pluginErrorCodes = [
15
+ 'invalid-input',
16
+ 'denied',
17
+ 'stale-state',
18
+ 'stale-context',
19
+ 'unavailable',
20
+ 'cancelled',
21
+ 'timeout',
22
+ 'closed',
23
+ 'failed',
24
+ ];
25
+ export function pluginErrorCode(error) {
26
+ const code = error instanceof Error && 'code' in error ? error.code : undefined;
27
+ return pluginErrorCodes.find((known) => known === code) ?? 'failed';
28
+ }
14
29
  export class PluginError extends NessoError {
15
30
  name = 'PluginError';
16
31
  code;
@@ -4,11 +4,16 @@ export declare const fileOpenOptions: z.ZodObject<{
4
4
  extensions: z.ZodArray<z.ZodString>;
5
5
  mimeTypes: z.ZodArray<z.ZodString>;
6
6
  }, z.core.$strict>;
7
- export declare const fileSaveOptions: z.ZodObject<{
7
+ export declare const fileBase64: z.ZodString;
8
+ export declare const fileSaveOptions: z.ZodUnion<readonly [z.ZodObject<{
8
9
  name: z.ZodString;
9
10
  mediaType: z.ZodString;
10
11
  text: z.ZodString;
11
- }, z.core.$strict>;
12
+ }, z.core.$strict>, z.ZodObject<{
13
+ name: z.ZodString;
14
+ mediaType: z.ZodString;
15
+ base64: z.ZodString;
16
+ }, z.core.$strict>]>;
12
17
  export declare const fileOpenResult: z.ZodNullable<z.ZodObject<{
13
18
  name: z.ZodString;
14
19
  mediaType: z.ZodString;
@@ -12,7 +12,7 @@ export const fileOpenOptions = z.strictObject({
12
12
  .max(16),
13
13
  mimeTypes: z.array(mediaType).max(16),
14
14
  });
15
- export const fileSaveOptions = z.strictObject({
15
+ const fileFields = {
16
16
  name: z
17
17
  .string()
18
18
  .trim()
@@ -23,13 +23,30 @@ export const fileSaveOptions = z.strictObject({
23
23
  value !== '..' &&
24
24
  [...value].every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)),
25
25
  mediaType,
26
- text: z
27
- .string()
28
- .max(fileTextLimit)
29
- .refine((value) => new TextEncoder().encode(value).byteLength <= fileTextLimit, 'File text byte limit exceeded'),
30
- });
26
+ };
27
+ const fileText = z
28
+ .string()
29
+ .max(fileTextLimit)
30
+ .refine((value) => new TextEncoder().encode(value).byteLength <= fileTextLimit, 'File text byte limit exceeded');
31
+ export const fileBase64 = z
32
+ .string()
33
+ .max(4 * Math.ceil(fileTextLimit / 3))
34
+ .regex(/^[A-Za-z0-9+/]*={0,2}$/)
35
+ .refine((value) => {
36
+ const size = (value.length / 4) * 3 - (value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0);
37
+ try {
38
+ return value.length % 4 === 0 && size <= fileTextLimit && btoa(atob(value)) === value;
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }, 'Invalid base64 or file byte limit exceeded');
44
+ export const fileSaveOptions = z.union([
45
+ z.strictObject({ ...fileFields, text: fileText }),
46
+ z.strictObject({ ...fileFields, base64: fileBase64 }),
47
+ ]);
31
48
  export const fileOpenResult = z
32
- .strictObject({ name: z.string().min(1).max(240), mediaType, text: fileSaveOptions.shape.text })
49
+ .strictObject({ name: z.string().min(1).max(240), mediaType, text: fileText })
33
50
  .nullable();
34
51
  export function parseFileOptions(kind, value) {
35
52
  return parseOrThrow(kind === 'open' ? fileOpenOptions : fileSaveOptions, value);
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ export declare const imageRenderOptions: z.ZodObject<{
3
+ format: z.ZodLiteral<"png">;
4
+ scale: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<2>, z.ZodLiteral<4>]>>;
5
+ }, z.core.$strict>;
6
+ export declare const renderedImage: z.ZodObject<{
7
+ mediaType: z.ZodLiteral<"image/png">;
8
+ base64: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export type ImageRenderOptions = Readonly<z.infer<typeof imageRenderOptions>>;
11
+ export type RenderedImage = Readonly<z.infer<typeof renderedImage>>;
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ import { fileBase64 } from './files.js';
3
+ export const imageRenderOptions = z.strictObject({
4
+ format: z.literal('png'),
5
+ scale: z.union([z.literal(2), z.literal(4)]).optional(),
6
+ });
7
+ export const renderedImage = z.strictObject({
8
+ mediaType: z.literal('image/png'),
9
+ base64: fileBase64,
10
+ });
@@ -3,4 +3,5 @@ export type { ThemeDefinition } from './definitions.ts';
3
3
  export { PluginError } from './errors.ts';
4
4
  export type { ActionContext, ActionBadgeInput, ActionBadgeResult, ActionContribution, ActionDescriptor, ActionIconName, ActionState, LocalizedText, PluginI18n, PluginManifest, } from './runtime.ts';
5
5
  export { actionIconNames } from './runtime.ts';
6
- export type { PluginStorage, PluginStorageKey, PluginStorageRecord } from './storage.ts';
6
+ export type { ImageRenderOptions, RenderedImage } from './images.ts';
7
+ export type { PluginStorage, PluginStorageKey, PluginStorageRecord, PluginStorageScope, } from './storage.ts';
@@ -1,8 +1,6 @@
1
1
  import { type PluginI18n, type PluginManifest } from './runtime.ts';
2
2
  export declare const packageLimits: {
3
3
  readonly entry: number;
4
- readonly font: number;
5
- readonly fonts: 32;
6
4
  readonly record: number;
7
5
  readonly installed: 32;
8
6
  readonly total: number;
@@ -22,13 +20,8 @@ export type PreparedPlugin = {
22
20
  readonly nesso: PluginManifest;
23
21
  readonly i18n: PluginI18n;
24
22
  readonly code: string;
25
- readonly fonts: readonly {
26
- readonly path: string;
27
- readonly data: string;
28
- }[];
29
23
  readonly contentId: string;
30
24
  };
31
25
  export declare function parsePackageIdentity(value: unknown): any;
32
26
  export declare function preparePluginPackage(input: PluginPackageInput): Promise<PreparedPlugin>;
33
- export declare function packageFonts(value: PreparedPlugin): ReadonlyMap<string, Uint8Array>;
34
27
  export declare function verifyPluginPackage(value: PreparedPlugin): Promise<PreparedPlugin>;