@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/README.md +25 -20
- package/bin/check.mjs +3 -3
- package/check/coda/adapters/plugin-modules.mjs +2 -7
- package/check/coda/adapters/plugin-test-host.d.mts +0 -2
- package/check/coda/api-surface.txt +0 -1
- package/check/coda/builtin.json +1 -264
- package/check/coda/components/plugins/plugin-extensions.mjs +2 -2
- package/check/coda/components/plugins/plugin-rules.mjs +3 -3
- package/check/coda/components/plugins/plugin-source-rules.mjs +1 -1
- package/check/coda/contract.json +8 -11
- package/check/index.mjs +2 -4
- package/check/leftovers.mjs +1 -1
- package/check/manifest.mjs +7 -9
- package/check/module.mjs +0 -1
- package/check/report.mjs +1 -1
- package/package.json +4 -3
- package/templates/resource/package.json +13 -10
- package/templates/resource/scripts/act.mjs +20 -0
- package/templates/resource/scripts/{resources.mjs → resource.mjs} +10 -5
- package/check/coda/resources/plugins/resources/panels/panels.mjs +0 -313
- package/check/coda/resources/plugins/resources/panels/rules.mjs +0 -232
- package/check/coda/resources/plugins/resources/panels/sign-in.mjs +0 -122
- package/check/panel.mjs +0 -78
- package/templates/resource/scripts/mark.mjs +0 -6
|
@@ -1,232 +0,0 @@
|
|
|
1
|
-
// What a resource type is (docs/plugins.md「资源」): how a plugin declares one (`contributes.resources`, of the schema the
|
|
2
|
-
// resources plugin declares for its point, resources.schema.json, checked where the plugin is installed) and what its
|
|
3
|
-
// command may print, checked here, where the types are read. Nothing here knows what a resource is about: CPU, an account's
|
|
4
|
-
// quota and a disk are all names and values. A plugin still declaring the panels before them (`contributes.panels`,
|
|
5
|
-
// schema.json) has them read as they were, for the page to take as resources (docs/plugins.md「旧的面板」).
|
|
6
|
-
|
|
7
|
-
// What is not as it must be: the panel says so where it would show.
|
|
8
|
-
export class PanelError extends Error {
|
|
9
|
-
constructor(code, message) { super(message); this.code = code; }
|
|
10
|
-
}
|
|
11
|
-
function check(condition, code, message) {
|
|
12
|
-
if (!condition) throw new PanelError(code, message);
|
|
13
|
-
return condition;
|
|
14
|
-
}
|
|
15
|
-
// An ISO 8601 duration as panels write their `maxAge` (`PT5M`, `P1D`), in milliseconds: weeks, days and time.
|
|
16
|
-
const DURATION = /^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;
|
|
17
|
-
function durationMs(text) {
|
|
18
|
-
const [, w = 0, d = 0, h = 0, min = 0, s = 0] = DURATION.exec(text);
|
|
19
|
-
return ((((+w * 7 + +d) * 24 + +h) * 60 + +min) * 60 + +s) * 1000;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export const ITEM_TYPES = ['card', 'meter', 'stat', 'markdown', 'button', 'error'];
|
|
23
|
-
// How many resources a reading lists, and how many values and buttons one has.
|
|
24
|
-
const RESOURCES = 50, VALUES = 8, ACTIONS = 8;
|
|
25
|
-
export const ARGS_LIMIT = 4 * 1024;
|
|
26
|
-
const ITEMS = 50, CARD_ITEMS = 20, LABEL = 80, IDENTITY = 200, MARKDOWN = 4000, ERROR = 500, CONFIRM = 200, LINK = 2000;
|
|
27
|
-
const fail = (code, message) => check(false, code, message);
|
|
28
|
-
const keys = (value, allowed, where, code) => {
|
|
29
|
-
const extra = Object.keys(value).filter(k => !allowed.includes(k));
|
|
30
|
-
check(!extra.length, code, `${where} 里有 Coda 不支持的键:${extra.join('、')}`);
|
|
31
|
-
};
|
|
32
|
-
const text = (value, max, where, code, { need = true, line = true } = {}) => {
|
|
33
|
-
if (value === undefined && !need) return undefined;
|
|
34
|
-
check(typeof value === 'string' && value.trim() && [...value].length <= max && !value.includes('\0') && (!line || !/[\r\n]/.test(value)), code,
|
|
35
|
-
`${where} 须为不超过 ${max} 字的${line ? '一行' : ''}文本`);
|
|
36
|
-
return value;
|
|
37
|
-
};
|
|
38
|
-
const object = (value, where, code) => check(value && typeof value === 'object' && !Array.isArray(value), code, `${where} 须为对象`);
|
|
39
|
-
|
|
40
|
-
// ---- Declarations (`contributes.resources`, or the panels before them) ----
|
|
41
|
-
// A plugin's types as it declares them, in its order, each with the actions its buttons may take (none when it declares
|
|
42
|
-
// none), how long a reading may be shown again without asking (`maxAge`), and how often a kind's reading is reported.
|
|
43
|
-
export function panelDeclarations(raw = []) {
|
|
44
|
-
return raw.map(panel => ({ ...panel, actions: panel.actions ?? {}, ...(panel.maxAge ? { maxAgeMs: durationMs(panel.maxAge) } : {}),
|
|
45
|
-
...(panel.report ? { reportMs: durationMs(panel.report) } : {}) }));
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// ---- What a panel's command prints ----
|
|
49
|
-
// `{ items: [...] }`, each item one of ITEM_TYPES; a card holds the others. A button names one of the panel's actions,
|
|
50
|
-
// or one of its plugin's views for the client to open (docs/plugins.md「视图」). `scope`: `{ actions, views }`, what the
|
|
51
|
-
// panel declares and the ids of its plugin's views. Returned as the clients get it: only the keys each type has.
|
|
52
|
-
function item(raw, where, scope, inCard) {
|
|
53
|
-
object(raw, where, 'invalid_panel');
|
|
54
|
-
const { display, ...content } = raw;
|
|
55
|
-
const out = plainItem(content, where, scope, inCard);
|
|
56
|
-
if (display !== undefined) {
|
|
57
|
-
object(display, `${where}.display`, 'invalid_panel');
|
|
58
|
-
keys(display, ['id', 'default'], `${where}.display`, 'invalid_panel');
|
|
59
|
-
check(['meter', 'stat'].includes(out.type), 'invalid_panel', '只有数值项可以声明 display');
|
|
60
|
-
check(typeof display.default === 'boolean', 'invalid_panel', 'display.default 须为开或关');
|
|
61
|
-
out.display = { id: text(display.id, 200, 'display.id', 'invalid_panel'), default: display.default };
|
|
62
|
-
}
|
|
63
|
-
return out;
|
|
64
|
-
}
|
|
65
|
-
function plainItem(raw, where, scope, inCard) {
|
|
66
|
-
const code = 'invalid_panel';
|
|
67
|
-
object(raw, where, code);
|
|
68
|
-
check(ITEM_TYPES.includes(raw.type), code, `${where} 的 type 只能是 ${ITEM_TYPES.join('、')}`);
|
|
69
|
-
check(!(inCard && raw.type === 'card'), code, `${where}:卡片里不能再放卡片`);
|
|
70
|
-
switch (raw.type) {
|
|
71
|
-
case 'card': {
|
|
72
|
-
keys(raw, ['type', 'title', 'subtitle', 'identity', 'items'], where, code);
|
|
73
|
-
check(Array.isArray(raw.items) && raw.items.length <= CARD_ITEMS, code, `${where} 的 items 须为不超过 ${CARD_ITEMS} 项的数组`);
|
|
74
|
-
// The outside identity it shows (an account), compared and nothing else: a group view shows cards naming the same
|
|
75
|
-
// one once for the machines that have them.
|
|
76
|
-
return { type: 'card', title: text(raw.title, LABEL, `${where} 的 title`, code),
|
|
77
|
-
...(raw.subtitle !== undefined ? { subtitle: text(raw.subtitle, LABEL, `${where} 的 subtitle`, code) } : {}),
|
|
78
|
-
...(raw.identity !== undefined ? { identity: text(raw.identity, IDENTITY, `${where} 的 identity`, code) } : {}),
|
|
79
|
-
items: raw.items.map((r, i) => item(r, `${where}.items[${i}]`, scope, true)) };
|
|
80
|
-
}
|
|
81
|
-
case 'meter': {
|
|
82
|
-
keys(raw, ['type', 'label', 'value', 'fraction', 'note', 'time', 'timeLabel'], where, code);
|
|
83
|
-
// Unknown is said by leaving the fraction out, never by a zero.
|
|
84
|
-
check(raw.fraction === undefined || raw.fraction === null || (typeof raw.fraction === 'number' && raw.fraction >= 0 && raw.fraction <= 1), code,
|
|
85
|
-
`${where} 的 fraction 须在 0–1 之间,不知道时不写`);
|
|
86
|
-
check(raw.time === undefined || (typeof raw.time === 'string' && Number.isFinite(Date.parse(raw.time))), code, `${where} 的 time 须为 ISO 8601 时间`);
|
|
87
|
-
return { type: 'meter', label: text(raw.label, LABEL, `${where} 的 label`, code),
|
|
88
|
-
...(raw.value !== undefined ? { value: text(raw.value, LABEL, `${where} 的 value`, code) } : {}),
|
|
89
|
-
...(typeof raw.fraction === 'number' ? { fraction: raw.fraction } : {}),
|
|
90
|
-
...(raw.note !== undefined ? { note: text(raw.note, LABEL, `${where} 的 note`, code) } : {}),
|
|
91
|
-
...(raw.time !== undefined ? { time: new Date(raw.time).toISOString() } : {}),
|
|
92
|
-
...(raw.timeLabel !== undefined ? { timeLabel: text(raw.timeLabel, LABEL, `${where} 的 timeLabel`, code) } : {}) };
|
|
93
|
-
}
|
|
94
|
-
case 'stat':
|
|
95
|
-
keys(raw, ['type', 'label', 'value'], where, code);
|
|
96
|
-
return { type: 'stat', label: text(raw.label, LABEL, `${where} 的 label`, code), value: text(raw.value, LABEL, `${where} 的 value`, code) };
|
|
97
|
-
case 'markdown':
|
|
98
|
-
keys(raw, ['type', 'text'], where, code);
|
|
99
|
-
return { type: 'markdown', text: text(raw.text, MARKDOWN, `${where} 的 text`, code, { line: false }) };
|
|
100
|
-
case 'error':
|
|
101
|
-
keys(raw, ['type', 'text'], where, code);
|
|
102
|
-
return { type: 'error', text: text(raw.text, ERROR, `${where} 的 text`, code, { line: false }) };
|
|
103
|
-
case 'button':
|
|
104
|
-
keys(raw, ['type', ...BUTTON_KEYS], where, code);
|
|
105
|
-
return { type: 'button', ...button(raw, where, scope) };
|
|
106
|
-
}
|
|
107
|
-
return fail(code, `${where} 的 type 不受支持`);
|
|
108
|
-
}
|
|
109
|
-
const BUTTON_KEYS = ['label', 'action', 'view', 'args', 'disabled', 'confirm'];
|
|
110
|
-
// What a button does: run one of the type's actions here, open one of its plugin's views in the client, or (a resource's,
|
|
111
|
-
// `url` among `keys`) open a web page on the device.
|
|
112
|
-
function button(raw, where, scope, keys = BUTTON_KEYS) {
|
|
113
|
-
const code = 'invalid_panel';
|
|
114
|
-
const does = ['action', 'view', 'url'].filter(k => keys.includes(k) && raw[k] !== undefined);
|
|
115
|
-
check(does.length === 1, code, `${where} 须有 ${keys.includes('url') ? 'action、view 或 url' : 'action 或 view'} 之一`);
|
|
116
|
-
const [kind] = does;
|
|
117
|
-
if (kind === 'view') check(typeof raw.view === 'string' && scope.views.includes(raw.view), code, `${where} 的 view 须是插件声明的视图:${raw.view}`);
|
|
118
|
-
else if (kind === 'action') check(typeof raw.action === 'string' && Object.hasOwn(scope.actions, raw.action), code, `${where} 的 action 须是声明的动作:${raw.action}`);
|
|
119
|
-
else check(typeof raw.url === 'string' && raw.url.length <= LINK && /^https:\/\/[^\s]+$/.test(raw.url), code, `${where} 的 url 须为不超过 ${LINK} 字的 https 地址`);
|
|
120
|
-
check(kind !== 'url' || (raw.args === undefined && raw.confirm === undefined), code, `${where}:打开网页的按钮不带 args 与 confirm`);
|
|
121
|
-
check(raw.args === undefined || (raw.args && typeof raw.args === 'object' && !Array.isArray(raw.args) && JSON.stringify(raw.args).length <= ARGS_LIMIT), code,
|
|
122
|
-
`${where} 的 args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
|
|
123
|
-
check(raw.disabled === undefined || typeof raw.disabled === 'boolean', code, `${where} 的 disabled 须为开或关`);
|
|
124
|
-
// Its own question, for what this one button does (which account, which credit), in place of its action's.
|
|
125
|
-
return { label: text(raw.label, LABEL, `${where} 的 label`, code), [kind]: raw[kind],
|
|
126
|
-
...(raw.args ? { args: raw.args } : {}), ...(raw.disabled ? { disabled: true } : {}),
|
|
127
|
-
...(raw.confirm !== undefined ? { confirm: text(raw.confirm, CONFIRM, `${where} 的 confirm`, code, { line: false }) } : {}) };
|
|
128
|
-
}
|
|
129
|
-
// A panel's reading from what its command printed. Anything it cannot be fails the reading, with where. `views`: the ids
|
|
130
|
-
// of its plugin's views, which a button may open.
|
|
131
|
-
export function panelItems(output, panel, views = []) {
|
|
132
|
-
const code = 'invalid_panel';
|
|
133
|
-
let value;
|
|
134
|
-
try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
|
|
135
|
-
object(value, '输出', code);
|
|
136
|
-
keys(value, ['items'], '输出', code);
|
|
137
|
-
check(Array.isArray(value.items) && value.items.length <= ITEMS, code, `输出的 items 须为不超过 ${ITEMS} 项的数组`);
|
|
138
|
-
const items = value.items.map((r, i) => item(r, `items[${i}]`, { actions: panel.actions, views }, false));
|
|
139
|
-
const ids = items.flatMap(i => i.type === 'card' ? i.items : [i]).filter(i => i.display).map(i => i.display.id);
|
|
140
|
-
check(!ids.length || panel.displaySetting, code, '数值项的 display 需要面板声明 displaySetting');
|
|
141
|
-
check(new Set(ids).size === ids.length, code, 'display.id 不能重复');
|
|
142
|
-
return items;
|
|
143
|
-
}
|
|
144
|
-
// A type's reading from what its command printed: `{ resources: [...] }`, each a name, the outside identity it is (an
|
|
145
|
-
// account, compared and nothing else), its values, one line of what is wrong with it, and its buttons. Nothing that
|
|
146
|
-
// explains: a value is a name and what it reads (docs/plugins.md「资源」). Anything else fails the reading, with where.
|
|
147
|
-
export function resourceItems(output, type, views = []) {
|
|
148
|
-
const code = 'invalid_panel';
|
|
149
|
-
let value;
|
|
150
|
-
try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
|
|
151
|
-
object(value, '输出', code);
|
|
152
|
-
keys(value, ['resources'], '输出', code);
|
|
153
|
-
check(Array.isArray(value.resources) && value.resources.length <= RESOURCES, code, `输出的 resources 须为不超过 ${RESOURCES} 项的数组`);
|
|
154
|
-
return value.resources.map((r, i) => resource(r, `resources[${i}]`, { actions: type.actions, views }));
|
|
155
|
-
}
|
|
156
|
-
function resource(raw, where, scope) {
|
|
157
|
-
const code = 'invalid_panel';
|
|
158
|
-
object(raw, where, code);
|
|
159
|
-
keys(raw, ['name', 'identity', 'values', 'error', 'actions'], where, code);
|
|
160
|
-
const list = (value, max, name) => {
|
|
161
|
-
check(value === undefined || (Array.isArray(value) && value.length <= max), code, `${where} 的 ${name} 须为不超过 ${max} 项的数组`);
|
|
162
|
-
return value ?? [];
|
|
163
|
-
};
|
|
164
|
-
const name = text(raw.name, LABEL, `${where} 的 name`, code, { need: false });
|
|
165
|
-
const values = list(raw.values, VALUES, 'values').map((v, i) => reading(v, `${where}.values[${i}]`));
|
|
166
|
-
const actions = list(raw.actions, ACTIONS, 'actions').map((b, i) => {
|
|
167
|
-
const at = `${where}.actions[${i}]`;
|
|
168
|
-
object(b, at, code);
|
|
169
|
-
keys(b, [...BUTTON_KEYS, 'url'], at, code);
|
|
170
|
-
return button(b, at, scope, [...BUTTON_KEYS, 'url']);
|
|
171
|
-
});
|
|
172
|
-
check(name !== undefined || values.length, code, `${where} 须有 name 或 values`);
|
|
173
|
-
return { ...(name !== undefined ? { name } : {}),
|
|
174
|
-
...(raw.identity !== undefined ? { identity: text(raw.identity, IDENTITY, `${where} 的 identity`, code) } : {}),
|
|
175
|
-
values, ...(raw.error !== undefined ? { error: text(raw.error, LABEL, `${where} 的 error`, code) } : {}), actions };
|
|
176
|
-
}
|
|
177
|
-
// One value: what it is called (left out where its resource has only it), what it reads, how much of it is left (0–1,
|
|
178
|
-
// left out when not known: never drawn as empty), and a time it comes with (when a quota is back).
|
|
179
|
-
function reading(raw, where) {
|
|
180
|
-
const code = 'invalid_panel';
|
|
181
|
-
object(raw, where, code);
|
|
182
|
-
keys(raw, ['label', 'value', 'fraction', 'time'], where, code);
|
|
183
|
-
check(raw.fraction === undefined || raw.fraction === null || (typeof raw.fraction === 'number' && raw.fraction >= 0 && raw.fraction <= 1), code,
|
|
184
|
-
`${where} 的 fraction 须在 0–1 之间,不知道时不写`);
|
|
185
|
-
check(raw.time === undefined || (typeof raw.time === 'string' && Number.isFinite(Date.parse(raw.time))), code, `${where} 的 time 须为 ISO 8601 时间`);
|
|
186
|
-
check(raw.value !== undefined || typeof raw.fraction === 'number', code, `${where} 须有 value 或 fraction`);
|
|
187
|
-
return { ...(raw.label !== undefined ? { label: text(raw.label, LABEL, `${where} 的 label`, code) } : {}),
|
|
188
|
-
...(raw.value !== undefined ? { value: text(raw.value, LABEL, `${where} 的 value`, code) } : {}),
|
|
189
|
-
...(typeof raw.fraction === 'number' ? { fraction: raw.fraction } : {}),
|
|
190
|
-
...(raw.time !== undefined ? { time: new Date(raw.time).toISOString() } : {}) };
|
|
191
|
-
}
|
|
192
|
-
// What a button sends: an object the action's command reads as JSON.
|
|
193
|
-
export function actionArgs(value) {
|
|
194
|
-
if (value === undefined || value === null) return {};
|
|
195
|
-
check(typeof value === 'object' && !Array.isArray(value) && JSON.stringify(value).length <= ARGS_LIMIT, 'invalid_input', `args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
|
|
196
|
-
return value;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// A reading keeps all measurements in memory; display choices are ordinary plugin settings, applied at read time.
|
|
200
|
-
export function shownItems(items, choices = {}) {
|
|
201
|
-
return items.flatMap(({ display, ...item }) => {
|
|
202
|
-
if (display && !(choices[display.id] ?? display.default)) return [];
|
|
203
|
-
if (item.type === 'card') {
|
|
204
|
-
item.items = shownItems(item.items, choices);
|
|
205
|
-
if (!item.items.length) return [];
|
|
206
|
-
}
|
|
207
|
-
return [item];
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
export function displayOptions(items, values = {}) {
|
|
211
|
-
return items.flatMap(item => (item.type === 'card' ? item.items : [item]).filter(i => i.display).map(i => ({
|
|
212
|
-
id: i.display.id, label: i.label, group: item.type === 'card' ? item.title : '',
|
|
213
|
-
enabled: values[i.display.id] ?? i.display.default, default: i.display.default,
|
|
214
|
-
})));
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// A disconnected device keeps its place for this backend's lifetime, with no old number presented as current.
|
|
218
|
-
export function keepMissingMetrics(items, previous) {
|
|
219
|
-
const ids = new Set(items.flatMap(i => i.type === 'card' ? i.items : [i]).flatMap(i => i.display ? [i.display.id] : []));
|
|
220
|
-
const result = [...items];
|
|
221
|
-
for (const old of previous) {
|
|
222
|
-
const missing = (old.type === 'card' ? old.items : [old]).filter(i => i.display && !ids.has(i.display.id))
|
|
223
|
-
.map(i => ({ type: 'stat', label: i.label, value: '暂不可读', display: i.display }));
|
|
224
|
-
if (!missing.length) continue;
|
|
225
|
-
if (old.type === 'card') {
|
|
226
|
-
const same = result.find(i => i.type === 'card' && i.title === old.title);
|
|
227
|
-
if (same) same.items = [...same.items, ...missing].slice(0, 20);
|
|
228
|
-
else if (result.length < 50) result.push({ ...old, items: missing });
|
|
229
|
-
} else if (result.length < 50) result.push(...missing);
|
|
230
|
-
}
|
|
231
|
-
return result;
|
|
232
|
-
}
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { lastLine, settle, startPluginCommand } from '../../../../adapters/plugin-command.mjs';
|
|
3
|
-
import { PanelError } from './rules.mjs';
|
|
4
|
-
|
|
5
|
-
const check = (condition, code, message) => { if (!condition) throw new PanelError(code, message); };
|
|
6
|
-
|
|
7
|
-
const ansi = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
8
|
-
// A device-code login prints a verification URL that carries the code (`grok login --device-auth`, `kimi login`), or the
|
|
9
|
-
// code alone on a line after it. Only whole lines are read: output arrives in pieces, and a URL cut short would carry a
|
|
10
|
-
// code cut short. Codex uses a 4-5 code; Grok and Kimi use 4-4.
|
|
11
|
-
const codeFormat = /^[A-Z0-9]{4}-[A-Z0-9]{4,5}$/;
|
|
12
|
-
export function deviceCode(text) {
|
|
13
|
-
const plain = text.slice(0, text.lastIndexOf('\n') + 1).replace(ansi, '');
|
|
14
|
-
const url = plain.match(/https:\/\/\S+/)?.[0] ?? null;
|
|
15
|
-
let code = null;
|
|
16
|
-
try { code = url && new URL(url).searchParams.get('user_code'); } catch { return null; }
|
|
17
|
-
code ||= plain.match(/^\s*([A-Z0-9]{4}-[A-Z0-9]{4,5})\s*$/m)?.[1] ?? null;
|
|
18
|
-
return url && code && codeFormat.test(code) ? { url, code } : null;
|
|
19
|
-
}
|
|
20
|
-
// A login that asks for the authorization code its page shows prints the page's link and waits: the first whole line's
|
|
21
|
-
// link is it. Checking that the code belongs to this login is the login's own job.
|
|
22
|
-
export function authorizationLink(text) {
|
|
23
|
-
const url = text.slice(0, text.lastIndexOf('\n') + 1).replace(ansi, '').match(/https:\/\/\S+/)?.[0];
|
|
24
|
-
try { return url ? { url: new URL(url).href, input: 'authorizationCode' } : null; } catch { return null; }
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Signing in from Coda through a plugin's panel (docs/plugins.md「面板的登录」, panels.mjs): `login` is the
|
|
28
|
-
// panel's own — its login command, whether what it signs in to is there (`installed()`), the command that installs it, and
|
|
29
|
-
// how the link and code are read from what the login prints (`readCode`); `input`, whether the login asks for the
|
|
30
|
-
// authorization code its page shows, which goes to its standard input. Coda passes the link and code on; the command writes
|
|
31
|
-
// and renews the credentials, which Coda never reads.
|
|
32
|
-
// One login or install of each at a time: any page starting it again sees the one under way, and every page is told as it
|
|
33
|
-
// moves (`onChange`). Neither outlives the module that started it (`close` ends it), so neither is kept for after a restart.
|
|
34
|
-
// Both run as every plugin command does (adapters/plugin-command.mjs, docs/plugins.md「命令的约定」), through `start`, from
|
|
35
|
-
// the plugin's directory: in a process group of their own, cancelled with TERM and made to end past the grace. Neither
|
|
36
|
-
// answers: what they print is read for the link and code, or for why they failed, and ending with 0 is all of it.
|
|
37
|
-
export class SignIn {
|
|
38
|
-
constructor(login, { start, env = () => process.env, onChange = () => {}, onSignedIn = () => {}, onInstalled = () => {}, timeoutMs = 15 * 60 * 1000, startTimeoutMs = 20000, installTimeoutMs = 10 * 60 * 1000 }) {
|
|
39
|
-
this.login = login; this.processStart = start; this.env = env; this.onChange = onChange; this.onSignedIn = onSignedIn; this.onInstalled = onInstalled;
|
|
40
|
-
this.timeoutMs = timeoutMs; this.startTimeoutMs = startTimeoutMs; this.installTimeoutMs = installTimeoutMs;
|
|
41
|
-
this._state = { state: 'idle' }; this.child = null;
|
|
42
|
-
}
|
|
43
|
-
get state() { return this._state; }
|
|
44
|
-
set state(value) { this._state = value; this.onChange(); }
|
|
45
|
-
get available() { return this.login.installed(); }
|
|
46
|
-
view() { return { provider: this.login.provider, name: this.login.name, installed: this.available,
|
|
47
|
-
...(this.login.note ? { note: this.login.note } : {}), ...this.state }; }
|
|
48
|
-
get busy() { return ['starting', 'waiting', 'installing'].includes(this.state.state); }
|
|
49
|
-
spawn(command, { open = false, tail = false, timeoutMs, onOutput }) {
|
|
50
|
-
const env = this.env();
|
|
51
|
-
return startPluginCommand(command, { start: this.processStart, cwd: env.CODA_PLUGIN_PATH, env, open, tail, timeoutMs, onOutput });
|
|
52
|
-
}
|
|
53
|
-
// Starts the installer and answers at once: clients follow a download as they follow a waiting login.
|
|
54
|
-
install() {
|
|
55
|
-
if (this.busy) return this.view();
|
|
56
|
-
if (this.available) { this.state = { state: 'idle' }; return this.view(); }
|
|
57
|
-
if (!this.login.install) { this.state = { state: 'failed', error: `这台机器没有安装 ${this.login.name},Coda 不能代为安装` }; return this.view(); }
|
|
58
|
-
// An installer may say much on its way: the last of it is kept, and it is never stopped for that.
|
|
59
|
-
const child = this.spawn(this.login.install, { tail: true, timeoutMs: this.installTimeoutMs });
|
|
60
|
-
this.child = child;
|
|
61
|
-
this.state = { state: 'installing' };
|
|
62
|
-
child.done.then(ran => {
|
|
63
|
-
if (this.child === child) {
|
|
64
|
-
this.child = null;
|
|
65
|
-
const { error } = settle(ran, { answers: false, what: '安装' });
|
|
66
|
-
// Asked anew: what was there a moment ago is not what the installer left.
|
|
67
|
-
this.state = !error && this.login.installed(true) ? { state: 'idle' } : { state: 'failed', error: error?.message ?? '安装没有完成' };
|
|
68
|
-
if (this.state.state === 'idle') this.onInstalled();
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
return this.view();
|
|
72
|
-
}
|
|
73
|
-
// Resolves once the link and code are known, or the login has failed.
|
|
74
|
-
start() {
|
|
75
|
-
if (this.busy) return this.ready ?? Promise.resolve(this.view());
|
|
76
|
-
if (!this.available) { this.state = { state: 'failed', error: `这台机器没有安装 ${this.login.name}` }; return Promise.resolve(this.view()); }
|
|
77
|
-
const attemptId = randomUUID();
|
|
78
|
-
let output = '', silent = false, settleReady;
|
|
79
|
-
const ready = new Promise(resolve => { settleReady = resolve; });
|
|
80
|
-
const done = () => { settleReady(this.view()); if (this.ready === ready) this.ready = null; };
|
|
81
|
-
const read = chunk => {
|
|
82
|
-
output = (output + chunk).slice(-8000);
|
|
83
|
-
const found = this.state.state === 'starting' && this.child === child && this.login.readCode(output);
|
|
84
|
-
if (found) { this.state = { state: 'waiting', ...found, ...(this.login.input ? { attemptId } : {}) }; done(); }
|
|
85
|
-
};
|
|
86
|
-
const child = this.spawn(this.login.command, { open: this.login.input, timeoutMs: this.timeoutMs, onOutput: read });
|
|
87
|
-
this.child = child;
|
|
88
|
-
this.ready = ready;
|
|
89
|
-
this.state = { state: 'starting' };
|
|
90
|
-
const startTimer = setTimeout(() => { if (this.child === child && this.state.state === 'starting') { silent = true; child.stop(); } }, this.startTimeoutMs);
|
|
91
|
-
child.done.then(ran => {
|
|
92
|
-
clearTimeout(startTimer);
|
|
93
|
-
if (this.child !== child) return done(); // Cancelled: the state is already idle.
|
|
94
|
-
this.child = null;
|
|
95
|
-
const { error } = settle(ran, { answers: false, what: '登录' });
|
|
96
|
-
if (!error) { this.state = { state: 'idle' }; this.onSignedIn(); }
|
|
97
|
-
else if (ran.timedOut) this.state = { state: 'expired' };
|
|
98
|
-
// Stopped for printing no link in time, it failed as it says, not as one cancelled.
|
|
99
|
-
else if (this.state.state !== 'idle') this.state = { state: 'failed', error: silent ? lastLine(output) || '登录没有完成' : error.message };
|
|
100
|
-
done();
|
|
101
|
-
});
|
|
102
|
-
return ready;
|
|
103
|
-
}
|
|
104
|
-
submit({ attemptId, code } = {}) {
|
|
105
|
-
check(this.login.input && this.child && this.state.state === 'waiting' && attemptId === this.state.attemptId,
|
|
106
|
-
'invalid_input', '此登录已结束,请重新登录');
|
|
107
|
-
check(typeof code === 'string' && code.length <= 4096, 'invalid_input', '请粘贴完整的授权码');
|
|
108
|
-
if (!this.state.submitted) {
|
|
109
|
-
this.child.write(`${code.trim()}\n`);
|
|
110
|
-
this.state = { ...this.state, submitted: true };
|
|
111
|
-
}
|
|
112
|
-
return this.view();
|
|
113
|
-
}
|
|
114
|
-
cancel() {
|
|
115
|
-
const child = this.child; this.child = null;
|
|
116
|
-
child?.stop();
|
|
117
|
-
this.state = { state: 'idle' };
|
|
118
|
-
return this.view();
|
|
119
|
-
}
|
|
120
|
-
// `signal`: KILL as the module goes (the plugin host stopping), when nothing would end one that does not stop when asked.
|
|
121
|
-
close(signal = 'SIGTERM') { if (signal === 'SIGKILL') this.child?.kill(); else this.child?.stop(); this.child = null; }
|
|
122
|
-
}
|
package/check/panel.mjs
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
// A resource type (or a panel before them) at the handshake level: read once by Coda's own resources module
|
|
2
|
-
// (check/coda/resources/plugins/resources/panels/, Panels), given what Coda's plugin host gives it
|
|
3
|
-
// (components/plugins/plugin-host.mjs): the installed plugins as it watches them, here the one checked, and each one's
|
|
4
|
-
// environment, as Coda gives every process of the plugin's.
|
|
5
|
-
// Its actions are not run: a button may change things (switch an account, spend a reset), and only a person presses it.
|
|
6
|
-
import { dirname } from 'node:path';
|
|
7
|
-
import { cleared } from './coda/components/plugins/plugin-rules.mjs';
|
|
8
|
-
import { ENVELOPE } from './coda/adapters/call-limit.mjs';
|
|
9
|
-
import { runPluginCommand } from './coda/adapters/plugin-command.mjs';
|
|
10
|
-
import { Panels } from './coda/resources/plugins/resources/panels/panels.mjs';
|
|
11
|
-
import { panelItems, resourceItems } from './coda/resources/plugins/resources/panels/rules.mjs';
|
|
12
|
-
import { closing, temporary } from './leftovers.mjs';
|
|
13
|
-
|
|
14
|
-
// The session a process would belong to: the host's belong to none.
|
|
15
|
-
const THREAD_ENV = 'CODA_THREAD_ID';
|
|
16
|
-
|
|
17
|
-
// The item types a reading holds, cards' items included.
|
|
18
|
-
const typesOf = items => items.flatMap(item => item.type === 'card' ? ['card', ...item.items.map(i => i.type)] : [item.type]);
|
|
19
|
-
// What a panel's command printed as Coda takes it (panelItems), by type; throws PanelError with where it went wrong. For the
|
|
20
|
-
// tests of a plugin's panel.
|
|
21
|
-
export const panelTypes = (output, panel, views = []) => typesOf(panelItems(output, panel, views));
|
|
22
|
-
// What a resource type's command printed as Coda takes it (resourceItems): its resources, each with only the keys it has and
|
|
23
|
-
// its values and buttons; throws PanelError with where it went wrong. For the tests of a plugin's resources.
|
|
24
|
-
export const readResources = (output, type, views = []) => resourceItems(output, type, views);
|
|
25
|
-
// A reading of resources in a line: how many, and how many values and buttons they have.
|
|
26
|
-
const counted = resources => `${resources.length} 个资源,读数 ${resources.reduce((n, r) => n + r.values.length, 0)} 个,按钮 ${resources.reduce((n, r) => n + r.actions.length, 0)} 个${
|
|
27
|
-
resources.some(r => r.error) ? `,${resources.filter(r => r.error).length} 个写了错误` : ''}`;
|
|
28
|
-
|
|
29
|
-
// `checked`: the plugin as the manifest level read it (manifest.mjs checkManifest). `limit`: how long a reading may take, as
|
|
30
|
-
// Panels has it unless given.
|
|
31
|
-
export async function checkPanel({ panel, checked, say, limit }) {
|
|
32
|
-
const { plugin } = checked;
|
|
33
|
-
// The plugin's state directory, which Coda keeps for it; here a temporary one, gone however the checker ends.
|
|
34
|
-
const state = temporary('coda-plugin-check-state-');
|
|
35
|
-
// The host's environment of a plugin (env): its processes', the backend's `node` first on the PATH, and the concurrency
|
|
36
|
-
// groups in use as it is asked for (none here).
|
|
37
|
-
const environment = async () => {
|
|
38
|
-
const env = { ...cleared(process.env), ...checked.env(state.dir) };
|
|
39
|
-
delete env[THREAD_ENV];
|
|
40
|
-
env.PATH = [dirname(process.execPath), env.PATH].filter(Boolean).join(':');
|
|
41
|
-
env.CODA_GROUPS_STATE = JSON.stringify({ now: Date.now(), groups: [] });
|
|
42
|
-
return env;
|
|
43
|
-
};
|
|
44
|
-
// The installed plugins as a module watches them (components/plugins/plugins.mjs offered).
|
|
45
|
-
const offered = { id: plugin.id, name: plugin.displayName, version: plugin.version, source: plugin.source, views: plugin.views.map(v => v.id), contributes: plugin.offers ?? {} };
|
|
46
|
-
const coda = { plugin: { state: null }, environment,
|
|
47
|
-
watch: async (name, told) => { told({ type: 'ADDED', id: offered.id, object: offered }); return { dispose() {} }; } };
|
|
48
|
-
// The command's own result, beside what the page shows of it: whether it ended well and what it printed was not a panel's.
|
|
49
|
-
let result = null;
|
|
50
|
-
const panels = new Panels(coda, { run: async (command, options) => (result = await runPluginCommand(command, options)), ...(limit ? { readTimeoutMs: limit } : {}) });
|
|
51
|
-
const done = closing(() => panels.close());
|
|
52
|
-
try {
|
|
53
|
-
await panels.start();
|
|
54
|
-
const started = Date.now(), reading = await panels.read(`${plugin.id}/${panel.id}`), took = ((Date.now() - started) / 1000).toFixed(1);
|
|
55
|
-
const kind = panel.format === 'resources' ? '资源' : '面板';
|
|
56
|
-
if (reading.error && result && result.code === 0 && !result.timedOut && !result.overflow) return say.fail('panel.output', `输出不合${kind}格式:资源页显示「${reading.error}」`);
|
|
57
|
-
if (reading.error) {
|
|
58
|
-
const why = !result ? '没有运行' : result.timedOut ? `${panels.readTimeoutMs / 1000} 秒没读完,Coda 停下这次读取` : result.overflow ? `标准输出超过 ${ENVELOPE / 1024 / 1024} MiB,Coda 停下这次读取`
|
|
59
|
-
: result.error ? '命令起不来' : `退出码 ${result.code}`;
|
|
60
|
-
return say.fail('panel.read', `读取没成功(${why}):资源页显示「${reading.error}」`);
|
|
61
|
-
}
|
|
62
|
-
const empty = `资源页不显示它${panel.signIn ? ',它出现在「添加资源」里' : ''}`;
|
|
63
|
-
if (panel.format === 'resources') {
|
|
64
|
-
if (!reading.resources.length) say.info('panel.read', `读出空的 resources(${took} 秒):${empty}`);
|
|
65
|
-
else say.pass('panel.read', `读取 ${took} 秒,输出合资源格式:${counted(reading.resources)}`);
|
|
66
|
-
} else {
|
|
67
|
-
const types = typesOf(reading.items);
|
|
68
|
-
const counts = Object.entries(Object.groupBy(types, t => t)).map(([t, list]) => `${t} ×${list.length}`).join(',');
|
|
69
|
-
if (!types.length) say.info('panel.read', `读出空的 items(${took} 秒):${empty}`);
|
|
70
|
-
else say.pass('panel.read', `读取 ${took} 秒,输出合面板格式:${counts}`);
|
|
71
|
-
}
|
|
72
|
-
if (Object.keys(panel.actions).length) say.skip('panel.actions', `动作 ${Object.keys(panel.actions).join('、')} 不运行:按钮可能改动东西,只由人点`);
|
|
73
|
-
} finally {
|
|
74
|
-
panels.close();
|
|
75
|
-
done();
|
|
76
|
-
state.remove();
|
|
77
|
-
}
|
|
78
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
// 「记下此刻」按钮的动作:Coda 在点按钮(并确认)后运行它,退出码 0 就算成功,随后重读这个类型。
|
|
2
|
-
// 按钮带的 args 在 CODA_PANEL_ARGS 里(JSON),这个按钮没带。
|
|
3
|
-
import { writeFileSync } from 'node:fs';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
|
|
6
|
-
writeFileSync(join(process.env.CODA_PLUGIN_STATE, 'mark.json'), JSON.stringify({ at: new Date().toISOString() }));
|