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.
@@ -0,0 +1,215 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { pluginConfigV1 } from "../services.mjs";
4
+ import { pluginId } from "./clients.mjs";
5
+ import { dataDirOf } from "./data.mjs";
6
+ import { installInjectableAccessor } from "./owner.mjs";
7
+ import { serviceError } from "./services.mjs";
8
+ import { SOURCE } from "./sources.mjs";
9
+ import { INTERNAL } from "./status.mjs";
10
+
11
+ export const CONFIG_FILE = "config.json";
12
+
13
+ function isPlainObject(value) {
14
+ return value !== null && typeof value === "object" && !Array.isArray(value);
15
+ }
16
+
17
+ function defaultsOf(schema) {
18
+ const defaults = {};
19
+ if (!isPlainObject(schema?.properties)) return defaults;
20
+ for (const [key, prop] of Object.entries(schema.properties)) {
21
+ if (isPlainObject(prop) && prop.default !== undefined) {
22
+ defaults[key] = structuredClone(prop.default);
23
+ }
24
+ }
25
+ return defaults;
26
+ }
27
+
28
+ function checkPropertyValue(key, value, prop) {
29
+ if (!isPlainObject(prop)) return `unknown config key "${key}"`;
30
+ switch (prop.type) {
31
+ case "boolean":
32
+ if (typeof value !== "boolean") return `config "${key}" must be a boolean`;
33
+ break;
34
+ case "string":
35
+ if (typeof value !== "string") return `config "${key}" must be a string`;
36
+ break;
37
+ case "number":
38
+ if (typeof value !== "number" || !Number.isFinite(value)) return `config "${key}" must be a finite number`;
39
+ break;
40
+ case "integer":
41
+ if (typeof value !== "number" || !Number.isInteger(value)) return `config "${key}" must be an integer`;
42
+ break;
43
+ default:
44
+ return `config "${key}" has unsupported schema type "${String(prop.type)}"`;
45
+ }
46
+ if (Array.isArray(prop.enum) && !prop.enum.includes(value)) {
47
+ return `config "${key}" must be one of ${prop.enum.map((item) => JSON.stringify(item)).join(", ")}`;
48
+ }
49
+ if (typeof prop.minimum === "number" && typeof value === "number" && value < prop.minimum) {
50
+ return `config "${key}" must be >= ${prop.minimum}`;
51
+ }
52
+ if (typeof prop.maximum === "number" && typeof value === "number" && value > prop.maximum) {
53
+ return `config "${key}" must be <= ${prop.maximum}`;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ export class PluginConfig {
59
+ constructor({ dataRoot, services, usage = null }) {
60
+ this.dataRoot = dataRoot;
61
+ this.services = services;
62
+ this.usage = usage;
63
+ this.ctx = null;
64
+ this.handle = null;
65
+ this.listeners = new Map();
66
+ }
67
+
68
+ install(ctx) {
69
+ this.ctx = ctx;
70
+ const config = this;
71
+ const unaccess = installInjectableAccessor(ctx, "config", function () {
72
+ const caller = this;
73
+ const id = pluginId(caller);
74
+ return Object.freeze({
75
+ get: () => config.get({ id }).values,
76
+ set: async (patch) => config.set({ id, values: patch }).values,
77
+ reset: async () => config.reset({ id }).values,
78
+ onChange: (listener) => config.onChange(caller, id, listener),
79
+ });
80
+ });
81
+ this.handle = this.services.provideBuiltin(ctx, pluginConfigV1, {
82
+ list: () => this.list(),
83
+ get: (params) => this.get(params),
84
+ set: (params) => this.set(params),
85
+ reset: (params) => this.reset(params),
86
+ });
87
+ return () => {
88
+ void unaccess();
89
+ void this.handle?.dispose();
90
+ };
91
+ }
92
+
93
+ configFileOf(id) {
94
+ if (typeof id !== "string" || !id) throw serviceError("bad-params", "plugin-config needs { id }");
95
+ try {
96
+ return join(dataDirOf(this.dataRoot, id), CONFIG_FILE);
97
+ } catch (error) {
98
+ throw serviceError("bad-params", error.message);
99
+ }
100
+ }
101
+
102
+ schemaOf(id) {
103
+ for (const entry of this.ctx?.loader?.entries() ?? []) {
104
+ if (entry.options.id === id) return entry.options[SOURCE]?.configSchema ?? null;
105
+ }
106
+ return null;
107
+ }
108
+
109
+ readValidOverrides(file, schema) {
110
+ let raw;
111
+ try {
112
+ raw = JSON.parse(readFileSync(file, "utf8"));
113
+ } catch {
114
+ return {};
115
+ }
116
+ if (!isPlainObject(raw)) return {};
117
+ if (!schema) return { ...raw };
118
+ const props = isPlainObject(schema.properties) ? schema.properties : {};
119
+ const valid = {};
120
+ for (const [key, value] of Object.entries(raw)) {
121
+ if (Object.hasOwn(props, key) && checkPropertyValue(key, value, props[key]) === null) {
122
+ valid[key] = value;
123
+ }
124
+ }
125
+ return valid;
126
+ }
127
+
128
+ list() {
129
+ const items = [];
130
+ for (const entry of this.ctx?.loader?.entries() ?? []) {
131
+ if (INTERNAL.has(entry.options.name)) continue;
132
+ if (!entry.options[SOURCE]?.configSchema) continue;
133
+ items.push(this.get({ id: entry.options.id }));
134
+ }
135
+ return { items };
136
+ }
137
+
138
+ get(params = {}) {
139
+ const id = params?.id;
140
+ const file = this.configFileOf(id);
141
+ const schema = this.schemaOf(id);
142
+ const defaults = defaultsOf(schema);
143
+ const overrides = this.readValidOverrides(file, schema);
144
+ const values = { ...defaults, ...overrides };
145
+ return { id, schema, values, defaults };
146
+ }
147
+
148
+ set(params = {}) {
149
+ const id = params?.id;
150
+ const patch = params?.values;
151
+ const file = this.configFileOf(id);
152
+ if (!isPlainObject(patch)) throw serviceError("bad-params", "plugin-config.set needs { id, values }");
153
+ const schema = this.schemaOf(id);
154
+ if (schema) {
155
+ const props = isPlainObject(schema.properties) ? schema.properties : {};
156
+ for (const [key, value] of Object.entries(patch)) {
157
+ if (!Object.hasOwn(props, key)) {
158
+ throw serviceError("bad-config", `unknown config key "${key}"`, { id, key });
159
+ }
160
+ const problem = checkPropertyValue(key, value, props[key]);
161
+ if (problem) throw serviceError("bad-config", problem, { id, key });
162
+ }
163
+ }
164
+ const defaults = defaultsOf(schema);
165
+ const current = this.readValidOverrides(file, schema);
166
+ const nextOverrides = { ...current, ...patch };
167
+ mkdirSync(dirname(file), { recursive: true });
168
+ writeFileSync(file, `${JSON.stringify(nextOverrides, null, 2)}\n`);
169
+ const values = { ...defaults, ...nextOverrides };
170
+ this.notify(id, values);
171
+ return { id, schema, values, defaults };
172
+ }
173
+
174
+ reset(params = {}) {
175
+ const id = params?.id;
176
+ const file = this.configFileOf(id);
177
+ rmSync(file, { force: true });
178
+ const schema = this.schemaOf(id);
179
+ const defaults = defaultsOf(schema);
180
+ const values = { ...defaults };
181
+ this.notify(id, values);
182
+ return { id, schema, values, defaults };
183
+ }
184
+
185
+ onChange(ctx, id, listener) {
186
+ if (typeof listener !== "function") throw new TypeError("ctx.config.onChange needs a listener function");
187
+ const run = this.usage ? this.usage.wrap(id, listener) : listener;
188
+ return ctx.effect(() => {
189
+ let set = this.listeners.get(id);
190
+ if (!set) this.listeners.set(id, (set = new Set()));
191
+ const hook = { ctx, run, active: true };
192
+ set.add(hook);
193
+ return () => {
194
+ hook.active = false;
195
+ set.delete(hook);
196
+ if (set.size === 0 && this.listeners.get(id) === set) this.listeners.delete(id);
197
+ };
198
+ }, "ctx.config.onChange()");
199
+ }
200
+
201
+ notify(id, values) {
202
+ const hooks = this.listeners.get(id);
203
+ if (hooks) {
204
+ for (const hook of [...hooks]) {
205
+ if (!hook.active) continue;
206
+ try {
207
+ hook.run(structuredClone(values));
208
+ } catch (error) {
209
+ hook.ctx.logger.error(error);
210
+ }
211
+ }
212
+ }
213
+ this.handle?.emit("changed", { id, values: structuredClone(values) });
214
+ }
215
+ }
@@ -51,6 +51,7 @@ function disabledServicesOf(ctx) {
51
51
  export class Services {
52
52
  constructor() {
53
53
  this.providers = new Map();
54
+ this.builtins = new Map();
54
55
  this.interest = new Map();
55
56
  this.watchers = new Set();
56
57
  this.windows = null;
@@ -70,6 +71,30 @@ export class Services {
70
71
  });
71
72
  }
72
73
 
74
+ provideBuiltin(ctx, definition, impl) {
75
+ checkDefinition(definition);
76
+ const methods = {};
77
+ for (const method of Object.keys(definition.methods)) {
78
+ if (typeof impl?.[method] !== "function") throw new TypeError(`the provider of ${definition.name} has no method ${method}`);
79
+ methods[method] = impl[method];
80
+ }
81
+ const provider = { definition, impl, methods, plugin: "host", ctx, pending: new Set(), active: true };
82
+ const handle = {
83
+ emit: (event, data) => this.emit(provider, event, data),
84
+ dispose: () => Promise.all([unregister(), unprovide()]).then(() => {}),
85
+ };
86
+ const unprovide = ctx.provide(definition.name, Object.freeze({ service: definition.name }));
87
+ const unregister = ctx.effect(() => {
88
+ this.builtins.set(definition.name, provider);
89
+ return () => {
90
+ provider.active = false;
91
+ if (this.builtins.get(definition.name) === provider) this.builtins.delete(definition.name);
92
+ for (const call of [...provider.pending]) call.fail(serviceError("peer-gone", `the provider of ${definition.name} went away before ${call.method} answered`, { service: definition.name, method: call.method }));
93
+ };
94
+ }, `builtins.provide(${definition.name})`);
95
+ return Object.freeze(handle);
96
+ }
97
+
73
98
  provide(ctx, definition, impl) {
74
99
  checkDefinition(definition);
75
100
  const methods = {};
@@ -119,7 +144,7 @@ export class Services {
119
144
  } catch (error) {
120
145
  return Promise.reject(error);
121
146
  }
122
- const provider = this.providers.get(name);
147
+ const provider = this.providers.get(name) ?? this.builtins.get(name);
123
148
  if (!provider) return Promise.reject(serviceError("not-ready", `the service ${name} has no provider right now`, { service: name }));
124
149
  if (!declared(provider.definition.methods, method)) return Promise.reject(serviceError("no-method", `${name} declares no method ${String(method)}`, { service: name }));
125
150
  const declaredMs = provider.definition.methods[method].timeoutMs ?? SERVICE_TIMEOUT_MS;
@@ -157,7 +182,8 @@ export class Services {
157
182
  emit(provider, event, data) {
158
183
  const name = provider.definition.name;
159
184
  if (!declared(provider.definition.events, event)) throw serviceError("no-event", `${name} declares no event ${String(event)}`);
160
- if (!provider.active || this.providers.get(name) !== provider) return false;
185
+ const current = this.providers.get(name) ?? this.builtins.get(name);
186
+ if (!provider.active || current !== provider) return false;
161
187
  provider.ctx.emit(eventKey(name, event), data);
162
188
  this.toWindows(name, event, data);
163
189
  return true;
@@ -193,7 +219,7 @@ export class Services {
193
219
  if (wanted && !wanted.size) this.interest.delete(key);
194
220
  return true;
195
221
  }
196
- const provider = this.providers.get(params.service);
222
+ const provider = this.providers.get(params.service) ?? this.builtins.get(params.service);
197
223
  if (provider && !declared(provider.definition.events, params.event)) throw serviceError("no-event", `${params.service} declares no event ${params.event}`);
198
224
  if (!this.interest.has(key)) this.interest.set(key, new Set());
199
225
  this.interest.get(key).add(window);
@@ -37,9 +37,27 @@ function declaredOf(app) {
37
37
  provides: [...(app.provides ?? []), ...(app.replaces ?? [])],
38
38
  client: Object.keys(app.client ?? {}),
39
39
  slots: [...(app.slots ?? [])],
40
+ commands: (app.commands ?? []).map((command) => command.id),
41
+ network: [...(app.network ?? [])],
42
+ experimental: [...(app.experimental ?? [])],
40
43
  };
41
44
  }
42
45
 
46
+ function readConfigSchema(root, configPath) {
47
+ if (configPath === undefined) return null;
48
+ const file = entryFile(root, configPath, "fuyu.config");
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(readFileSync(file, "utf8"));
52
+ } catch (error) {
53
+ throw rejection(`fuyu.config (${configPath}) is not valid JSON: ${error?.message ?? error}`);
54
+ }
55
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
56
+ throw rejection(`fuyu.config (${configPath}) must be a JSON object`);
57
+ }
58
+ return parsed;
59
+ }
60
+
43
61
  export function readManifest(root, options) {
44
62
  let text;
45
63
  try {
@@ -61,7 +79,19 @@ export function readManifest(root, options) {
61
79
  if (!WINDOW.test(window)) throw rejection(`fuyu.client.${window}: ${window} is not a window name`);
62
80
  return { window, file: entryFile(root, path, `fuyu.client.${window}`) };
63
81
  });
64
- return { package: pkg.name, version: pkg.version, host, clients, declared: declaredOf(app) };
82
+ const configSchema = readConfigSchema(root, app.config);
83
+ return {
84
+ package: pkg.name,
85
+ version: pkg.version,
86
+ displayName: app.displayName ?? null,
87
+ host,
88
+ clients,
89
+ commands: app.commands ?? [],
90
+ network: app.network ?? [],
91
+ experimental: app.experimental ?? [],
92
+ configSchema,
93
+ declared: declaredOf(app),
94
+ };
65
95
  }
66
96
 
67
97
  function installedRoot(id, packages) {
@@ -62,19 +62,22 @@ function describe(entry, logs, gate) {
62
62
 
63
63
  export const INTERNAL = new Set([new URL("./plugins-file.mjs", import.meta.url).href, new URL("../../vendor/cordis/hmr/lib/index.js", import.meta.url).href]);
64
64
 
65
- function undeclaredOf(entry, services, clients) {
65
+ function undeclaredOf(entry, services, clients, commands, network) {
66
66
  const declared = entry.options[SOURCE]?.declared;
67
67
  if (!declared) return null;
68
68
  const { id } = entry.options;
69
+ const declaredCommands = declared.commands ?? [];
69
70
  const found = {
70
71
  provides: services.filter((service) => service.plugin === id && !declared.provides.includes(service.name)).map((service) => service.name),
71
72
  client: [...new Set(clients.filter((client) => client.plugin === id && !declared.client.includes(client.window)).map((client) => client.window))],
73
+ commands: (commands?.(id) ?? []).filter((cmd) => !declaredCommands.includes(cmd)),
74
+ network: network?.(id) ?? [],
72
75
  };
73
76
  const listed = Object.entries(found).filter(([, names]) => names.length > 0);
74
77
  return listed.length ? Object.fromEntries(listed) : null;
75
78
  }
76
79
 
77
- export function pluginStatus(ctx, logs = [], { gate, usage, services, clients } = {}) {
80
+ export function pluginStatus(ctx, logs = [], { gate, usage, services, clients, undeclaredCommands, undeclaredNetwork } = {}) {
78
81
  const report = usage?.();
79
82
  const provided = services?.() ?? [];
80
83
  const windows = clients?.() ?? [];
@@ -87,7 +90,7 @@ export function pluginStatus(ctx, logs = [], { gate, usage, services, clients }
87
90
  if (report) extra.usage = report(status.id);
88
91
  const last = gate?.report(status.id).last;
89
92
  if (last) extra.lastError = last;
90
- const undeclared = undeclaredOf(entry, provided, windows);
93
+ const undeclared = undeclaredOf(entry, provided, windows, undeclaredCommands, undeclaredNetwork);
91
94
  if (undeclared) extra.undeclared = undeclared;
92
95
  const disabledServices = Array.isArray(entry.options.disabledServices) ? entry.options.disabledServices.filter((s) => typeof s === "string") : [];
93
96
  if (disabledServices.length > 0) extra.disabledServices = disabledServices;
@@ -105,8 +108,8 @@ export function pluginStatus(ctx, logs = [], { gate, usage, services, clients }
105
108
  });
106
109
  }
107
110
 
108
- export function watchStatus(ctx, logs, onChange, { delayMs = 20, tickMs = 0, gate, usage, services, clients, subscribe } = {}) {
109
- const read = () => pluginStatus(ctx, logs, { gate, usage, services, clients });
111
+ export function watchStatus(ctx, logs, onChange, { delayMs = 20, tickMs = 0, gate, usage, services, clients, undeclaredCommands, undeclaredNetwork, subscribe } = {}) {
112
+ const read = () => pluginStatus(ctx, logs, { gate, usage, services, clients, undeclaredCommands, undeclaredNetwork });
110
113
  let last = JSON.stringify(read());
111
114
  let timer = null;
112
115
  const check = () => {