@auto-mas/auto-mas-plugin-devices 0.0.0-stage → 0.1.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,76 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ export class Store {
5
+ db;
6
+ lease;
7
+ constructor(directory) {
8
+ mkdirSync(directory, { recursive: true });
9
+ this.lease = new DatabaseSync(join(directory, 'session.db'));
10
+ try {
11
+ this.lease.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
12
+ }
13
+ catch (error) {
14
+ this.lease.close();
15
+ if (error.errcode === 5)
16
+ throw new Error('该数据目录已有 MAS 后端在运行');
17
+ throw error;
18
+ }
19
+ try {
20
+ this.db = new DatabaseSync(join(directory, 'mas.db'));
21
+ this.db.exec(`PRAGMA journal_mode = WAL;
22
+ CREATE TABLE IF NOT EXISTS entries (
23
+ collection TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
24
+ PRIMARY KEY (collection, id)
25
+ );
26
+ CREATE INDEX IF NOT EXISTS run_start ON entries (
27
+ unixepoch(json_extract(value, '$.started'), 'subsec') DESC
28
+ ) WHERE collection = 'runs'`);
29
+ }
30
+ catch (error) {
31
+ this.lease.close();
32
+ throw error;
33
+ }
34
+ }
35
+ recentRuns() {
36
+ return this.db.prepare(`SELECT value FROM entries WHERE collection = 'runs'
37
+ ORDER BY unixepoch(json_extract(value, '$.started'), 'subsec') DESC, rowid DESC LIMIT 200`)
38
+ .all().map(row => JSON.parse(String(row.value)));
39
+ }
40
+ list(collection) {
41
+ const rows = this.db.prepare('SELECT value FROM entries WHERE collection = ? ORDER BY rowid').all(collection);
42
+ return rows.map(row => JSON.parse(String(row.value)));
43
+ }
44
+ get(collection, id) {
45
+ const row = this.db.prepare('SELECT value FROM entries WHERE collection = ? AND id = ?').get(collection, id);
46
+ return row && JSON.parse(String(row.value));
47
+ }
48
+ put(collection, entry) {
49
+ this.db.prepare('INSERT INTO entries VALUES (?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET value = excluded.value')
50
+ .run(collection, entry.id, JSON.stringify(entry));
51
+ return entry;
52
+ }
53
+ remove(collection, id) {
54
+ this.db.prepare('DELETE FROM entries WHERE collection = ? AND id = ?').run(collection, id);
55
+ }
56
+ transaction(callback) {
57
+ this.db.exec('BEGIN IMMEDIATE');
58
+ try {
59
+ const result = callback();
60
+ this.db.exec('COMMIT');
61
+ return result;
62
+ }
63
+ catch (error) {
64
+ this.db.exec('ROLLBACK');
65
+ throw error;
66
+ }
67
+ }
68
+ close() {
69
+ try {
70
+ this.db.close();
71
+ }
72
+ finally {
73
+ this.lease.close();
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,171 @@
1
+ import {} from 'cordis';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpathSync, watch } from 'node:fs';
4
+ import { realpath, stat } from 'node:fs/promises';
5
+ import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';
6
+ import { describeSchema, parseConfig } from './schema.js';
7
+ export const viewAssetPrefix = '/api/ui/v1/views/';
8
+ const assets = new Map(Object.entries({
9
+ '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
10
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
11
+ '.gif': 'image/gif', '.cur': 'image/x-icon',
12
+ '.woff': 'font/woff', '.woff2': 'font/woff2',
13
+ }));
14
+ const assetSegment = /^[\w-][\w.-]*$/;
15
+ const viewId = /^(?:builtin:)?[\w-][\w.-]*$/u;
16
+ export { DownloadFile } from './download.js';
17
+ export class UiRegistry {
18
+ pages = new Map();
19
+ queries = new Map();
20
+ actions = new Map();
21
+ downloads = new Map();
22
+ panels = new Map();
23
+ routes = new Map();
24
+ resolvers = new Set();
25
+ clients = new Map();
26
+ images = new Map();
27
+ changed;
28
+ constructor(changed = () => { }) {
29
+ this.changed = changed;
30
+ }
31
+ /** Register the browser bundle for a page's view id for this Cordis scope. */
32
+ client(ctx, id, options) {
33
+ if (!viewId.test(id) || !isAbsolute(options.root) || !options.entry.split('/').every(part => assetSegment.test(part))
34
+ || !['.js', '.mjs'].includes(extname(options.entry)))
35
+ throw new Error('页面客户端注册无效');
36
+ ctx.effect(() => {
37
+ if (this.clients.has(id) || this.images.has(id))
38
+ throw new Error(`重复注册页面客户端: ${id}`);
39
+ this.clients.set(id, { ...options, root: realpathSync(options.root), revision: randomUUID() });
40
+ return () => { this.clients.delete(id); };
41
+ });
42
+ ctx.inject(['hmr'], scope => {
43
+ const client = this.clients.get(id);
44
+ if (!client)
45
+ return;
46
+ scope.effect(() => {
47
+ let timer;
48
+ let watcher;
49
+ const warn = () => scope.logger('webui').warn('无法监听页面模块 %s 的资源', id);
50
+ try {
51
+ watcher = watch(client.root, { recursive: true, persistent: false }, (_, file) => {
52
+ if (file && !assets.has(extname(file)))
53
+ return;
54
+ clearTimeout(timer);
55
+ timer = setTimeout(() => {
56
+ client.revision = randomUUID();
57
+ this.changed();
58
+ }, 150);
59
+ });
60
+ watcher.on('error', warn);
61
+ }
62
+ catch {
63
+ warn();
64
+ }
65
+ return () => {
66
+ clearTimeout(timer);
67
+ watcher?.close();
68
+ };
69
+ });
70
+ });
71
+ }
72
+ /** Publish one image owned by a plugin for the lifetime of its scope. */
73
+ image(ctx, id, file) {
74
+ const entry = basename(file);
75
+ if (!viewId.test(id) || !isAbsolute(file) || !assetSegment.test(entry) || !assets.get(extname(entry))?.startsWith('image/')) {
76
+ throw new Error('插件图标声明无效');
77
+ }
78
+ const revision = randomUUID();
79
+ ctx.effect(() => {
80
+ if (this.images.has(id) || this.clients.has(id))
81
+ throw new Error(`重复注册插件图标: ${id}`);
82
+ this.images.set(id, { entry, root: realpathSync(dirname(file)), revision });
83
+ return () => { this.images.delete(id); };
84
+ });
85
+ return `${viewAssetPrefix}${id}/${revision}/${entry}`;
86
+ }
87
+ describePage(page) {
88
+ const client = page.view && this.clients.get(page.view);
89
+ return { ...page, viewModule: client ? `${viewAssetPrefix}${page.view}/${client.revision}/${client.entry}` : undefined };
90
+ }
91
+ async viewAsset(pathname) {
92
+ const [id, revision, ...parts] = pathname.slice(viewAssetPrefix.length).split('/');
93
+ const image = this.images.get(id);
94
+ if (image && (parts.length !== 1 || parts[0] !== image.entry))
95
+ return;
96
+ const client = image ?? this.clients.get(id);
97
+ if (!client || client.revision !== revision || !parts.length || !parts.every(part => assetSegment.test(part)))
98
+ return;
99
+ const type = assets.get(extname(parts.at(-1)));
100
+ if (!type)
101
+ return;
102
+ const path = await realpath(resolve(client.root, ...parts)).catch(() => undefined);
103
+ if (!path)
104
+ return;
105
+ const inside = relative(client.root, path);
106
+ if (!inside || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside))
107
+ return;
108
+ const info = await stat(path).catch(() => undefined);
109
+ if (info?.isFile())
110
+ return { path, type, size: info.size };
111
+ }
112
+ schemaForm(ctx, action, schema, onSubmit) {
113
+ this.scope(ctx, undefined, {}, { [action]: input => onSubmit(parseConfig(schema, input.config), input) });
114
+ return describeSchema(schema);
115
+ }
116
+ resolve(path) {
117
+ for (const page of this.pages.values()) {
118
+ if ((page.path ?? `/${page.id}`) === path || `/${page.id}` === path)
119
+ return page;
120
+ }
121
+ for (const resolve of this.resolvers) {
122
+ const page = resolve(path);
123
+ if (page)
124
+ return page;
125
+ }
126
+ }
127
+ pageRoutes(ctx, resolve) {
128
+ ctx.effect(() => {
129
+ this.resolvers.add(resolve);
130
+ return () => { this.resolvers.delete(resolve); };
131
+ });
132
+ }
133
+ route(ctx, path, handler) {
134
+ ctx.effect(() => {
135
+ if (this.routes.has(path))
136
+ throw new Error(`重复注册路由: ${path}`);
137
+ this.routes.set(path, handler);
138
+ return () => { this.routes.delete(path); };
139
+ });
140
+ }
141
+ download(ctx, id, handler) {
142
+ ctx.effect(() => {
143
+ if (this.downloads.has(id))
144
+ throw new Error(`重复注册下载: ${id}`);
145
+ this.downloads.set(id, handler);
146
+ return () => { this.downloads.delete(id); };
147
+ });
148
+ }
149
+ panel(ctx, pluginId, components, queries = {}, actions = {}) {
150
+ this.register(ctx, [[this.panels, pluginId, components]], queries, actions);
151
+ }
152
+ scope(ctx, page, queries = {}, actions = {}) {
153
+ this.register(ctx, page ? [[this.pages, page.id, page]] : [], queries, actions);
154
+ }
155
+ register(ctx, entries, queries, actions) {
156
+ ctx.effect(() => {
157
+ const pending = [...entries];
158
+ for (const [id, value] of Object.entries(queries))
159
+ pending.push([this.queries, id, value]);
160
+ for (const [id, value] of Object.entries(actions))
161
+ pending.push([this.actions, id, value]);
162
+ for (const [map, id] of pending)
163
+ if (map.has(id))
164
+ throw new Error(`重复注册页面或操作: ${id}`);
165
+ for (const [map, id, value] of pending)
166
+ map.set(id, value);
167
+ return () => { for (const [map, id] of pending)
168
+ map.delete(id); };
169
+ });
170
+ }
171
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
- {
2
- "name": "@auto-mas/auto-mas-plugin-devices",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@auto-mas/auto-mas-plugin-devices",
3
+ "version": "0.1.0",
4
+ "license": "AGPL-3.0-only",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "exports": "./dist/index.js",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "engines": {
12
+ "node": ">=24"
13
+ },
14
+ "keywords": [
15
+ "auto-mas-plugin"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "description": "AUTO-MAS devices Cordis component",
21
+ "autoMas": {
22
+ "id": "devices",
23
+ "abi": 1,
24
+ "hostDependencies": {
25
+ "cordis": "4.0.0-rc.13",
26
+ "jsonc-parser": "3.3.1",
27
+ "schemastery": "3.18.0"
28
+ }
29
+ }
30
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.