tauri-cordis 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tauri-cordis",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Everything-is-a-plugin runtime base for Tauri + Node + React built on Cordis: host supervisor protocol, versioned services, managed side effects, and window slots",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -64,13 +64,13 @@
64
64
  "dependencies": {
65
65
  "@babel/code-frame": "^7.29.0",
66
66
  "@standard-schema/spec": "^1.1.0",
67
+ "@tauri-cordis/manifest": "0.2.0",
67
68
  "chokidar": "^4.0.3",
68
69
  "cosmokit": "^1.8.1",
69
70
  "picomatch": "^4.0.3",
70
71
  "schemastery": "^3.18.0",
71
72
  "ws": "^8.23.0",
72
- "yaml": "^2.9.1",
73
- "@tauri-cordis/manifest": "0.1.0"
73
+ "yaml": "^2.9.1"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "react": "^19.0.0"
@@ -63,18 +63,25 @@ export function readBuiltins(dir) {
63
63
  function fromPackage(root, at) {
64
64
  try {
65
65
  const manifest = readManifest(root, { official: true });
66
- return { host: manifest.host && pathToFileURL(manifest.host).href, clients: manifest.clients, declared: manifest.declared };
66
+ return {
67
+ host: manifest.host && pathToFileURL(manifest.host).href,
68
+ clients: manifest.clients,
69
+ declared: manifest.declared,
70
+ displayName: manifest.displayName,
71
+ commands: manifest.commands,
72
+ configSchema: manifest.configSchema,
73
+ };
67
74
  } catch (error) {
68
75
  throw new Error(`${at}: there is no host in the list, and ${error.message}`);
69
76
  }
70
77
  }
71
78
 
72
79
  export function builtinEntries(plugins = []) {
73
- return plugins.map(({ id, host, kind, root, clients = [], declared = null, provides }) => ({
80
+ return plugins.map(({ id, host, kind, root, clients = [], declared = null, provides, displayName = null, commands = [], configSchema = null }) => ({
74
81
  id,
75
82
  name: host ?? CLIENT_ONLY,
76
83
  kind,
77
- [SOURCE]: { source: "builtin", root, clients, declared, ...(provides?.length ? { provides } : {}) },
84
+ [SOURCE]: { source: "builtin", root, clients, declared, displayName, commands, configSchema, ...(provides?.length ? { provides } : {}) },
78
85
  }));
79
86
  }
80
87
 
@@ -0,0 +1,322 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { commandsV1 } from "../services.mjs";
4
+ import { pluginId } from "./clients.mjs";
5
+ import { entryOf, installInjectableAccessor } from "./owner.mjs";
6
+ import { serviceError } from "./services.mjs";
7
+ import { SOURCE } from "./sources.mjs";
8
+ import { INTERNAL } from "./status.mjs";
9
+
10
+ export const KEYBINDINGS_FILE = "keybindings.json";
11
+
12
+ function readOverrides(file) {
13
+ try {
14
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
15
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
16
+ const clean = {};
17
+ for (const [plugin, map] of Object.entries(parsed)) {
18
+ if (!map || typeof map !== "object" || Array.isArray(map)) continue;
19
+ const entries = Object.entries(map).filter(([, val]) => typeof val === "string");
20
+ if (entries.length > 0) clean[plugin] = Object.fromEntries(entries);
21
+ }
22
+ return clean;
23
+ } catch {
24
+ return {};
25
+ }
26
+ }
27
+
28
+ function writeOverrides(file, overrides) {
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ writeFileSync(file, `${JSON.stringify(overrides, null, 2)}\n`);
31
+ }
32
+
33
+ export class Commands {
34
+ constructor({ dir, services, usage = null }) {
35
+ this.file = join(dir, KEYBINDINGS_FILE);
36
+ this.services = services;
37
+ this.usage = usage;
38
+ this.ctx = null;
39
+ this.rpc = null;
40
+ this.handle = null;
41
+ this.registered = new Map();
42
+ this.undeclared = new Map();
43
+ this.watchers = new Set();
44
+ this.overrides = readOverrides(this.file);
45
+ this.conflicts = {};
46
+ this.lastBindingsKey = null;
47
+ }
48
+
49
+ install(ctx) {
50
+ this.ctx = ctx;
51
+ const commands = this;
52
+ const unaccess = installInjectableAccessor(ctx, "commands", function () {
53
+ const caller = this;
54
+ return Object.freeze({
55
+ register: (commandId, handler, meta) => commands.register(caller, commandId, handler, meta),
56
+ });
57
+ });
58
+ this.handle = this.services.provideBuiltin(ctx, commandsV1, {
59
+ list: () => this.list(),
60
+ run: (params) => this.run(params),
61
+ setKeybinding: (params) => this.setKeybinding(params),
62
+ });
63
+ const offStatus = ctx.on("internal/status", () => {
64
+ void this.syncIfChanged();
65
+ });
66
+ const offInit = ctx.on("loader/entry-init", () => {
67
+ void this.syncIfChanged();
68
+ });
69
+ return () => {
70
+ offStatus();
71
+ offInit();
72
+ void unaccess();
73
+ void this.handle?.dispose();
74
+ };
75
+ }
76
+
77
+ attach(rpc) {
78
+ this.rpc = rpc;
79
+ rpc.handle("hotkey", (params) =>
80
+ this.run({
81
+ plugin: params?.pluginId ?? params?.plugin,
82
+ command: params?.command,
83
+ args: params?.args,
84
+ }),
85
+ );
86
+ }
87
+
88
+ register(ctx, commandId, handler, meta) {
89
+ if (typeof commandId !== "string" || commandId.trim() === "") {
90
+ throw new TypeError("ctx.commands.register needs a non-empty command id");
91
+ }
92
+ if (typeof handler !== "function") {
93
+ throw new TypeError(`ctx.commands.register(${commandId}) needs a handler function`);
94
+ }
95
+ const entry = entryOf(ctx);
96
+ const id = entry?.options?.id ?? pluginId(ctx);
97
+ const run = this.usage ? this.usage.wrap(id, handler) : handler;
98
+ const declared = entry?.options?.[SOURCE]?.declared;
99
+ const isUndeclared = Boolean(declared && !(declared.commands ?? []).includes(commandId));
100
+ return ctx.effect(() => {
101
+ let bucket = this.registered.get(id);
102
+ if (!bucket) this.registered.set(id, (bucket = new Map()));
103
+ if (bucket.has(commandId)) throw new Error(`command ${commandId} is already registered by ${id}`);
104
+ bucket.set(commandId, {
105
+ handler: run,
106
+ title: meta?.title ?? { "zh-CN": commandId, en: commandId },
107
+ defaultKeybinding: typeof meta?.keybinding === "string" ? meta.keybinding : null,
108
+ });
109
+ if (isUndeclared) {
110
+ let set = this.undeclared.get(id);
111
+ if (!set) this.undeclared.set(id, (set = new Set()));
112
+ set.add(commandId);
113
+ this.notifyWatchers();
114
+ }
115
+ void this.syncIfChanged();
116
+ this.emitChanged();
117
+ return () => {
118
+ bucket.delete(commandId);
119
+ if (bucket.size === 0 && this.registered.get(id) === bucket) this.registered.delete(id);
120
+ if (isUndeclared) {
121
+ const set = this.undeclared.get(id);
122
+ set?.delete(commandId);
123
+ if (set && set.size === 0) this.undeclared.delete(id);
124
+ this.notifyWatchers();
125
+ }
126
+ void this.syncIfChanged();
127
+ this.emitChanged();
128
+ };
129
+ }, `ctx.commands.register(${commandId})`);
130
+ }
131
+
132
+ effectiveKeybinding(plugin, commandId, defaultKeybinding) {
133
+ const pluginMap = this.overrides[plugin];
134
+ if (pluginMap && Object.hasOwn(pluginMap, commandId)) {
135
+ const override = pluginMap[commandId];
136
+ return override === "" ? null : override;
137
+ }
138
+ return defaultKeybinding ?? null;
139
+ }
140
+
141
+ conflictsFor(plugin, commandId, keybinding, active, siblingItems) {
142
+ if (!active || !keybinding) return [];
143
+ const direct = this.conflicts[`${plugin}:${commandId}`] ?? this.conflicts[`${plugin}/${commandId}`];
144
+ const list = Array.isArray(direct) ? [...direct] : [];
145
+ const pluginList = this.conflicts[plugin];
146
+ if (!Array.isArray(pluginList) || pluginList.length === 0) return list;
147
+ const matchesItem = (msg, item) =>
148
+ msg === item.keybinding ||
149
+ msg === item.id ||
150
+ (item.keybinding && msg.includes(item.keybinding)) ||
151
+ msg.includes(item.id);
152
+ for (const msg of pluginList) {
153
+ if (typeof msg !== "string") continue;
154
+ const matchedAny = siblingItems.some((item) => item.active && item.keybinding && matchesItem(msg, item));
155
+ if (!matchedAny || matchesItem(msg, { id: commandId, keybinding })) {
156
+ if (!list.includes(msg)) list.push(msg);
157
+ }
158
+ }
159
+ return list;
160
+ }
161
+
162
+ rawItems() {
163
+ if (!this.ctx) return [];
164
+ const visited = new Set();
165
+ const groups = [];
166
+ for (const entry of this.ctx.loader?.entries() ?? []) {
167
+ if (INTERNAL.has(entry.options.name)) continue;
168
+ const id = entry.options.id;
169
+ visited.add(id);
170
+ const meta = entry.options[SOURCE];
171
+ const pluginName = meta?.displayName ?? null;
172
+ const active = entry.options.disabled !== true && !meta?.rejected;
173
+ const seenCmds = new Set();
174
+ const pluginItems = [];
175
+ for (const cmd of meta?.commands ?? []) {
176
+ seenCmds.add(cmd.id);
177
+ const defaultKeybinding = cmd.keybinding ?? null;
178
+ pluginItems.push({
179
+ pluginId: id,
180
+ pluginName,
181
+ id: cmd.id,
182
+ title: cmd.title,
183
+ defaultKeybinding,
184
+ keybinding: this.effectiveKeybinding(id, cmd.id, defaultKeybinding),
185
+ active,
186
+ });
187
+ }
188
+ const runtime = this.registered.get(id);
189
+ if (runtime) {
190
+ for (const [cmdId, info] of runtime.entries()) {
191
+ if (seenCmds.has(cmdId)) continue;
192
+ pluginItems.push({
193
+ pluginId: id,
194
+ pluginName,
195
+ id: cmdId,
196
+ title: info.title,
197
+ defaultKeybinding: info.defaultKeybinding,
198
+ keybinding: this.effectiveKeybinding(id, cmdId, info.defaultKeybinding),
199
+ active,
200
+ });
201
+ }
202
+ }
203
+ if (pluginItems.length > 0) groups.push(pluginItems);
204
+ }
205
+ for (const [id, runtime] of this.registered.entries()) {
206
+ if (visited.has(id)) continue;
207
+ const pluginItems = [];
208
+ for (const [cmdId, info] of runtime.entries()) {
209
+ pluginItems.push({
210
+ pluginId: id,
211
+ pluginName: null,
212
+ id: cmdId,
213
+ title: info.title,
214
+ defaultKeybinding: info.defaultKeybinding,
215
+ keybinding: this.effectiveKeybinding(id, cmdId, info.defaultKeybinding),
216
+ active: true,
217
+ });
218
+ }
219
+ if (pluginItems.length > 0) groups.push(pluginItems);
220
+ }
221
+ return groups.flatMap((group) =>
222
+ group.map((item) => ({
223
+ ...item,
224
+ conflicts: this.conflictsFor(item.pluginId, item.id, item.keybinding, item.active, group),
225
+ })),
226
+ );
227
+ }
228
+
229
+ list() {
230
+ return { items: this.rawItems() };
231
+ }
232
+
233
+ async run(params = {}) {
234
+ const plugin = params?.plugin;
235
+ const command = params?.command;
236
+ if (typeof plugin !== "string" || !plugin || typeof command !== "string" || !command) {
237
+ throw serviceError("bad-params", "commands.run needs { plugin, command }");
238
+ }
239
+ const entry = this.registered.get(plugin)?.get(command);
240
+ if (!entry) {
241
+ throw serviceError("not-running", `command ${command} of plugin ${plugin} is not running`, { plugin, command });
242
+ }
243
+ const result = await entry.handler(params?.args);
244
+ return result === undefined ? null : result;
245
+ }
246
+
247
+ async setKeybinding(params = {}) {
248
+ const { plugin, command, keybinding } = params ?? {};
249
+ if (typeof plugin !== "string" || !plugin || typeof command !== "string" || !command) {
250
+ throw serviceError("bad-params", "commands.setKeybinding needs { plugin, command, keybinding }");
251
+ }
252
+ if (keybinding !== null && typeof keybinding !== "string") {
253
+ throw serviceError("bad-params", "keybinding must be a string or null");
254
+ }
255
+ if (keybinding === null) {
256
+ if (this.overrides[plugin]) {
257
+ delete this.overrides[plugin][command];
258
+ if (Object.keys(this.overrides[plugin]).length === 0) delete this.overrides[plugin];
259
+ }
260
+ } else {
261
+ this.overrides[plugin] ??= {};
262
+ this.overrides[plugin][command] = keybinding;
263
+ }
264
+ writeOverrides(this.file, this.overrides);
265
+ await this.syncHotkeys();
266
+ const result = this.list();
267
+ this.handle?.emit("changed", result);
268
+ return result;
269
+ }
270
+
271
+ bindingsPayload() {
272
+ return this.rawItems()
273
+ .filter((item) => item.active && item.keybinding)
274
+ .map((item) => ({ pluginId: item.pluginId, command: item.id, shortcut: item.keybinding }));
275
+ }
276
+
277
+ async syncIfChanged() {
278
+ if (!this.rpc || !this.ctx) return;
279
+ const bindings = this.bindingsPayload();
280
+ const key = JSON.stringify(bindings);
281
+ if (this.lastBindingsKey === null && bindings.length === 0) {
282
+ this.lastBindingsKey = key;
283
+ return;
284
+ }
285
+ if (key === this.lastBindingsKey) return;
286
+ await this.syncHotkeys(bindings, key);
287
+ }
288
+
289
+ async syncHotkeys(precomputed = null, precomputedKey = null) {
290
+ if (!this.rpc || !this.ctx) return;
291
+ const bindings = precomputed ?? this.bindingsPayload();
292
+ this.lastBindingsKey = precomputedKey ?? JSON.stringify(bindings);
293
+ let response;
294
+ try {
295
+ response = await this.rpc.call("pluginKernel.syncHotkeys", { bindings });
296
+ } catch {
297
+ return;
298
+ }
299
+ const next = response?.conflicts && typeof response.conflicts === "object" && !Array.isArray(response.conflicts) ? response.conflicts : {};
300
+ if (JSON.stringify(next) !== JSON.stringify(this.conflicts)) {
301
+ this.conflicts = next;
302
+ this.emitChanged();
303
+ }
304
+ }
305
+
306
+ emitChanged() {
307
+ this.handle?.emit("changed", this.list());
308
+ }
309
+
310
+ undeclaredOf(plugin) {
311
+ return [...(this.undeclared.get(plugin) ?? [])];
312
+ }
313
+
314
+ watch(listener) {
315
+ this.watchers.add(listener);
316
+ return () => this.watchers.delete(listener);
317
+ }
318
+
319
+ notifyWatchers() {
320
+ for (const listener of this.watchers) listener();
321
+ }
322
+ }
@@ -0,0 +1,85 @@
1
+ import { pluginId } from "./clients.mjs";
2
+ import { entryOf, installInjectableAccessor } from "./owner.mjs";
3
+ import { SOURCE } from "./sources.mjs";
4
+
5
+ function isAllowedTarget(url, declaredList) {
6
+ const hostname = url.hostname.toLowerCase();
7
+ const isLocal = (hostname === "localhost" || hostname === "127.0.0.1") && declaredList.includes("localhost");
8
+ const hostAllowed =
9
+ isLocal ||
10
+ declaredList.includes(hostname) ||
11
+ declaredList.some((pattern) => pattern.startsWith("*.") && hostname.endsWith(pattern.slice(1)) && hostname !== pattern.slice(2));
12
+ if (!hostAllowed) return false;
13
+ return url.protocol === "https:" || (url.protocol === "http:" && isLocal);
14
+ }
15
+
16
+ export class ControlledHttp {
17
+ constructor({ fetchImpl = globalThis.fetch } = {}) {
18
+ this.fetchImpl = fetchImpl;
19
+ this.undeclared = new Map();
20
+ this.watchers = new Set();
21
+ }
22
+
23
+ install(ctx) {
24
+ const http = this;
25
+ const offInit = ctx.on("loader/entry-init", (entry) => {
26
+ const id = entry?.options?.id;
27
+ if (id && this.undeclared.delete(id)) this.notifyWatchers();
28
+ });
29
+ const unaccess = installInjectableAccessor(ctx, "http", function () {
30
+ const caller = this;
31
+ return Object.freeze({
32
+ fetch: (input, init) => http.fetch(caller, input, init),
33
+ });
34
+ });
35
+ return () => {
36
+ offInit();
37
+ void unaccess();
38
+ };
39
+ }
40
+
41
+ fetch(ctx, input, init) {
42
+ const invoke = () => (init === undefined ? this.fetchImpl(input) : this.fetchImpl(input, init));
43
+ const entry = entryOf(ctx);
44
+ const meta = entry?.options?.[SOURCE];
45
+ if (!meta || meta.source === "builtin" || !meta.declared) {
46
+ return Promise.resolve().then(invoke);
47
+ }
48
+ let url;
49
+ try {
50
+ url = typeof input === "string" || input instanceof URL ? new URL(String(input)) : new URL(input.url);
51
+ } catch (error) {
52
+ return Promise.reject(error);
53
+ }
54
+ const hostname = url.hostname.toLowerCase();
55
+ const declared = (meta.declared.network ?? []).map((item) => item.toLowerCase());
56
+ if (!isAllowedTarget(url, declared)) {
57
+ const id = entry.options.id ?? pluginId(ctx);
58
+ let set = this.undeclared.get(id);
59
+ if (!set) this.undeclared.set(id, (set = new Set()));
60
+ const before = set.size;
61
+ set.add(hostname);
62
+ if (set.size !== before) this.notifyWatchers();
63
+ return Promise.reject(
64
+ Object.assign(new Error(`plugin ${id} fetched undeclared host ${hostname}`), {
65
+ code: "undeclared-network",
66
+ host: hostname,
67
+ }),
68
+ );
69
+ }
70
+ return Promise.resolve().then(invoke);
71
+ }
72
+
73
+ undeclaredOf(plugin) {
74
+ return [...(this.undeclared.get(plugin) ?? [])];
75
+ }
76
+
77
+ watch(listener) {
78
+ this.watchers.add(listener);
79
+ return () => this.watchers.delete(listener);
80
+ }
81
+
82
+ notifyWatchers() {
83
+ for (const listener of this.watchers) listener();
84
+ }
85
+ }
@@ -39,7 +39,10 @@ export interface PluginStatus {
39
39
  lastError?: { at: number; text: string };
40
40
  usage?: PluginUsage;
41
41
  source?: PluginSource;
42
- undeclared?: { provides?: string[]; client?: string[]; slots?: string[] };
42
+ undeclared?: { provides?: string[]; client?: string[]; slots?: string[]; commands?: string[]; network?: string[] };
43
+ disabledServices?: string[];
44
+ provides?: string[];
45
+ replacedServices?: Array<{ service: string; by: string }>;
43
46
  }
44
47
 
45
48
  export type PluginSource = "builtin" | "market" | "manual" | "dev" | "file";
@@ -131,6 +134,7 @@ export interface HostOptions {
131
134
  faultLimit?: Partial<FaultLimit>;
132
135
  onLog?: (entry: LogEntry) => void;
133
136
  rpc?: HostRpc | null;
137
+ fetchImpl?: (input: any, init?: any) => Promise<any>;
134
138
  }
135
139
 
136
140
  export interface Host {
@@ -189,6 +193,9 @@ export interface DeclaredUse {
189
193
  provides: string[];
190
194
  client: string[];
191
195
  slots: string[];
196
+ commands: string[];
197
+ network: string[];
198
+ experimental: string[];
192
199
  }
193
200
 
194
201
  export interface BuiltinPlugin {
@@ -198,13 +205,21 @@ export interface BuiltinPlugin {
198
205
  host: string | null;
199
206
  clients: PluginWindowFile[];
200
207
  declared: DeclaredUse | null;
208
+ displayName?: Record<string, string> | null;
209
+ commands?: Array<{ id: string; title: Record<string, string>; keybinding?: string }>;
210
+ configSchema?: Record<string, unknown> | null;
201
211
  }
202
212
 
203
213
  export interface PluginPackage {
204
214
  package: string;
205
215
  version: string;
216
+ displayName: Record<string, string> | null;
206
217
  host: string | null;
207
218
  clients: PluginWindowFile[];
219
+ commands: Array<{ id: string; title: Record<string, string>; keybinding?: string }>;
220
+ network: string[];
221
+ experimental: string[];
222
+ configSchema: Record<string, unknown> | null;
208
223
  declared: DeclaredUse;
209
224
  }
210
225
 
@@ -224,3 +239,8 @@ export const DEV_PREFIX: "dev";
224
239
  export const INSTALLED_SOURCES: readonly ["market", "manual"];
225
240
  export const SOURCES: readonly ["market", "manual", "dev"];
226
241
  export function readManifest(root: string, options: ValidateManifestOptions): PluginPackage;
242
+ export const KEYBINDINGS_FILE: "keybindings.json";
243
+ export const CONFIG_FILE: "config.json";
244
+ export const WINDOW_RULES_FILE: "window-rules.json";
245
+ export const MAX_WINDOWS_PER_PLUGIN: 8;
246
+ export const MAX_WINDOWS_TOTAL: 24;
@@ -8,3 +8,6 @@ export { RUST_TIMEOUT_MS, RustBridge, rustError } from "./rust.mjs";
8
8
  export { BUILTINS_FILE, BUILTINS_FORMAT, BUILTIN_PREFIX, readBuiltins } from "./builtins.mjs";
9
9
  export { DATA_DIR, dataDirOf } from "./data.mjs";
10
10
  export { DEV_PREFIX, INSTALLED_SOURCES, PACKAGES_DIR, SOURCES, readManifest } from "./sources.mjs";
11
+ export { KEYBINDINGS_FILE } from "./commands.mjs";
12
+ export { CONFIG_FILE } from "./plugin-config.mjs";
13
+ export { MAX_WINDOWS_PER_PLUGIN, MAX_WINDOWS_TOTAL, WINDOW_RULES_FILE } from "./windows.mjs";
@@ -8,17 +8,21 @@ import { Context } from "../../vendor/cordis/core/lib/index.js";
8
8
  import { HOST_SHARED_MODULES } from "../protocol.mjs";
9
9
  import { builtinMounts, readBuiltins } from "./builtins.mjs";
10
10
  import { Clients } from "./clients.mjs";
11
+ import { Commands } from "./commands.mjs";
11
12
  import { DATA_DIR, installDataDir } from "./data.mjs";
12
- import { DEV_WATCHED, watchBuiltins } from "./reload.mjs";
13
- import { Services } from "./services.mjs";
14
- import { DEV_PREFIX, SOURCE } from "./sources.mjs";
13
+ import { Gate } from "./gate.mjs";
14
+ import { ControlledHttp } from "./http.mjs";
15
15
  import { recordLogs } from "./logs.mjs";
16
+ import { PluginConfig } from "./plugin-config.mjs";
17
+ import { DEV_WATCHED, watchBuiltins } from "./reload.mjs";
16
18
  import { RustBridge } from "./rust.mjs";
19
+ import { Services } from "./services.mjs";
17
20
  import { shareModules } from "./share.mjs";
18
- import { Gate } from "./gate.mjs";
19
- import { Timers } from "./timer.mjs";
21
+ import { DEV_PREFIX, SOURCE } from "./sources.mjs";
20
22
  import { INTERNAL, pluginStatus, trackImportErrors, watchStatus } from "./status.mjs";
23
+ import { Timers } from "./timer.mjs";
21
24
  import { Usage } from "./usage.mjs";
25
+ import { PluginWindows } from "./windows.mjs";
22
26
 
23
27
  const API = new URL("../index.mjs", import.meta.url).href;
24
28
  const SHARED_FILES = {
@@ -62,7 +66,7 @@ function hostInfo(startedAt, safe, dev) {
62
66
  return { pid: process.pid, node: process.versions.node, startedAt, safe, dev, rssBytes: memory.rss, heapUsedBytes: memory.heapUsed, cpuMs: Math.round((cpu.user + cpu.system) / 1000) };
63
67
  }
64
68
 
65
- export async function startHost({ dir, config = "plugins.yml", builtins = null, dataDir = null, appVersion = null, apiNames = [], watch = false, dev = false, safe = null, bisect = [], faultLimit, onLog, rpc = null } = {}) {
69
+ export async function startHost({ dir, config = "plugins.yml", builtins = null, dataDir = null, appVersion = null, apiNames = [], watch = false, dev = false, safe = null, bisect = [], faultLimit, onLog, rpc = null, fetchImpl = globalThis.fetch } = {}) {
66
70
  if (!dir) throw new Error("startHost needs the directory that holds the plugin configuration");
67
71
  const startedAt = Date.now();
68
72
  const catalog = builtins ? readBuiltins(builtins) : null;
@@ -77,13 +81,24 @@ export async function startHost({ dir, config = "plugins.yml", builtins = null,
77
81
  usage.install(ctx);
78
82
  const timers = new Timers(usage);
79
83
  timers.install(ctx);
80
- installDataDir(ctx, dataDir ?? join(dir, DATA_DIR));
84
+ const dataRoot = dataDir ?? join(dir, DATA_DIR);
85
+ installDataDir(ctx, dataRoot);
81
86
  await ctx.plugin(Clients, { root: dir, mounts: builtinMounts(catalog) });
82
87
  const services = new Services();
83
88
  services.install(ctx);
84
89
  const rust = new RustBridge(usage);
85
90
  rust.install(ctx);
86
91
  if (rpc) rust.attach(rpc);
92
+ const commands = new Commands({ dir, services, usage });
93
+ commands.install(ctx);
94
+ if (rpc) commands.attach(rpc);
95
+ const pluginConfig = new PluginConfig({ dataRoot, services, usage });
96
+ pluginConfig.install(ctx);
97
+ const http = new ControlledHttp({ fetchImpl });
98
+ http.install(ctx);
99
+ const windows = new PluginWindows({ dir, services, usage });
100
+ windows.install(ctx);
101
+ if (rpc) windows.attach(rpc);
87
102
  await ctx.use(Loader);
88
103
  trackImportErrors(ctx);
89
104
  gate.install(ctx);
@@ -94,13 +109,21 @@ export async function startHost({ dir, config = "plugins.yml", builtins = null,
94
109
  }
95
110
  const id = await ctx.loader.create({ name: PLUGINS_FILE, config: { path: config, builtins: catalog?.plugins ?? [], dir, appVersion } });
96
111
  if (watch) await watchConfig(ctx, id);
112
+ if (rpc) void commands.syncIfChanged();
97
113
  const report = () => usage.report(ctx, timers.counts(), (plugin) => gate.report(plugin), rust.counts());
98
114
  const extras = {
99
115
  gate,
100
116
  usage: report,
101
117
  services: () => services.list(),
102
118
  clients: () => ctx.clients.list(),
103
- subscribe: (listener) => [services.watch(listener), ctx.clients.watch(listener)],
119
+ undeclaredCommands: (plugin) => commands.undeclaredOf(plugin),
120
+ undeclaredNetwork: (plugin) => http.undeclaredOf(plugin),
121
+ subscribe: (listener) => [
122
+ services.watch(listener),
123
+ ctx.clients.watch(listener),
124
+ commands.watch(listener),
125
+ http.watch(listener),
126
+ ],
104
127
  };
105
128
  return {
106
129
  ctx,
@@ -1,10 +1,23 @@
1
- export function ownerOf(fiber) {
2
- let current = fiber;
1
+ export function entryOf(ctx) {
2
+ let current = ctx?.fiber;
3
3
  while (current) {
4
- if (current.entry) return current.entry.options.id;
4
+ if (current.entry) return current.entry;
5
5
  const next = current.parent?.fiber;
6
6
  if (!next || next === current) return null;
7
7
  current = next;
8
8
  }
9
9
  return null;
10
10
  }
11
+
12
+ export function ownerOf(fiber) {
13
+ return entryOf({ fiber })?.options.id ?? null;
14
+ }
15
+
16
+ export function installInjectableAccessor(ctx, name, get) {
17
+ const unprovide = ctx.provide(name, true);
18
+ ctx.reflect.props[name] = { type: "accessor", get };
19
+ const cleanup = ctx.effect(() => () => {
20
+ delete ctx.reflect.props[name];
21
+ }, `accessor(${name})`);
22
+ return () => Promise.all([cleanup(), unprovide()]);
23
+ }