@nesso-how/plugin 0.1.1 → 0.3.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
@@ -1,64 +1,178 @@
1
- # @nesso-how/plugin
1
+ # Nesso Plugin SDK
2
2
 
3
- Types, validation, and asynchronous clients for isolated Nesso actions plus data-only vocabularies and themes. The canvas is a trusted renderer, not a plugin.
3
+ Build Nesso plugins with TypeScript: **actions** read and edit graphs, **vocabularies** define relation types, and **themes** customize appearance.
4
4
 
5
5
  ## Create a plugin
6
6
 
7
- Start with the [standalone action example](example/README.md). Actions export `create(context)` and build one self-contained browser JavaScript entry, bundling any dependencies. Nesso does not install dependencies, run package scripts, compile received source, or load module graphs. Themes and vocabularies ship a JSON definition file instead; the host validates it and never executes it.
7
+ Copy the [standalone action example](example/) into a separate project. It includes the SDK, TypeScript configuration, and bundler setup:
8
8
 
9
- - **Actions** return `{ id, label, supportsViews, run }` records. Discovery has no document access or effects; each invocation runs in a fresh worker. See [Import](../../plugins/import) and [Export](../../plugins/export).
10
- - **Vocabularies** ship a `VocabDefinition` JSON file with stable absolute relation-type IRIs and a default among their own types. See [Base Vocab](../../plugins/base-vocab).
11
- - **Themes** ship a light-only `ThemeDefinition` JSON file with colors, metrics, and local WOFF2 font descriptors. Include exactly the referenced fonts: at most 32 files, 4 MiB each. The host validates and applies them; arbitrary CSS and remote fonts are not supported. See [Kernel](../../plugins/kernel).
9
+ ```sh
10
+ npm install
11
+ npm run build
12
+ ```
12
13
 
13
- Nesso injects the context. Import types such as `ActionContext` and `ActionContribution` from `@nesso-how/plugin`; there is no need to create a client yourself.
14
+ Choose your own package name and action ID, then edit `src/index.ts`:
14
15
 
15
- ## Manifest and translations
16
+ ```ts
17
+ import type { ActionContribution, NessoOperation } from '@nesso-how/plugin'
18
+ import source from '../package.json' with { type: 'json' }
16
19
 
17
- Use the [example package.json](example/package.json). Package names must be valid npm names and versions exact SemVer. Technical declarations live under `nesso`; all fields below are required.
20
+ export const create = (): readonly ActionContribution[] => {
21
+ const action: ActionContribution = {
22
+ id: 'uppercase-labels',
23
+ label: source.i18n.metadata.name,
24
+ run: async ({ store }) => {
25
+ const state = store.getState()
18
26
 
19
- | `nesso` field | Supported value |
20
- | --- | --- |
21
- | `apiVersion` | `1` |
22
- | `kind` | `actions`, `vocab`, or `theme` |
23
- | `entry` | Actions: package-local `.js` path, such as `dist/index.js`. Themes and vocabularies: package-local `.json` definition path, such as `dist/definition.json` |
24
- | `writes` | Document-content operation kinds, without duplicates |
25
- | `capabilities` | Subset of `files.open`, `files.save`, `notifications.notify`, without duplicates |
27
+ const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({
28
+ kind: 'concept.label',
29
+ id,
30
+ value: label.toUpperCase(),
31
+ }))
26
32
 
27
- Themes and vocabularies require empty `writes` and `capabilities`. Unknown declarations are rejected. Contribution IDs are unique by kind and use lowercase kebab-case.
33
+ await store.applyOperations(operations)
34
+ },
35
+ }
28
36
 
29
- The top-level `i18n.metadata` requires `name`, `description`, and `documentation`. Each is a `LocalizedText` object: `{ en: string, it?: string, 'zh-CN'?: string }`. Other `i18n` keys use the same shape. Nesso resolves the current language with an English fallback; no translation library is needed. Bundle JSON imports at build time.
37
+ return [action]
38
+ }
39
+ ```
30
40
 
31
- Use `label: i18n.label` for an action, or reuse `i18n.metadata.name` when the wording matches. Notification titles/descriptions and `PluginError`'s optional third argument also accept localized text. Diagnostic `issues` remain `{ path, message }[]` strings.
41
+ This changes labels in the invoked view in one undoable batch. Shared concepts change in every view containing them.
42
+
43
+ How the example works:
44
+
45
+ - `create()` defines the actions. Nesso supplies the execution context to `run`, where graph data is always available.
46
+ - `applyOperations` takes an array of edits. Here, `.map()` creates one `concept.label` edit per concept, with its ID and new label.
47
+ - Writes automatically check that the snapshot you read is still current. If it changed, the entire batch is rejected rather than overwriting newer edits.
48
+
49
+ ### Package metadata and permissions
50
+
51
+ Keep the example's build configuration and set these fields in `package.json`:
52
+
53
+ ```json
54
+ {
55
+ "name": "nesso-plugin-my-action",
56
+ "version": "1.0.0",
57
+ "keywords": ["nesso-plugin"],
58
+ "nesso": {
59
+ "apiVersion": 1,
60
+ "kind": "actions",
61
+ "entry": "dist/index.js",
62
+ "writes": ["concept.label"],
63
+ "capabilities": []
64
+ },
65
+ "i18n": {
66
+ "metadata": {
67
+ "name": { "en": "Uppercase labels" },
68
+ "description": { "en": "Uppercase concept labels in a view." },
69
+ "documentation": { "en": "Updates labels in one undoable batch." }
70
+ }
71
+ }
72
+ }
73
+ ```
32
74
 
33
- ## Action context
75
+ Declare the operations your action uses in `writes` and file/notification access in `capabilities`. All fields shown under `nesso` and `i18n.metadata` are required. Add the `nesso-plugin` keyword for discovery in Settings → Plugins.
34
76
 
35
- `create` receives `{ store, files, notifications, signal }`. Keep discovery free of effects and return stable descriptors. Actions have no persistent background instance.
77
+ Labels and metadata use `{ en: string, it?: string, 'zh-CN'?: string }`, with English required as the fallback.
36
78
 
37
- - `store.getState()` and `subscribe()` are synchronous. Narrow with `'viewGraph' in state` before accessing invocation data. Actions always receive the invoked view; invoking on All exposes the complete graph.
38
- - Await write helpers such as `setConceptLabel`, `addConcept`, and `setViewMembership`. Use `applyOperations(operations, { atRevision })` for one atomic, revision-checked batch. Separate calls are separate transactions; never retry mutations automatically.
39
- - Receiving the invoked view is not a write sandbox. Declared writes can affect the whole document.
40
- - `run({ viewId })` keeps its invocation target despite navigation; `null` means All. Target deletion or document reset revokes the context. Use `refresh()` after deferred work and honor `signal`.
41
- - `files.open()`/`save()` mediate UTF-8 text files up to 16 MiB through the host, returning `null`/`{ saved: false }` on cancellation. `notifications.notify()` posts internal `info`/`warning` messages. Each effect requires its declared capability and must be awaited before returning.
79
+ ### Build and test
42
80
 
43
- Failures reject with `PluginError`, carrying `code` and bounded `issues`. Public types, validators, and tests define the full contract and limits: see `src/runtime.ts`, `src/definitions.ts`, and `test/`.
81
+ Run `npm run build`, then follow the example's [local testing instructions](example/README.md#test-an-unpublished-build).
44
82
 
45
- ## Installation and isolation
83
+ Actions must ship one self-contained browser ES module with dependencies bundled; the example's build handles this. Test and install external plugins in the desktop app.
46
84
 
47
- External installation is desktop-only; web runs bundled plugins only. Publish versioned npm packages; every installation pins an exact version and the host revalidates the received files. Nesso never installs dependencies or runs package scripts. For local development, see the example's `propose` call.
85
+ ## Action API
48
86
 
49
- Each action invocation runs in a fresh isolated worker; themes and vocabularies are validated data and never executed. Installation binds approval to the exact received content and its declarations; failed updates keep the previous installation.
87
+ Nesso passes `{ store, files, notifications, signal, viewId }` to `run` as `ActionContext`.
50
88
 
51
- The host validates requests and revokes effects before teardown. Plugins receive no Node, host DOM, credentials, arbitrary filesystem, or network access. Actions use interruptible workers; themes and vocabularies are validated data and never executed. This does not guarantee hard CPU/RAM containment or host responsiveness.
89
+ `create()` receives no arguments and returns an array of actions with unique lowercase kebab-case IDs, localized labels, optional icons, and `run(context)` handlers. Use `ActionIconName` for supported icons.
52
90
 
53
- ## SDK development
91
+ Keep graph reads and effects inside `run`. **Await every write, file dialog, and notification** before returning; the action ends when `run` finishes. Use `signal` to detect cancellation.
54
92
 
55
- From the Nesso repository:
93
+ ### Read the invoked view
56
94
 
57
- ```sh
58
- pnpm --dir packages/plugin build
59
- pnpm --dir packages/plugin pack --pack-destination /absolute/output
95
+ - `store.getState()` returns the latest readonly local snapshot synchronously and makes it the basis for subsequent writes.
96
+ - `await store.refresh()` fetches and reads a fresh snapshot. Use it after deferred work, such as a file dialog, before computing edits.
97
+ - `store.subscribe(listener)` notifies you of snapshot changes and returns an unsubscribe function. Read the new state with `getState()`.
98
+
99
+ The graph snapshot provides:
100
+
101
+ - `viewGraph`: `{ concepts, relations, relationTypes }` for the invoked view.
102
+ - `selected`: the invoked view's selection.
103
+ - `targetViewId`: the invoked view's ID, or `null` for All; navigation does not change the target.
104
+ - `activeVocab`: the current vocabulary, or `null`.
105
+
106
+ Concept and relation-type IDs are absolute IRIs. Relations are `{ source, predicate, target }` triples; use `JSON.stringify([source, predicate, target])` as their selection/write ID.
107
+
108
+ ### Write the graph
109
+
110
+ Call helpers on `store` and declare their operation kinds in `nesso.writes`:
111
+
112
+ | Helper | Required `writes` entry |
113
+ | --- | --- |
114
+ | `setConceptLabel(id, value)` | `concept.label` |
115
+ | `setConceptDescription(id, value)` | `concept.description` |
116
+ | `setConceptColor(id, value)` | `concept.color` |
117
+ | `setConceptBold(id, value)` | `concept.bold` |
118
+ | `setConceptItalic(id, value)` | `concept.italic` |
119
+ | `setConceptPosition(id, { x, y })` | `concept.position` |
120
+ | `setConceptPositions([{ id, position: { x, y } }])` | `concept.positions` |
121
+ | `addConcept(position?)` | `concept.add` |
122
+ | `removeConcept(id)` | `concept.remove` |
123
+ | `connect(source, target)` | `relation.connect` |
124
+ | `reconnectRelation(id, source, target)` | `relation.reconnect` |
125
+ | `setRelationType(id, typeId)` | `relation.type` |
126
+ | `createRelationType(id, label)` | `relation.type.create` |
127
+ | `removeRelation(id)` | `relation.remove` |
128
+ | `setSelection([{ kind, id }])` | `selection.set` |
129
+ | `setViewMembership(viewId, conceptId, included)` | `view.membership` |
130
+
131
+ `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.
132
+
133
+ For related edits, use `store.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.
134
+
135
+ 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.
136
+
137
+ The invoked view is **not a write sandbox**: permitted writes can affect the whole document. Only the operations listed above are available to plugins.
138
+
139
+ ### Files, notifications, and failures
140
+
141
+ | API | Required capability | Result |
142
+ | --- | --- | --- |
143
+ | `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files.open` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
144
+ | `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files.save` | `{ saved: boolean }`; cancellation returns `false`. |
145
+ | `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications.notify` | A notification ID. Tone is `info` or `warning`; description is optional. |
146
+
147
+ Files use UTF-8 text. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
148
+
149
+ 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.
150
+
151
+ ## Vocabularies
152
+
153
+ Set `nesso.kind` to `"vocab"`, `entry` to a package-local JSON file such as `"dist/definition.json"`, and both `writes` and `capabilities` to `[]`. Keep the same package metadata structure. The entry contains a `VocabDefinition`:
154
+
155
+ ```json
156
+ {
157
+ "id": "my-vocab",
158
+ "relationTypes": [
159
+ { "id": "urn:my-vocab:depends-on", "label": "depends on" }
160
+ ],
161
+ "defaultTypeId": "urn:my-vocab:depends-on"
162
+ }
60
163
  ```
61
164
 
62
- Use **pnpm pack** so workspace exports become compiled ESM and declarations. The SDK exposes `@nesso-how/plugin` for authors, `/runtime` for runtime validation/client code, and `/package` for package tooling. Consumers do not need other Nesso workspace packages.
165
+ Use stable absolute IRIs for relation types and choose a default from your own list. See [Base Vocab](../../plugins/base-vocab/) for a larger example.
166
+
167
+ ## Themes
168
+
169
+ Set `nesso.kind` to `"theme"`, point `entry` to your JSON definition, and use empty `writes` and `capabilities`. A `ThemeDefinition` contains:
170
+
171
+ - `id`: a lowercase kebab-case contribution ID.
172
+ - `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).
173
+ - `metrics`: `radius-control` and `radius-object` in pixels, and `duration-state` in milliseconds.
174
+ - `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"`.
175
+
176
+ Only light themes are supported. Use readable text contrast; arbitrary CSS and remote fonts are unsupported.
63
177
 
64
- Run `pnpm test` for contract tests and `pnpm test:plugin-runtime` for desktop/web integration checks.
178
+ For the full API and validation rules, see [action types](src/runtime.ts), [graph operations](src/types.ts), and [theme/vocabulary schemas](src/definitions.ts).
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as NessoOperation, B as Selection, D as LocalizedText, F as Notifications, G as ThemeDefinition, H as VocabDefinition, I as PanelSizes, L as Preferences, M as NessoStore, N as Notification, P as NotificationAction, R as SavedView, T as PluginError, U as WorkspaceState, V as Viewport, a as BaseState, c as PluginManifest, i as ActionState, j as NessoState, k as GraphSnapshot, l as ViewState, n as ActionContribution, o as PluginContext, r as ActionDescriptor, s as PluginI18n, t as ActionContext, w as createWriteCommands, z as SectionId } from "./runtime-CeTVu8np.js";
2
- export { type ActionContext, type ActionContribution, type ActionDescriptor, type ActionState, type BaseState, type GraphSnapshot, type LocalizedText, type NessoOperation, type NessoState, type NessoStore, type Notification, type NotificationAction, type Notifications, type PanelSizes, type PluginContext, PluginError, type PluginI18n, type PluginManifest, type Preferences, type SavedView, type SectionId, type Selection, type ThemeDefinition, type ViewState, type Viewport, type VocabDefinition, type WorkspaceState, createWriteCommands };
1
+ import { A as NessoState, B as Viewport, C as createWriteCommands, E as LocalizedText, F as PanelSizes, H as WorkspaceState, I as Preferences, L as SavedView, M as Notification, N as NotificationAction, O as GraphSnapshot, P as Notifications, R as SectionId, V as VocabDefinition, W as ThemeDefinition, a as ActionState, c as actionIconNames, i as ActionIconName, j as NessoStore, k as NessoOperation, n as ActionContribution, o as PluginI18n, r as ActionDescriptor, s as PluginManifest, t as ActionContext, w as PluginError, z as Selection } from "./runtime-NJhqaq_J.js";
2
+ export { type ActionContext, type ActionContribution, type ActionDescriptor, type ActionIconName, type ActionState, type GraphSnapshot, type LocalizedText, type NessoOperation, type NessoState, type NessoStore, type Notification, type NotificationAction, type Notifications, type PanelSizes, PluginError, type PluginI18n, type PluginManifest, type Preferences, type SavedView, type SectionId, type Selection, type ThemeDefinition, type Viewport, type VocabDefinition, type WorkspaceState, actionIconNames, createWriteCommands };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { i as PluginError, t as createWriteCommands } from "./commands-xXIv9QeH.js";
1
+ export { _ as PluginError, t as actionIconNames, g as createWriteCommands } from "./runtime-Dl8Rcuy8.js";
package/dist/package.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as PluginManifest, s as PluginI18n } from "./runtime-CeTVu8np.js";
1
+ import { o as PluginI18n, s as PluginManifest } from "./runtime-NJhqaq_J.js";
2
2
  //#region src/package.d.ts
3
3
  export declare const packageLimits: {
4
4
  readonly entry: number;
package/dist/package.js CHANGED
@@ -1,5 +1,4 @@
1
- import { a as parseOrThrow, i as PluginError } from "./commands-xXIv9QeH.js";
2
- import { a as parsePluginManifest, c as sha256Hex, i as parsePluginI18n, p as parseDefinition, t as checkMessageSize } from "./runtime-Dfjx2_F9.js";
1
+ import { _ as PluginError, a as parsePluginI18n, l as sha256Hex, m as parseDefinition, n as checkMessageSize, o as parsePluginManifest, v as parseOrThrow } from "./runtime-Dl8Rcuy8.js";
3
2
  import { z } from "zod";
4
3
  import parseVersion from "semver/functions/parse.js";
5
4
  import validateName from "validate-npm-package-name";
@@ -1,5 +1,204 @@
1
- import { a as parseOrThrow, i as PluginError, n as isAbsoluteIri, r as relationKey, t as createWriteCommands } from "./commands-xXIv9QeH.js";
2
1
  import { z } from "zod";
2
+ //#region ../errors/src/index.ts
3
+ var NessoError = class extends Error {
4
+ name = "NessoError";
5
+ issues;
6
+ constructor(issues) {
7
+ super(issues.map(({ path, message }) => path ? `${path}: ${message}` : message).join("\n"));
8
+ this.issues = issues;
9
+ }
10
+ };
11
+ //#endregion
12
+ //#region src/errors.ts
13
+ const boundText = (text, limit) => {
14
+ let result = "";
15
+ let bytes = 0;
16
+ const encoder = new TextEncoder();
17
+ for (const character of text) {
18
+ bytes += encoder.encode(character).byteLength;
19
+ if (bytes > limit) break;
20
+ result += character;
21
+ }
22
+ return result;
23
+ };
24
+ var PluginError = class extends NessoError {
25
+ name = "PluginError";
26
+ code;
27
+ displayMessage;
28
+ constructor(code, issues, displayMessage) {
29
+ const bounded = issues.slice(0, 32).map(({ path, message }) => ({
30
+ path: boundText(path, 256),
31
+ message: boundText(message, 2048)
32
+ }));
33
+ if (!bounded.length) bounded.push({
34
+ path: "plugin",
35
+ message: "Plugin request failed"
36
+ });
37
+ super(bounded);
38
+ this.code = code;
39
+ if (displayMessage) this.displayMessage = {
40
+ en: boundText(displayMessage.en, 2048),
41
+ ...displayMessage.it !== void 0 ? { it: boundText(displayMessage.it, 2048) } : {},
42
+ ...displayMessage["zh-CN"] !== void 0 ? { "zh-CN": boundText(displayMessage["zh-CN"], 2048) } : {}
43
+ };
44
+ }
45
+ };
46
+ function parseOrThrow(schema, value, prefix = "") {
47
+ const parsed = schema.safeParse(value);
48
+ if (!parsed.success) throw new PluginError("invalid-input", parsed.error.issues.map((issue) => ({
49
+ path: `${prefix}${issue.path.join(".")}`,
50
+ message: issue.message
51
+ })));
52
+ return parsed.data;
53
+ }
54
+ //#endregion
55
+ //#region ../schema/src/core.ts
56
+ const newIri = () => `urn:uuid:${crypto.randomUUID()}`;
57
+ const isAbsoluteIri = (value) => typeof value === "string" && /^[a-z][a-z0-9+.-]*:/i.test(value);
58
+ const relationKey = ({ source, predicate, target }) => JSON.stringify([
59
+ source,
60
+ predicate,
61
+ target
62
+ ]);
63
+ //#endregion
64
+ //#region src/commands.ts
65
+ function createWriteCommands(applyOperations, created) {
66
+ return {
67
+ undo: () => applyOperations([{ kind: "history.undo" }]),
68
+ redo: () => applyOperations([{ kind: "history.redo" }]),
69
+ setSelection: (value) => applyOperations([{
70
+ kind: "selection.set",
71
+ value
72
+ }]),
73
+ setView: (id) => applyOperations([{
74
+ kind: "view.activate",
75
+ id
76
+ }]),
77
+ setConceptPosition: (id, value, historyGroup) => applyOperations([{
78
+ kind: "concept.position",
79
+ id,
80
+ value
81
+ }], historyGroup ? { historyGroup } : void 0),
82
+ setConceptPositions: (updates, historyGroup) => applyOperations([{
83
+ kind: "concept.positions",
84
+ updates
85
+ }], historyGroup ? { historyGroup } : void 0),
86
+ setConceptLabel: (id, value, historyGroup) => applyOperations([{
87
+ kind: "concept.label",
88
+ id,
89
+ value
90
+ }], historyGroup ? { historyGroup } : void 0),
91
+ setConceptDescription: (id, value, historyGroup) => applyOperations([{
92
+ kind: "concept.description",
93
+ id,
94
+ value
95
+ }], historyGroup ? { historyGroup } : void 0),
96
+ setConceptColor: (id, value, historyGroup) => applyOperations([{
97
+ kind: "concept.color",
98
+ id,
99
+ value
100
+ }], historyGroup ? { historyGroup } : void 0),
101
+ setConceptBold: (id, value, historyGroup) => applyOperations([{
102
+ kind: "concept.bold",
103
+ id,
104
+ value
105
+ }], historyGroup ? { historyGroup } : void 0),
106
+ setConceptItalic: (id, value, historyGroup) => applyOperations([{
107
+ kind: "concept.italic",
108
+ id,
109
+ value
110
+ }], historyGroup ? { historyGroup } : void 0),
111
+ addConcept: (position, historyGroup) => {
112
+ const id = newIri();
113
+ return created(id, applyOperations([{
114
+ kind: "concept.add",
115
+ id,
116
+ position
117
+ }], historyGroup ? { historyGroup } : void 0));
118
+ },
119
+ connect: (source, target) => applyOperations([{
120
+ kind: "relation.connect",
121
+ source,
122
+ target
123
+ }]),
124
+ reconnectRelation: (id, source, target) => applyOperations([{
125
+ kind: "relation.reconnect",
126
+ id,
127
+ source,
128
+ target
129
+ }]),
130
+ setRelationType: (id, typeId) => applyOperations([{
131
+ kind: "relation.type",
132
+ id,
133
+ typeId
134
+ }]),
135
+ createRelationType: (id, label) => applyOperations([{
136
+ kind: "relation.type.create",
137
+ id,
138
+ typeId: newIri(),
139
+ label
140
+ }]),
141
+ removeConcept: (id) => applyOperations([{
142
+ kind: "concept.remove",
143
+ id
144
+ }]),
145
+ removeRelation: (id) => applyOperations([{
146
+ kind: "relation.remove",
147
+ id
148
+ }]),
149
+ setActiveVocab: (id) => applyOperations([{
150
+ kind: "preferences.vocab",
151
+ id
152
+ }]),
153
+ setActiveTheme: (id) => applyOperations([{
154
+ kind: "preferences.theme",
155
+ id
156
+ }]),
157
+ setLocale: (value) => applyOperations([{
158
+ kind: "preferences.locale",
159
+ value
160
+ }]),
161
+ setPanelSizes: (value) => applyOperations([{
162
+ kind: "preferences.panels",
163
+ value
164
+ }]),
165
+ setSectionOpen: (id, open) => applyOperations([{
166
+ kind: "preferences.section",
167
+ id,
168
+ open
169
+ }]),
170
+ createView: (name, conceptIds) => {
171
+ const id = newIri();
172
+ return created(id, applyOperations([{
173
+ kind: "view.create",
174
+ id,
175
+ name,
176
+ conceptIds
177
+ }]));
178
+ },
179
+ renameView: (id, name) => applyOperations([{
180
+ kind: "view.rename",
181
+ id,
182
+ name
183
+ }]),
184
+ setViewPinned: (id, pinned) => applyOperations([{
185
+ kind: "view.pin",
186
+ id,
187
+ pinned
188
+ }]),
189
+ setViewMembership: (viewId, conceptId, included) => applyOperations([{
190
+ kind: "view.membership",
191
+ viewId,
192
+ conceptId,
193
+ included
194
+ }]),
195
+ deleteView: (id) => applyOperations([{
196
+ kind: "view.remove",
197
+ id
198
+ }])
199
+ };
200
+ }
201
+ //#endregion
3
202
  //#region ../schema/src/validate.ts
4
203
  function validateGraph(graph) {
5
204
  const issues = [];
@@ -28,6 +227,14 @@ function validateGraph(graph) {
28
227
  path: `concepts[${index}].color`,
29
228
  message: `Invalid color: ${concept.id}`
30
229
  });
230
+ if (concept.bold !== void 0 && typeof concept.bold !== "boolean") issues.push({
231
+ path: `concepts[${index}].bold`,
232
+ message: "Expected a boolean"
233
+ });
234
+ if (concept.italic !== void 0 && typeof concept.italic !== "boolean") issues.push({
235
+ path: `concepts[${index}].italic`,
236
+ message: "Expected a boolean"
237
+ });
31
238
  }
32
239
  for (const [index, type] of graph.relationTypes.entries()) {
33
240
  if (!isAbsoluteIri(type.id)) issues.push({
@@ -247,6 +454,16 @@ const operation = z.discriminatedUnion("kind", [
247
454
  id,
248
455
  value: z.string()
249
456
  }),
457
+ z.strictObject({
458
+ kind: z.literal("concept.bold"),
459
+ id,
460
+ value: z.boolean()
461
+ }),
462
+ z.strictObject({
463
+ kind: z.literal("concept.italic"),
464
+ id,
465
+ value: z.boolean()
466
+ }),
250
467
  z.strictObject({
251
468
  kind: z.literal("concept.position"),
252
469
  id,
@@ -364,10 +581,7 @@ const operation = z.discriminatedUnion("kind", [
364
581
  open: z.boolean()
365
582
  })
366
583
  ]);
367
- const options = z.strictObject({
368
- historyGroup: id.optional(),
369
- atRevision: z.number().int().nonnegative().optional()
370
- });
584
+ const options = z.strictObject({ historyGroup: id.optional() });
371
585
  const metadata = z.strictObject({
372
586
  name: localizedText(128),
373
587
  description: localizedText(2048),
@@ -385,6 +599,8 @@ const operationDeclarations = z.array(z.enum([
385
599
  "concept.label",
386
600
  "concept.description",
387
601
  "concept.color",
602
+ "concept.bold",
603
+ "concept.italic",
388
604
  "concept.position",
389
605
  "concept.positions",
390
606
  "concept.add",
@@ -429,6 +645,7 @@ const request = z.discriminatedUnion("method", [
429
645
  method: z.literal("store.applyOperations"),
430
646
  params: z.strictObject({
431
647
  operations: z.array(operation).max(5e4),
648
+ revision: z.number().int().nonnegative(),
432
649
  options: options.optional()
433
650
  })
434
651
  }),
@@ -498,8 +715,30 @@ const message = z.union([
498
715
  const actionDescriptor = z.strictObject({
499
716
  id: z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
500
717
  label: localizedText(128),
501
- supportsViews: z.boolean()
718
+ icon: z.string().min(1).max(32).regex(/^[a-z]+(?:-[a-z]+)*$/).optional()
502
719
  });
720
+ const actionIconNames = [
721
+ "arrow-right",
722
+ "book-open",
723
+ "clipboard-paste",
724
+ "copy",
725
+ "download",
726
+ "file-down",
727
+ "file-up",
728
+ "folder",
729
+ "globe",
730
+ "layers",
731
+ "pencil",
732
+ "play",
733
+ "plus",
734
+ "refresh",
735
+ "scissors",
736
+ "search",
737
+ "share",
738
+ "sparkles",
739
+ "upload",
740
+ "zap"
741
+ ];
503
742
  const actionDescriptors = z.array(actionDescriptor).min(1).max(64).refine((value) => new Set(value.map(({ id }) => id)).size === value.length, "Action IDs must be unique");
504
743
  function parseContribution(kind, value) {
505
744
  checkMessageSize(value, 1048576);
@@ -512,6 +751,8 @@ const graph = z.strictObject({
512
751
  label: z.string(),
513
752
  description: z.string().optional(),
514
753
  color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
754
+ bold: z.boolean().optional(),
755
+ italic: z.boolean().optional(),
515
756
  position
516
757
  })),
517
758
  relationTypes: z.array(relationType),
@@ -521,14 +762,12 @@ const graph = z.strictObject({
521
762
  target: id
522
763
  }))
523
764
  });
524
- const baseStateSchema = z.strictObject({
765
+ const actionStateSchema = z.strictObject({
525
766
  revision: z.number().int().nonnegative(),
526
767
  contextId: id,
527
768
  locale,
528
769
  theme: z.strictObject(Object.fromEntries(themeTokens.map((token) => [token, z.string().max(512).regex(/^[#\w\s.,()%/"'-]*$/)]))),
529
- conceptPlacementOffset: position
530
- });
531
- const viewStateSchema = baseStateSchema.extend({
770
+ conceptPlacementOffset: position,
532
771
  viewGraph: graph,
533
772
  selected: selection,
534
773
  targetViewId: id.nullable(),
@@ -546,15 +785,14 @@ const viewStateSchema = baseStateSchema.extend({
546
785
  savedViews: z.array(z.strictObject({
547
786
  id,
548
787
  name: z.string(),
549
- pinned: z.boolean(),
550
- conceptIds: z.array(id).optional()
788
+ pinned: z.boolean()
551
789
  }))
552
790
  })
553
791
  });
554
- const replies = (state) => z.union([
792
+ const reply = z.union([
555
793
  z.strictObject({
556
794
  type: z.literal("state"),
557
- state
795
+ state: actionStateSchema
558
796
  }),
559
797
  z.strictObject({
560
798
  type: z.literal("response"),
@@ -568,11 +806,6 @@ const replies = (state) => z.union([
568
806
  ok: z.literal(false),
569
807
  error: wireError
570
808
  }),
571
- z.strictObject({
572
- type: z.literal("invoke"),
573
- actionId: id,
574
- invocation: z.strictObject({ viewId: id.nullable() })
575
- }),
576
809
  z.strictObject({
577
810
  type: z.literal("close"),
578
811
  reason: z.string().max(2048)
@@ -626,9 +859,8 @@ function checkMessageSize(value, limit) {
626
859
  }]);
627
860
  }
628
861
  function createPluginClient(port, initial) {
629
- const schema = "viewGraph" in initial ? viewStateSchema : baseStateSchema;
630
- const reply = replies(schema);
631
- let state = parseOrThrow(schema, initial);
862
+ let state = parseOrThrow(actionStateSchema, initial);
863
+ let readRevision = state.revision;
632
864
  let sequence = 0;
633
865
  const listeners = /* @__PURE__ */ new Set();
634
866
  const controller = new AbortController();
@@ -725,10 +957,19 @@ function createPluginClient(port, initial) {
725
957
  };
726
958
  port.onmessageerror = close;
727
959
  port.start();
728
- const applyOperations = (operations, options) => call("store.applyOperations", {
729
- operations,
730
- ...options ? { options } : {}
731
- });
960
+ const getState = () => {
961
+ readRevision = state.revision;
962
+ return state;
963
+ };
964
+ const applyOperations = async (operations, options) => {
965
+ const result = await call("store.applyOperations", {
966
+ operations,
967
+ revision: readRevision,
968
+ ...options ? { options } : {}
969
+ });
970
+ readRevision = Math.max(readRevision, result.revision);
971
+ return result;
972
+ };
732
973
  const { undo: _undo, redo: _redo, setView: _view, setActiveVocab: _vocab, setActiveTheme: _theme, setLocale: _locale, setPanelSizes: _panels, setSectionOpen: _section, createView: _createView, renameView: _renameView, setViewPinned: _pin, deleteView: _deleteView, ...writes } = createWriteCommands(async (operations, options) => {
733
974
  await applyOperations(operations, options);
734
975
  }, async (id, committed) => {
@@ -737,16 +978,17 @@ function createPluginClient(port, initial) {
737
978
  });
738
979
  return {
739
980
  context: {
981
+ viewId: state.targetViewId,
740
982
  store: {
741
983
  ...writes,
742
- getState: () => state,
984
+ getState,
743
985
  subscribe: (listener) => {
744
986
  listeners.add(listener);
745
987
  return () => listeners.delete(listener);
746
988
  },
747
989
  refresh: async () => {
748
990
  await call("store.refresh", {});
749
- return state;
991
+ return getState();
750
992
  },
751
993
  applyOperations
752
994
  },
@@ -761,4 +1003,4 @@ function createPluginClient(port, initial) {
761
1003
  };
762
1004
  }
763
1005
  //#endregion
764
- export { parsePluginManifest as a, sha256Hex as c, fileTextLimit as d, parseFileOptions as f, parsePluginI18n as i, themeTokens as l, themeColors as m, createPluginClient as n, parsePluginMessage as o, parseDefinition as p, parseContribution as r, runtimeLimits as s, checkMessageSize as t, resolvePluginText as u };
1006
+ export { PluginError as _, parsePluginI18n as a, runtimeLimits as c, resolvePluginText as d, fileTextLimit as f, createWriteCommands as g, themeColors as h, parseContribution as i, sha256Hex as l, parseDefinition as m, checkMessageSize as n, parsePluginManifest as o, parseFileOptions as p, createPluginClient as r, parsePluginMessage as s, actionIconNames as t, themeTokens as u, parseOrThrow as v };
@@ -20,6 +20,8 @@ type Concept = {
20
20
  label: string;
21
21
  description?: string;
22
22
  color?: string;
23
+ bold?: boolean;
24
+ italic?: boolean;
23
25
  position: Position;
24
26
  };
25
27
  type RelationType = {
@@ -119,6 +121,14 @@ type NessoOperation = {
119
121
  readonly kind: 'concept.color';
120
122
  readonly id: string;
121
123
  readonly value: string;
124
+ } | {
125
+ readonly kind: 'concept.bold';
126
+ readonly id: string;
127
+ readonly value: boolean;
128
+ } | {
129
+ readonly kind: 'concept.italic';
130
+ readonly id: string;
131
+ readonly value: boolean;
122
132
  } | {
123
133
  readonly kind: 'concept.position';
124
134
  readonly id: string;
@@ -279,6 +289,8 @@ type NessoStore = {
279
289
  readonly setConceptLabel: (id: string, label: string, historyGroup?: string) => void;
280
290
  readonly setConceptDescription: (id: string, description: string, historyGroup?: string) => void;
281
291
  readonly setConceptColor: (id: string, color: string, historyGroup?: string) => void;
292
+ readonly setConceptBold: (id: string, value: boolean, historyGroup?: string) => void;
293
+ readonly setConceptItalic: (id: string, value: boolean, historyGroup?: string) => void;
282
294
  readonly addConcept: (position?: Readonly<Position>, historyGroup?: string) => string;
283
295
  readonly connect: (source: string, target: string) => void;
284
296
  readonly reconnectRelation: (id: string, source: string, target: string) => void;
@@ -403,8 +415,10 @@ declare const manifest: z.ZodDiscriminatedUnion<[z.ZodObject<{
403
415
  entry: z.ZodString;
404
416
  writes: z.ZodArray<z.ZodEnum<{
405
417
  "concept.add": "concept.add";
418
+ "concept.bold": "concept.bold";
406
419
  "concept.color": "concept.color";
407
420
  "concept.description": "concept.description";
421
+ "concept.italic": "concept.italic";
408
422
  "concept.label": "concept.label";
409
423
  "concept.position": "concept.position";
410
424
  "concept.positions": "concept.positions";
@@ -449,6 +463,14 @@ declare const message: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject
449
463
  kind: z.ZodLiteral<"concept.color">;
450
464
  id: z.ZodString;
451
465
  value: z.ZodString;
466
+ }, z.core.$strict>, z.ZodObject<{
467
+ kind: z.ZodLiteral<"concept.bold">;
468
+ id: z.ZodString;
469
+ value: z.ZodBoolean;
470
+ }, z.core.$strict>, z.ZodObject<{
471
+ kind: z.ZodLiteral<"concept.italic">;
472
+ id: z.ZodString;
473
+ value: z.ZodBoolean;
452
474
  }, z.core.$strict>, z.ZodObject<{
453
475
  kind: z.ZodLiteral<"concept.position">;
454
476
  id: z.ZodString;
@@ -569,9 +591,9 @@ declare const message: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject
569
591
  }>;
570
592
  open: z.ZodBoolean;
571
593
  }, z.core.$strict>], "kind">>;
594
+ revision: z.ZodNumber;
572
595
  options: z.ZodOptional<z.ZodObject<{
573
596
  historyGroup: z.ZodOptional<z.ZodString>;
574
- atRevision: z.ZodOptional<z.ZodNumber>;
575
597
  }, z.core.$strict>>;
576
598
  }, z.core.$strict>;
577
599
  }, z.core.$strict>, z.ZodObject<{
@@ -662,17 +684,17 @@ declare const actionDescriptor: z.ZodObject<{
662
684
  it: z.ZodOptional<z.ZodString>;
663
685
  'zh-CN': z.ZodOptional<z.ZodString>;
664
686
  }, z.core.$strict>;
665
- supportsViews: z.ZodBoolean;
687
+ icon: z.ZodOptional<z.ZodString>;
666
688
  }, z.core.$strict>;
689
+ declare const actionIconNames: readonly ['arrow-right', 'book-open', 'clipboard-paste', 'copy', 'download', 'file-down', 'file-up', 'folder', 'globe', 'layers', 'pencil', 'play', 'plus', 'refresh', 'scissors', 'search', 'share', 'sparkles', 'upload', 'zap'];
690
+ type ActionIconName = typeof actionIconNames[number];
667
691
  type ActionDescriptor = DeepReadonly<z.infer<typeof actionDescriptor>>;
668
692
  type ActionContribution = ActionDescriptor & {
669
- readonly run: (invocation: {
670
- readonly viewId: string | null;
671
- }) => void | Promise<void>;
693
+ readonly run: (context: ActionContext) => void | Promise<void>;
672
694
  };
673
695
  declare function parseContribution(kind: 'theme' | 'vocab', value: unknown): Definition;
674
696
  declare function parseContribution(kind: 'actions', value: unknown): readonly ActionDescriptor[];
675
- type BaseState = {
697
+ type ActionState = {
676
698
  readonly revision: number;
677
699
  readonly contextId: string;
678
700
  readonly locale: Locale;
@@ -681,8 +703,6 @@ type BaseState = {
681
703
  x: number;
682
704
  y: number;
683
705
  }>;
684
- };
685
- type ViewState = BaseState & {
686
706
  readonly viewGraph: GraphSnapshot;
687
707
  readonly selected: Selection;
688
708
  readonly workspace: {
@@ -696,17 +716,16 @@ type ViewState = BaseState & {
696
716
  readonly canRedo: boolean;
697
717
  };
698
718
  };
699
- type ActionState = BaseState | ViewState;
700
719
  type WriteOptions = {
701
720
  readonly historyGroup?: string;
702
- readonly atRevision?: number;
703
721
  };
704
722
  type PluginWrites = Omit<ReturnType<typeof createWriteCommands<Promise<void>, Promise<string>>>, 'undo' | 'redo' | 'setView' | 'setActiveVocab' | 'setActiveTheme' | 'setLocale' | 'setPanelSizes' | 'setSectionOpen' | 'createView' | 'renameView' | 'setViewPinned' | 'deleteView'>;
705
- type PluginContext<S extends BaseState = BaseState> = {
723
+ type ActionContext = {
724
+ readonly viewId: string | null;
706
725
  readonly store: PluginWrites & {
707
- readonly getState: () => S;
726
+ readonly getState: () => ActionState;
708
727
  readonly subscribe: (listener: () => void) => () => void;
709
- readonly refresh: () => Promise<S>;
728
+ readonly refresh: () => Promise<ActionState>;
710
729
  readonly applyOperations: (operations: readonly NessoOperation[], options?: WriteOptions) => Promise<{
711
730
  readonly revision: number;
712
731
  readonly changed: boolean;
@@ -727,13 +746,12 @@ type PluginContext<S extends BaseState = BaseState> = {
727
746
  };
728
747
  readonly signal: AbortSignal;
729
748
  };
730
- type ActionContext = PluginContext<ActionState>;
731
749
  declare function parsePluginMessage(value: unknown): z.infer<typeof message>;
732
750
  declare function sha256Hex(bytes: Uint8Array): Promise<string>;
733
751
  declare function checkMessageSize(value: unknown, limit: number): void;
734
- declare function createPluginClient<S extends BaseState>(port: MessagePort, initial: S): {
735
- context: PluginContext<S>;
752
+ declare function createPluginClient(port: MessagePort, initial: unknown): {
753
+ context: ActionContext;
736
754
  close: () => void;
737
755
  };
738
756
  //#endregion
739
- export { NessoOperation as A, Selection as B, parseFileOptions as C, LocalizedText as D, parseOrThrow as E, Notifications as F, ThemeDefinition as G, VocabDefinition as H, PanelSizes as I, parseDefinition as K, Preferences as L, NessoStore as M, Notification as N, resolvePluginText as O, NotificationAction as P, SavedView as R, fileTextLimit as S, PluginError as T, WorkspaceState as U, Viewport as V, Definition as W, sha256Hex as _, BaseState as a, FileOpenResult as b, PluginManifest as c, createPluginClient as d, parseContribution as f, runtimeLimits as g, parsePluginMessage as h, ActionState as i, NessoState as j, GraphSnapshot as k, ViewState as l, parsePluginManifest as m, ActionContribution as n, PluginContext as o, parsePluginI18n as p, themeColors as q, ActionDescriptor as r, PluginI18n as s, ActionContext as t, checkMessageSize as u, themeTokens as v, createWriteCommands as w, FileSaveOptions as x, FileOpenOptions as y, SectionId as z };
757
+ export { NessoState as A, Viewport as B, createWriteCommands as C, resolvePluginText as D, LocalizedText as E, PanelSizes as F, parseDefinition as G, WorkspaceState as H, Preferences as I, themeColors as K, SavedView as L, Notification as M, NotificationAction as N, GraphSnapshot as O, Notifications as P, SectionId as R, parseFileOptions as S, parseOrThrow as T, Definition as U, VocabDefinition as V, ThemeDefinition as W, themeTokens as _, ActionState as a, FileSaveOptions as b, actionIconNames as c, parseContribution as d, parsePluginI18n as f, sha256Hex as g, runtimeLimits as h, ActionIconName as i, NessoStore as j, NessoOperation as k, checkMessageSize as l, parsePluginMessage as m, ActionContribution as n, PluginI18n as o, parsePluginManifest as p, ActionDescriptor as r, PluginManifest as s, ActionContext as t, createPluginClient as u, FileOpenOptions as v, PluginError as w, fileTextLimit as x, FileOpenResult as y, Selection as z };
package/dist/runtime.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as parseFileOptions, D as LocalizedText, E as parseOrThrow, K as parseDefinition, O as resolvePluginText, S as fileTextLimit, T as PluginError, W as Definition, _ as sha256Hex, a as BaseState, b as FileOpenResult, c as PluginManifest, d as createPluginClient, f as parseContribution, g as runtimeLimits, h as parsePluginMessage, i as ActionState, l as ViewState, m as parsePluginManifest, n as ActionContribution, o as PluginContext, p as parsePluginI18n, q as themeColors, r as ActionDescriptor, s as PluginI18n, t as ActionContext, u as checkMessageSize, v as themeTokens, x as FileSaveOptions, y as FileOpenOptions } from "./runtime-CeTVu8np.js";
2
- export { ActionContext, ActionContribution, ActionDescriptor, ActionState, BaseState, type Definition, type FileOpenOptions, type FileOpenResult, type FileSaveOptions, type LocalizedText, PluginContext, PluginError, PluginI18n, PluginManifest, ViewState, checkMessageSize, createPluginClient, fileTextLimit, parseContribution, parseDefinition, parseFileOptions, parseOrThrow, parsePluginI18n, parsePluginManifest, parsePluginMessage, resolvePluginText, runtimeLimits, sha256Hex, themeColors, themeTokens };
1
+ import { D as resolvePluginText, E as LocalizedText, G as parseDefinition, K as themeColors, S as parseFileOptions, T as parseOrThrow, U as Definition, _ as themeTokens, a as ActionState, b as FileSaveOptions, c as actionIconNames, d as parseContribution, f as parsePluginI18n, g as sha256Hex, h as runtimeLimits, i as ActionIconName, l as checkMessageSize, m as parsePluginMessage, n as ActionContribution, o as PluginI18n, p as parsePluginManifest, r as ActionDescriptor, s as PluginManifest, t as ActionContext, u as createPluginClient, v as FileOpenOptions, w as PluginError, x as fileTextLimit, y as FileOpenResult } from "./runtime-NJhqaq_J.js";
2
+ export { ActionContext, ActionContribution, ActionDescriptor, ActionIconName, ActionState, type Definition, type FileOpenOptions, type FileOpenResult, type FileSaveOptions, type LocalizedText, PluginError, PluginI18n, PluginManifest, actionIconNames, checkMessageSize, createPluginClient, fileTextLimit, parseContribution, parseDefinition, parseFileOptions, parseOrThrow, parsePluginI18n, parsePluginManifest, parsePluginMessage, resolvePluginText, runtimeLimits, sha256Hex, themeColors, themeTokens };
package/dist/runtime.js CHANGED
@@ -1,3 +1 @@
1
- import { a as parseOrThrow, i as PluginError } from "./commands-xXIv9QeH.js";
2
- import { a as parsePluginManifest, c as sha256Hex, d as fileTextLimit, f as parseFileOptions, i as parsePluginI18n, l as themeTokens, m as themeColors, n as createPluginClient, o as parsePluginMessage, p as parseDefinition, r as parseContribution, s as runtimeLimits, t as checkMessageSize, u as resolvePluginText } from "./runtime-Dfjx2_F9.js";
3
- export { PluginError, checkMessageSize, createPluginClient, fileTextLimit, parseContribution, parseDefinition, parseFileOptions, parseOrThrow, parsePluginI18n, parsePluginManifest, parsePluginMessage, resolvePluginText, runtimeLimits, sha256Hex, themeColors, themeTokens };
1
+ export { _ as PluginError, t as actionIconNames, n as checkMessageSize, r as createPluginClient, f as fileTextLimit, i as parseContribution, m as parseDefinition, p as parseFileOptions, v as parseOrThrow, a as parsePluginI18n, o as parsePluginManifest, s as parsePluginMessage, d as resolvePluginText, c as runtimeLimits, l as sha256Hex, h as themeColors, u as themeTokens } from "./runtime-Dl8Rcuy8.js";
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Omar Desogus and Paolo Manfredotti
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/example/README.md CHANGED
@@ -1,24 +1,36 @@
1
1
  # Uppercase labels
2
2
 
3
- Uppercases labels in the invoked view with one undoable batch. Shared concepts change in every view containing them.
3
+ The official Nesso action plugin example, published as [`@nesso-how/plugin-example`](https://www.npmjs.com/package/@nesso-how/plugin-example). It uppercases labels in the invoked view with one undoable batch. Shared concepts change in every view containing them.
4
4
 
5
- Copy this directory outside the workspace, then install the published SDK and build:
5
+ ## Install and try
6
+
7
+ In the desktop app, open Settings → Plugins, search for `@nesso-how/plugin-example`, and install it. Approve its declared access to concept labels.
8
+
9
+ Run **Uppercase labels** from a view's context menu in the Explorer, or from the view's actions in the Inspector with no concepts or relations selected. Use Undo to restore the original labels.
10
+
11
+ ## Build your own
12
+
13
+ Copy this example into a separate project, then install dependencies and build:
6
14
 
7
15
  ```sh
8
- npm install --save-dev @nesso-how/plugin@^0.1.0
16
+ npm install
9
17
  npm run build
10
18
  ```
11
19
 
12
- The build typechecks and bundles `src/index.ts` and its package metadata into `dist/index.js`. Choose your own package name and action ID before publishing.
20
+ The build typechecks `src/index.ts` and bundles it with the package metadata into a self-contained `dist/index.js`.
21
+
22
+ Choose your own package name and action ID before publishing a derived plugin.
23
+
24
+ ## Test an unpublished build
13
25
 
14
- To try it in desktop DevTools, set `manifest` to your parsed `package.json` and `compiledCode` to the text of `dist/index.js`:
26
+ Open `package.json` and `dist/index.js` in a text editor. In desktop DevTools, set `manifest` to the parsed package JSON and `compiledCode` to the bundled JavaScript as a string:
15
27
 
16
28
  ```ts
17
- await window.nessoPlugins.propose(
29
+ const result = await window.nessoPlugins.propose(
18
30
  crypto.randomUUID(),
19
31
  { manifest, files: [{ path: manifest.nesso.entry, bytes: new TextEncoder().encode(compiledCode) }] },
20
32
  'en'
21
33
  )
22
34
  ```
23
35
 
24
- Approve the Nesso access dialog. Installation persists; disable or remove it in Settings. To replace a build, pass its installed `contentId` as the fourth argument; development proposals require fresh approval.
36
+ Approve the Nesso access dialog. Installation persists. On success, `result.value` contains the installed package; it is `null` if approval is declined. Failures return `result.issues`. To replace a build, pass the installed package's `contentId` as the fourth argument; development proposals require fresh approval.
@@ -1,17 +1,27 @@
1
1
  {
2
- "name": "nesso-plugin-uppercase",
3
- "version": "1.0.0",
2
+ "name": "@nesso-how/plugin-example",
3
+ "version": "0.3.0",
4
4
  "description": "Uppercase concept labels in the invoked Nesso view",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nesso-how/nesso.git",
9
+ "directory": "packages/plugin/example"
10
+ },
6
11
  "type": "module",
7
12
  "keywords": ["nesso-plugin"],
8
- "files": ["dist"],
13
+ "files": ["dist", "src", "tsconfig.json"],
9
14
  "scripts": {
10
15
  "check": "tsc",
11
- "build": "npm run check && esbuild src/index.ts --bundle --format=esm --platform=browser --target=es2022 --outfile=dist/index.js"
16
+ "build": "npm run check && esbuild src/index.ts --bundle --format=esm --platform=browser --target=es2022 --outfile=dist/index.js",
17
+ "prepack": "npm run build"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "registry": "https://registry.npmjs.org/"
12
22
  },
13
23
  "devDependencies": {
14
- "@nesso-how/plugin": "^0.1.0",
24
+ "@nesso-how/plugin": "0.3.0",
15
25
  "esbuild": "^0.28.2",
16
26
  "typescript": "~7.0.2"
17
27
  },
@@ -1,14 +1,22 @@
1
- import type { ActionContext, ActionContribution, NessoOperation } from '@nesso-how/plugin'
1
+ import type { ActionContribution, NessoOperation } from '@nesso-how/plugin'
2
2
  import source from '../package.json' with { type: 'json' }
3
3
 
4
- export const create = ({ store }: ActionContext): readonly ActionContribution[] => [{
5
- id: 'uppercase-labels',
6
- label: source.i18n.metadata.name,
7
- supportsViews: true,
8
- run: async () => {
9
- const state = store.getState()
10
- if (!('viewGraph' in state)) return
11
- const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({ kind: 'concept.label', id, value: label.toUpperCase() }))
12
- await store.applyOperations(operations, { atRevision: state.revision })
13
- },
14
- }]
4
+ export const create = (): readonly ActionContribution[] => {
5
+ const action: ActionContribution = {
6
+ id: 'uppercase-labels',
7
+ label: source.i18n.metadata.name,
8
+ run: async ({ store }) => {
9
+ const state = store.getState()
10
+
11
+ const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({
12
+ kind: 'concept.label',
13
+ id,
14
+ value: label.toUpperCase(),
15
+ }))
16
+
17
+ await store.applyOperations(operations)
18
+ },
19
+ }
20
+
21
+ return [action]
22
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nesso-how/plugin",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Types, validation, and asynchronous clients for isolated Nesso plugins",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,191 +0,0 @@
1
- //#region ../errors/src/index.ts
2
- var NessoError = class extends Error {
3
- name = "NessoError";
4
- issues;
5
- constructor(issues) {
6
- super(issues.map(({ path, message }) => path ? `${path}: ${message}` : message).join("\n"));
7
- this.issues = issues;
8
- }
9
- };
10
- //#endregion
11
- //#region src/errors.ts
12
- const boundText = (text, limit) => {
13
- let result = "";
14
- let bytes = 0;
15
- const encoder = new TextEncoder();
16
- for (const character of text) {
17
- bytes += encoder.encode(character).byteLength;
18
- if (bytes > limit) break;
19
- result += character;
20
- }
21
- return result;
22
- };
23
- var PluginError = class extends NessoError {
24
- name = "PluginError";
25
- code;
26
- displayMessage;
27
- constructor(code, issues, displayMessage) {
28
- const bounded = issues.slice(0, 32).map(({ path, message }) => ({
29
- path: boundText(path, 256),
30
- message: boundText(message, 2048)
31
- }));
32
- if (!bounded.length) bounded.push({
33
- path: "plugin",
34
- message: "Plugin request failed"
35
- });
36
- super(bounded);
37
- this.code = code;
38
- if (displayMessage) this.displayMessage = {
39
- en: boundText(displayMessage.en, 2048),
40
- ...displayMessage.it !== void 0 ? { it: boundText(displayMessage.it, 2048) } : {},
41
- ...displayMessage["zh-CN"] !== void 0 ? { "zh-CN": boundText(displayMessage["zh-CN"], 2048) } : {}
42
- };
43
- }
44
- };
45
- function parseOrThrow(schema, value, prefix = "") {
46
- const parsed = schema.safeParse(value);
47
- if (!parsed.success) throw new PluginError("invalid-input", parsed.error.issues.map((issue) => ({
48
- path: `${prefix}${issue.path.join(".")}`,
49
- message: issue.message
50
- })));
51
- return parsed.data;
52
- }
53
- //#endregion
54
- //#region ../schema/src/core.ts
55
- const newIri = () => `urn:uuid:${crypto.randomUUID()}`;
56
- const isAbsoluteIri = (value) => typeof value === "string" && /^[a-z][a-z0-9+.-]*:/i.test(value);
57
- const relationKey = ({ source, predicate, target }) => JSON.stringify([
58
- source,
59
- predicate,
60
- target
61
- ]);
62
- //#endregion
63
- //#region src/commands.ts
64
- function createWriteCommands(applyOperations, created) {
65
- return {
66
- undo: () => applyOperations([{ kind: "history.undo" }]),
67
- redo: () => applyOperations([{ kind: "history.redo" }]),
68
- setSelection: (value) => applyOperations([{
69
- kind: "selection.set",
70
- value
71
- }]),
72
- setView: (id) => applyOperations([{
73
- kind: "view.activate",
74
- id
75
- }]),
76
- setConceptPosition: (id, value, historyGroup) => applyOperations([{
77
- kind: "concept.position",
78
- id,
79
- value
80
- }], historyGroup ? { historyGroup } : void 0),
81
- setConceptPositions: (updates, historyGroup) => applyOperations([{
82
- kind: "concept.positions",
83
- updates
84
- }], historyGroup ? { historyGroup } : void 0),
85
- setConceptLabel: (id, value, historyGroup) => applyOperations([{
86
- kind: "concept.label",
87
- id,
88
- value
89
- }], historyGroup ? { historyGroup } : void 0),
90
- setConceptDescription: (id, value, historyGroup) => applyOperations([{
91
- kind: "concept.description",
92
- id,
93
- value
94
- }], historyGroup ? { historyGroup } : void 0),
95
- setConceptColor: (id, value, historyGroup) => applyOperations([{
96
- kind: "concept.color",
97
- id,
98
- value
99
- }], historyGroup ? { historyGroup } : void 0),
100
- addConcept: (position, historyGroup) => {
101
- const id = newIri();
102
- return created(id, applyOperations([{
103
- kind: "concept.add",
104
- id,
105
- position
106
- }], historyGroup ? { historyGroup } : void 0));
107
- },
108
- connect: (source, target) => applyOperations([{
109
- kind: "relation.connect",
110
- source,
111
- target
112
- }]),
113
- reconnectRelation: (id, source, target) => applyOperations([{
114
- kind: "relation.reconnect",
115
- id,
116
- source,
117
- target
118
- }]),
119
- setRelationType: (id, typeId) => applyOperations([{
120
- kind: "relation.type",
121
- id,
122
- typeId
123
- }]),
124
- createRelationType: (id, label) => applyOperations([{
125
- kind: "relation.type.create",
126
- id,
127
- typeId: newIri(),
128
- label
129
- }]),
130
- removeConcept: (id) => applyOperations([{
131
- kind: "concept.remove",
132
- id
133
- }]),
134
- removeRelation: (id) => applyOperations([{
135
- kind: "relation.remove",
136
- id
137
- }]),
138
- setActiveVocab: (id) => applyOperations([{
139
- kind: "preferences.vocab",
140
- id
141
- }]),
142
- setActiveTheme: (id) => applyOperations([{
143
- kind: "preferences.theme",
144
- id
145
- }]),
146
- setLocale: (value) => applyOperations([{
147
- kind: "preferences.locale",
148
- value
149
- }]),
150
- setPanelSizes: (value) => applyOperations([{
151
- kind: "preferences.panels",
152
- value
153
- }]),
154
- setSectionOpen: (id, open) => applyOperations([{
155
- kind: "preferences.section",
156
- id,
157
- open
158
- }]),
159
- createView: (name, conceptIds) => {
160
- const id = newIri();
161
- return created(id, applyOperations([{
162
- kind: "view.create",
163
- id,
164
- name,
165
- conceptIds
166
- }]));
167
- },
168
- renameView: (id, name) => applyOperations([{
169
- kind: "view.rename",
170
- id,
171
- name
172
- }]),
173
- setViewPinned: (id, pinned) => applyOperations([{
174
- kind: "view.pin",
175
- id,
176
- pinned
177
- }]),
178
- setViewMembership: (viewId, conceptId, included) => applyOperations([{
179
- kind: "view.membership",
180
- viewId,
181
- conceptId,
182
- included
183
- }]),
184
- deleteView: (id) => applyOperations([{
185
- kind: "view.remove",
186
- id
187
- }])
188
- };
189
- }
190
- //#endregion
191
- export { parseOrThrow as a, PluginError as i, isAbsoluteIri as n, relationKey as r, createWriteCommands as t };