@type32/vertex-plugin 1.0.0 → 1.1.1

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.
@@ -150,7 +150,8 @@
150
150
  }
151
151
 
152
152
  .dark {
153
- --color-submuted: oklch(var(--ui-bg-muted));
153
+
154
+ --color-submuted: color-mix(in oklab, var(--ui-bg) 98%, var(--ui-bg-inverted));
154
155
 
155
156
  --ncm-code-bg: var(--ui-bg-muted);
156
157
  --ncm-code-bg-hover: var(--ui-bg-elevated);
@@ -159,10 +160,6 @@
159
160
  --ncm-text-muted: var(--ui-text-muted);
160
161
  --ncm-text-xmuted: var(--ui-text-muted);
161
162
  --ncm-overlay-bg: rgba(var(--ui-bg), 0.98);
162
-
163
- .bg-submuted {
164
- @apply bg-inverted/2;
165
- }
166
163
  }
167
164
 
168
165
 
@@ -14,6 +14,7 @@ import type { PluginManifest, WindowKind } from './manifest';
14
14
  export type { ActiveSession, ActiveWorkspaceFileIndex, UITreeNode };
15
15
  export type { PluginManifest, WindowKind };
16
16
  export type * from './contributions';
17
+ export type * from './components';
17
18
  export type PluginSource = 'core' | 'global' | 'workspace';
18
19
  export type MenuSection = 'app' | 'file' | 'edit' | 'view' | 'help';
19
20
  export interface PluginCommand {
@@ -343,6 +344,21 @@ export interface HostServices {
343
344
  }): Promise<string | null>;
344
345
  save(options?: DialogOptions): Promise<string | null>;
345
346
  };
347
+ /** The app's strings and language. A plugin's own are `plugins.<id>.…`, from its `locales/<locale>.json`. */
348
+ i18n: {
349
+ /** The string for an i18n key in the window's language, `{params}` filled in; the key itself when there's none. Reactive. */
350
+ t(key: string, params?: Record<string, unknown>): string;
351
+ /** The window's language (`en`, `zh-CN`). Reactive. */
352
+ readonly locale: string;
353
+ };
354
+ ui: {
355
+ /** The window's theme as the page draws it. Reactive: it follows light and dark, the colours, a workspace's theme. */
356
+ theme: {
357
+ readonly dark: boolean;
358
+ /** A CSS custom property as the page resolves it now (`--ui-primary` → a colour), for what CSS can't reach (a canvas). */
359
+ value(property: string): string;
360
+ };
361
+ };
346
362
  /**
347
363
  * Trust for programs from a vault (the trusted folders and files, Settings → Trust), so every plugin that runs one
348
364
  * asks the same way. Paths are absolute; `hash` names a program's content (the format's `hash`).
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The props and events of the components `/ui` publishes (`app/plugin/ui.ts`), by the names it exports them under:
3
+ * `<Name>Props`, and `<Name>Emits` for one that emits. Each component declares its props with these, so they can't
4
+ * drift; the SDK's build types each export from them, so `vue-tsc` checks what a plugin passes.
5
+ */
6
+ import type { InternalLinkClickDetail } from '@type32/codemirror-rich-obsidian-editor';
7
+ import type { UiSlot } from './contributions';
8
+ /** One setting: label and description on the left, its control (the default slot) on the right. */
9
+ export interface SettingsRowProps {
10
+ label: string;
11
+ /** An Iconify name, drawn before the label (a plugin's row). */
12
+ icon?: string;
13
+ description?: string;
14
+ /** Replaces the description, in the error colour. */
15
+ error?: string;
16
+ /**
17
+ * The setting it edits (`plugins.config.<id>.depth`): it then follows the Settings window's scope (Global only,
18
+ * Changed in this workspace, Use global).
19
+ */
20
+ setting?: string;
21
+ }
22
+ /** A group of `SettingsRow`s under a title, with `actions` beside it. */
23
+ export interface SettingsSectionProps {
24
+ title: string;
25
+ description?: string;
26
+ /** Shows the reset button, which emits `reset`; what "dirty" means is the caller's. */
27
+ dirty?: boolean;
28
+ }
29
+ export interface SettingsSectionEmits {
30
+ reset: [];
31
+ }
32
+ /** A settings page: a sticky header with the title (`header-leading`, `header-trailing`) over the scrolling content. */
33
+ export interface SettingsScrollLayoutProps {
34
+ title?: string;
35
+ /** Read-only while the Settings window edits a workspace: none of the page's settings can be overridden there. */
36
+ globalOnly?: boolean;
37
+ }
38
+ /**
39
+ * A file viewer's frame: the header with the file's name (editable, `v-model:fileName`), the content, the status bar
40
+ * with the registered status items. Slots: `header-left`, `header-right`, the default (with `contentWidthClass`),
41
+ * `status-bar`.
42
+ */
43
+ export interface ViewerLayoutProps {
44
+ /** The file's name without its extension; renaming it emits `update:fileName`. */
45
+ fileName?: string;
46
+ showHeader?: boolean;
47
+ showBreadcrumbs?: boolean;
48
+ renaming?: boolean;
49
+ filePath?: string;
50
+ /** Default `vertical`. */
51
+ scrollMode?: 'vertical' | 'both' | 'none';
52
+ showScrollbar?: boolean;
53
+ showStatusBar?: boolean;
54
+ /** Default `center`. */
55
+ contentAlignment?: 'center' | 'start' | 'stretch';
56
+ /** A Tailwind class; default `max-w-2xl`. */
57
+ contentMaxWidth?: string;
58
+ contentPadding?: boolean;
59
+ cursorText?: boolean;
60
+ /** Room for the header above the content (default `true`); without it the content runs under the header's fade. */
61
+ topSpacing?: boolean;
62
+ bottomSpacing?: boolean;
63
+ ui?: {
64
+ root?: string;
65
+ };
66
+ }
67
+ export interface ViewerLayoutEmits {
68
+ 'update:fileName': [name: string];
69
+ 'on-rename': [oldValue: string, newValue: string];
70
+ }
71
+ /** A Markdown editor inside something else (a card, a form): the note editor's rendering, links and syntax. */
72
+ export interface NoteEditorProps {
73
+ text: string;
74
+ /** The file it's in, for its links and embeds. */
75
+ notePath: string;
76
+ }
77
+ export interface NoteEditorEmits {
78
+ update: [text: string];
79
+ /** Esc. */
80
+ done: [];
81
+ /** An internal link's click, for the caller to follow. */
82
+ openLink: [detail: InternalLinkClickDetail];
83
+ }
84
+ /** Draws a contribution's UI (`component` or `mount`) with `props`, inside an error boundary that names its plugin. */
85
+ export interface PluginMountProps {
86
+ ui: UiSlot<never>;
87
+ props: object;
88
+ }
89
+ /** The vault picker: files or folders of the workspace (`v-model`: workspace-relative paths). */
90
+ export interface VaultPickerProps {
91
+ modelValue?: string[];
92
+ sessionId: string;
93
+ /** Default `any`. */
94
+ kind?: 'file' | 'folder' | 'any';
95
+ multiple?: boolean;
96
+ /** Comma-separated, without dots (`png,jpg`). */
97
+ extensions?: string;
98
+ }
99
+ export interface VaultPickerEmits {
100
+ 'update:modelValue': [paths: string[]];
101
+ }
102
+ /** Two versions of a text, line by line; `header` gets the +/− counts. `sides` missing: still loading. */
103
+ export interface TextDiffProps {
104
+ sides?: {
105
+ before?: string;
106
+ after?: string;
107
+ };
108
+ failed?: boolean;
109
+ }
@@ -253,12 +253,13 @@ export interface ScopedConfig {
253
253
  /** The full setting path of `path` (`plugins.config.<id>.<path>`), for `SettingsRow`'s `setting`. */
254
254
  path(path: string): `plugins.config.${string}`;
255
255
  }
256
- /** A page in the Settings window, at `/settings/<id>/…`, listed in its nav after the kernel's. */
256
+ /** A page in the Settings window, at `/settings/<id>/…`, listed in its nav with its plugin's group. */
257
257
  export interface SettingsPageDef extends UiSlot<SettingsPageProps> {
258
258
  id: string;
259
259
  /** i18n key. */
260
260
  label: string;
261
- icon: string;
261
+ /** Default: its plugin's manifest's `icon`. */
262
+ icon?: string;
262
263
  /** Sub-entries in the nav (`path` below the page); a page with children is a group. */
263
264
  children?: {
264
265
  label: string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A plugin's strings: one file per locale (`en.json`, `zh-CN.json`), each `{"plugins": {"<id>": {…}}}`, the same
3
+ * shape a core plugin's layer has in `i18n/locales/`. A community plugin ships them in `locales/` beside `main.js`;
4
+ * the host merges only `plugins.<id>`, so a plugin's strings can't replace the app's or another plugin's.
5
+ */
6
+ import type { PluginManifest } from './manifest';
7
+ /** A messages object's strings by dotted key (`plugins.graph.view`); a value that isn't an object or a string is skipped. */
8
+ export declare function messageLeaves(messages: unknown, prefix?: string): Map<string, string>;
9
+ /** The i18n keys a manifest names: its settings schema's labels, descriptions and options. */
10
+ export declare function manifestKeys(manifest: Pick<PluginManifest, 'config'>): string[];
11
+ /**
12
+ * What's wrong with plugin `id`'s strings, `files` by locale (`en`, `zh-CN`): each file is an object of strings,
13
+ * all under `plugins.<id>`; `en` is there, and every other locale has exactly its keys, with the same `{params}`;
14
+ * `en` has every key the manifest names. `locales`: the locales there must be a file for (a core plugin's are the
15
+ * app's; a community plugin's others fall back to `en`). Empty when nothing is.
16
+ */
17
+ export declare function checkPluginMessages(id: string, files: Readonly<Record<string, unknown>>, manifest?: Pick<PluginManifest, 'config'>, locales?: readonly string[]): string[];
18
+ /**
19
+ * What the app merges for plugin `id` in each of its `locales`: only `plugins.<id>` of the plugin's files, a locale's
20
+ * strings over `en`'s, so a missing locale or key shows English. A locale with no strings is left out.
21
+ */
22
+ export declare function messagesFor(id: string, files: Readonly<Record<string, unknown>>, locales: readonly string[]): Record<string, Record<string, unknown>>;
@@ -1,12 +1,29 @@
1
- import type { Component, ComputedRef, MaybeRefOrGetter } from 'vue';
2
- export declare const SettingsRow: Component;
3
- export declare const SettingsSection: Component;
4
- export declare const SettingsScrollLayout: Component;
5
- export declare const ViewerLayout: Component;
6
- export declare const NoteEditor: Component;
7
- export declare const PluginMount: Component;
8
- export declare const VaultPicker: Component;
9
- export declare const TextDiff: Component;
1
+ import type { ComputedRef, EmitsToProps, MaybeRefOrGetter } from 'vue';
2
+ import type { NoteEditorEmits, NoteEditorProps, PluginMountProps, SettingsRowProps, SettingsScrollLayoutProps, SettingsSectionEmits, SettingsSectionProps, TextDiffProps, VaultPickerEmits, VaultPickerProps, ViewerLayoutEmits, ViewerLayoutProps } from '#shared/plugin/components';
3
+ export declare const SettingsRow: new () => {
4
+ $props: SettingsRowProps;
5
+ };
6
+ export declare const SettingsSection: new () => {
7
+ $props: SettingsSectionProps & EmitsToProps<SettingsSectionEmits>;
8
+ };
9
+ export declare const SettingsScrollLayout: new () => {
10
+ $props: SettingsScrollLayoutProps;
11
+ };
12
+ export declare const ViewerLayout: new () => {
13
+ $props: ViewerLayoutProps & EmitsToProps<ViewerLayoutEmits>;
14
+ };
15
+ export declare const NoteEditor: new () => {
16
+ $props: NoteEditorProps & EmitsToProps<NoteEditorEmits>;
17
+ };
18
+ export declare const PluginMount: new () => {
19
+ $props: PluginMountProps;
20
+ };
21
+ export declare const VaultPicker: new () => {
22
+ $props: VaultPickerProps & EmitsToProps<VaultPickerEmits>;
23
+ };
24
+ export declare const TextDiff: new () => {
25
+ $props: TextDiffProps;
26
+ };
10
27
  export declare const openExternal: (url: string) => Promise<void>;
11
28
  export declare const useScrollFade: (target: MaybeRefOrGetter<HTMLElement | null | undefined>, options?: {
12
29
  bottom?: boolean | undefined;
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, readdirSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
2
  import { join, relative, resolve, sep } from "node:path";
3
3
  import { crc32, deflateRawSync } from "node:zlib";
4
4
  import tailwindcss from "@tailwindcss/vite";
@@ -47,7 +47,7 @@ var KEYS = /* @__PURE__ */ new Set([
47
47
  ]);
48
48
  var isString = (v) => typeof v === "string";
49
49
  var isStringList = (v) => Array.isArray(v) && v.every(isString);
50
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
50
+ var isObject$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
51
51
  var isNumber = (v) => typeof v === "number" && Number.isFinite(v);
52
52
  var CONFIG_PATH = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/;
53
53
  var FIELD_KEYS = {
@@ -64,7 +64,7 @@ var FIELD_KEYS = {
64
64
  path: ["kind"]
65
65
  };
66
66
  function validateField(f, at, errors) {
67
- if (!isObject(f)) return void errors.push(`${at} must be an object`);
67
+ if (!isObject$1(f)) return void errors.push(`${at} must be an object`);
68
68
  const type = f.type;
69
69
  if (!(type in FIELD_KEYS)) return void errors.push(`${at}.type must be one of ${Object.keys(FIELD_KEYS).join(", ")}`);
70
70
  for (const key of Object.keys(f)) if (![
@@ -95,15 +95,15 @@ function validateField(f, at, errors) {
95
95
  }
96
96
  if (type === "select") {
97
97
  const options = f.options;
98
- if (!Array.isArray(options) || !options.length || !options.every((o) => isObject(o) && isString(o.value) && isString(o.label))) errors.push(`${at}.options must be a non-empty list of {value, label}`);
98
+ if (!Array.isArray(options) || !options.length || !options.every((o) => isObject$1(o) && isString(o.value) && isString(o.label))) errors.push(`${at}.options must be a non-empty list of {value, label}`);
99
99
  else if (!options.some((o) => o.value === d)) errors.push(`${at}.default must be one of its options`);
100
100
  }
101
101
  }
102
102
  function validateConfig(config, errors) {
103
- if (!isObject(config)) return void errors.push("\"config\" must be an object");
103
+ if (!isObject$1(config)) return void errors.push("\"config\" must be an object");
104
104
  for (const key of Object.keys(config)) if (key !== "overridable" && key !== "schema") errors.push(`unknown key "config.${key}"`);
105
105
  if (config.overridable !== void 0) {
106
- if (!isObject(config.overridable)) errors.push("\"config.overridable\" must map paths to \"workspace\" or \"trustedWorkspace\"");
106
+ if (!isObject$1(config.overridable)) errors.push("\"config.overridable\" must map paths to \"workspace\" or \"trustedWorkspace\"");
107
107
  else for (const [path, level] of Object.entries(config.overridable)) {
108
108
  if (!CONFIG_PATH.test(path)) errors.push(`"config.overridable" has an invalid path "${path}"`);
109
109
  if (!OVERRIDE_LEVELS.includes(level)) errors.push(`"config.overridable.${path}" must be "workspace" or "trustedWorkspace"`);
@@ -114,7 +114,7 @@ function validateConfig(config, errors) {
114
114
  const keys = /* @__PURE__ */ new Set();
115
115
  config.schema.forEach((field, i) => {
116
116
  validateField(field, `"config.schema[${i}]"`, errors);
117
- const key = isObject(field) ? field.key : void 0;
117
+ const key = isObject$1(field) ? field.key : void 0;
118
118
  if (keys.has(key)) errors.push(`"config.schema[${i}].key" "${String(key)}" is used twice`);
119
119
  keys.add(key);
120
120
  });
@@ -178,6 +178,61 @@ function validateManifest(raw, appVersion) {
178
178
  manifest: m
179
179
  };
180
180
  }
181
+ // ../../shared/plugin/messages.ts
182
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
183
+ /** A messages object's strings by dotted key (`plugins.graph.view`); a value that isn't an object or a string is skipped. */
184
+ function messageLeaves(messages, prefix = "") {
185
+ const out = /* @__PURE__ */ new Map();
186
+ if (!isObject(messages)) return out;
187
+ for (const [key, value] of Object.entries(messages)) {
188
+ const at = prefix ? `${prefix}.${key}` : key;
189
+ if (isObject(value)) for (const [k, v] of messageLeaves(value, at)) out.set(k, v);
190
+ else if (typeof value === "string") out.set(at, value);
191
+ }
192
+ return out;
193
+ }
194
+ var params = (text) => [...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
195
+ /** The i18n keys a manifest names: its settings schema's labels, descriptions and options. */
196
+ function manifestKeys(manifest) {
197
+ return (manifest.config?.schema ?? []).flatMap((field) => [
198
+ field.label,
199
+ field.description,
200
+ ...field.type === "select" ? field.options.map((o) => o.label) : []
201
+ ].filter((k) => !!k));
202
+ }
203
+ /**
204
+ * What's wrong with plugin `id`'s strings, `files` by locale (`en`, `zh-CN`): each file is an object of strings,
205
+ * all under `plugins.<id>`; `en` is there, and every other locale has exactly its keys, with the same `{params}`;
206
+ * `en` has every key the manifest names. `locales`: the locales there must be a file for (a core plugin's are the
207
+ * app's; a community plugin's others fall back to `en`). Empty when nothing is.
208
+ */
209
+ function checkPluginMessages(id, files, manifest, locales = []) {
210
+ const errors = [];
211
+ const prefix = `plugins.${id}.`;
212
+ for (const locale of locales) if (!(locale in files)) errors.push(`no ${locale}.json`);
213
+ const leaves = Object.fromEntries(Object.entries(files).map(([locale, messages]) => {
214
+ if (!isObject(messages)) errors.push(`${locale}.json isn't an object`);
215
+ const strings = messageLeaves(messages);
216
+ for (const key of strings.keys()) if (!key.startsWith(prefix)) errors.push(`${locale}.json: "${key}" isn't under "${prefix.slice(0, -1)}"`);
217
+ return [locale, strings];
218
+ }));
219
+ const en = leaves.en;
220
+ if (!en) {
221
+ if (!locales.includes("en") && (Object.keys(files).length || manifest && manifestKeys(manifest).length)) errors.push("no en.json");
222
+ return errors;
223
+ }
224
+ for (const [locale, strings] of Object.entries(leaves)) {
225
+ if (locale === "en") continue;
226
+ for (const key of en.keys()) if (!strings.has(key)) errors.push(`${locale}.json has no "${key}"`);
227
+ for (const key of strings.keys()) if (!en.has(key)) errors.push(`${locale}.json has "${key}", which en.json doesn't`);
228
+ for (const [key, text] of en) {
229
+ const other = strings.get(key);
230
+ if (other !== void 0 && params(other).join() !== params(text).join()) errors.push(`${locale}.json: "${key}" takes other {params} than en.json's`);
231
+ }
232
+ }
233
+ for (const key of manifest ? manifestKeys(manifest) : []) if (!en.has(key)) errors.push(`en.json has no "${key}", which plugin.json names`);
234
+ return errors;
235
+ }
181
236
  // ../../shared/plugin/modules.ts
182
237
  /**
183
238
  * The modules a community plugin imports and gets the host's copy of, so there is one Vue, one CodeMirror, one editor
@@ -190,7 +245,7 @@ var SHARED_GLOBAL = "__vertexModules";
190
245
  /**
191
246
  * The Vite preset a community plugin builds with: `plugins: [vertex()]` in its `vite.config.ts` turns `src/main.ts`
192
247
  * and `plugin.json` into `dist/`, the folder Vertex installs (`plugin.json`, one `main.js`, `styles.css` when there's
193
- * CSS, the files of `public/`); with `pack`, also `plugin.zip` for a release.
248
+ * CSS, the strings of `locales/`, the files of `public/`); with `pack`, also `plugin.zip` for a release.
194
249
  */
195
250
  var PREFIX = "\0vertex-shared:";
196
251
  /**
@@ -272,7 +327,7 @@ function vertex(options = {}) {
272
327
  tailwindcss(),
273
328
  {
274
329
  name: "vertex:package",
275
- config: () => ({
330
+ config: (config) => ({
276
331
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
277
332
  build: {
278
333
  lib: {
@@ -281,7 +336,8 @@ function vertex(options = {}) {
281
336
  fileName: () => "main.js",
282
337
  cssFileName: "styles"
283
338
  },
284
- rolldownOptions: { output: { inlineDynamicImports: true } }
339
+ rolldownOptions: { output: { codeSplitting: false } },
340
+ ...config.build?.watch && { watch: { exclude: [`${resolve(config.root ?? process.cwd(), config.build.outDir ?? "dist")}/**`, resolve(config.root ?? process.cwd(), "plugin.zip")] } }
285
341
  }
286
342
  }),
287
343
  configResolved(config) {
@@ -296,6 +352,15 @@ function vertex(options = {}) {
296
352
  fileName: "plugin.json",
297
353
  source: `${JSON.stringify(result.manifest, null, 2)}\n`
298
354
  });
355
+ const dir = resolve(root, "locales");
356
+ const files = Object.fromEntries((existsSync(dir) ? readdirSync(dir) : []).filter((f) => f.endsWith(".json")).map((f) => [f.slice(0, -5), JSON.parse(readFileSync(join(dir, f), "utf8"))]));
357
+ const errors = checkPluginMessages(result.manifest.id, files, result.manifest);
358
+ if (errors.length) this.error(`locales/:\n - ${errors.join("\n - ")}`);
359
+ for (const [locale, messages] of Object.entries(files)) this.emitFile({
360
+ type: "asset",
361
+ fileName: `locales/${locale}.json`,
362
+ source: `${JSON.stringify(messages, null, 2)}\n`
363
+ });
299
364
  },
300
365
  closeBundle() {
301
366
  if (!options.pack) return;
package/docs/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # Writing a Vertex plugin
2
+
3
+ A Vertex plugin is a folder: `plugin.json`, one `main.js`, maybe `styles.css`, its strings and its assets. Vertex
4
+ loads it at runtime in its windows, where it adds what it registers: panel views, tabs, file viewers, file types,
5
+ commands, editor syntax and widgets, settings pages. It's written in TypeScript and Vue against this package,
6
+ `@type32/vertex-plugin`, whose types are the contract and whose Vite preset builds the folder.
7
+
8
+ Vertex's own features are plugins on the same contract (Files, Canvas, Bases, Git, Chat…), so what they do, a plugin
9
+ can do.
10
+
11
+ | Page | What's in it |
12
+ | --- | --- |
13
+ | [Start](start.md) | A plugin from an empty folder to a panel running in Vertex; the development loop. |
14
+ | [The package](package.md) | `plugin.json` key by key; what the build makes; dependencies; strings; what can't be done. |
15
+ | [The plugin's context](context.md) | `ctx`, what `setup` gets: every contribution point, with an example. |
16
+ | [The session](session.md) | `session`, what views and `onSession` get: the workspace's index, files, tabs, editors. |
17
+ | [UI](ui.md) | Mounting, Vue and Nuxt UI, Vertex's own components, Tailwind, the theme. |
18
+ | [Config, data, secrets](config.md) | Settings drawn from the manifest, workspace overrides, stored documents, the keychain, the network, permissions. |
19
+ | [Trust](trust.md) | What a user is told and agrees to; a workspace's plugins; trust for programs a plugin runs. |
20
+ | [Publishing](publishing.md) | Releases with `plugin.zip`, a branch of built files, updates, pins. |
21
+ | [Versions](versions.md) | `apiVersion`, `minAppVersion`, this package's versions. |
22
+
23
+ The types say more than these pages: each member is documented where it's declared, so an editor shows it on hover.
24
+ A starting point: [`Type-32/vertex-plugin-template`](https://github.com/Type-32/vertex-plugin-template).
package/docs/config.md ADDED
@@ -0,0 +1,132 @@
1
+ # Config, data, secrets
2
+
3
+ | What | Where it lives | Use it for |
4
+ | --- | --- | --- |
5
+ | [Config](#ctxconfig) | The user's settings, `plugins.config.<id>`; a workspace's `.vertex/settings.json` for what it may override | What the user sets: options, filters, colours. |
6
+ | [Data](#ctxdataglobal-ctxdataworkspace) | A JSON document of the plugin's, for the app or for a workspace | What the plugin keeps: state, caches, per-folder notes. |
7
+ | [Secrets](#ctxsecretsget-ctxsecretsset-ctxsecretsdelete) | The system's keychain | Keys and tokens. |
8
+
9
+ ## Config
10
+
11
+ ### `ctx.config`
12
+
13
+ ```ts
14
+ import {definePlugin} from '@type32/vertex-plugin'
15
+ import {computed} from 'vue'
16
+
17
+ interface Config {
18
+ depth: number
19
+ showTags: boolean
20
+ }
21
+
22
+ export default definePlugin<Config>({
23
+ setup(ctx) {
24
+ const depth = computed(() => ctx.config.value.depth)
25
+ void ctx.config.set({depth: 3})
26
+ },
27
+ })
28
+ ```
29
+
30
+ - `value`: the config in this window, a workspace's overrides applied, every [schema](#the-schema) field checked and
31
+ defaulted. Reactive: it follows the Settings window, other windows and a change of workspace settings.
32
+ - `set(patch, scope)`: writes paths inside the config (`{depth: 3}`, `{'colors.tags': '#f00'}`), `null` removing one.
33
+ `scope` is `global` (default: the user's settings) or `workspace` (this window's workspace, for a path the manifest
34
+ lets it override; anything else is refused).
35
+ - `overridden(path)`: whether this window's workspace overrides the path.
36
+
37
+ ### The schema
38
+
39
+ Settings the Settings window draws from `plugin.json`, without running the plugin: the plugin needs no settings page
40
+ of its own. A field's `default` is the config's default, so `ctx.config.value` has it too.
41
+
42
+ ```json
43
+ "config": {
44
+ "overridable": {"showTags": "workspace", "folder": "trustedWorkspace"},
45
+ "schema": [
46
+ {"key": "depth", "type": "number", "label": "plugins.hello.depth", "description": "plugins.hello.depthHelp", "default": 2, "min": 1, "max": 5},
47
+ {"key": "showTags", "type": "switch", "label": "plugins.hello.showTags", "default": true},
48
+ {"key": "folder", "type": "path", "kind": "folder", "label": "plugins.hello.folder", "default": ""}
49
+ ]
50
+ }
51
+ ```
52
+
53
+ | `type` | Value | Extra keys |
54
+ | --- | --- | --- |
55
+ | `switch` | `true` / `false` | |
56
+ | `text` | a string | `placeholder` |
57
+ | `color` | a CSS colour | `placeholder` |
58
+ | `number` | a number | `min`, `max`, `step` |
59
+ | `select` | one of the options' `value`s | `options: [{value, label}]` (labels are i18n keys) |
60
+ | `list` | a list of strings | `placeholder` |
61
+ | `path` | a workspace-relative path | `kind`: `file` or `folder` (its picker shows while a workspace's settings are edited) |
62
+
63
+ Every field has `key` (a path in the config: `depth`, `colors.tags`), `type`, `label` and `default`; `description`
64
+ is optional. `label`, `description` and options' labels are i18n keys of the plugin's, which `en.json` must have.
65
+
66
+ ### Workspace overrides
67
+
68
+ A workspace can change some of the user's settings for itself, in its `.vertex/settings.json`, which travels with it.
69
+ `overridable` says which of the plugin's paths: `workspace` (any workspace) or `trustedWorkspace` (only once the user
70
+ trusts it: a path a stranger's vault shouldn't set, like a folder the plugin writes to). A path not listed is the
71
+ user's only. Settings shows the overridable ones while a workspace is edited, with Changed in this workspace and Use
72
+ global.
73
+
74
+ On a page of its own, a plugin edits its config through its `config` prop (`ScopedConfig`), which is the scope
75
+ Settings is editing ([a settings page](ui.md#vertexs-components)).
76
+
77
+ ## Data
78
+
79
+ ### `ctx.data.global`, `ctx.data.workspace`
80
+
81
+ A JSON document of the plugin's: `global` in Vertex's data folder, `workspace` in the window's workspace
82
+ (`.vertex/plugins-data/<id>.json`, which travels with it; `undefined` outside a workspace window).
83
+
84
+ ```ts
85
+ const store = ctx.data.workspace
86
+ if (store) {
87
+ const colours = (await store.get() ?? {}) as Record<string, string>
88
+ await store.set({...colours, projects: 'red'})
89
+ store.onChange(value => console.log(value))
90
+ }
91
+ ```
92
+
93
+ `get()` is `undefined` until something is set; `set(value)` replaces the document, atomically; `onChange` runs after
94
+ every write from any window. Keep it small: it's read and written whole.
95
+
96
+ ## Secrets
97
+
98
+ ### `ctx.secrets.get`, `ctx.secrets.set`, `ctx.secrets.delete`
99
+
100
+ Strings in the system's keychain (macOS Keychain, Windows Credential Manager), by name, the plugin's own: Vertex's
101
+ entries are `plugin:<id>:<name>`. `get` is `undefined` for a name with none. Needs the `secrets` permission.
102
+
103
+ ```ts
104
+ await ctx.secrets.set('token', 'abc')
105
+ const token = await ctx.secrets.get('token')
106
+ ```
107
+
108
+ ## The network
109
+
110
+ ### `ctx.http.fetch`
111
+
112
+ One GET from Vertex's native side, outside the webview's CORS rules, with the `Accept` header passed on. Redirects
113
+ come back unfollowed, the body stops past 2 MiB, and addresses on this computer or the local network are refused.
114
+ Needs the `network` permission.
115
+
116
+ ```ts
117
+ const response = await ctx.http.fetch('https://api.example.com/items', {headers: {Accept: 'application/json'}})
118
+ const items = await response.json()
119
+ ```
120
+
121
+ The webview's own `fetch` works too, under the web's rules: only from servers that allow it (CORS).
122
+
123
+ ## Permissions
124
+
125
+ What a plugin may do beyond any window's own, in `plugin.json`'s `permissions`. The install dialog lists them; a call
126
+ the plugin hasn't asked for is refused.
127
+
128
+ | Permission | Grants |
129
+ | --- | --- |
130
+ | `network` | `ctx.http.fetch`. |
131
+ | `secrets` | `ctx.secrets`. |
132
+ | `files-outside-workspace` | Every file on the computer, in each window it runs in. Without it, a window reaches its workspace, the files the user picks in a dialog there, and the clipboard's. |