@coda-console/plugin-check 0.8.21 → 0.8.23

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.
@@ -7,6 +7,7 @@
7
7
  import { CORE_PROTOCOLS } from '@coda-console/protocol/protocol';
8
8
  import { pointProblem, valueProblem } from '@coda-console/protocol/validate';
9
9
  import { requireCondition as check } from '../../domain/errors.mjs';
10
+ import { payloadProblem } from '../protocols/protocol-events.mjs';
10
11
 
11
12
  const code = 'invalid_plugin';
12
13
 
@@ -71,42 +72,115 @@ export function operationProblem(plugin, plugins) {
71
72
  return null;
72
73
  }
73
74
  // A protocol's definition as this machine has it with `plugins` (the catalog): one of Coda's (namespace coda), a core
74
- // protocol of the protocol package or one Coda's components registered (`defined`: kind → its registered type, with the
75
- // title and permission groups it was registered with), else the one a plugin of the catalog defines; none without one.
75
+ // protocol of the protocol package or one of Coda's own (`defined`: kind → its definition, application/host-protocols.mjs),
76
+ // else the one a plugin of the catalog defines; none without one.
76
77
  export function protocolDefinition(kind, plugins, defined) {
77
78
  if (kind.startsWith('coda/')) return CORE_PROTOCOLS[kind] ?? defined(kind);
78
79
  return [...plugins.values()].flatMap(plugin => plugin.protocols ?? []).find(one => one.name === kind);
79
80
  }
80
- // Why a permission group a plugin uses (docs/plugins.md「用到的权限」) is not one of its protocol's definition in `plugins`
81
- // (the catalog once it is installed) or Coda's (`defined`), or null.
82
- export function usesProblem(plugin, plugins, defined) {
81
+ // What of the protocols a plugin uses (docs/plugins.md「用到的权限」) neither its definition in `plugins` (the catalog beside
82
+ // it) nor Coda's (`defined`) has: the protocol (`{ protocol }`), or one of its permission groups (`{ protocol, group }`);
83
+ // null when they have all of it.
84
+ export function usesMissing(plugin, plugins, defined) {
83
85
  for (const [kind, groups] of Object.entries(plugin.uses ?? {})) {
84
86
  const definition = protocolDefinition(kind, plugins, defined);
85
- if (!definition) return `插件 ${plugin.id} 用到的协议 ${kind} 不在这台机器上,也不随它一起装`;
86
- const missing = groups.find(group => !Object.hasOwn(definition.permissions ?? {}, group));
87
- if (missing) return `插件 ${plugin.id} 用到的协议 ${kind} 没有权限组 ${missing}`;
87
+ if (!definition) return { protocol: kind };
88
+ const group = groups.find(each => !Object.hasOwn(definition.permissions ?? {}, each));
89
+ if (group) return { protocol: kind, group };
88
90
  }
89
91
  return null;
90
92
  }
91
- // Why a plugin installing `id` installs uses a permission group `catalog` (the catalog once they are installed) or Coda
92
- // (`defined`) does not define, or null: it, and what it needs this machine has not installed (`installed`: the installed
93
- // rows by ID), as reading it and installing it both say. The plugins installed already are not checked again: what they
94
- // use is theirs to answer for (docs/plugins.md「用到的权限」). One needed and nowhere is said missing, not here.
95
- export function installingUsesProblem(catalog, installed, id, defined) {
93
+ // The first protocol a plugin implements (`protocolImplementations`) that neither it, `plugins` (the catalog beside it) nor
94
+ // Coda (`defined`) defines, as `{ protocol }`; null when all are here.
95
+ export function implementsMissing(plugin, plugins, defined) {
96
+ const found = (plugin.protocolImplementations ?? []).find(({ kind }) => !(plugin.protocols ?? []).some(one => one.name === kind) && !protocolDefinition(kind, plugins, defined));
97
+ return found ? { protocol: found.kind } : null;
98
+ }
99
+ // This Coda's API Level (docs/plugins.md「兼容」): what it offers plugins, counted. A manifest's `engines.coda` names the least
100
+ // a plugin needs; one naming none needs 0, which any Coda has.
101
+ export const API_LEVEL = 1;
102
+ // The API Level a package's registry metadata asks for in its `engines`: a positive integer, or its digits as text (what
103
+ // npm's registry may make of one); undefined when it asks for none, null when it is anything else. A manifest read from
104
+ // its directory has the schema's shape (plugin-rules.mjs readPlugin).
105
+ export function wantedLevel(engines) {
106
+ const value = engines?.coda;
107
+ if (value === undefined) return undefined;
108
+ if (Number.isInteger(value) && value >= 1) return value;
109
+ return typeof value === 'string' && /^[1-9][0-9]{0,8}$/.test(value) ? Number(value) : null;
110
+ }
111
+ // Whether a plugin runs on this machine (docs/plugins.md「兼容」): the one judgment reading a source, installing, the store and
112
+ // the catalog take. Null when it does; else what it needs (`need`), what is missing (`missing`) and why, as the user is
113
+ // told (`error`). `host`: this machine — its API Level (`level`), its backend's channel, the catalog beside the plugin and
114
+ // Coda's own protocols (`defined`, as usesMissing takes them). A Level above this Coda's is Coda's to catch up with
115
+ // (`coda`); short of that, a channel it is not for, or a protocol or permission group it uses or a protocol it implements
116
+ // that is not here, is the plugin's to update (`update`): Coda no longer offers what it was made for.
117
+ export function compatibility(plugin, { catalog = new Map(), defined = () => null, ...here }) {
118
+ const own = ownIncompatibility(plugin, here);
119
+ if (own) return own;
120
+ const used = usesMissing(plugin, catalog, defined), missing = used ?? implementsMissing(plugin, catalog, defined);
121
+ if (!missing) return null;
122
+ const { protocol, group } = missing, coda = protocol.startsWith('coda/');
123
+ const error = group ? (coda ? `本机的 Coda 已不提供 ${protocol} 的权限组 ${group},插件需要更新` : `协议 ${protocol} 已没有权限组 ${group},插件需要更新`)
124
+ : coda ? `本机的 Coda 已不提供协议 ${protocol},插件需要更新` : `${used ? '用到' : '实现'}的协议 ${protocol} 不在这台机器上,也不随它一起装`;
125
+ return { need: 'update', missing, error };
126
+ }
127
+ // What of that a plugin answers by itself, whatever else is here: the API Level it needs, the channels it is for.
128
+ export function ownIncompatibility(plugin, { level = API_LEVEL, channel = null }) {
129
+ const wanted = plugin.engines?.coda ?? 0;
130
+ if (wanted > level) return { need: 'coda', missing: { level: wanted }, error: `这个版本要 Coda API Level ≥ ${wanted}(本机 ${level}),请先升级 Coda` };
131
+ const channelProblem = pluginChannelProblem(plugin, channel);
132
+ return channelProblem ? { need: 'update', missing: { channel }, error: channelProblem } : null;
133
+ }
134
+ // The same for installing `id`, `here` this machine but for the catalog (`catalog`: the catalog once it and what comes along are installed; `installed`: the
135
+ // installed rows by ID): it, and what it needs that this machine has not installed, that one named. Those installed
136
+ // already are the catalog's to judge (components/plugins/plugins.mjs refresh). One needed and nowhere is said missing, not here.
137
+ export function installingIncompatibility(catalog, installed, id, here) {
96
138
  for (const each of withDependencies(catalog, id)) {
97
139
  if ((each !== id && installed.has(each)) || !catalog.has(each)) continue;
98
- const problem = usesProblem(catalog.get(each), catalog, defined);
99
- if (problem) return problem;
140
+ const found = compatibility(catalog.get(each), { ...here, catalog });
141
+ if (found) return each === id ? found : { ...found, error: `${each}:${found.error}` };
100
142
  }
101
143
  return null;
102
144
  }
145
+ // Whether plugin `plugin` (its catalog entry) defines kind `kind` or implements it: what it may reach of it and the events it may publish.
146
+ export const ownsProtocol = (plugin, kind) =>
147
+ (plugin.protocols ?? []).some(one => one.name === kind) || (plugin.protocolImplementations ?? []).some(one => one.kind === kind);
148
+ // What an event is about: `<kind>:<ID>`, at most 500 characters.
149
+ const SUBJECT = /^(?=.{3,500}$)[a-z][a-z0-9_-]*:\S+$/;
150
+ // Why plugin `plugin` (its catalog entry) may not publish (by `how`: publish-event, coda event, coda.emit) event `name`
151
+ // about `subject`, saying `payload`, or null — `event` the event of that name on this machine (components/protocols/
152
+ // protocol-events.mjs), or none: it is one of a protocol the plugin defines or implements and not Coda's own (`codaOnly`:
153
+ // application/host-protocols.mjs; a plugin implementing coda/thread@1 publishes no session's), about a subject it names (not a
154
+ // session's: `thread:` is Coda's), saying a JSON object its payload schema has, no more than 100 KB of it and nothing of
155
+ // `coda` (Coda's, beside it in a run). Where it is published is the backend's to check, as the backend and the plugin host
156
+ // for a plugin's tests (adapters/plugin-test-host.mjs) both check the rest.
157
+ export function publishedProblem(how, plugin, event, { name, subject, payload }) {
158
+ if (!event || !ownsProtocol(plugin, event.kind)) return `插件 ${plugin.id} 定义或实现的协议里没有事件 ${name}`;
159
+ if (event.codaOnly) return `插件 ${plugin.id} 不能发布事件 ${name}:它是 Coda 自己的协议 ${event.kind} 的,只由 Coda 发布`;
160
+ if (typeof subject !== 'string' || !SUBJECT.test(subject) || subject.startsWith('thread:'))
161
+ return `${how} 的 subject 须为「<种类>:<标识>」(如 pull_request:<地址>),不超过 500 个字符;thread: 是会话的,由 Coda 发布`;
162
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) return `${how} 的 payload 须为 JSON 对象`;
163
+ if (JSON.stringify(payload).length > 100_000) return `${how} 的 payload 不能超过 100 KB`;
164
+ if (Object.hasOwn(payload, 'coda')) return `${how} 的 payload 顶层不能有 coda,那是 Coda 的`;
165
+ const problem = payloadProblem(event, payload);
166
+ return problem && `${how} 的 payload ${problem}`;
167
+ }
168
+ // The events plugin `plugin` (its catalog entry) subscribes to: those of the event groups it uses of the protocols this
169
+ // machine has with `plugins` (the catalog) and Coda's own (`defined`, as `protocolDefinition` takes them). What its module
170
+ // may handle (`coda.on`), as the backend delivers them (./plugin-events.mjs) and the plugin host for a plugin's tests has it.
171
+ export function subscribed(plugin, plugins, defined) {
172
+ return Object.entries(plugin.uses ?? {}).flatMap(([kind, groups]) => {
173
+ const permissions = protocolDefinition(kind, plugins, defined)?.permissions ?? {};
174
+ return groups.flatMap(group => permissions[group]?.events ?? []);
175
+ });
176
+ }
103
177
  // Why plugin `plugin` (its catalog entry) may not reach kind `kind` as `need` says — an operation of it (`{ operation }`),
104
178
  // a stream of its records (`{ stream }`), or reading its records (`'read'`; writing them is the implementer's alone) —
105
179
  // `definition` its protocol's (`protocolDefinition`), or null (docs/plugins.md「用到的权限」). The plugin that implements or
106
180
  // defines the kind may; any other, a built-in one too, only by a group of the kind's it uses that has the operation or the
107
181
  // stream, or reads its records. An operation or a stream in no group is open to no plugin.
108
182
  export function usesRefusal(plugin, kind, need, definition) {
109
- if ((plugin.protocols ?? []).some(one => one.name === kind) || (plugin.protocolImplementations ?? []).some(one => one.kind === kind)) return null;
183
+ if (ownsProtocol(plugin, kind)) return null;
110
184
  const groups = Object.entries(definition?.permissions ?? {}), used = new Set(plugin.uses?.[kind] ?? []);
111
185
  const covers = ([, group]) => typeof need === 'string' ? group[need] === true
112
186
  : need.stream !== undefined ? (group.streams ?? []).includes(need.stream) : (group.operations ?? []).includes(need.operation);
@@ -142,7 +216,7 @@ export function withDependencies(catalog, id) {
142
216
  return order;
143
217
  }
144
218
  // A channel restriction is the target backend's, never the client's. An unknown channel cannot satisfy an explicit list.
145
- // The store reads registry metadata; installation reads the package itself. Both use the same schema and rule.
219
+ // The store reads registry metadata; installation reads the package itself. Both judge it so (compatibility).
146
220
  export function pluginChannelProblem(plugin, channel) {
147
221
  if (plugin.coda === undefined) return null;
148
222
  const problem = valueProblem('plugin.json#/properties/coda', plugin.coda, 'coda');
@@ -152,14 +226,6 @@ export function pluginChannelProblem(plugin, channel) {
152
226
  const names = channels.map(value => value === 'preview' ? '预览版' : '正式版').join('或');
153
227
  return `此插件仅支持 Coda ${names}后端${channel ? '' : ',当前后端没有发布通道记录'}`;
154
228
  }
155
- // The same dependency closure used by installation, after resolving each dependency to its actual local or source version.
156
- export function catalogChannelProblem(catalog, id, channel) {
157
- for (const each of withDependencies(catalog, id)) {
158
- const plugin = catalog.get(each), problem = plugin && pluginChannelProblem(plugin, channel);
159
- if (problem) return each === id ? problem : `${each}:${problem}`;
160
- }
161
- return null;
162
- }
163
229
  // The installed plugins that need this one, directly or through another, by ID.
164
230
  export function dependents(catalog, installed, id) {
165
231
  const found = new Set();
@@ -24,8 +24,6 @@ import { claims, COMMIT, INTEGRITY, NPM_VERSION, npmPluginId, repoAddress, sourc
24
24
  import { CONTRIBUTION_POINTS } from './contribution-points.mjs';
25
25
 
26
26
  const ID = /^[a-z][a-z0-9-]{0,39}$/;
27
- // The domains of the events Coda publishes itself; a plugin's are of a domain of its own (schemas/events.json).
28
- export const CODA_EVENT_DOMAINS = ['workflow', 'session', 'user'];
29
27
  // Plugins that ship with Coda, as VS Code's built-in extensions ship with it: updated with Coda itself.
30
28
  export const BUILTIN_DIR = fileURLToPath(new URL('../../resources/plugins/', import.meta.url));
31
29
  // The package the backend runs from (the runtime clone's, or the release's), whose npm dependencies may be built-in plugins
@@ -131,8 +129,10 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
131
129
  category: manifestCategory(manifest), ...(icon ? { icon } : {}), ...(readmeFile(dir) ? { readme: true } : {}),
132
130
  source, dir, title: typeof configuration.title === 'string' ? configuration.title : displayName, properties,
133
131
  ...(manifest.coda !== undefined ? { coda: manifest.coda } : {}),
132
+ // The API Level it needs (plugin-extensions.mjs compatibility).
133
+ ...(manifest.engines?.coda !== undefined ? { engines: { coda: manifest.engines.coda } } : {}),
134
134
  // The permission groups of others' protocols it uses (docs/plugins.md「用到的权限」), by protocol: checked against the
135
- // catalog as it is installed (plugin-extensions.mjs usesProblem).
135
+ // catalog it is installed into, and whenever the catalog is read (plugin-extensions.mjs compatibility).
136
136
  ...(manifest.uses && Object.keys(manifest.uses).length ? { uses: structuredClone(manifest.uses) } : {}),
137
137
  ...(manifest.main ? { main: posix.normalize(manifest.main) } : {}), ...(activation.includes('onStartupFinished') ? { startup: true } : {}),
138
138
  ...(required.length ? { required: [...required] } : {}), workflows: files('.coda/workflows'),
@@ -7,8 +7,9 @@
7
7
  import { createHash } from 'node:crypto';
8
8
  import { normalize } from 'node:path';
9
9
  import { requireCondition as check } from '../../domain/errors.mjs';
10
- import { catalogChannelProblem, installingUsesProblem, offerPoint, offeredCommands, offerProblem, protocolDefinition, withDependencies } from './plugin-extensions.mjs';
10
+ import { installingIncompatibility, offerPoint, offeredCommands, offerProblem, protocolDefinition, withDependencies } from './plugin-extensions.mjs';
11
11
  import { CONTRIBUTION_POINTS } from './contribution-points.mjs';
12
+ import { definedEvents, eventsProblem } from '../protocols/protocol-events.mjs';
12
13
 
13
14
  export const COMMIT = /^[0-9a-f]{40}$/;
14
15
  const ID = /^[a-z][a-z0-9-]{0,39}$/;
@@ -169,7 +170,8 @@ export function npmManifest(id, own, skills) {
169
170
  }
170
171
  if (!Object.keys(contributes).length) return { problem: '这个 npm 包读不成插件:package.json 没有 contributes,没有 Skill 目录,也不是写了 mcpName 的 MCP 服务器' };
171
172
  return { manifest: { name: id, displayName: own.name, description: typeof own.description === 'string' ? own.description.slice(0, 500) : '',
172
- version: String(own.version ?? ''), ...(own.coda !== undefined ? { coda: own.coda } : {}), contributes } };
173
+ version: String(own.version ?? ''), ...(own.coda !== undefined ? { coda: own.coda } : {}),
174
+ ...(own.engines?.coda !== undefined ? { engines: { coda: own.engines.coda } } : {}), contributes } };
173
175
  }
174
176
  // The packages npm installs for a package from npm, by name with the range it asks for: its dependencies are not pinned
175
177
  // (docs/plugins.md「从 npm 安装」), unless it brings an `npm-shrinkwrap.json`, whose versions they then are. Among them the
@@ -265,7 +267,7 @@ export const claims = plugin => [...[...CONTRIBUTION_POINTS.values()].flatMap(po
265
267
  // Why a plugin cannot sit beside those this machine has (`catalog`: built-in and installed, by ID; `builtin`: the plugins
266
268
  // Coda ships, by ID), or null: an installed built-in one's ID from another source (builtinProblem), what a component's
267
269
  // contribution point lets only a built-in plugin bring (its `builtinOnly`, of the plugin read: why, none when it brings none
268
- // of it), or what only one plugin may declare (claims) another plugin declares. What it needs of the others — the plugins it depends on,
270
+ // of it), or what only one plugin may declare (claims), a protocol or an event of one, another plugin declares. What it needs of the others — the plugins it depends on,
269
271
  // the points it plugs into or writes for (plugin-extensions.mjs offerProblem) — is checked once all of them are there.
270
272
  export function catalogProblem(plugin, catalog, builtin, installed) {
271
273
  const named = builtinProblem(plugin.id, plugin.source, builtin, installed);
@@ -284,7 +286,14 @@ export function catalogProblem(plugin, catalog, builtin, installed) {
284
286
  const owner = [...catalog.values()].find(p => p.id !== plugin.id && p.protocols?.some(other => other.name === definition.name));
285
287
  if (owner) return `协议 ${definition.name} 已由插件 ${owner.displayName} 定义`;
286
288
  }
287
- return null;
289
+ // An event is known by its name on this machine (components/protocols/protocol-events.mjs): one protocol's alone.
290
+ const events = definedEvents(plugin), again = events.find((name, i) => events.indexOf(name) !== i);
291
+ if (again) return `事件 ${again} 在插件的两个协议里都定义了`;
292
+ for (const name of events) {
293
+ const owner = [...catalog.values()].find(p => p.id !== plugin.id && definedEvents(p).includes(name));
294
+ if (owner) return `事件 ${name} 已由插件 ${owner.displayName} 的协议定义`;
295
+ }
296
+ return eventsProblem(plugin);
288
297
  }
289
298
  // What installing a plugin from a repository brings along, in the order installing does it (components/plugins/plugin-extensions.mjs
290
299
  // withDependencies, as components/plugins/plugins.mjs installFrom): what this version of it needs, directly or through another,
@@ -349,7 +358,7 @@ export function contributions(plugin, catalog = new Map(), defined = () => null)
349
358
  }
350
359
  // Each permission group it uses (docs/plugins.md「用到的权限」): its protocol, by the definition's title (its name without
351
360
  // one), and what the group lets it do, whether on trial; by protocol, then group. One its protocol does not define is
352
- // why it cannot be installed (usesProblem), not listed.
361
+ // why it cannot be installed (plugin-extensions.mjs compatibility), not listed.
353
362
  function permissions(plugin, catalog, defined) {
354
363
  return Object.entries(plugin.uses ?? {}).flatMap(([kind, groups]) => {
355
364
  const definition = protocolDefinition(kind, catalog, defined), declared = definition?.permissions ?? {};
@@ -365,20 +374,21 @@ export const manifestId = manifest => manifest?.id ?? manifest?.name;
365
374
  // One plugin of a source as its reading lists it, said against what this machine has (`known`: the catalog, the installed
366
375
  // rows, the built-in plugins): what it is, the one of its ID installed here, why it cannot be installed, what comes along
367
376
  // with it (`siblings`: the other plugins of the same commit, by ID) and what it brings. `manifest`: what is known of it
368
- // when it does not read as a plugin, its ID `fallback` without a name. `defined`: the protocols Coda defines, for the
369
- // permission groups it and what comes along use (plugin-extensions.mjs installingUsesProblem).
370
- export function candidate({ path, manifest, plugin, problem, fallback }, { catalog, installed, builtin, channel, defined = () => null }, siblings) {
377
+ // when it does not read as a plugin, its ID `fallback` without a name. `channel`, `level` and `defined` (the protocols
378
+ // Coda defines): this machine, which it and what comes along are judged against (plugin-extensions.mjs compatibility);
379
+ // one that does not run here says why in `incompatible`, as installing it and the store say.
380
+ export function candidate({ path, manifest, plugin, problem, fallback }, { catalog, installed, builtin, channel, level, defined = () => null }, siblings) {
371
381
  const id = plugin?.id ?? (typeof manifestId(manifest) === 'string' ? manifestId(manifest) : fallback);
372
382
  const row = installed.get(id), along = plugin ? together(plugin, { catalog, installed, siblings, defined }) : [];
373
383
  const missing = along.filter(each => each.from === 'missing').map(each => each.id);
374
384
  // What this machine has once it is installed, those installed with it among them: the points it may write for.
375
385
  const after = plugin ? catalogAfter(plugin, { catalog, siblings }) : catalog;
386
+ const incompatible = plugin ? installingIncompatibility(after, installed, id, { channel, level, defined }) : null;
376
387
  return { path, id, displayName: plugin?.displayName ?? (typeof manifest?.displayName === 'string' ? manifest.displayName : id),
377
388
  description: plugin?.description ?? (typeof manifest?.description === 'string' ? manifest.description : ''), version: plugin?.version ?? '',
378
389
  installed: row ? row.source ?? builtin.get(id)?.source ?? { kind: 'builtin' } : null,
379
- problem: problem ?? (plugin ? catalogChannelProblem(after, id, channel) ?? catalogProblem(plugin, catalog, builtin, installed) ?? offerProblem(plugin, after)
380
- ?? installingUsesProblem(after, installed, id, defined) : null)
390
+ problem: problem ?? incompatible?.error ?? (plugin ? catalogProblem(plugin, catalog, builtin, installed) ?? offerProblem(plugin, after) : null)
381
391
  ?? (missing.length ? `要一起装的 ${missing.join('、')} 不在这台机器上${plugin.source?.kind === 'npm' ? '' : ',也不在这个提交里'}` : null),
382
- together: along.filter(each => each.from !== 'missing'),
392
+ ...(!problem && incompatible ? { incompatible } : {}), together: along.filter(each => each.from !== 'missing'),
383
393
  ...(plugin ? { contributes: contributions(plugin, after, defined) } : {}) };
384
394
  }
@@ -0,0 +1,49 @@
1
+ // The events of this machine's protocols (docs/plugins.md「事件」), each as its protocol's definition says it (`events`,
2
+ // @coda-console/protocol definition.json): those of Coda's own definitions (application/host-protocols.mjs),
3
+ // and those the plugins of the catalog define. An event is known by its name, one on this machine: a plugin defining one
4
+ // another plugin's protocol has is refused as it is installed (components/plugins/plugin-source-rules.mjs catalogProblem).
5
+ // Its version is its protocol's major version.
6
+ import { newAjv } from '@coda-console/protocol/validate';
7
+
8
+ // The events of protocol `kind` (`events` as its definition has them), each `{ name, kind, payload, starts, ends, codaOnly }`:
9
+ // `payload`, the JSON Schema of what it says; `starts`, whether it may start a workflow's run (false: only handed to those
10
+ // going for its subject already); `ends`, whether it ends its subject; `codaOnly`, whether the protocol is Coda's own, its
11
+ // events Coda's alone to publish.
12
+ const eventsOf = (kind, events = {}, codaOnly = false) => Object.entries(events).map(([name, event]) =>
13
+ ({ name, kind, payload: event.payload, starts: event.starts !== false, ends: event.ends === true, codaOnly }));
14
+
15
+ // The names of the events a plugin's own protocols define.
16
+ export const definedEvents = plugin => (plugin.protocols ?? []).flatMap(definition => Object.keys(definition.events ?? {}));
17
+
18
+ // Every event on this machine, by name: of Coda's definitions `coda` (each `{ kind, events }`) and those of
19
+ // the plugins of `catalog` (plugin ID → its catalog entry). Coda's own are never another's: a definition of the same name
20
+ // does not take one of them over.
21
+ export function protocolEvents(catalog, coda = []) {
22
+ return new Map([...[...catalog.values()].flatMap(plugin => (plugin.protocols ?? []).flatMap(({ name, events }) => eventsOf(name, events))),
23
+ ...[...coda].flatMap(({ kind, events }) => eventsOf(kind, events, true))]
24
+ .map(event => [event.name, event]));
25
+ }
26
+
27
+ // The check of what an event says (`payload`, its JSON Schema), compiled the one way it is here, as the protocol package
28
+ // compiles a definition's schemas (@coda-console/protocol protocol.mjs definitionProblem): as installing it and reading
29
+ // the catalog again check (eventsProblem), as it is published (payloadProblem). Once each, as long as it is read; throws
30
+ // when it does not compile.
31
+ const ajv = newAjv({ ownProperties: true, addUsedSchema: false, strict: false }), compiled = new WeakMap();
32
+ function payloadCheck(payload) {
33
+ if (typeof payload !== 'object') return ajv.compile(payload);
34
+ if (!compiled.has(payload)) compiled.set(payload, ajv.compile(payload));
35
+ return compiled.get(payload);
36
+ }
37
+ // Why the payload schema of an event of a plugin's protocols does not compile here, or null.
38
+ export function eventsProblem(plugin) {
39
+ for (const { name, events = {} } of plugin.protocols ?? []) for (const [event, { payload }] of Object.entries(events)) {
40
+ try { payloadCheck(payload); } catch (e) { return `协议 ${name} 的事件 ${event} 的 payload 不是可用的 JSON Schema:${e.message}`; }
41
+ }
42
+ return null;
43
+ }
44
+ // Why what an event says is not as its payload schema has it, or null: the schema not compiling too.
45
+ export function payloadProblem(event, value) {
46
+ let check;
47
+ try { check = payloadCheck(event.payload); } catch (e) { return `没法按事件 ${event.name}(${event.kind})的格式查:它的 payload schema 编不过(${e.message})`; }
48
+ return check(value) ? null : `不合事件 ${event.name}(${event.kind})的格式:${ajv.errorsText(check.errors, { dataVar: 'payload' })}`;
49
+ }
@@ -6,22 +6,27 @@ import { derivedUUID } from '../../domain/values.mjs';
6
6
 
7
7
  // Where a kind's records are, said once for every kind (Protocols `register` reads it). The kinds only this machine keeps:
8
8
  // Coda's composers and what is submitted through them, the runs of its posts to sessions, and the kinds it serves whole
9
- // from its own tables: `coda/thread@1`, `coda/card@1`, `coda/plugin@1` and the workflows' `coda/workflow@1` and
10
- // `coda/workflow-run@1` (one of another backend is found by asking the space: mirror.mjs `place`). `coda/session@1` is shared (Coda's sessions are served beside
9
+ // from its own tables: `coda/thread@1`, `coda/project@1`, `coda/card@1`, `coda/plugin@1` and the workflows' `coda/workflow@1`
10
+ // and `coda/workflow-run@1` (one of another backend is found by asking the space: mirror.mjs `place`). `coda/session@1` is shared (Coda's sessions are served beside
11
11
  // it, a plugin's external sessions are written in the record directory). They are never in the record directory, and no
12
12
  // plugin writes one. Every other kind, every one a plugin defines among them, is shared: its records are this machine's rows of
13
13
  // the record directory, which the other backends of a space copy.
14
- export const LOCAL_KINDS = new Set(['coda/composer@1', 'coda/submission@1', 'coda/run@1', 'coda/thread@1', 'coda/card@1',
14
+ export const LOCAL_KINDS = new Set(['coda/composer@1', 'coda/submission@1', 'coda/run@1', 'coda/thread@1', 'coda/project@1', 'coda/card@1',
15
15
  'coda/plugin@1', 'coda/workflow@1', 'coda/workflow-run@1']);
16
- // `list(kind, { scope?, id? })`: this machine's records (`local`) or this machine's and the others' (`available`, unsaid),
17
- // all of them or those of an ID.
16
+ // `list(kind, { scope?, id?, labels? })`: this machine's records (`local`) or this machine's and the others' (`available`,
17
+ // unsaid), all of them, those of an ID, or those whose labels have each of these values (`labels`, as Kubernetes' equality
18
+ // selector: nothing but equality).
18
19
  export function readFilter(filter) {
19
20
  check(filter == null || (typeof filter === 'object' && !Array.isArray(filter)), 'invalid_input', '筛选须为对象');
20
- const { scope = 'available', id, ...rest } = filter ?? {};
21
+ const { scope = 'available', id, labels, ...rest } = filter ?? {};
21
22
  check(['local', 'available'].includes(scope) && !Object.keys(rest).length && (id === undefined || (typeof id === 'string' && id)),
22
- 'invalid_input', '筛选只认 scope(local 或 available)和 id');
23
- return { scope, id };
23
+ 'invalid_input', '筛选只认 scope(local 或 available)、id 和 labels');
24
+ check(labels === undefined || (labels && typeof labels === 'object' && !Array.isArray(labels) && Object.values(labels).every(value => typeof value === 'string')),
25
+ 'invalid_input', '筛选的 labels 须为文本键值对象');
26
+ return { scope, id, labels };
24
27
  }
28
+ // Whether a record's labels have each value a filter's `labels` asks for (none asked, any record has).
29
+ export const labelled = (labels, asked) => asked === undefined || Object.entries(asked).every(([name, value]) => labels?.[name] === value);
25
30
  // `get({ kind, id })`.
26
31
  export function readRef(ref) {
27
32
  const { kind, id, ...rest } = ref ?? {};
@@ -23,7 +23,7 @@ export class ProtocolTypes {
23
23
  constructor() { this.types = new Map(); }
24
24
  // `side`: for one of Coda's own protocols, the side of the call kernel on each backend that does its doing operations
25
25
  // (`<backend ID>/<side>`, components/plugins/plugin-callers.mjs `route`); none for one a plugin implements.
26
- register({ kind, title, spec, status, operations = {}, streams = {}, permissions, contributions = {}, participants = () => [], side }, registered = () => {}, replace = false) {
26
+ register({ kind, title, spec, status, operations = {}, streams = {}, contributions = {}, participants = () => [], side }, registered = () => {}, replace = false) {
27
27
  if (!parseProtocolName(kind) || (this.types.has(kind) && !replace)) throw new TypeError(`协议名无效或已登记:${kind}`);
28
28
  if (spec?.type !== 'object' || status?.type !== 'object') throw new TypeError(`${kind}: spec 与 status 须为对象 schema`);
29
29
  if (typeof participants !== 'function' || !object(contributions)) throw new TypeError(`${kind}: 需要 participants 与 contributions`);
@@ -62,9 +62,9 @@ export class ProtocolTypes {
62
62
  }
63
63
  Object.defineProperty(properties, field, { value: schema, enumerable: true });
64
64
  }
65
- // Its title and permission groups as defined (@coda-console/protocol definition.json), for what a plugin's `uses` names
66
- // (components/plugins/plugin-extensions.mjs usesProblem).
67
- const type = { kind, ...(title ? { title } : {}), ...(permissions ? { permissions: structuredClone(permissions) } : {}), ...(side ? { side } : {}),
65
+ // Its title as defined (@coda-console/protocol definition.json). Its permission groups are judged as defined, not as
66
+ // registered (components/plugins/plugin-extensions.mjs compatibility).
67
+ const type = { kind, ...(title ? { title } : {}), ...(side ? { side } : {}),
68
68
  participants, contributions: structuredClone(contributions), operations: compiled, streams: readable,
69
69
  spec: compile(spec, defaults), status: compile(status, defaults),
70
70
  // Before supplementation only merge operands must be shaped correctly. Required fields and counts apply to the
@@ -1,5 +1,6 @@
1
1
  // What workflows take of plugins (components/plugins/contribution-points.mjs): the capabilities a plugin's workflows
2
- // stand for (schemas/capabilities.json) and the events it publishes (schemas/events.json), defined as this module loads.
2
+ // stand for (schemas/capabilities.json), defined as this module loads. The events it publishes are its protocols'
3
+ // (components/protocols/protocol-events.mjs).
3
4
  // Its concurrency groups are its coda/group@1 records (components/concurrency-groups/schemas.mjs), not of its manifest.
4
5
  // Descriptions only: nothing here imports a component, for the plugins read with them are read before any is made.
5
6
  import { defineContributionPoint } from '../plugins/contribution-points.mjs';
@@ -7,4 +8,3 @@ import { SCHEMAS } from '@coda-console/protocol/validate';
7
8
 
8
9
  defineContributionPoint({ key: 'capabilities', schema: SCHEMAS['capabilities.json'], read: (raw = []) => ({ capabilities: [...raw].sort() }),
9
10
  confirm: plugin => ({ capabilities: plugin.capabilities }) });
10
- defineContributionPoint({ key: 'events', schema: SCHEMAS['events.json'], read: raw => raw?.length ? { events: raw.map(e => ({ name: e.name, starts: e.starts !== false, ...(e.ends ? { ends: true } : {}) })) } : {} });