@coda-console/plugin-check 0.8.27 → 0.8.28

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/check/index.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  // The contract check of one plugin directory: the manifest and its workflows, its module if it has one, then each agent's handshake (and with `live`, a
2
- // turn) and each resource type's (or panel's) reading. The manifest is checked against Coda's schemas of its types and its workflows against Coda's
2
+ // turn) and the reading of its resource records. The manifest is checked against Coda's schemas of its types and its workflows against Coda's
3
3
  // dialect of BPMN (both the protocol's), the rest by Coda's own code (check/coda/), run where a plugin is written.
4
4
  import { resolve } from 'node:path';
5
5
  import { checkAgent } from './agent.mjs';
6
6
  import { checkLevel } from './level.mjs';
7
7
  import { checkManifest } from './manifest.mjs';
8
8
  import { checkModule } from './module.mjs';
9
- import { checkPanel } from './panel.mjs';
10
9
  import { checkResources, RESOURCE } from './resources.mjs';
11
10
  import { checkWorkflows } from './workflows.mjs';
12
11
  import { Report } from './report.mjs';
@@ -22,12 +21,11 @@ export async function checkPlugin(dir, { agent: only = null, manifestOnly = fals
22
21
  if (only && !agents.length) report.scope('manifest').fail('options.agent', `清单里没有能检查的 Agent ${only}`);
23
22
  const resources = plugin.plugin.records?.some(one => one.kind === RESOURCE);
24
23
  if (manifestOnly) {
25
- if (agents.length || plugin.panels.length || resources) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
24
+ if (agents.length || resources) report.scope('handshake').skip('options.manifest', '只查清单(--manifest):不启动 Agent、不读资源');
26
25
  return { report, plugin };
27
26
  }
28
27
  if (plugin.plugin.main) await checkModule({ checked: plugin, say: report.scope('module'), note: report.scope('note'), limit: limits?.activate });
29
28
  for (const agent of agents) await checkAgent({ agent, checked: plugin, live, prompt, limits, say: level => report.scope(level, `Agent ${agent.id}`) });
30
- if (!only) for (const panel of plugin.panels) await checkPanel({ panel, checked: plugin, say: report.scope('handshake', `${panel.format === 'resources' ? '资源类型' : '面板'} ${panel.id}`) });
31
29
  if (!only && resources) await checkResources({ checked: plugin, say: report.scope('handshake', `资源记录 ${RESOURCE}`) });
32
30
  return { report, plugin };
33
31
  }
@@ -1,4 +1,4 @@
1
- // What the checker starts and makes goes however it ends: the process groups of agents and panels it started (detached,
1
+ // What the checker starts and makes goes however it ends: the process groups of agents and record commands it started (detached,
2
2
  // so a Ctrl-C at the terminal does not reach them), what stops those it had Coda's code start, and its temporary
3
3
  // directories. bin/check.mjs turns SIGINT and SIGTERM into an exit, which runs this.
4
4
  import { mkdtempSync, rmSync } from 'node:fs';
@@ -13,9 +13,8 @@ import { HOST_PROTOCOLS } from './coda/application/host-protocols.mjs';
13
13
  import shipped from './coda/builtin.json' with { type: 'json' };
14
14
  import { CORE_PROTOCOLS } from '@coda-console/protocol/protocol';
15
15
  import { manifestProblem } from '@coda-console/protocol/validate';
16
- import { offerProblem, protocolDefinition, usesMissing } from './coda/components/plugins/plugin-extensions.mjs';
16
+ import { offerProblem, ownIncompatibility, protocolDefinition, usesMissing } from './coda/components/plugins/plugin-extensions.mjs';
17
17
  import { choosesModelProviders, pluginEnv, readPlugin, resolveSettings } from './coda/components/plugins/plugin-rules.mjs';
18
- import { panelDeclarations } from './coda/resources/plugins/resources/panels/rules.mjs';
19
18
 
20
19
  // The plugins Coda ships, by ID. Their files are Coda's, not here: none has a directory on this machine.
21
20
  const builtin = new Map(shipped.map(plugin => [plugin.id, { ...plugin, dir: undefined }]));
@@ -63,7 +62,7 @@ function pageSize(data) {
63
62
  }
64
63
 
65
64
  // Checks the manifest in `dir` and reports under `say` (report.mjs). Returns what the later levels need — the plugin as Coda
66
- // reads it, its agents and the panels the resources plugin can read, its settings for every project, the directories of the
65
+ // reads it, its agents, its settings for every project, the directories of the
67
66
  // plugins it depends on that are here, `definitionOf(kind)`, a protocol's definition as far as it is here (its own, Coda's
68
67
  // or a plugin's beside it; undefined if not), `definitions`, all of those that are here, and `env(stateDir)`, what Coda gives each of its processes —; null when it is no
69
68
  // plugin, or not of the types it names.
@@ -132,11 +131,10 @@ export function checkManifest(dir, say) {
132
131
  else say.pass('manifest.events', `用到 ${kind} 的权限组 ${group}:不含事件`);
133
132
  }
134
133
  }
135
- // Its resource types, or the panels before them, as the resources plugin reads what is written for its point once that is
136
- // of the point's schema: one declaring types has those alone.
137
- const format = plugin.offers?.resources ? 'resources' : 'panels', what = format === 'resources' ? '资源类型' : '面板';
138
- const panels = offered ? [] : panelDeclarations(plugin.offers?.[format]).map(panel => ({ ...panel, format }));
139
- for (const panel of panels) say.pass('manifest.panels', `${what} ${panel.id}「${panel.title}」:动作 ${Object.keys(panel.actions).join('、') || '无'}${panel.signIn ? ',可从 Coda 登录' : ''}`);
134
+ // The keys of `contributes` Coda retired (`resources`, `panels`): a manifest still writing one is one Coda calls for an update
135
+ // (ownIncompatibility, of the retired keys alone: the Level and the channel are another level's and the installing machine's).
136
+ const retired = ownIncompatibility({ retired: plugin.retired }, {});
137
+ if (retired) say.fail('manifest.retired', retired.error);
140
138
 
141
139
  // What its processes are given (pluginEnv): the plugins it depends on, those beside it here; one Coda ships has its
142
140
  // directory in Coda, not here, even with one of its ID beside it (Coda picks its own), and one found nowhere is not named.
@@ -152,6 +150,6 @@ export function checkManifest(dir, say) {
152
150
  // The model services of a machine with none, for one that chooses them; the PATH has no directories of Coda's own here.
153
151
  const env = stateDir => pluginEnv({ catalog: given, installed, id: plugin.id, stateDir: id => id === plugin.id ? stateDir : null, settings,
154
152
  providers: choosesModelProviders(plugin) ? {} : null, userPath: process.env.PATH ?? '' });
155
- return { id: plugin.id, manifest, plugin, agents: plugin.agents, panels, settings, dependencies, env, definitionOf: kind => protocolDefinition(kind, protocols, hosted),
153
+ return { id: plugin.id, manifest, plugin, agents: plugin.agents, settings, dependencies, env, definitionOf: kind => protocolDefinition(kind, protocols, hosted),
156
154
  definitions: [...Object.values(CORE_PROTOCOLS), ...HOST_PROTOCOLS, ...[...protocols.values()].flatMap(each => each.protocols ?? [])] };
157
155
  }
package/check/module.mjs CHANGED
@@ -20,7 +20,6 @@ export const NOT_PROVIDED = {
20
20
  'services.register': { message: '测试宿主没有后端,不答 serviceRegister' },
21
21
  tell: { message: '测试宿主没有后端,不答 tell' },
22
22
  api: { message: 'Coda 还在启动,稍后再试' },
23
- environment: { message: '测试宿主没有后端,不答 environment' },
24
23
  'protocols.resolve': { message: '测试宿主没有后端,不答 provider' },
25
24
  'protocols.upload': { message: '测试宿主没有后端,不答 provider' },
26
25
  'pluginSetup.retry': { code: 'unsupported', message: '测试宿主不提供 coda.pluginSetup' },
package/check/report.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // What a check found, in the order found: each line a level (清单, 模块, 握手, 一轮, 说明), what it is about (the plugin, an agent, a panel),
1
+ // What a check found, in the order found: each line a level (清单, 模块, 握手, 一轮, 说明), what it is about (the plugin, an agent, a resource record),
2
2
  // whether it passed, failed, was skipped or is worth a look (warn, info), a rule ID the tests name, and a line of Chinese.
3
3
  export const LEVELS = { manifest: '清单', module: '模块', handshake: '握手', live: '一轮', note: '说明' };
4
4
  const MARKS = { pass: '✓', fail: '✗', warn: '!', skip: '-', info: '·' };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coda-console/plugin-check",
3
- "version": "0.8.27",
4
- "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源类型(与旧的面板)。",
3
+ "version": "0.8.28",
4
+ "description": "Coda 插件的契约检查:扮演 Coda 读清单、启动 Agent 讲 ACP 与 _coda/wait、读资源记录。",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -13,7 +13,8 @@
13
13
  },
14
14
  "exports": {
15
15
  "./types": "./check/coda/adapters/plugin-test-host.d.mts",
16
- "./test-host": "./check/coda/adapters/plugin-test-host.mjs"
16
+ "./test-host": "./check/coda/adapters/plugin-test-host.mjs",
17
+ "./resources": "./check/resources.mjs"
17
18
  },
18
19
  "bin": {
19
20
  "coda-plugin-check": "bin/check.mjs"
@@ -3,20 +3,23 @@
3
3
  "displayName": "运行时间(模板)",
4
4
  "description": "最小的资源插件模板",
5
5
  "version": "1.0.0",
6
+ "engines": {
7
+ "coda": 6
8
+ },
6
9
  "contributes": {
7
- "resources": [
10
+ "protocolImplementations": [
8
11
  {
9
- "id": "uptime",
10
- "title": "运行时间",
11
- "command": "node \"$CODA_PLUGIN_PATH/scripts/resources.mjs\"",
12
- "maxAge": "PT1M",
13
- "actions": {
14
- "mark": {
15
- "command": "node \"$CODA_PLUGIN_PATH/scripts/mark.mjs\"",
16
- "confirm": "记下此刻?\n之后显示距这次记下过了多久。"
17
- }
12
+ "kind": "coda/resource@1",
13
+ "commands": {
14
+ "act": "scripts/act.mjs"
18
15
  }
19
16
  }
17
+ ],
18
+ "records": [
19
+ {
20
+ "kind": "coda/resource@1",
21
+ "command": "scripts/resource.mjs"
22
+ }
20
23
  ]
21
24
  }
22
25
  }
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ // 资源上按钮的动作(`coda/resource@1` 的 `act` 操作,contributes.protocolImplementations 里的 commands.act):
3
+ // Coda 在点按钮(并确认)后运行它,`{ action, args }` 在标准输入里(args 是按钮带的参数,这个按钮没带,是 {})。
4
+ // 退出码 0 且标准输出是 `{}` 就算成功;失败就退出 1,标准错误的最后一行是按钮旁显示的原因。
5
+ // 不认识的动作要让调用失败,不要悄悄成功。
6
+ import { readFileSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ // 「记下此刻」:存在插件的状态目录里(CODA_PLUGIN_STATE,跨读取、跨版本保留),记录命令下次运行时读它。
10
+ function mark() {
11
+ writeFileSync(join(process.env.CODA_PLUGIN_STATE, 'mark.json'), JSON.stringify({ at: new Date().toISOString() }));
12
+ }
13
+
14
+ const actions = { mark };
15
+ const { action } = JSON.parse(readFileSync(0, 'utf8'));
16
+ try {
17
+ if (!Object.hasOwn(actions, action)) throw new Error(`不认识的动作:${action}`);
18
+ actions[action]();
19
+ console.log('{}');
20
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
@@ -1,6 +1,9 @@
1
- // 「运行时间」资源类型的取数命令:Coda 在打开资源页或点「刷新」时用 `sh -c` 运行它,标准输出就是资源的 JSON
2
- // (docs/plugins.md「资源」)。`node` 是 Coda 后端自己的 Node;只用 Node 自带的模块。
3
- // 读不懂的键会让这次读取失败;格式里没有说明性的字段,每个资源只有名字、读数、一行错误和按钮。
1
+ #!/usr/bin/env node
2
+ // 「运行时间」资源类型的记录命令(`coda/resource@1` 的记录,清单的 contributes.records):Coda 在启动、更新、设置改动、
3
+ // 动作之后与资源页打开、点「刷新」时运行它(清单里写 `every` 才另按周期运行)。标准输出是这个插件在这台机器上这一类的
4
+ // 整组记录:`[{ key, spec }]`,key 是类型 ID,spec.type 与它相同。`node` 是 Coda 后端自己的 Node;只用 Node 自带的模块。
5
+ // 读不懂的键会让这次写入失败;记录里没有说明性的字段,每个资源只有名字、读数、一行错误和按钮。
6
+ // 命令失败(退出 1,标准错误的最后一行写原因)就保留 Coda 已有的记录,不写空的。
4
7
  import { execFileSync } from 'node:child_process';
5
8
  import { readFileSync } from 'node:fs';
6
9
  import { cpus, loadavg, uptime } from 'node:os';
@@ -19,7 +22,7 @@ const since = seconds => {
19
22
  const days = Math.floor(seconds / 86400), hours = Math.floor(seconds % 86400 / 3600), minutes = Math.floor(seconds % 3600 / 60);
20
23
  return days ? `${days} 天 ${hours} 小时` : hours ? `${hours} 小时 ${minutes} 分钟` : `${minutes} 分钟`;
21
24
  };
22
- // 按钮动作记下的时刻,存在插件的状态目录里(CODA_PLUGIN_STATE,跨读取、跨版本保留)。
25
+ // 按钮动作(scripts/act.mjs)记下的时刻,存在插件的状态目录里(CODA_PLUGIN_STATE,跨读取、跨版本保留)。
23
26
  function marked() {
24
27
  try { return JSON.parse(readFileSync(join(process.env.CODA_PLUGIN_STATE, 'mark.json'), 'utf8')).at; } catch { return null; }
25
28
  }
@@ -32,4 +35,6 @@ const values = [
32
35
  { label: '已开机', value: since(up), time: new Date(Date.now() - up * 1000).toISOString() },
33
36
  ...(mark ? [{ label: '距上次记下', value: since((Date.now() - Date.parse(mark)) / 1000) }] : []),
34
37
  ];
35
- process.stdout.write(JSON.stringify({ resources: [{ values, actions: [{ label: '记下此刻', action: 'mark' }] }] }));
38
+ // 按钮调 `act` 操作(scripts/act.mjs)做 `mark`;confirm 是执行前问的话。
39
+ const buttons = [{ label: '记下此刻', action: 'mark', confirm: '记下此刻?\n之后显示距这次记下过了多久。' }];
40
+ process.stdout.write(JSON.stringify([{ key: 'uptime', spec: { type: 'uptime', title: '运行时间', resources: [{ values, buttons }] } }]));
@@ -1,313 +0,0 @@
1
- // The resource types installed plugins bring to this machine's resources page (docs/plugins.md「资源」), read and acted on
2
- // here, in the resources plugin's module: what each plugin declares comes from Coda's collection of the installed plugins
3
- // (`coda.watch("plugins")`), and each command runs with that plugin's own environment (`coda.environment(null, { plugin })`),
4
- // as Coda gives every process of the plugin's, with no token of its (docs/plugins.md「令牌」: a module never holds another
5
- // plugin's; the host is to run them, coda#2749 H9). A plugin declaring `resources` has those; one still declaring the panels
6
- // before them has its panels, read as they were (`format`), for the page to take as resources (docs/plugins.md「旧的面板」).
7
- // A type is read when a page asks (opening it, refreshing, an action), or, for a kind declaring `report`, on its period
8
- // while this machine shows it; nothing else is read in the background, and no reading is kept on disk.
9
- // What every type gets from here and not from its plugin: one reading at a time (a second ask joins it), the last good
10
- // reading shown again within the type's `maxAge` and listed with it, and on failure the last good one kept and marked as
11
- // such. The machine keeps which it shows and which not, in this plugin's state; their order is their plugins'
12
- // (docs/resources-page.md「顺序」). Inside, a type is still called a panel, as the page's view and its messages are.
13
- import { spawn, spawnSync } from 'node:child_process';
14
- import { readFileSync, writeFileSync, renameSync } from 'node:fs';
15
- import { tmpdir } from 'node:os';
16
- import { join } from 'node:path';
17
- import { runPluginCommand, settle } from '../../../../adapters/plugin-command.mjs';
18
- import { PanelError, panelDeclarations, panelItems, resourceItems, actionArgs, shownItems, displayOptions, keepMissingMetrics } from './rules.mjs';
19
- import { SignIn, authorizationLink, deviceCode } from './sign-in.mjs';
20
-
21
- const fail = (code, message) => { throw new PanelError(code, message); };
22
- // How a command starts here, in the plugin host's tree, whose root is registered: in a process group of its own, as the
23
- // backend's registry door starts one (adapters/process-start.mjs), registering nothing.
24
- const start = { spawn: (_owner, _entry, file, args, options) => spawn(file, args, { ...options, detached: true }), remove: () => {} };
25
-
26
- export class Panels {
27
- // `onChange(key)`: a panel moved (its reading, its login, whether it is hidden); none for the list as a whole.
28
- // `run`: how a command runs (adapters/plugin-command.mjs runPluginCommand, from its plugin's directory with its environment,
29
- // started here); `now()`: the time, as readings are dated by it.
30
- constructor(coda, { run = runPluginCommand, now = Date.now, readTimeoutMs = 30_000, actionTimeoutMs = 10 * 60_000, timer = true } = {}) {
31
- this.coda = coda; this.run = run; this.now = now; this.readTimeoutMs = readTimeoutMs; this.actionTimeoutMs = actionTimeoutMs; this.timerOn = timer;
32
- // `last`: each panel's last good items, for a failed reading to show again; `shown`: what its last reading answered.
33
- this.plugins = new Map(); this.last = new Map(); this.shown = new Map(); this.reading = new Map(); this.acting = new Map(); this.failures = new Map();
34
- this.logins = new Map(); this.envs = new Map(); this.listeners = new Set(); this.closing = new AbortController();
35
- this.file = join(coda.plugin.state ?? tmpdir(), 'hidden.json');
36
- this.hides = Promise.resolve();
37
- // The kind types this module reported, by kind (`{ plugin, type }`), and why an upload last failed, said once.
38
- this.reportedKinds = new Map(); this.reportSaid = new Map(); this.reportedAt = new Map(); this.timer = null;
39
- }
40
- listen(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
41
- // Nothing is told before the plugins' environments are there (`ready`): what a login says of whether its program is
42
- // installed is checked with its plugin's own.
43
- changed(key = null) { if (this.ready) for (const fn of this.listeners) try { fn(key); } catch {} }
44
- // Once: the installed plugins watched, what this machine shows and hides, and the environment of each plugin whose panels sign in.
45
- start() {
46
- this.started ??= (async () => {
47
- this.choices = this.readHidden();
48
- const watched = await this.coda.watch('plugins', ({ type, id, object }) => {
49
- if (type === 'DELETED') this.plugins.delete(id); else this.plugins.set(id, object);
50
- // Another version (another directory, another environment): what was checked with the last is checked again.
51
- this.envs.delete(id);
52
- for (const [key, login] of this.logins) if (key.startsWith(`${id}/`)) login.recheck();
53
- // A login of a panel gone (its plugin removed, or a version without it) goes with it.
54
- const keys = new Set(this.installed().map(e => e.key));
55
- for (const [key, login] of this.logins) if (!keys.has(key)) { login.close(); this.logins.delete(key); }
56
- if (this.ready) this.prepare().then(() => { this.dropMissing(); this.forgetHidden(); this.changed(); });
57
- });
58
- this.unwatch = () => watched.dispose();
59
- await this.prepare();
60
- this.ready = true;
61
- // A kind declaring a report is read on its own period while this machine shows it (none before it is chosen).
62
- this.forgetHidden();
63
- if (this.timerOn) { this.timer = setInterval(() => this.tick(), 1000); this.timer.unref?.(); }
64
- })();
65
- return this.started;
66
- }
67
- // What the machine was told to hide or show, by panel: none when nothing is, or what is cannot be read. Kept before as
68
- // the list of those hidden.
69
- readHidden() {
70
- try {
71
- const kept = JSON.parse(readFileSync(this.file, 'utf8'));
72
- return Array.isArray(kept) ? Object.fromEntries(kept.map(key => [key, true])) : kept && typeof kept === 'object' ? kept : {};
73
- } catch { return {}; }
74
- }
75
- keepHidden(choices) {
76
- const next = `${this.file}.next`;
77
- writeFileSync(next, JSON.stringify(Object.fromEntries(Object.entries(choices).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
78
- renameSync(next, this.file);
79
- }
80
- // Whether the machine hides it: as it was told, else as its type says (`hidden`, shown only once chosen).
81
- hiddenOf({ key, panel }) { return this.choices[key] ?? !!panel.hidden; }
82
- // The installed plugins' types, by plugin id, each plugin's in the order it declares them: its resource types, or the
83
- // panels of one that declares none. A project disabling a plugin does not take them away: the page is the machine's,
84
- // not a project's.
85
- installed() {
86
- return [...this.plugins.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).flatMap(plugin => {
87
- const format = plugin.contributes?.resources ? 'resources' : 'panels';
88
- return panelDeclarations(plugin.contributes?.[format]).map(panel => ({ plugin, panel, key: `${plugin.id}/${panel.id}`, format }));
89
- });
90
- }
91
- find(key) {
92
- return this.installed().find(e => e.key === key) ?? fail('not_found', `没有面板 ${key}`);
93
- }
94
- // Before a list is shown: the environment of each plugin whose panels sign in, for whether what they sign in to is there.
95
- async prepare() {
96
- const plugins = new Set(this.installed().filter(e => e.panel.signIn && !this.envs.has(e.plugin.id)).map(e => e.plugin.id));
97
- await Promise.all([...plugins].map(id => this.env(id).catch(() => {})));
98
- }
99
- // What a page shows of a panel: what it is, whether the machine hides it, what was last read and how that stands now.
100
- view(entry, index) {
101
- const { plugin, panel, key, format } = entry, shown = this.shown.get(key), acting = this.acting.get(key);
102
- return { plugin: plugin.id, pluginName: plugin.name, panel: panel.id, title: panel.title, format, version: plugin.version ?? '', source: plugin.source ?? { kind: 'builtin' },
103
- ...(panel.kind ? { kind: panel.kind } : {}),
104
- actions: Object.fromEntries(Object.entries(panel.actions ?? {}).map(([name, a]) => [name, a.confirm ? { confirm: a.confirm } : {}])),
105
- configurable: !!panel.displaySetting, signsIn: !!panel.signIn, hidden: this.hiddenOf(entry), index,
106
- signIn: panel.signIn ? this.login(entry).view() : null,
107
- reading: shown ? this.present(entry, shown) : null,
108
- busy: this.reading.has(key), failure: this.failures.get(key) ?? null,
109
- // The action under way, by its button; or why the last one did not go through, with the button it was.
110
- acting: acting && !acting.error ? acting.button : null, actionError: acting?.error ?? null, failedButton: acting?.error ? acting.button : null };
111
- }
112
- list() { return this.installed().map((entry, index) => [entry.key, this.view(entry, index)]); }
113
- // One panel's, as `list` has it; none for one no longer installed.
114
- viewOf(key) {
115
- const listed = this.installed(), index = listed.findIndex(e => e.key === key);
116
- return index < 0 ? null : this.view(listed[index], index);
117
- }
118
- // The plugin's environment, as Coda gives every process of it, read again for each command: what it holds (its
119
- // settings, the concurrency groups now) is of the moment.
120
- async env(plugin, extra = {}) {
121
- const env = { ...(await this.coda.environment(null, { plugin })), ...extra };
122
- this.envs.set(plugin, env);
123
- return env;
124
- }
125
- settingsOf(plugin) {
126
- try { return JSON.parse(this.envs.get(plugin)?.CODA_PLUGIN_SETTINGS ?? '{}'); } catch { return {}; }
127
- }
128
- present({ plugin, panel }, reading) {
129
- if (!panel.displaySetting) return reading;
130
- const values = this.settingsOf(plugin.id)[panel.displaySetting] ?? {};
131
- return { ...reading, items: shownItems(reading.items, values), display: { setting: panel.displaySetting, options: displayOptions(reading.items, values) } };
132
- }
133
- // `{ resources, readAt }` (a panel's `{ items, readAt }`), or with `error` when this reading failed: then the last good
134
- // one with `stale`, or none.
135
- read(key, { force = false } = {}) {
136
- const entry = this.find(key);
137
- const pending = this.reading.get(key);
138
- if (pending) return pending;
139
- const last = this.last.get(key);
140
- if (!force && last && entry.panel.maxAgeMs && this.now() - last.at < entry.panel.maxAgeMs && !this.shown.get(key)?.error) return Promise.resolve(this.present(entry, { ...last.content, readAt: last.at }));
141
- const reading = this.fetch(entry).finally(() => { this.reading.delete(key); this.changed(key); });
142
- this.reading.set(key, reading);
143
- this.changed(key);
144
- return reading;
145
- }
146
- async fetch(entry) {
147
- const { plugin, panel, key } = entry;
148
- if (panel.reportMs) this.reportedAt.set(key, this.now());
149
- let failure;
150
- try {
151
- const env = await this.env(plugin.id);
152
- const ran = await this.run(panel.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: '{}', timeoutMs: this.readTimeoutMs, signal: this.closing.signal });
153
- const { error } = settle(ran, { what: '读取' });
154
- if (!error) {
155
- const content = this.content(entry, ran.stdout), at = this.now();
156
- this.last.set(key, { content, at }); this.failures.delete(key);
157
- this.shown.set(key, { ...content, readAt: at });
158
- // A kind's reading is what this machine reports of it: a failed one reports nothing, so the last good objects stay.
159
- if (entry.panel.kind) await this.report(entry, content.resources, at);
160
- return this.present(entry, { ...content, readAt: at });
161
- }
162
- failure = error.message;
163
- } catch (e) {
164
- if (!(e instanceof PanelError)) { this.failures.set(key, e.message); throw e; }
165
- failure = `输出无效:${e.message}`;
166
- }
167
- const last = this.last.get(key);
168
- const reading = last ? { ...last.content, readAt: last.at, stale: true, error: failure } : { [entry.format === 'resources' ? 'resources' : 'items']: [], error: failure };
169
- this.shown.set(key, reading);
170
- return this.present(entry, reading);
171
- }
172
- // What a command printed, as its format has it: resources, or a panel's items (those it chooses among keeping their places).
173
- content({ plugin, panel, key, format }, output) {
174
- if (format === 'resources') return { resources: resourceItems(output, panel, plugin.views ?? []) };
175
- const items = panelItems(output, panel, plugin.views ?? []);
176
- return { items: panel.displaySetting ? keepMissingMetrics(items, this.last.get(key)?.content.items ?? []) : items };
177
- }
178
- // A kind's reading reported to this machine's backend (GET /v1/resources gives it back to the page and explain): the
179
- // fields Coda keeps are the name, the outside identity it is, its values, what is wrong, and when it was read. Buttons
180
- // and what they send stay here; a failure reports nothing, so the last good objects stay.
181
- async report(entry, resources, at) {
182
- const { plugin, panel } = entry;
183
- const body = { plugin: plugin.id, type: panel.id, kind: panel.kind, observedAt: new Date(at).toISOString(),
184
- resources: resources.map(({ name, identity, values, error }) => ({ ...(name !== undefined ? { name } : {}), ...(identity !== undefined ? { identity } : {}),
185
- values: values ?? [], ...(error !== undefined ? { error } : {}) })) };
186
- try {
187
- await this.coda.api('resource-reports', body);
188
- this.reportedKinds.set(panel.kind, { plugin: plugin.id, type: panel.id });
189
- this.reportSaid.delete(entry.key);
190
- } catch (e) {
191
- if (this.reportSaid.get(entry.key) === e.message) return;
192
- this.reportSaid.set(entry.key, e.message);
193
- console.error(`[资源] ${panel.title} 没有上报读数:${e.message}`);
194
- }
195
- }
196
- // This machine no longer shows or has the type: its objects go, and it is not read on its period.
197
- // This machine no longer shows or has the type: its objects go, and it is not read on its period. Asked whether this
198
- // module reported it or not: after a restart neither it nor the backend remembers, while the kernel still has them.
199
- forgetKind(kind) {
200
- if (!kind) return Promise.resolve();
201
- return this.coda.api('resource-reports/forget', { kind }).then(() => { this.reportedKinds.delete(kind); }, e => {
202
- const said = `forget ${kind}`;
203
- if (this.reportSaid.get(said) === e.message) return;
204
- this.reportSaid.set(said, e.message);
205
- console.error(`[资源] ${kind} 没有停止上报:${e.message}`);
206
- });
207
- }
208
- // The kinds this machine hides now: their objects go once the module starts (and when they are hidden), even when this
209
- // module has no memory of reading them.
210
- forgetHidden() {
211
- for (const entry of this.installed()) if (entry.panel.kind && this.hiddenOf(entry)) void this.forgetKind(entry.panel.kind);
212
- }
213
- // Kinds no longer declared by an installed plugin: their objects go.
214
- dropMissing() {
215
- const kinds = new Set(this.installed().filter(entry => entry.panel.kind).map(entry => entry.panel.kind));
216
- for (const kind of [...this.reportedKinds.keys()]) if (!kinds.has(kind)) void this.forgetKind(kind);
217
- }
218
- // The kinds due to report now: each shown one with a report period, read again (and so reported once it ends).
219
- tick() {
220
- if (!this.ready) return;
221
- const now = this.now();
222
- for (const entry of this.installed()) {
223
- const { panel } = entry;
224
- if (!panel.kind || !panel.reportMs || this.hiddenOf(entry)) continue;
225
- const last = this.reportedAt.get(entry.key);
226
- if (last !== undefined && now - last < panel.reportMs) continue;
227
- this.reportedAt.set(entry.key, now);
228
- this.read(entry.key, { force: true }).catch(() => {});
229
- }
230
- }
231
- // Runs one of a panel's actions with what its button sent, then reads the panel again. One action of a panel at a time;
232
- // one under way goes on to its end even when whoever asked has gone.
233
- async act(key, name, args, button = name) {
234
- const entry = this.find(key), { plugin, panel } = entry, now = this.acting.get(key);
235
- if (now && !now.error) fail('panel_busy', `${panel.title} 正在进行另一项操作`);
236
- // What went wrong is said under the panel, whatever it was.
237
- try {
238
- const action = panel.actions?.[name] ?? fail('not_found', `面板 ${panel.title} 没有动作 ${name}`);
239
- const given = actionArgs(args);
240
- this.acting.set(key, { button }); this.changed(key);
241
- const env = await this.env(plugin.id, { CODA_PANEL_ARGS: JSON.stringify(given) });
242
- const ran = await this.run(action.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: JSON.stringify(given), timeoutMs: this.actionTimeoutMs, signal: this.closing.signal });
243
- // What an action prints is what it says, not a result: ending with 0 is all of it.
244
- const { error } = settle(ran, { answers: false, what: '操作' });
245
- if (error) fail(error.code, error.message);
246
- this.acting.delete(key);
247
- } catch (e) {
248
- this.acting.set(key, { button, error: e.message }); this.changed(key);
249
- throw e;
250
- }
251
- // A reading that began before the action ended may not show what it did.
252
- await this.reading.get(key);
253
- return this.read(key, { force: true });
254
- }
255
- // One type hidden or shown on this machine, the others as they were: one change at a time.
256
- hide(key, hidden) {
257
- const entry = this.installed().find(e => e.key === key);
258
- const change = this.hides.then(async () => {
259
- const next = { ...this.choices, [key]: !!hidden };
260
- this.keepHidden(next);
261
- this.choices = next;
262
- // Hidden, a kind is neither read nor reported: what it gave the kernel goes.
263
- if (hidden && entry?.panel.kind) await this.forgetKind(entry.panel.kind);
264
- this.changed(key);
265
- });
266
- this.hides = change.catch(() => {});
267
- return change;
268
- }
269
- // A panel's login from Coda (docs/plugins.md「面板的登录」), one per panel at a time. Signed in, the panel is read anew;
270
- // its CLI installed, the plugin's setup is run again (docs/plugins.md「准备运行环境」; `coda.pluginSetup`, asked as this
271
- // plugin), which done well has Coda read its agents again: what they offer may be readable now.
272
- login(entry) {
273
- const { plugin, panel, key } = entry, known = this.logins.get(key);
274
- const declared = panel.signIn ?? fail('not_found', `${panel.title} 不能从 Coda 登录`);
275
- if (known?.declared === JSON.stringify(declared)) return known;
276
- known?.close();
277
- const env = () => this.envs.get(plugin.id) ?? process.env;
278
- // Whether it is there: a quick check with the plugin's own environment, asked again after a moment at most. Without
279
- // one, it always is; without the environment yet, it is not checked, and nothing is kept of it.
280
- let checkedAt = 0, there = false;
281
- const installed = (fresh = false) => {
282
- if (!declared.installed) return true;
283
- const given = this.envs.get(plugin.id);
284
- if (!given) return false;
285
- if (fresh || Date.now() - checkedAt > 2000) { there = spawnSync('/bin/sh', ['-c', declared.installed], { cwd: given.CODA_PLUGIN_PATH, env: given, stdio: 'ignore', timeout: 2000 }).status === 0; checkedAt = Date.now(); }
286
- return there;
287
- };
288
- const login = new SignIn({ provider: key, name: panel.title, command: declared.command, installed, install: declared.install ?? null,
289
- readCode: declared.input ? authorizationLink : deviceCode, input: !!declared.input, note: declared.note ?? null },
290
- { start, env, onChange: () => this.changed(key),
291
- onSignedIn: () => { this.read(key, { force: true }).catch(() => {}); },
292
- onInstalled: () => { checkedAt = 0; this.coda.pluginSetup.retry(plugin.id).catch(() => {}); } });
293
- login.declared = JSON.stringify(declared);
294
- login.recheck = () => { checkedAt = 0; };
295
- this.logins.set(key, login);
296
- return login;
297
- }
298
- async signIn(key, what, body = {}) {
299
- const entry = this.find(key);
300
- // The command runs with the plugin's environment as it is now.
301
- await this.env(entry.plugin.id);
302
- const login = this.login(entry);
303
- switch (what) {
304
- case 'signIn': return login.start();
305
- case 'install': return login.install();
306
- case 'cancelSignIn': return login.cancel();
307
- case 'submitSignIn': return login.submit(body);
308
- default: return login.view();
309
- }
310
- }
311
- // The module going (the plugin host stopping): what runs in a process group of its own is made to end, as nothing would later.
312
- close() { this.closing.abort(); clearInterval(this.timer); this.unwatch?.(); for (const login of this.logins.values()) login.close('SIGKILL'); }
313
- }