@nesso-how/plugin 0.3.1 → 0.4.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
@@ -21,8 +21,8 @@ export const create = (): readonly ActionContribution[] => {
21
21
  const action: ActionContribution = {
22
22
  id: 'uppercase-labels',
23
23
  label: source.i18n.metadata.name,
24
- run: async ({ store }) => {
25
- const state = store.getState()
24
+ run: async ({ document }) => {
25
+ const state = document.getState()
26
26
 
27
27
  const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({
28
28
  kind: 'concept.label',
@@ -30,7 +30,7 @@ export const create = (): readonly ActionContribution[] => {
30
30
  value: label.toUpperCase(),
31
31
  }))
32
32
 
33
- await store.applyOperations(operations)
33
+ await document.applyOperations(operations)
34
34
  },
35
35
  }
36
36
 
@@ -72,7 +72,7 @@ Keep the example's build configuration and set these fields in `package.json`:
72
72
  }
73
73
  ```
74
74
 
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.
75
+ Declare the operations your action uses in `writes`. The optional permissions listed in `capabilities` are `files`, `notifications`, and `storage`; each authorizes all methods of that API. All fields shown under `nesso` and `i18n.metadata` are required. Add the `nesso-plugin` keyword for discovery in Settings → Plugins.
76
76
 
77
77
  Labels and metadata use `{ en: string, it?: string, 'zh-CN'?: string }`, with English required as the fallback.
78
78
 
@@ -84,7 +84,7 @@ Actions must ship one self-contained browser ES module with dependencies bundled
84
84
 
85
85
  ## Action API
86
86
 
87
- Nesso passes `{ store, files, notifications, signal, viewId }` to `run` as `ActionContext`.
87
+ 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.
88
88
 
89
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.
90
90
 
@@ -92,9 +92,9 @@ Keep graph reads and effects inside `run`. **Await every write, file dialog, and
92
92
 
93
93
  ### Read the invoked view
94
94
 
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()`.
95
+ - `document.getState()` returns the latest readonly local snapshot synchronously and makes it the basis for subsequent writes.
96
+ - `await document.refresh()` fetches and reads a fresh snapshot. Use it after deferred work, such as a file dialog, before computing edits.
97
+ - `document.subscribe(listener)` notifies you of snapshot changes and returns an unsubscribe function. Read the new state with `getState()`.
98
98
 
99
99
  The graph snapshot provides:
100
100
 
@@ -107,7 +107,7 @@ Concept and relation-type IDs are absolute IRIs. Relations are `{ source, predic
107
107
 
108
108
  ### Write the graph
109
109
 
110
- Call helpers on `store` and declare their operation kinds in `nesso.writes`:
110
+ Call helpers on `document` and declare their operation kinds in `nesso.writes`:
111
111
 
112
112
  | Helper | Required `writes` entry |
113
113
  | --- | --- |
@@ -130,7 +130,7 @@ Call helpers on `store` and declare their operation kinds in `nesso.writes`:
130
130
 
131
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
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.
133
+ 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.
134
134
 
135
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
136
 
@@ -140,14 +140,64 @@ The invoked view is **not a write sandbox**: permitted writes can affect the who
140
140
 
141
141
  | API | Required capability | Result |
142
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. |
143
+ | `files.open({ extensions: ['json'], mimeTypes: ['application/json'] })` | `files` | `{ name, mediaType, text }`, or `null` on cancellation. Extensions omit the dot. |
144
+ | `files.save({ name: 'graph.json', mediaType: 'application/json', text })` | `files` | `{ saved: boolean }`; cancellation returns `false`. |
145
+ | `notifications.notify({ tone: 'info', title: { en: 'Done' }, description: { en: 'Labels updated' } })` | `notifications` | A notification ID. Tone is `info` or `warning`; description is optional. |
146
146
 
147
- Files use UTF-8 text. Plugins have no Node, host DOM, direct filesystem, clipboard, or network access.
147
+ 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.
148
148
 
149
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
150
 
151
+ ### Private persistent storage
152
+
153
+ 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.
154
+
155
+ ```ts
156
+ const records = await storage.list()
157
+
158
+ await storage.set('progress', { attempts: 1, answers: ['good'] }, concept.id)
159
+ await storage.set('settings', { enabled: true })
160
+ await storage.delete('progress', concept.id)
161
+ ```
162
+
163
+ `storage.list()` returns all records as an array. Each record has a `key`, a JSON `value`, and optionally a `conceptId`:
164
+
165
+ - Without `conceptId`, the record belongs to the document, for example plugin configuration.
166
+ - With `conceptId`, it belongs to that concept in the document. The same key can be used for different concepts and for document-level data.
167
+ - Views do not create storage namespaces. A concept's data is shared across all views containing it.
168
+ - Payloads belong to the plugin: the host does not interpret their fields or implement domain logic.
169
+
170
+ `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`.
171
+
172
+ 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.
173
+
174
+ 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.
175
+
176
+ #### Data lifecycle
177
+
178
+ - 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.
179
+ - Removing a view or changing membership does not delete concept data.
180
+ - Deleting a concept retains its records during the current app session so document Undo/Redo can recover it. Private storage changes themselves do not enter graph history.
181
+ - On startup, after the document and plugin storage restore successfully, Nesso removes records whose explicit `conceptId` is absent from the graph. Graph history does not survive restart. Cleanup is skipped after failed restoration and does not execute plugin code.
182
+ - Put data that should be cleaned with a concept, including its logs, inside concept-associated records. IDs embedded in arbitrary payloads are opaque and cannot be cleaned by the host.
183
+ - Disabling, uninstalling, replacing, or crashing a plugin does not delete its stored data. Startup reference cleanup still applies even when the plugin is absent.
184
+
185
+ #### Limits
186
+
187
+ Storage accepts finite JSON primitives, dense arrays, and plain objects, including `null`; not `undefined`, dates, maps, functions, cyclic data, or custom prototypes. Returned snapshots and stored payloads are independent copies.
188
+
189
+ | Budget | Limit |
190
+ | --- | --- |
191
+ | Record, encoded as UTF-8 JSON | 256 KiB |
192
+ | Namespace snapshot | 8 MiB |
193
+ | Total plugin storage per document | 64 MiB |
194
+ | Records per plugin | 10,000 |
195
+ | Plugin namespaces per document | 128 |
196
+ | Record nesting | 24 levels |
197
+ | Record key | 1–128 characters |
198
+
199
+ 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.
200
+
151
201
  ## Vocabularies
152
202
 
153
203
  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`:
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
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 };
1
+ import { A as createWriteCommands, B as NotificationAction, F as GraphSnapshot, G as SectionId, H as PanelSizes, I as NessoOperation, J as VocabDefinition, K as Selection, L as NessoState, N as LocalizedText, R as NessoStore, U as Preferences, V as Notifications, W as SavedView, Y as WorkspaceState, Z as ThemeDefinition, a as ActionState, b as PluginStorageRecord, c as actionIconNames, i as ActionIconName, j as PluginError, n as ActionContribution, o as PluginI18n, q as Viewport, r as ActionDescriptor, s as PluginManifest, t as ActionContext, v as PluginStorage, y as PluginStorageKey, z as Notification } from "./runtime-BrWPGuBB.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 PluginStorage, type PluginStorageKey, type PluginStorageRecord, 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 { _ as PluginError, t as actionIconNames, g as createWriteCommands } from "./runtime-Dl8Rcuy8.js";
1
+ export { x as PluginError, t as actionIconNames, b as createWriteCommands } from "./runtime-C-k6OiHL.js";
package/dist/package.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as PluginI18n, s as PluginManifest } from "./runtime-NJhqaq_J.js";
1
+ import { o as PluginI18n, s as PluginManifest } from "./runtime-BrWPGuBB.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,4 +1,4 @@
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";
1
+ import { S as parseOrThrow, a as parsePluginManifest, c as sha256Hex, i as parsePluginI18n, m as checkMessageSize, v as parseDefinition, x as PluginError } from "./runtime-C-k6OiHL.js";
2
2
  import { z } from "zod";
3
3
  import parseVersion from "semver/functions/parse.js";
4
4
  import validateName from "validate-npm-package-name";
@@ -376,6 +376,53 @@ type FileSaveOptions = z.infer<typeof fileSaveOptions>;
376
376
  type FileOpenResult = z.infer<typeof fileOpenResult>;
377
377
  declare function parseFileOptions<K extends 'open' | 'save'>(kind: K, value: unknown): K extends 'open' ? FileOpenOptions : FileSaveOptions;
378
378
  //#endregion
379
+ //#region src/storage.d.ts
380
+ declare const pluginStorageLimits: {
381
+ readonly record: number;
382
+ readonly namespace: number;
383
+ readonly total: number;
384
+ readonly records: 10000;
385
+ readonly namespaces: 128;
386
+ readonly depth: 24;
387
+ };
388
+ type JsonValue = null | string | number | boolean | readonly JsonValue[] | {
389
+ readonly [key: string]: JsonValue;
390
+ };
391
+ declare const pluginStorageKey: z.ZodObject<{
392
+ key: z.ZodString;
393
+ conceptId: z.ZodOptional<z.ZodString>;
394
+ }, z.core.$strict>;
395
+ declare const pluginStorageRecord: z.ZodObject<{
396
+ key: z.ZodString;
397
+ conceptId: z.ZodOptional<z.ZodString>;
398
+ value: z.ZodPipe<z.ZodCustom<JsonValue, JsonValue>, z.ZodTransform<string | number | boolean | readonly JsonValue[] | {
399
+ readonly [key: string]: JsonValue;
400
+ } | null, JsonValue>>;
401
+ }, z.core.$strict>;
402
+ declare const pluginStorageSnapshot: z.ZodObject<{
403
+ revision: z.ZodNumber;
404
+ records: z.ZodArray<z.ZodObject<{
405
+ key: z.ZodString;
406
+ conceptId: z.ZodOptional<z.ZodString>;
407
+ value: z.ZodPipe<z.ZodCustom<JsonValue, JsonValue>, z.ZodTransform<string | number | boolean | readonly JsonValue[] | {
408
+ readonly [key: string]: JsonValue;
409
+ } | null, JsonValue>>;
410
+ }, z.core.$strict>>;
411
+ }, z.core.$strict>;
412
+ type PluginStorageRecord = DeepReadonly<z.infer<typeof pluginStorageRecord>>;
413
+ type PluginStorageKey = DeepReadonly<z.infer<typeof pluginStorageKey>>;
414
+ type PluginStorage = {
415
+ readonly list: () => Promise<readonly PluginStorageRecord[]>;
416
+ readonly set: (key: string, value: PluginStorageRecord['value'], conceptId?: string) => Promise<boolean>;
417
+ readonly delete: (key: string, conceptId?: string) => Promise<boolean>;
418
+ };
419
+ declare function parsePluginStorageSnapshot(value: unknown): DeepReadonly<z.infer<typeof pluginStorageSnapshot>>;
420
+ declare function parsePluginStorageRecord(value: unknown): PluginStorageRecord;
421
+ declare function parsePluginStorageKey(value: unknown): PluginStorageKey;
422
+ //#endregion
423
+ //#region src/data.d.ts
424
+ declare function checkMessageSize(value: unknown, limit: number, maximumDepth?: number): void;
425
+ //#endregion
379
426
  //#region src/runtime.d.ts
380
427
  declare const runtimeLimits: {
381
428
  readonly request: number;
@@ -432,9 +479,9 @@ declare const manifest: z.ZodDiscriminatedUnion<[z.ZodObject<{
432
479
  "view.membership": "view.membership";
433
480
  }>>;
434
481
  capabilities: z.ZodArray<z.ZodEnum<{
435
- "files.open": "files.open";
436
- "files.save": "files.save";
437
- "notifications.notify": "notifications.notify";
482
+ files: "files";
483
+ notifications: "notifications";
484
+ storage: "storage";
438
485
  }>>;
439
486
  }, z.core.$strict>, ...z.ZodObject<{
440
487
  apiVersion: z.ZodLiteral<1>;
@@ -449,7 +496,7 @@ declare const message: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject
449
496
  type: z.ZodLiteral<"request">;
450
497
  id: z.ZodNumber;
451
498
  contextId: z.ZodString;
452
- method: z.ZodLiteral<"store.applyOperations">;
499
+ method: z.ZodLiteral<"document.applyOperations">;
453
500
  params: z.ZodObject<{
454
501
  operations: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
455
502
  kind: z.ZodLiteral<"concept.label">;
@@ -600,8 +647,131 @@ declare const message: z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject
600
647
  type: z.ZodLiteral<"request">;
601
648
  id: z.ZodNumber;
602
649
  contextId: z.ZodString;
603
- method: z.ZodLiteral<"store.refresh">;
650
+ method: z.ZodLiteral<"document.refresh">;
604
651
  params: z.ZodObject<{}, z.core.$strict>;
652
+ }, z.core.$strict>, z.ZodObject<{
653
+ type: z.ZodLiteral<"request">;
654
+ id: z.ZodNumber;
655
+ contextId: z.ZodString;
656
+ method: z.ZodLiteral<"storage.list">;
657
+ params: z.ZodObject<{}, z.core.$strict>;
658
+ }, z.core.$strict>, z.ZodObject<{
659
+ type: z.ZodLiteral<"request">;
660
+ id: z.ZodNumber;
661
+ contextId: z.ZodString;
662
+ method: z.ZodLiteral<"storage.set">;
663
+ params: z.ZodObject<{
664
+ key: z.ZodString;
665
+ conceptId: z.ZodOptional<z.ZodString>;
666
+ value: z.ZodPipe<z.ZodCustom<string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | /*elided*/ any | {
667
+ readonly [key: string]: string | number | boolean | /*elided*/ any | /*elided*/ any | null;
668
+ } | null)[] | {
669
+ readonly [key: string]: string | number | boolean | any | any | null;
670
+ } | null)[] | {
671
+ readonly [key: string]: string | number | boolean | any | any | null;
672
+ } | null)[] | {
673
+ readonly [key: string]: string | number | boolean | any | any | null;
674
+ } | null)[] | {
675
+ readonly [key: string]: string | number | boolean | any | any | null;
676
+ } | null)[] | {
677
+ readonly [key: string]: string | number | boolean | any | any | null;
678
+ } | null)[] | {
679
+ readonly [key: string]: string | number | boolean | any | any | null;
680
+ } | null)[] | {
681
+ readonly [key: string]: string | number | boolean | any | any | null;
682
+ } | null)[] | {
683
+ readonly [key: string]: string | number | boolean | any | any | null;
684
+ } | null)[] | {
685
+ readonly [key: string]: string | number | boolean | any | any | null;
686
+ } | null)[] | {
687
+ readonly [key: string]: string | number | boolean | any | any | null;
688
+ } | null)[] | {
689
+ readonly [key: string]: string | number | boolean | any | any | null;
690
+ } | null, string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | any | {
691
+ readonly [key: string]: string | number | boolean | any | any | null;
692
+ } | null)[] | {
693
+ readonly [key: string]: string | number | boolean | any | any | null;
694
+ } | null)[] | {
695
+ readonly [key: string]: string | number | boolean | any | any | null;
696
+ } | null)[] | {
697
+ readonly [key: string]: string | number | boolean | any | any | null;
698
+ } | null)[] | {
699
+ readonly [key: string]: string | number | boolean | any | any | null;
700
+ } | null)[] | {
701
+ readonly [key: string]: string | number | boolean | any | any | null;
702
+ } | null)[] | {
703
+ readonly [key: string]: string | number | boolean | any | any | null;
704
+ } | null)[] | {
705
+ readonly [key: string]: string | number | boolean | any | any | null;
706
+ } | null)[] | {
707
+ readonly [key: string]: string | number | boolean | any | any | null;
708
+ } | null)[] | {
709
+ readonly [key: string]: string | number | boolean | any | any | null;
710
+ } | null)[] | {
711
+ readonly [key: string]: string | number | boolean | any | any | null;
712
+ } | null)[] | {
713
+ readonly [key: string]: string | number | boolean | any | any | null;
714
+ } | null>, z.ZodTransform<string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | any | {
715
+ readonly [key: string]: string | number | boolean | any | any | null;
716
+ } | null)[] | {
717
+ readonly [key: string]: string | number | boolean | any | any | null;
718
+ } | null)[] | {
719
+ readonly [key: string]: string | number | boolean | any | any | null;
720
+ } | null)[] | {
721
+ readonly [key: string]: string | number | boolean | any | any | null;
722
+ } | null)[] | {
723
+ readonly [key: string]: string | number | boolean | any | any | null;
724
+ } | null)[] | {
725
+ readonly [key: string]: string | number | boolean | any | any | null;
726
+ } | null)[] | {
727
+ readonly [key: string]: string | number | boolean | any | any | null;
728
+ } | null)[] | {
729
+ readonly [key: string]: string | number | boolean | any | any | null;
730
+ } | null)[] | {
731
+ readonly [key: string]: string | number | boolean | any | any | null;
732
+ } | null)[] | {
733
+ readonly [key: string]: string | number | boolean | any | any | null;
734
+ } | null)[] | {
735
+ readonly [key: string]: string | number | boolean | any | any | null;
736
+ } | null)[] | {
737
+ readonly [key: string]: string | number | boolean | any | any | null;
738
+ } | null, string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | readonly (string | number | boolean | any | {
739
+ readonly [key: string]: string | number | boolean | any | any | null;
740
+ } | null)[] | {
741
+ readonly [key: string]: string | number | boolean | any | any | null;
742
+ } | null)[] | {
743
+ readonly [key: string]: string | number | boolean | any | any | null;
744
+ } | null)[] | {
745
+ readonly [key: string]: string | number | boolean | any | any | null;
746
+ } | null)[] | {
747
+ readonly [key: string]: string | number | boolean | any | any | null;
748
+ } | null)[] | {
749
+ readonly [key: string]: string | number | boolean | any | any | null;
750
+ } | null)[] | {
751
+ readonly [key: string]: string | number | boolean | any | any | null;
752
+ } | null)[] | {
753
+ readonly [key: string]: string | number | boolean | any | any | null;
754
+ } | null)[] | {
755
+ readonly [key: string]: string | number | boolean | any | any | null;
756
+ } | null)[] | {
757
+ readonly [key: string]: string | number | boolean | any | any | null;
758
+ } | null)[] | {
759
+ readonly [key: string]: string | number | boolean | any | any | null;
760
+ } | null)[] | {
761
+ readonly [key: string]: string | number | boolean | any | any | null;
762
+ } | null>>;
763
+ revision: z.ZodNumber;
764
+ }, z.core.$strict>;
765
+ }, z.core.$strict>, z.ZodObject<{
766
+ type: z.ZodLiteral<"request">;
767
+ id: z.ZodNumber;
768
+ contextId: z.ZodString;
769
+ method: z.ZodLiteral<"storage.delete">;
770
+ params: z.ZodObject<{
771
+ key: z.ZodString;
772
+ conceptId: z.ZodOptional<z.ZodString>;
773
+ revision: z.ZodNumber;
774
+ }, z.core.$strict>;
605
775
  }, z.core.$strict>, z.ZodObject<{
606
776
  type: z.ZodLiteral<"request">;
607
777
  id: z.ZodNumber;
@@ -722,7 +892,7 @@ type WriteOptions = {
722
892
  type PluginWrites = Omit<ReturnType<typeof createWriteCommands<Promise<void>, Promise<string>>>, 'undo' | 'redo' | 'setView' | 'setActiveVocab' | 'setActiveTheme' | 'setLocale' | 'setPanelSizes' | 'setSectionOpen' | 'createView' | 'renameView' | 'setViewPinned' | 'deleteView'>;
723
893
  type ActionContext = {
724
894
  readonly viewId: string | null;
725
- readonly store: PluginWrites & {
895
+ readonly document: PluginWrites & {
726
896
  readonly getState: () => ActionState;
727
897
  readonly subscribe: (listener: () => void) => () => void;
728
898
  readonly refresh: () => Promise<ActionState>;
@@ -744,14 +914,14 @@ type ActionContext = {
744
914
  readonly saved: boolean;
745
915
  }>;
746
916
  };
917
+ readonly storage: PluginStorage;
747
918
  readonly signal: AbortSignal;
748
919
  };
749
920
  declare function parsePluginMessage(value: unknown): z.infer<typeof message>;
750
921
  declare function sha256Hex(bytes: Uint8Array): Promise<string>;
751
- declare function checkMessageSize(value: unknown, limit: number): void;
752
922
  declare function createPluginClient(port: MessagePort, initial: unknown): {
753
923
  context: ActionContext;
754
924
  close: () => void;
755
925
  };
756
926
  //#endregion
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 };
927
+ export { themeColors as $, createWriteCommands as A, NotificationAction as B, parsePluginStorageSnapshot as C, FileSaveOptions as D, FileOpenResult as E, GraphSnapshot as F, SectionId as G, PanelSizes as H, NessoOperation as I, VocabDefinition as J, Selection as K, NessoState as L, parseOrThrow as M, LocalizedText as N, fileTextLimit as O, resolvePluginText as P, parseDefinition as Q, NessoStore as R, parsePluginStorageRecord as S, FileOpenOptions as T, Preferences as U, Notifications as V, SavedView as W, Definition as X, WorkspaceState as Y, ThemeDefinition as Z, checkMessageSize as _, ActionState as a, PluginStorageRecord as b, actionIconNames as c, parsePluginI18n as d, parsePluginManifest as f, themeTokens as g, sha256Hex as h, ActionIconName as i, PluginError as j, parseFileOptions as k, createPluginClient as l, runtimeLimits as m, ActionContribution as n, PluginI18n as o, parsePluginMessage as p, Viewport as q, ActionDescriptor as r, PluginManifest as s, ActionContext as t, parseContribution as u, PluginStorage as v, pluginStorageLimits as w, parsePluginStorageKey as x, PluginStorageKey as y, Notification as z };
@@ -402,6 +402,90 @@ const localizedText = (limit) => z.strictObject({
402
402
  });
403
403
  const resolvePluginText = (value, locale) => value[locale] ?? value.en;
404
404
  //#endregion
405
+ //#region src/data.ts
406
+ function checkMessageSize(value, limit, maximumDepth = 32) {
407
+ const visit = (value, depth) => {
408
+ if (depth > maximumDepth) throw new PluginError("invalid-input", [{
409
+ path: "message",
410
+ message: "Nesting limit exceeded"
411
+ }]);
412
+ if (value === null) return;
413
+ if (typeof value === "object") {
414
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new PluginError("invalid-input", [{
415
+ path: "message",
416
+ message: "Expected plain data"
417
+ }]);
418
+ for (const item of Object.values(value)) visit(item, depth + 1);
419
+ } else if (![
420
+ "string",
421
+ "number",
422
+ "boolean",
423
+ "undefined"
424
+ ].includes(typeof value) || typeof value === "number" && !Number.isFinite(value)) throw new PluginError("invalid-input", [{
425
+ path: "message",
426
+ message: "Expected serializable data"
427
+ }]);
428
+ };
429
+ visit(value, 0);
430
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit) throw new PluginError("invalid-input", [{
431
+ path: "message",
432
+ message: "Message limit exceeded"
433
+ }]);
434
+ }
435
+ //#endregion
436
+ //#region src/storage.ts
437
+ const pluginStorageLimits = {
438
+ record: 262144,
439
+ namespace: 8388608,
440
+ total: 67108864,
441
+ records: 1e4,
442
+ namespaces: 128,
443
+ depth: 24
444
+ };
445
+ const isJsonValue = (value, depth = 0) => {
446
+ if (depth > pluginStorageLimits.depth) return false;
447
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
448
+ if (typeof value === "number") return Number.isFinite(value);
449
+ if (typeof value !== "object") return false;
450
+ if (Array.isArray(value)) return Reflect.ownKeys(value).length === value.length + 1 && Array.from(value).every((item) => isJsonValue(item, depth + 1));
451
+ return Object.getPrototypeOf(value) === Object.prototype && Reflect.ownKeys(value).length === Object.keys(value).length && Object.values(value).every((item) => isJsonValue(item, depth + 1));
452
+ };
453
+ const fields = {
454
+ key: z.string().min(1).max(128),
455
+ conceptId: z.string().max(2048).optional()
456
+ };
457
+ const pluginStorageKey = z.strictObject(fields);
458
+ const pluginStorageRecord = z.strictObject({
459
+ ...fields,
460
+ value: z.custom((value) => isJsonValue(value), "Expected a bounded JSON value").transform((value) => structuredClone(value))
461
+ }).superRefine((value, context) => {
462
+ try {
463
+ checkMessageSize(value, pluginStorageLimits.record, pluginStorageLimits.depth);
464
+ } catch (error) {
465
+ context.addIssue({
466
+ code: "custom",
467
+ message: error instanceof PluginError ? error.message : "Invalid storage record"
468
+ });
469
+ }
470
+ });
471
+ const pluginStorageRevision = z.number().int().nonnegative();
472
+ const pluginStorageSnapshot = z.strictObject({
473
+ revision: pluginStorageRevision,
474
+ records: z.array(pluginStorageRecord).max(pluginStorageLimits.records)
475
+ });
476
+ function parsePluginStorageSnapshot(value) {
477
+ checkMessageSize(value, pluginStorageLimits.namespace);
478
+ return parseOrThrow(pluginStorageSnapshot, value);
479
+ }
480
+ function parsePluginStorageRecord(value) {
481
+ checkMessageSize(value, pluginStorageLimits.record, pluginStorageLimits.depth);
482
+ return parseOrThrow(pluginStorageRecord, value);
483
+ }
484
+ function parsePluginStorageKey(value) {
485
+ checkMessageSize(value, 4096);
486
+ return parseOrThrow(pluginStorageKey, value);
487
+ }
488
+ //#endregion
405
489
  //#region src/runtime.ts
406
490
  const runtimeLimits = {
407
491
  request: 33554432,
@@ -619,9 +703,9 @@ const manifest = z.discriminatedUnion("kind", [z.strictObject({
619
703
  entry: jsEntry,
620
704
  writes: operationDeclarations,
621
705
  capabilities: z.array(z.enum([
622
- "files.open",
623
- "files.save",
624
- "notifications.notify"
706
+ "files",
707
+ "notifications",
708
+ "storage"
625
709
  ]))
626
710
  }), ...["theme", "vocab"].map((kind) => z.strictObject({
627
711
  ...manifestFields,
@@ -642,7 +726,7 @@ const envelope = {
642
726
  const request = z.discriminatedUnion("method", [
643
727
  z.strictObject({
644
728
  ...envelope,
645
- method: z.literal("store.applyOperations"),
729
+ method: z.literal("document.applyOperations"),
646
730
  params: z.strictObject({
647
731
  operations: z.array(operation).max(5e4),
648
732
  revision: z.number().int().nonnegative(),
@@ -651,9 +735,24 @@ const request = z.discriminatedUnion("method", [
651
735
  }),
652
736
  z.strictObject({
653
737
  ...envelope,
654
- method: z.literal("store.refresh"),
738
+ method: z.literal("document.refresh"),
655
739
  params: z.strictObject({})
656
740
  }),
741
+ z.strictObject({
742
+ ...envelope,
743
+ method: z.literal("storage.list"),
744
+ params: z.strictObject({})
745
+ }),
746
+ z.strictObject({
747
+ ...envelope,
748
+ method: z.literal("storage.set"),
749
+ params: pluginStorageRecord.extend({ revision: pluginStorageRevision })
750
+ }),
751
+ z.strictObject({
752
+ ...envelope,
753
+ method: z.literal("storage.delete"),
754
+ params: pluginStorageKey.extend({ revision: pluginStorageRevision })
755
+ }),
657
756
  z.strictObject({
658
757
  ...envelope,
659
758
  method: z.literal("notifications.notify"),
@@ -812,11 +911,20 @@ const reply = z.union([
812
911
  })
813
912
  ]);
814
913
  const results = {
815
- "store.applyOperations": z.strictObject({
914
+ "document.applyOperations": z.strictObject({
816
915
  revision: z.number().int().nonnegative(),
817
916
  changed: z.boolean()
818
917
  }),
819
- "store.refresh": z.null(),
918
+ "document.refresh": z.null(),
919
+ "storage.list": pluginStorageSnapshot,
920
+ "storage.set": z.strictObject({
921
+ revision: pluginStorageRevision,
922
+ changed: z.boolean()
923
+ }),
924
+ "storage.delete": z.strictObject({
925
+ revision: pluginStorageRevision,
926
+ changed: z.boolean()
927
+ }),
820
928
  "notifications.notify": id,
821
929
  "files.open": fileOpenResult,
822
930
  "files.save": z.strictObject({ saved: z.boolean() })
@@ -829,38 +937,10 @@ async function sha256Hex(bytes) {
829
937
  const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
830
938
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
831
939
  }
832
- function checkMessageSize(value, limit) {
833
- const visit = (value, depth) => {
834
- if (depth > 32) throw new PluginError("invalid-input", [{
835
- path: "message",
836
- message: "Nesting limit exceeded"
837
- }]);
838
- if (value === null) return;
839
- if (typeof value === "object") {
840
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new PluginError("invalid-input", [{
841
- path: "message",
842
- message: "Expected plain data"
843
- }]);
844
- for (const item of Object.values(value)) visit(item, depth + 1);
845
- } else if (![
846
- "string",
847
- "number",
848
- "boolean",
849
- "undefined"
850
- ].includes(typeof value)) throw new PluginError("invalid-input", [{
851
- path: "message",
852
- message: "Expected serializable data"
853
- }]);
854
- };
855
- visit(value, 0);
856
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limit) throw new PluginError("invalid-input", [{
857
- path: "message",
858
- message: "Message limit exceeded"
859
- }]);
860
- }
861
940
  function createPluginClient(port, initial) {
862
941
  let state = parseOrThrow(actionStateSchema, initial);
863
942
  let readRevision = state.revision;
943
+ let storageRevision;
864
944
  let sequence = 0;
865
945
  const listeners = /* @__PURE__ */ new Set();
866
946
  const controller = new AbortController();
@@ -962,7 +1042,7 @@ function createPluginClient(port, initial) {
962
1042
  return state;
963
1043
  };
964
1044
  const applyOperations = async (operations, options) => {
965
- const result = await call("store.applyOperations", {
1045
+ const result = await call("document.applyOperations", {
966
1046
  operations,
967
1047
  revision: readRevision,
968
1048
  ...options ? { options } : {}
@@ -976,10 +1056,24 @@ function createPluginClient(port, initial) {
976
1056
  await committed;
977
1057
  return id;
978
1058
  });
1059
+ const listStorage = async () => {
1060
+ const snapshot = await call("storage.list", {});
1061
+ storageRevision = Math.max(storageRevision ?? 0, snapshot.revision);
1062
+ return snapshot.records;
1063
+ };
1064
+ const mutateStorage = async (method, params) => {
1065
+ if (storageRevision === void 0) await listStorage();
1066
+ const result = await call(method, {
1067
+ ...params,
1068
+ revision: storageRevision
1069
+ });
1070
+ storageRevision = Math.max(storageRevision ?? 0, result.revision);
1071
+ return result.changed;
1072
+ };
979
1073
  return {
980
1074
  context: {
981
1075
  viewId: state.targetViewId,
982
- store: {
1076
+ document: {
983
1077
  ...writes,
984
1078
  getState,
985
1079
  subscribe: (listener) => {
@@ -987,7 +1081,7 @@ function createPluginClient(port, initial) {
987
1081
  return () => listeners.delete(listener);
988
1082
  },
989
1083
  refresh: async () => {
990
- await call("store.refresh", {});
1084
+ await call("document.refresh", {});
991
1085
  return getState();
992
1086
  },
993
1087
  applyOperations
@@ -997,10 +1091,25 @@ function createPluginClient(port, initial) {
997
1091
  open: (options) => call("files.open", options),
998
1092
  save: (options) => call("files.save", options)
999
1093
  },
1094
+ storage: {
1095
+ list: listStorage,
1096
+ set: (key, value, conceptId) => mutateStorage("storage.set", conceptId === void 0 ? {
1097
+ key,
1098
+ value
1099
+ } : {
1100
+ key,
1101
+ value,
1102
+ conceptId
1103
+ }),
1104
+ delete: (key, conceptId) => mutateStorage("storage.delete", conceptId === void 0 ? { key } : {
1105
+ key,
1106
+ conceptId
1107
+ })
1108
+ },
1000
1109
  signal: controller.signal
1001
1110
  },
1002
1111
  close
1003
1112
  };
1004
1113
  }
1005
1114
  //#endregion
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 };
1115
+ export { parseOrThrow as S, parseFileOptions as _, parsePluginManifest as a, createWriteCommands as b, sha256Hex as c, parsePluginStorageRecord as d, parsePluginStorageSnapshot as f, fileTextLimit as g, resolvePluginText as h, parsePluginI18n as i, themeTokens as l, checkMessageSize as m, createPluginClient as n, parsePluginMessage as o, pluginStorageLimits as p, parseContribution as r, runtimeLimits as s, actionIconNames as t, parsePluginStorageKey as u, parseDefinition as v, PluginError as x, themeColors as y };
package/dist/runtime.d.ts CHANGED
@@ -1,2 +1,2 @@
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 };
1
+ import { $ as themeColors, C as parsePluginStorageSnapshot, D as FileSaveOptions, E as FileOpenResult, M as parseOrThrow, N as LocalizedText, O as fileTextLimit, P as resolvePluginText, Q as parseDefinition, S as parsePluginStorageRecord, T as FileOpenOptions, X as Definition, _ as checkMessageSize, a as ActionState, c as actionIconNames, d as parsePluginI18n, f as parsePluginManifest, g as themeTokens, h as sha256Hex, i as ActionIconName, j as PluginError, k as parseFileOptions, l as createPluginClient, m as runtimeLimits, n as ActionContribution, o as PluginI18n, p as parsePluginMessage, r as ActionDescriptor, s as PluginManifest, t as ActionContext, u as parseContribution, w as pluginStorageLimits, x as parsePluginStorageKey } from "./runtime-BrWPGuBB.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, parsePluginStorageKey, parsePluginStorageRecord, parsePluginStorageSnapshot, pluginStorageLimits, resolvePluginText, runtimeLimits, sha256Hex, themeColors, themeTokens };
package/dist/runtime.js CHANGED
@@ -1 +1 @@
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";
1
+ export { x as PluginError, t as actionIconNames, m as checkMessageSize, n as createPluginClient, g as fileTextLimit, r as parseContribution, v as parseDefinition, _ as parseFileOptions, S as parseOrThrow, i as parsePluginI18n, a as parsePluginManifest, o as parsePluginMessage, u as parsePluginStorageKey, d as parsePluginStorageRecord, f as parsePluginStorageSnapshot, p as pluginStorageLimits, h as resolvePluginText, s as runtimeLimits, c as sha256Hex, y as themeColors, l as themeTokens } from "./runtime-C-k6OiHL.js";
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nesso-how/plugin-example",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Uppercase concept labels in the invoked Nesso view",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,7 +21,7 @@
21
21
  "registry": "https://registry.npmjs.org/"
22
22
  },
23
23
  "devDependencies": {
24
- "@nesso-how/plugin": "0.3.1",
24
+ "@nesso-how/plugin": "0.4.0",
25
25
  "esbuild": "^0.28.2",
26
26
  "typescript": "~7.0.2"
27
27
  },
@@ -5,8 +5,8 @@ export const create = (): readonly ActionContribution[] => {
5
5
  const action: ActionContribution = {
6
6
  id: 'uppercase-labels',
7
7
  label: source.i18n.metadata.name,
8
- run: async ({ store }) => {
9
- const state = store.getState()
8
+ run: async ({ document }) => {
9
+ const state = document.getState()
10
10
 
11
11
  const operations: readonly NessoOperation[] = state.viewGraph.concepts.map(({ id, label }) => ({
12
12
  kind: 'concept.label',
@@ -14,7 +14,7 @@ export const create = (): readonly ActionContribution[] => {
14
14
  value: label.toUpperCase(),
15
15
  }))
16
16
 
17
- await store.applyOperations(operations)
17
+ await document.applyOperations(operations)
18
18
  },
19
19
  }
20
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nesso-how/plugin",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Types, validation, and asynchronous clients for isolated Nesso plugins",
5
5
  "license": "MIT",
6
6
  "repository": {