add notice after config

This commit is contained in:
2026-07-31 10:20:33 +08:00
parent 692d8dd18a
commit d45acaf50f
12 changed files with 2721 additions and 2277 deletions
+9
View File
@@ -0,0 +1,9 @@
# 默认所有文本文件使用 Windows 换行符
* text=auto eol=crlf
# server 文件夹下所有文件使用 Linux 换行符
server/** text eol=lf
# 特定文件类型明确指定
*.sh text eol=lf
*.bash text eol=lf
+199 -190
View File
@@ -1,191 +1,200 @@
const fs = require("node:fs"); const fs = require("node:fs");
const path = require("node:path"); const path = require("node:path");
const { parse } = require("csv-parse/sync"); const { parse } = require("csv-parse/sync");
const { callServer } = require("./server-client"); const { callServer } = require("./server-client");
const IDENTIFICATION_FIELDS = [ const IDENTIFICATION_FIELDS = [
"q_in_val", "dt", "n_order", "t_c", "levels", "q_in_val", "dt", "n_order", "t_c", "levels",
"dead_area", "xa_full", "V_val", "repeat" "dead_area", "xa_full", "V_val", "repeat"
]; ];
function getDeviceId(options = {}) { function getDeviceId(options = {}) {
const deviceId = String(options.deviceId || process.env.REINLOOP_DEVICE_ID || "").trim(); const deviceId = String(options.deviceId || process.env.REINLOOP_DEVICE_ID || "").trim();
if (!deviceId) throw new Error("发布或读取辨识配置时必须提供设备 ID"); if (!deviceId) throw new Error("发布或读取辨识配置时必须提供设备 ID");
return deviceId; return deviceId;
} }
async function readParameters(filePath) { async function readParameters(filePath) {
if (!filePath) throw new Error("发布参数时必须提供 JSON 文件路径"); if (!filePath) throw new Error("发布参数时必须提供 JSON 文件路径");
const content = await fs.promises.readFile(path.resolve(filePath), "utf8"); const content = await fs.promises.readFile(path.resolve(filePath), "utf8");
const config = JSON.parse(content); const config = JSON.parse(content);
return config.parameters || config; return config.parameters || config;
} }
async function uploadVolumeConfig(parameters, options = {}) { async function uploadVolumeConfig(parameters, options = {}) {
const deviceId = getDeviceId(options); const deviceId = getDeviceId(options);
const request = await callServer({ const request = await callServer({
type: "getPendingVolumeConfigRequest", type: "getPendingVolumeConfigRequest",
deviceId deviceId
}, options); }, options);
if (!request.pending) { if (!request.pending) {
throw new Error("ReinLoop 尚未发起容积参数请求,请先在客户端开始容积测试"); throw new Error("ReinLoop 尚未发起容积参数请求,请先在客户端开始容积测试");
} }
const result = await callServer({ const result = await callServer({
type: "uploadDataFile", type: "uploadDataFile",
fileName: "volume_measurement.json", fileName: "volume_measurement.json",
folder: `${deviceId}/volume_config_requests/${request.requestId}` folder: `${deviceId}/volume_config_requests/${request.requestId}`
}, options); }, options);
const metadata = result.uploadMetadata; const metadata = result.uploadMetadata;
if (!metadata || !metadata.url) { if (!metadata || !metadata.url) {
throw new Error("server 未返回有效的配置上传地址"); throw new Error("server 未返回有效的配置上传地址");
} }
const orderedConfig = { const orderedConfig = {
q_in_val: parameters.q_in_val, q_in_val: parameters.q_in_val,
dt: parameters.dt, dt: parameters.dt,
p_max: parameters.p_max, p_max: parameters.p_max,
fit_low: parameters.fit_low, fit_low: parameters.fit_low,
fit_high: parameters.fit_high, fit_high: parameters.fit_high,
T_delta: parameters.T_delta, T_delta: parameters.T_delta,
xa_full: parameters.xa_full, xa_full: parameters.xa_full,
num_runs: parameters.num_runs num_runs: parameters.num_runs
}; };
const form = new FormData(); const form = new FormData();
form.append( form.append(
"file", "file",
new Blob([`${JSON.stringify(orderedConfig, null, 2)}\n`], { type: "application/json" }), new Blob([`${JSON.stringify(orderedConfig, null, 2)}\n`], { type: "application/json" }),
"volume_measurement.json" "volume_measurement.json"
); );
const uploadResponse = await fetch(metadata.url, { method: "POST", body: form }); const uploadResponse = await fetch(metadata.url, { method: "POST", body: form });
if (uploadResponse.status !== 200 && uploadResponse.status !== 204) { if (uploadResponse.status !== 200 && uploadResponse.status !== 204) {
throw new Error(`配置文件直传失败: HTTP ${uploadResponse.status}`); throw new Error(`配置文件直传失败: HTTP ${uploadResponse.status}`);
} }
try { try {
return await callServer({ return await callServer({
type: "submitVolumeConfigFile", type: "submitVolumeConfigFile",
deviceId, deviceId,
requestId: request.requestId, requestId: request.requestId,
fileID: result.fileID, fileID: result.fileID,
fileName: "volume_measurement.json" fileName: "volume_measurement.json"
}, options); }, options);
} catch (error) { } catch (error) {
await callServer({ type: "deleteFile", fileID: result.fileID }, options).catch(() => {}); await callServer({ type: "deleteFile", fileID: result.fileID }, options).catch(() => {});
throw error; throw error;
} }
} }
function serializeIdentificationConfig(parameters) { function serializeIdentificationConfig(parameters) {
const rows = IDENTIFICATION_FIELDS.map((field) => { const rows = IDENTIFICATION_FIELDS.map((field) => {
const value = field === "levels" ? parameters[field].join(",") : parameters[field]; const value = field === "levels" ? parameters[field].join(",") : parameters[field];
return `${field},${field === "levels" ? `"${value}"` : value}`; return `${field},${field === "levels" ? `"${value}"` : value}`;
}); });
return `parameter,value\n${rows.join("\n")}\n`; return `parameter,value\n${rows.join("\n")}\n`;
} }
async function uploadIdentificationConfig(parameters, options = {}) { async function uploadIdentificationConfig(parameters, options = {}) {
const result = await callServer({ const result = await callServer({
type: "publishIdentificationConfig", type: "publishIdentificationConfig",
deviceId: getDeviceId(options), deviceId: getDeviceId(options),
parameters parameters
}, options); }, options);
const metadata = result.uploadMetadata; const metadata = result.uploadMetadata;
if (!metadata || !metadata.url) { if (!metadata || !metadata.url) {
throw new Error("server 未返回有效的配置上传地址"); throw new Error("server 未返回有效的配置上传地址");
} }
const form = new FormData(); const form = new FormData();
form.append( form.append(
"file", "file",
new Blob([serializeIdentificationConfig(parameters)], { type: "text/csv" }), new Blob([serializeIdentificationConfig(parameters)], { type: "text/csv" }),
"identification_config.csv" "identification_config.csv"
); );
const uploadResponse = await fetch(metadata.url, { method: "POST", body: form }); const uploadResponse = await fetch(metadata.url, { method: "POST", body: form });
if (uploadResponse.status !== 200 && uploadResponse.status !== 204) { if (uploadResponse.status !== 200 && uploadResponse.status !== 204) {
throw new Error(`配置文件直传失败: HTTP ${uploadResponse.status}`); throw new Error(`配置文件直传失败: HTTP ${uploadResponse.status}`);
} }
return result; return result;
} }
async function publishConfig(configType, parameters, options = {}) { async function publishConfig(configType, parameters, options = {}) {
if (configType === "volume") { if (configType === "volume") {
return uploadVolumeConfig(parameters, options); return uploadVolumeConfig(parameters, options);
} }
if (configType !== "identification") { if (configType !== "identification") {
throw new Error(`不支持的配置类型: ${configType}`); throw new Error(`不支持的配置类型: ${configType}`);
} }
return uploadIdentificationConfig(parameters, options); return uploadIdentificationConfig(parameters, options);
} }
async function getConfig(configType, options = {}) { async function getConfig(configType, options = {}) {
if (configType === "identification") { if (configType === "identification") {
const result = await callServer({ const result = await callServer({
type: "getIdentificationConfig", type: "getIdentificationConfig",
deviceId: getDeviceId(options) deviceId: getDeviceId(options)
}, options); }, options);
const response = await fetch(result.url); const response = await fetch(result.url);
if (!response.ok) throw new Error(`配置文件下载失败: HTTP ${response.status}`); if (!response.ok) throw new Error(`配置文件下载失败: HTTP ${response.status}`);
const records = parse(await response.text(), { columns: true, skip_empty_lines: true }); const records = parse(await response.text(), { columns: true, skip_empty_lines: true });
const values = Object.fromEntries(records.map((record) => [record.parameter, record.value])); const values = Object.fromEntries(records.map((record) => [record.parameter, record.value]));
return { return {
q_in_val: Number(values.q_in_val), q_in_val: Number(values.q_in_val),
dt: Number(values.dt), dt: Number(values.dt),
n_order: Number(values.n_order), n_order: Number(values.n_order),
t_c: Number(values.t_c), t_c: Number(values.t_c),
levels: String(values.levels).split(",").map(Number), levels: String(values.levels).split(",").map(Number),
dead_area: Number(values.dead_area), dead_area: Number(values.dead_area),
xa_full: Number(values.xa_full), xa_full: Number(values.xa_full),
V_val: Number(values.V_val), V_val: Number(values.V_val),
repeat: Number(values.repeat) repeat: Number(values.repeat)
}; };
} }
return callServer({ type: "getFunctionConfig", configType }, options); const result = await callServer({
} type: "getVolumeConfigFile",
deviceId: getDeviceId(options)
async function main() { }, options);
const [command, filePath] = process.argv.slice(2); if (result.found === false || !result.url) {
const commands = { throw new Error("当前产线尚无已成功提交的容积配置");
"publish-volume": { action: "upload-volume", configType: "volume" }, }
"publish-identification": { action: "publish", configType: "identification" }, const response = await fetch(result.url);
"get-volume": { action: "get", configType: "volume" }, if (!response.ok) throw new Error(`配置文件下载失败: HTTP ${response.status}`);
"get-identification": { action: "get", configType: "identification" } return JSON.parse(await response.text());
}; }
const selected = commands[command];
if (!selected) { async function main() {
throw new Error( const [command, filePath] = process.argv.slice(2);
"用法: node b-admin.js <publish-volume|publish-identification|get-volume|get-identification> [config.json]" const commands = {
); "publish-volume": { action: "upload-volume", configType: "volume" },
} "publish-identification": { action: "publish", configType: "identification" },
"get-volume": { action: "get", configType: "volume" },
if (selected.action === "upload-volume") { "get-identification": { action: "get", configType: "identification" }
const result = await publishConfig(selected.configType, await readParameters(filePath)); };
console.log(`配置已上传: ${result.fileID}`); const selected = commands[command];
return; if (!selected) {
} throw new Error(
"用法: node b-admin.js <publish-volume|publish-identification|get-volume|get-identification> [config.json]"
const result = selected.action === "publish" );
? await publishConfig(selected.configType, await readParameters(filePath)) }
: await getConfig(selected.configType);
if (selected.action === "publish") { if (selected.action === "upload-volume") {
console.log(`配置已上传: ${result.fileID}`); const result = await publishConfig(selected.configType, await readParameters(filePath));
return; console.log(`配置已上传: ${result.fileID}`);
} return;
console.dir(result, { depth: null, colors: true }); }
}
const result = selected.action === "publish"
if (require.main === module) { ? await publishConfig(selected.configType, await readParameters(filePath))
main().catch((error) => { : await getConfig(selected.configType);
console.error(error.message); if (selected.action === "publish") {
process.exitCode = 1; console.log(`配置已上传: ${result.fileID}`);
}); return;
} }
console.dir(result, { depth: null, colors: true });
module.exports = { }
getConfig,
publishConfig, if (require.main === module) {
readParameters, main().catch((error) => {
serializeIdentificationConfig, console.error(error.message);
uploadIdentificationConfig, process.exitCode = 1;
uploadVolumeConfig });
}
module.exports = {
getConfig,
publishConfig,
readParameters,
serializeIdentificationConfig,
uploadIdentificationConfig,
uploadVolumeConfig
}; };
+76 -1
View File
@@ -10,6 +10,9 @@ const { plotJson } = require("./plot-json");
const VOLUME_FIELDS = [ const VOLUME_FIELDS = [
"q_in_val", "dt", "p_max", "fit_low", "fit_high", "T_delta", "xa_full", "num_runs" "q_in_val", "dt", "p_max", "fit_low", "fit_high", "T_delta", "xa_full", "num_runs"
]; ];
const IDENTIFICATION_FIELDS = [
"q_in_val", "dt", "n_order", "t_c", "levels", "dead_area", "xa_full", "V_val", "repeat"
];
const DEFAULT_API_URL = "https://ReinLoop.dominatedconvergence.com"; const DEFAULT_API_URL = "https://ReinLoop.dominatedconvergence.com";
const API_URL = process.env.REINLOOP_API_URL || DEFAULT_API_URL; const API_URL = process.env.REINLOOP_API_URL || DEFAULT_API_URL;
const INBOX_POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS || 1000); const INBOX_POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS || 1000);
@@ -35,13 +38,42 @@ function startPanelInboxPoller(window) {
} }
let polling = false; let polling = false;
let notificationDeviceId = null;
const deliveredNotificationIds = new Set();
let notificationFailureReported = false;
async function pollNotifications(requestContext) {
if (notificationDeviceId !== requestContext.deviceId) {
notificationDeviceId = requestContext.deviceId;
deliveredNotificationIds.clear();
}
const pending = await callServer(
{ type: "getPendingPanelNotification", deviceId: requestContext.deviceId },
requestContext
);
notificationFailureReported = false;
const notification = pending.notification;
if (!pending.pending || !notification?.notificationId) return;
if (deliveredNotificationIds.has(notification.notificationId)) return;
deliveredNotificationIds.add(notification.notificationId);
window.webContents.send("panel:notification", notification);
}
const poll = async () => { const poll = async () => {
if (polling || window.isDestroyed()) return; if (polling || window.isDestroyed()) return;
if (!connectionState.deviceId || !connectionState.adminToken) return; if (!connectionState.deviceId || !connectionState.adminToken) return;
if (pendingReview) return;
const requestContext = { ...connectionState }; const requestContext = { ...connectionState };
polling = true; polling = true;
try { try {
try {
await pollNotifications(requestContext);
} catch (error) {
if (!notificationFailureReported) {
console.warn(`[${new Date().toISOString()}] Panel 通知轮询不可用: ${error.message}`);
notificationFailureReported = true;
}
}
if (pendingReview) return;
const pending = await callServer( const pending = await callServer(
{ type: "getPendingPanelFile", deviceId: requestContext.deviceId }, { type: "getPendingPanelFile", deviceId: requestContext.deviceId },
requestContext requestContext
@@ -128,7 +160,35 @@ function validateParameters(configType, parameters) {
if (!Number.isInteger(parameters.num_runs)) { if (!Number.isInteger(parameters.num_runs)) {
throw new Error("num_runs 必须是整数"); throw new Error("num_runs 必须是整数");
} }
return;
} }
if (configType === "identification") {
const fields = Object.keys(parameters);
const missing = IDENTIFICATION_FIELDS.filter((field) => !(field in parameters));
const extra = fields.filter((field) => !IDENTIFICATION_FIELDS.includes(field));
if (missing.length || extra.length) {
throw new Error(`系统辨识配置字段不匹配。缺少: ${missing.join(", ") || "无"};多余: ${extra.join(", ") || "无"}`);
}
for (const field of IDENTIFICATION_FIELDS) {
if (field === "levels") continue;
if (typeof parameters[field] !== "number" || !Number.isFinite(parameters[field])) {
throw new Error(`${field} 必须是有效数字`);
}
}
if (!Array.isArray(parameters.levels) || parameters.levels.some((value) => typeof value !== "number" || !Number.isFinite(value))) {
throw new Error("levels 必须是有效数字数组");
}
if (parameters.levels.length < 2 || (parameters.levels.length & (parameters.levels.length - 1)) !== 0) {
throw new Error("levels 元素个数必须是不小于 2 的 2 的整数次幂");
}
if (!Number.isInteger(parameters.n_order) || !Number.isInteger(parameters.repeat)) {
throw new Error("n_order 和 repeat 必须是整数");
}
return;
}
throw new Error(`不支持的配置类型: ${configType}`);
} }
function toDataUrl(filePath) { function toDataUrl(filePath) {
@@ -155,6 +215,21 @@ function registerHandlers() {
return { success: true }; return { success: true };
}); });
ipcMain.handle("panel:ack-notification", (_event, request) =>
callServer({
type: "ackPanelNotification",
deviceId: request.deviceId,
notificationId: request.notificationId
}, request.credentials));
ipcMain.handle("panel:open-notification-file", async (_event, request) => {
if (!request.fileID) throw new Error("该提醒未关联结果文件");
const download = await callServer({ type: "downloadModel", fileID: request.fileID }, request.credentials);
const sourcePath = await downloadFromUrl(download.url, download.fileName || "volume_result.json", request.credentials);
const error = await shell.openPath(sourcePath);
if (error) throw new Error(`无法打开结果文件: ${error}`);
return { filePath: sourcePath };
});
ipcMain.handle("connection:test", async (_event, request) => { ipcMain.handle("connection:test", async (_event, request) => {
const result = await callServer({ type: "listOrganizations" }, request); const result = await callServer({ type: "listOrganizations" }, request);
connectionState.apiUrl = String(request.apiUrl || API_URL).trim(); connectionState.apiUrl = String(request.apiUrl || API_URL).trim();
+4 -1
View File
@@ -30,6 +30,9 @@ contextBridge.exposeInMainWorld("reinloop", {
previewControlFile: (request) => ipcRenderer.invoke("control-data:preview", request), previewControlFile: (request) => ipcRenderer.invoke("control-data:preview", request),
downloadControlFile: (request) => ipcRenderer.invoke("control-data:download", request), downloadControlFile: (request) => ipcRenderer.invoke("control-data:download", request),
deleteControlFile: (request) => ipcRenderer.invoke("control-data:delete", request), deleteControlFile: (request) => ipcRenderer.invoke("control-data:delete", request),
acknowledgeNotification: (request) => ipcRenderer.invoke("panel:ack-notification", request),
openNotificationFile: (request) => ipcRenderer.invoke("panel:open-notification-file", request),
onCsvUpdated: (callback) => ipcRenderer.on("csv:updated", (_event, result) => callback(result)), onCsvUpdated: (callback) => ipcRenderer.on("csv:updated", (_event, result) => callback(result)),
onCsvWatchError: (callback) => ipcRenderer.on("csv:watch-error", (_event, message) => callback(message)) onCsvWatchError: (callback) => ipcRenderer.on("csv:watch-error", (_event, message) => callback(message)),
onPanelNotification: (callback) => ipcRenderer.on("panel:notification", (_event, notification) => callback(notification))
}); });
+4 -3
View File
@@ -43,7 +43,7 @@
<button class="tab active" data-target="plot-panel">绘图预览</button> <button class="tab active" data-target="plot-panel">绘图预览</button>
<button class="tab" data-target="identification-data-panel">辨识数据</button> <button class="tab" data-target="identification-data-panel">辨识数据</button>
<button class="tab" data-target="control-data-panel">控制数据</button> <button class="tab" data-target="control-data-panel">控制数据</button>
<button class="tab" data-target="config-panel">配置发布</button> <button class="tab" data-target="config-panel">配置发布 <span id="config-notification-badge" class="tab-badge" hidden>0</span></button>
<button class="tab" data-target="model-panel">模型管理</button> <button class="tab" data-target="model-panel">模型管理</button>
<button class="tab" data-target="license-panel">许可证</button> <button class="tab" data-target="license-panel">许可证</button>
<button class="tab" data-target="organization-panel">组织管理</button> <button class="tab" data-target="organization-panel">组织管理</button>
@@ -139,14 +139,15 @@
<button class="segment" data-type="identification">系统辨识</button> <button class="segment" data-type="identification">系统辨识</button>
</div> </div>
</div> </div>
<div id="config-notifications" class="notification-stack" aria-live="polite"></div>
<div class="editor-layout"> <div class="editor-layout">
<div class="editor-column"> <div class="editor-column">
<div class="editor-toolbar"> <div class="editor-toolbar">
<span id="config-label">容积测量配置</span> <span id="config-label">容积测量配置</span>
<button id="import-config" class="text-button">导入 JSON</button> <button id="import-config" class="text-button">导入 JSON</button>
</div> </div>
<textarea id="config-editor" spellcheck="false" aria-label="JSON 配置编辑器"></textarea> <form id="config-form" class="config-form" aria-label="配置字段"></form>
<p id="config-path" class="file-path">可直接编辑,或从本地 JSON 导入</p> <p id="config-path" class="file-path">字段名称固定;可填写右侧数据或从本地 JSON 导入</p>
</div> </div>
<aside class="publish-aside"> <aside class="publish-aside">
<h3>发布检查</h3> <h3>发布检查</h3>
+190 -14
View File
@@ -21,6 +21,11 @@ const identificationExample = {
repeat: 2 repeat: 2
}; };
const configFields = {
volume: Object.keys(volumeExample),
identification: Object.keys(identificationExample)
};
const state = { const state = {
configType: "volume", configType: "volume",
imagePaths: { csv: null, json: null }, imagePaths: { csv: null, json: null },
@@ -33,7 +38,9 @@ const state = {
defaultDeviceId: "", defaultDeviceId: "",
review: null, review: null,
retryDeviceId: null, retryDeviceId: null,
notificationDeviceId: null,
lightbox: { mediaType: null, scale: 1, fit: true, previousFocus: null }, lightbox: { mediaType: null, scale: 1, fit: true, previousFocus: null },
notifications: [],
connected: false connected: false
}; };
@@ -66,12 +73,14 @@ const elements = {
openImage: document.querySelector('[data-open-plot="json"]') openImage: document.querySelector('[data-open-plot="json"]')
} }
}, },
configEditor: document.querySelector("#config-editor"), configForm: document.querySelector("#config-form"),
configLabel: document.querySelector("#config-label"), configLabel: document.querySelector("#config-label"),
configPath: document.querySelector("#config-path"), configPath: document.querySelector("#config-path"),
publishTarget: document.querySelector("#publish-target"), publishTarget: document.querySelector("#publish-target"),
publishButton: document.querySelector("#publish-config"), publishButton: document.querySelector("#publish-config"),
publishResult: document.querySelector("#publish-result"), publishResult: document.querySelector("#publish-result"),
configNotifications: document.querySelector("#config-notifications"),
configNotificationBadge: document.querySelector("#config-notification-badge"),
lineCompany: document.querySelector("#line-company"), lineCompany: document.querySelector("#line-company"),
licenseTarget: document.querySelector("#license-target"), licenseTarget: document.querySelector("#license-target"),
licenseList: document.querySelector("#license-list"), licenseList: document.querySelector("#license-list"),
@@ -225,6 +234,11 @@ function renderLineOptions() {
function updateSelectedTarget() { function updateSelectedTarget() {
const company = selectedCompany(); const company = selectedCompany();
const line = selectedLine(); const line = selectedLine();
if (state.notificationDeviceId !== elements.deviceId.value) {
state.notificationDeviceId = elements.deviceId.value;
state.notifications = [];
renderNotifications();
}
elements.licenseTarget.value = company && line ? `${company.name} / ${line.name}` : ""; elements.licenseTarget.value = company && line ? `${company.name} / ${line.name}` : "";
void syncConnection(); void syncConnection();
} }
@@ -413,16 +427,91 @@ function activateTab(target) {
} }
function activateConfigType(configType) { function activateConfigType(configType) {
try { syncCurrentConfig();
state.configs[state.configType] = JSON.parse(elements.configEditor.value);
} catch (_error) {
// Keep the last valid configuration when changing views.
}
state.configType = configType; state.configType = configType;
document.querySelectorAll(".segment").forEach((item) => item.classList.toggle("active", item.dataset.type === configType)); document.querySelectorAll(".segment").forEach((item) => item.classList.toggle("active", item.dataset.type === configType));
renderConfig(); renderConfig();
} }
function isPowerOfTwo(value) {
return Number.isInteger(value) && value >= 2 && (value & (value - 1)) === 0;
}
function clearConfigErrors() {
elements.configForm.querySelectorAll("[aria-invalid]").forEach((input) => input.removeAttribute("aria-invalid"));
elements.configForm.querySelectorAll(".config-field-error").forEach((item) => item.remove());
}
function showConfigFieldError(field, message) {
const input = elements.configForm.querySelector(`[data-config-field="${field}"]`);
if (!input) return;
input.setAttribute("aria-invalid", "true");
const error = document.createElement("p");
error.className = "config-field-error";
error.textContent = message;
input.closest(".config-field").append(error);
}
function readConfigForm({ showErrors = false } = {}) {
const type = state.configType;
const parameters = {};
let invalidField = null;
let invalidMessage = null;
clearConfigErrors();
for (const field of configFields[type]) {
const input = elements.configForm.querySelector(`[data-config-field="${field}"]`);
const text = input?.value.trim() || "";
if (field === "levels") {
const values = text.split(",").map((value) => value.trim()).filter(Boolean);
parameters[field] = values.map(Number);
if (!values.length || parameters[field].some((value) => !Number.isFinite(value))) {
invalidField = field;
invalidMessage = "请输入以逗号分隔的有效数字。";
} else if (!isPowerOfTwo(parameters[field].length)) {
invalidField = field;
invalidMessage = "元素个数必须是不小于 2 的 2 的整数次幂。";
}
continue;
}
const value = Number(text);
parameters[field] = value;
if (!text || !Number.isFinite(value)) {
invalidField = field;
invalidMessage = "请输入有效数字。";
} else if (["num_runs", "n_order", "repeat"].includes(field) && !Number.isInteger(value)) {
invalidField = field;
invalidMessage = "请输入整数。";
}
}
if (invalidField) {
if (showErrors) showConfigFieldError(invalidField, invalidMessage);
throw new Error(`${invalidField}${invalidMessage}`);
}
return parameters;
}
function syncCurrentConfig() {
try {
state.configs[state.configType] = readConfigForm();
} catch (_error) {
// Preserve the last valid values until the user corrects the visible form.
}
}
function normalizeImportedConfig(parameters) {
if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
throw new Error("导入配置必须是 JSON 对象");
}
const fields = configFields[state.configType];
const unknown = Object.keys(parameters).filter((field) => !fields.includes(field));
if (unknown.length) throw new Error(`导入配置包含未知字段:${unknown.join(", ")}`);
const normalized = { ...state.configs[state.configType] };
for (const field of fields) {
if (parameters[field] !== undefined) normalized[field] = parameters[field];
}
return normalized;
}
function switchToIdentificationConfigForRetry() { function switchToIdentificationConfigForRetry() {
if (!state.review) return; if (!state.review) return;
state.retryDeviceId = state.review.deviceId; state.retryDeviceId = state.review.deviceId;
@@ -464,11 +553,16 @@ async function submitRetryReview() {
function renderConfig() { function renderConfig() {
const isVolume = state.configType === "volume"; const isVolume = state.configType === "volume";
elements.configEditor.value = JSON.stringify(state.configs[state.configType], null, 2); const config = state.configs[state.configType];
elements.configForm.innerHTML = configFields[state.configType].map((field) => {
const value = field === "levels" ? config[field].join(", ") : config[field];
const integer = ["num_runs", "n_order", "repeat"].includes(field);
return `<div class="config-field"><label for="config-${field}">${field}</label><input id="config-${field}" data-config-field="${field}" type="${field === "levels" ? "text" : "number"}"${field === "levels" ? "" : ` step="${integer ? "1" : "any"}"` } value="${escapeHtml(value)}" required></div>`;
}).join("");
elements.configLabel.textContent = isVolume ? "容积测量配置" : "系统辨识配置"; elements.configLabel.textContent = isVolume ? "容积测量配置" : "系统辨识配置";
elements.publishTarget.textContent = isVolume ? "Server 配置文件" : "设备辨识配置"; elements.publishTarget.textContent = isVolume ? "Server 配置文件" : "设备辨识配置";
elements.publishButton.textContent = isVolume ? "上传容积配置" : "发布辨识配置"; elements.publishButton.textContent = isVolume ? "上传容积配置" : "发布辨识配置";
elements.configPath.textContent = "可直接编辑,或从本地 JSON 导入"; elements.configPath.textContent = "字段名称固定;可填写右侧数据或从本地 JSON 导入";
elements.publishResult.textContent = "等待操作"; elements.publishResult.textContent = "等待操作";
delete elements.publishResult.dataset.tone; delete elements.publishResult.dataset.tone;
} }
@@ -688,8 +782,13 @@ elements.identificationFileList.addEventListener("click", async (event) => {
document.querySelector("#import-config").addEventListener("click", async () => { document.querySelector("#import-config").addEventListener("click", async () => {
const result = await runBusy("正在导入配置", () => window.reinloop.chooseConfig()); const result = await runBusy("正在导入配置", () => window.reinloop.chooseConfig());
if (!result) return; if (!result) return;
state.configs[state.configType] = result.parameters; try {
elements.configEditor.value = JSON.stringify(result.parameters, null, 2); state.configs[state.configType] = normalizeImportedConfig(result.parameters);
renderConfig();
} catch (error) {
showError(error);
return;
}
elements.configPath.textContent = result.filePath; elements.configPath.textContent = result.filePath;
setStatus("配置已导入", "success"); setStatus("配置已导入", "success");
}); });
@@ -700,8 +799,13 @@ document.querySelector("#load-server").addEventListener("click", async () => {
credentials: credentials() credentials: credentials()
})); }));
if (!parameters) return; if (!parameters) return;
state.configs[state.configType] = parameters; try {
elements.configEditor.value = JSON.stringify(parameters, null, 2); state.configs[state.configType] = normalizeImportedConfig(parameters);
renderConfig();
} catch (error) {
showError(new Error(`Server 配置无效:${error.message}`));
return;
}
elements.publishResult.textContent = "已读取当前 Server 配置"; elements.publishResult.textContent = "已读取当前 Server 配置";
elements.publishResult.dataset.tone = "success"; elements.publishResult.dataset.tone = "success";
setStatus("读取完成", "success"); setStatus("读取完成", "success");
@@ -710,9 +814,9 @@ document.querySelector("#load-server").addEventListener("click", async () => {
elements.publishButton.addEventListener("click", async () => { elements.publishButton.addEventListener("click", async () => {
let parameters; let parameters;
try { try {
parameters = JSON.parse(elements.configEditor.value); parameters = readConfigForm({ showErrors: true });
} catch (error) { } catch (error) {
showError(new Error(`JSON 格式错误: ${error.message}`)); showError(error);
return; return;
} }
@@ -732,6 +836,10 @@ elements.publishButton.addEventListener("click", async () => {
? `${result.message}: ${result.storagePath}` ? `${result.message}: ${result.storagePath}`
: result.message; : result.message;
elements.publishResult.dataset.tone = "success"; elements.publishResult.dataset.tone = "success";
if (state.configType === "volume") {
const notification = state.notifications.find((item) => item.type === "volume_request_started");
if (notification) void acknowledgeNotification(notification);
}
if (state.configType === "identification" && state.retryDeviceId) { if (state.configType === "identification" && state.retryDeviceId) {
await submitRetryReview(); await submitRetryReview();
} else { } else {
@@ -830,4 +938,72 @@ elements.controlFileList.addEventListener("click", async (event) => {
button.disabled = false; button.disabled = false;
} }
} }
});
function renderNotifications() {
elements.configNotificationBadge.hidden = state.notifications.length === 0;
elements.configNotificationBadge.textContent = String(state.notifications.length);
elements.configNotifications.innerHTML = state.notifications.map((notification) => {
const action = notification.type === "volume_request_started"
? "处理配置"
: notification.type === "volume_result_ready"
? "查看结果"
: "查看绘图";
const secondaryAction = notification.type === "identification_result_ready" ? "查看辨识数据" : "";
return `<article class="panel-notification" data-notification-id="${escapeHtml(notification.notificationId)}" data-type="${escapeHtml(notification.type)}"><div class="notification-copy"><strong>${escapeHtml(notification.title)}</strong><span>${escapeHtml(notification.message)}</span></div><div class="notification-actions"><button class="button secondary" data-notification-action="primary" data-notification-id="${escapeHtml(notification.notificationId)}">${action}</button>${secondaryAction ? `<button class="button secondary" data-notification-action="secondary" data-notification-id="${escapeHtml(notification.notificationId)}">${secondaryAction}</button>` : ""}<button class="button icon" title="关闭提醒" aria-label="关闭提醒" data-notification-action="close" data-notification-id="${escapeHtml(notification.notificationId)}">x</button></div></article>`;
}).join("");
}
async function acknowledgeNotification(notification) {
const result = await runBusy("正在确认提醒", () => window.reinloop.acknowledgeNotification({
deviceId: notification.deviceId,
notificationId: notification.notificationId,
credentials: credentials()
}));
if (!result) return false;
state.notifications = state.notifications.filter((item) => item.notificationId !== notification.notificationId);
renderNotifications();
return true;
}
async function handleNotificationAction(notification, action) {
if (action === "close") {
await acknowledgeNotification(notification);
return;
}
if (notification.type === "volume_request_started") {
activateTab("config-panel");
activateConfigType("volume");
elements.configForm.querySelector("input")?.focus();
return;
}
if (notification.type === "volume_result_ready") {
const result = await runBusy("正在打开容积测试结果", () => window.reinloop.openNotificationFile({
fileID: notification.fileID,
credentials: credentials()
}));
if (result) setStatus(`已打开结果文件:${result.filePath}`, "success");
return;
}
if (action === "primary") {
activateTab("plot-panel");
return;
}
activateTab("identification-data-panel");
await refreshIdentificationFiles();
}
elements.configNotifications.addEventListener("click", (event) => {
const button = event.target.closest("button[data-notification-id]");
if (!button) return;
const notification = state.notifications.find((item) => item.notificationId === button.dataset.notificationId);
if (notification) void handleNotificationAction(notification, button.dataset.notificationAction);
});
window.reinloop.onPanelNotification((notification) => {
if (!notification?.notificationId || notification.deviceId !== elements.deviceId.value) return;
state.notificationDeviceId = notification.deviceId;
if (state.notifications.some((item) => item.notificationId === notification.notificationId)) return;
state.notifications.push(notification);
renderNotifications();
}); });
+256 -257
View File
@@ -1,258 +1,257 @@
:root { :root {
color-scheme: light; color-scheme: light;
--ink: #15251f; --ink: #15251f;
--muted: #617069; --muted: #617069;
--line: #cfd7d2; --line: #cfd7d2;
--paper: #f2f4f1; --paper: #f2f4f1;
--surface: #ffffff; --surface: #ffffff;
--green: #146b4a; --green: #146b4a;
--green-dark: #0d4b34; --green-dark: #0d4b34;
--amber: #e7a928; --amber: #e7a928;
--red: #ad342d; --red: #ad342d;
} }
* { box-sizing: border-box; } * { box-sizing: border-box; }
[hidden] { display: none !important; } [hidden] { display: none !important; }
body { body {
margin: 0; margin: 0;
min-width: 900px; min-width: 900px;
color: var(--ink); color: var(--ink);
background: background:
linear-gradient(rgba(20, 107, 74, 0.035) 1px, transparent 1px), linear-gradient(rgba(20, 107, 74, 0.035) 1px, transparent 1px),
linear-gradient(90deg, rgba(20, 107, 74, 0.035) 1px, transparent 1px), linear-gradient(90deg, rgba(20, 107, 74, 0.035) 1px, transparent 1px),
var(--paper); var(--paper);
background-size: 28px 28px; background-size: 28px 28px;
font-family: "Microsoft YaHei UI", "Segoe UI", sans-serif; font-family: "Microsoft YaHei UI", "Segoe UI", sans-serif;
} }
button, input, textarea, select { font: inherit; } button, input, textarea, select { font: inherit; }
button { cursor: pointer; } button { cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: 0.45; } button:disabled { cursor: not-allowed; opacity: 0.45; }
.topbar { .topbar {
height: 104px; height: 104px;
padding: 20px 36px; padding: 20px 36px;
color: white; color: white;
background: var(--ink); background: var(--ink);
border-bottom: 5px solid var(--amber); border-bottom: 5px solid var(--amber);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
} }
h1, h2, h3, p { margin: 0; } h1, h2, h3, p { margin: 0; }
h1 { font-family: Georgia, "Microsoft YaHei UI", serif; font-size: 28px; font-weight: 600; letter-spacing: 0; } h1 { font-family: Georgia, "Microsoft YaHei UI", serif; font-size: 28px; font-weight: 600; letter-spacing: 0; }
h2 { font-family: Georgia, "Microsoft YaHei UI", serif; font-size: 25px; font-weight: 600; letter-spacing: 0; } h2 { font-family: Georgia, "Microsoft YaHei UI", serif; font-size: 25px; font-weight: 600; letter-spacing: 0; }
h3 { font-size: 15px; } h3 { font-size: 15px; }
.eyebrow, .section-kicker { font-size: 11px; letter-spacing: 0; font-weight: 700; } .eyebrow, .section-kicker { font-size: 11px; letter-spacing: 0; font-weight: 700; }
.eyebrow { color: #a9c1b6; margin-bottom: 5px; } .eyebrow { color: #a9c1b6; margin-bottom: 5px; }
.section-kicker { color: var(--green); margin-bottom: 5px; } .section-kicker { color: var(--green); margin-bottom: 5px; }
.status { .status {
min-width: 110px; min-width: 110px;
max-width: 420px; max-width: 420px;
padding: 8px 14px; padding: 8px 14px;
border: 1px solid #587067; border: 1px solid #587067;
border-radius: 4px; border-radius: 4px;
color: #d9e4df; color: #d9e4df;
text-align: center; text-align: center;
font-size: 13px; font-size: 13px;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} }
.status[data-tone="busy"] { border-color: var(--amber); color: #ffd985; } .status[data-tone="busy"] { border-color: var(--amber); color: #ffd985; }
.status[data-tone="success"] { border-color: #62b78f; color: #9fe1bf; } .status[data-tone="success"] { border-color: #62b78f; color: #9fe1bf; }
.status[data-tone="error"] { border-color: #df766e; color: #ffb5ae; } .status[data-tone="error"] { border-color: #df766e; color: #ffb5ae; }
main { max-width: 1500px; margin: 0 auto; padding: 22px 36px 36px; } main { max-width: 1500px; margin: 0 auto; padding: 22px 36px 36px; }
.connection-screen { .connection-screen {
min-height: calc(100vh - 104px); min-height: calc(100vh - 104px);
display: grid; display: grid;
place-items: center; place-items: center;
padding: 36px; padding: 36px;
} }
.connection-form { .connection-form {
width: min(480px, 100%); width: min(480px, 100%);
padding: 30px; padding: 30px;
display: grid; display: grid;
gap: 18px; gap: 18px;
background: var(--surface); background: var(--surface);
border: 1px solid var(--line); border: 1px solid var(--line);
border-top: 4px solid var(--green); border-top: 4px solid var(--green);
box-shadow: 0 18px 45px rgba(21, 37, 31, 0.12); box-shadow: 0 18px 45px rgba(21, 37, 31, 0.12);
} }
.connection-form h2 { margin-bottom: 6px; } .connection-form h2 { margin-bottom: 6px; }
.connection-form label { display: grid; gap: 7px; } .connection-form label { display: grid; gap: 7px; }
.connection-form label span { color: var(--muted); font-size: 12px; font-weight: 700; } .connection-form label span { color: var(--muted); font-size: 12px; font-weight: 700; }
.connection-form .button { width: 100%; margin-top: 4px; } .connection-form .button { width: 100%; margin-top: 4px; }
.connection-message { min-height: 20px; color: var(--muted); font-size: 12px; text-align: center; } .connection-message { min-height: 20px; color: var(--muted); font-size: 12px; text-align: center; }
.connection-message[data-tone="busy"] { color: #8a6414; } .connection-message[data-tone="busy"] { color: #8a6414; }
.connection-message[data-tone="error"] { color: var(--red); } .connection-message[data-tone="error"] { color: var(--red); }
.connection-band { .connection-band {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(260px, 1fr)); grid-template-columns: repeat(2, minmax(260px, 1fr));
gap: 18px; gap: 18px;
padding: 15px 18px; padding: 15px 18px;
background: #e4e9e5; background: #e4e9e5;
border: 1px solid var(--line); border: 1px solid var(--line);
border-left: 4px solid var(--green); border-left: 4px solid var(--green);
} }
.connection-band label { display: grid; grid-template-columns: 118px 1fr; align-items: center; gap: 10px; } .connection-band label { display: grid; grid-template-columns: 118px 1fr; align-items: center; gap: 10px; }
.connection-band span { font-size: 12px; font-weight: 700; color: var(--muted); } .connection-band span { font-size: 12px; font-weight: 700; color: var(--muted); }
input, select { input, select {
min-width: 0; min-width: 0;
height: 36px; height: 36px;
padding: 0 10px; padding: 0 10px;
border: 1px solid #b9c5be; border: 1px solid #b9c5be;
border-radius: 3px; border-radius: 3px;
background: white; background: white;
color: var(--ink); color: var(--ink);
outline: none; outline: none;
} }
input:focus, select:focus, textarea:focus { border-color: var(--green); box-shadow: 0 0 0 2px rgba(20, 107, 74, 0.12); } input:focus, select:focus, textarea:focus { border-color: var(--green); box-shadow: 0 0 0 2px rgba(20, 107, 74, 0.12); }
.tabs { display: flex; gap: 0; margin-top: 22px; border-bottom: 1px solid var(--line); } .tabs { display: flex; gap: 0; margin-top: 22px; border-bottom: 1px solid var(--line); }
.tab { .tab {
min-width: 132px; min-width: 132px;
padding: 12px 20px; padding: 12px 20px;
border: 0; border: 0;
border-bottom: 3px solid transparent; border-bottom: 3px solid transparent;
background: transparent; background: transparent;
color: var(--muted); color: var(--muted);
font-weight: 700; font-weight: 700;
} }
.tab.active { color: var(--green-dark); border-bottom-color: var(--green); } .tab.active { color: var(--green-dark); border-bottom-color: var(--green); }
.tab-badge { display: inline-grid; min-width: 18px; height: 18px; place-items: center; margin-left: 5px; padding: 0 5px; border-radius: 9px; color: white; background: var(--red); font-size: 11px; }
.panel { display: none; padding-top: 22px; }
.panel.active { display: block; animation: reveal 180ms ease-out; } .panel { display: none; padding-top: 22px; }
@keyframes reveal { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } } .panel.active { display: block; animation: reveal 180ms ease-out; }
.panel-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 16px; } @keyframes reveal { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
.actions { display: flex; gap: 8px; } .panel-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 16px; }
.button { .actions { display: flex; gap: 8px; }
height: 38px; .button {
padding: 0 16px; height: 38px;
border-radius: 3px; padding: 0 16px;
border: 1px solid transparent; border-radius: 3px;
font-weight: 700; border: 1px solid transparent;
} font-weight: 700;
.button.primary { color: white; background: var(--green); border-color: var(--green); } }
.button.primary:hover { background: var(--green-dark); } .button.primary { color: white; background: var(--green); border-color: var(--green); }
.button.secondary { color: var(--ink); background: white; border-color: #aebbb4; } .button.primary:hover { background: var(--green-dark); }
.button.secondary:hover { border-color: var(--green); color: var(--green); } .button.secondary { color: var(--ink); background: white; border-color: #aebbb4; }
.button.danger { color: var(--red); background: white; border-color: #d5a7a3; } .button.secondary:hover { border-color: var(--green); color: var(--green); }
.button.danger:hover { color: white; background: var(--red); border-color: var(--red); } .button.danger { color: var(--red); background: white; border-color: #d5a7a3; }
.button.icon { width: 38px; padding: 0; background: white; border-color: #aebbb4; font-size: 19px; } .button.danger:hover { color: white; background: var(--red); border-color: var(--red); }
.plot-actions { display: flex; gap: 6px; } .button.icon { width: 38px; padding: 0; background: white; border-color: #aebbb4; font-size: 19px; }
.button.full { width: 100%; margin-top: 10px; } .plot-actions { display: flex; gap: 6px; }
.review-actions { display: flex; align-items: center; gap: 8px; } .button.full { width: 100%; margin-top: 10px; }
.review-actions span { max-width: 320px; color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .review-actions { display: flex; align-items: center; gap: 8px; }
.review-actions span { max-width: 320px; color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.plot-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
.plot-item { min-width: 0; } .plot-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
.plot-title { .plot-item { min-width: 0; }
min-height: 54px; .plot-title {
padding: 9px 12px; min-height: 54px;
display: flex; padding: 9px 12px;
align-items: center; display: flex;
justify-content: space-between; align-items: center;
gap: 12px; justify-content: space-between;
background: var(--surface); gap: 12px;
border: 1px solid var(--line); background: var(--surface);
border-bottom: 0; border: 1px solid var(--line);
} border-bottom: 0;
.plot-title div { display: grid; gap: 3px; } }
.plot-title span { color: var(--green); font-size: 11px; font-weight: 700; } .plot-title div { display: grid; gap: 3px; }
.plot-title strong { font-size: 15px; } .plot-title span { color: var(--green); font-size: 11px; font-weight: 700; }
.plot-stage { .plot-title strong { font-size: 15px; }
height: calc(100vh - 405px); .plot-stage {
min-height: 300px; height: calc(100vh - 405px);
max-height: 620px; min-height: 300px;
display: grid; max-height: 620px;
place-items: center; display: grid;
overflow: auto; place-items: center;
background-color: #dce2de; overflow: auto;
background-image: linear-gradient(45deg, #d3dad5 25%, transparent 25%), linear-gradient(-45deg, #d3dad5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #d3dad5 75%), linear-gradient(-45deg, transparent 75%, #d3dad5 75%); background-color: #dce2de;
background-size: 20px 20px; background-image: linear-gradient(45deg, #d3dad5 25%, transparent 25%), linear-gradient(-45deg, #d3dad5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #d3dad5 75%), linear-gradient(-45deg, transparent 75%, #d3dad5 75%);
background-position: 0 0, 0 10px, 10px -10px, -10px 0; background-size: 20px 20px;
border: 1px solid #bdc8c1; background-position: 0 0, 0 10px, 10px -10px, -10px 0;
} border: 1px solid #bdc8c1;
.plot-stage img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; background: white; } }
.empty-state { display: grid; gap: 7px; text-align: center; color: var(--muted); } .plot-stage img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; background: white; }
.empty-state strong { color: var(--ink); font-size: 18px; } .empty-state { display: grid; gap: 7px; text-align: center; color: var(--muted); }
.empty-state span { font-size: 13px; } .empty-state strong { color: var(--ink); font-size: 18px; }
.plot-meta { min-height: 29px; display: flex; align-items: start; justify-content: space-between; gap: 24px; } .empty-state span { font-size: 13px; }
.file-path { min-height: 20px; margin-top: 9px; color: var(--muted); font: 12px Consolas, monospace; overflow-wrap: anywhere; } .plot-meta { min-height: 29px; display: flex; align-items: start; justify-content: space-between; gap: 24px; }
.upload-time { flex: 0 0 auto; margin-top: 9px; color: var(--green-dark); font-size: 12px; font-weight: 700; } .file-path { min-height: 20px; margin-top: 9px; color: var(--muted); font: 12px Consolas, monospace; overflow-wrap: anywhere; }
.upload-time { flex: 0 0 auto; margin-top: 9px; color: var(--green-dark); font-size: 12px; font-weight: 700; }
.segmented { display: flex; padding: 3px; background: #dfe5e1; border: 1px solid #c6d0ca; border-radius: 4px; }
.segment { height: 34px; padding: 0 16px; border: 0; border-radius: 3px; background: transparent; color: var(--muted); font-weight: 700; } .segmented { display: flex; padding: 3px; background: #dfe5e1; border: 1px solid #c6d0ca; border-radius: 4px; }
.segment.active { background: white; color: var(--green-dark); box-shadow: 0 1px 3px rgba(21, 37, 31, 0.14); } .segment { height: 34px; padding: 0 16px; border: 0; border-radius: 3px; background: transparent; color: var(--muted); font-weight: 700; }
.editor-layout { display: grid; grid-template-columns: minmax(0, 1fr) 270px; gap: 18px; } .segment.active { background: white; color: var(--green-dark); box-shadow: 0 1px 3px rgba(21, 37, 31, 0.14); }
.editor-column, .publish-aside { background: var(--surface); border: 1px solid var(--line); } .notification-stack { display: grid; gap: 8px; margin: 0 0 16px; }
.editor-toolbar { height: 46px; padding: 0 14px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); font-size: 13px; font-weight: 700; } .panel-notification { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 12px 14px; border: 1px solid #d6b362; border-left: 4px solid var(--amber); background: #fff8e6; }
.text-button { border: 0; background: transparent; color: var(--green); font-size: 13px; font-weight: 700; } .panel-notification[data-type="volume_result_ready"] { border-color: #8ebba5; border-left-color: var(--green); background: #edf8f1; }
textarea { .panel-notification[data-type="identification_result_ready"] { border-color: #9db6c8; border-left-color: #367294; background: #edf5fa; }
display: block; .notification-copy { display: grid; gap: 3px; min-width: 0; }
width: calc(100% - 28px); .notification-copy strong { font-size: 13px; }
height: calc(100vh - 385px); .notification-copy span { color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
min-height: 330px; .notification-actions { display: flex; gap: 8px; }
margin: 14px; .editor-layout { display: grid; grid-template-columns: minmax(0, 1fr) 270px; gap: 18px; }
padding: 16px; .editor-column, .publish-aside { background: var(--surface); border: 1px solid var(--line); }
resize: vertical; .editor-toolbar { height: 46px; padding: 0 14px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); font-size: 13px; font-weight: 700; }
border: 1px solid #bec9c2; .text-button { border: 0; background: transparent; color: var(--green); font-size: 13px; font-weight: 700; }
border-radius: 3px; .config-form { display: grid; gap: 10px; padding: 14px; }
background: #f8faf8; .config-field { display: grid; grid-template-columns: minmax(160px, 0.42fr) minmax(0, 1fr); align-items: center; gap: 12px; }
color: #18392d; .config-field label { color: var(--muted); font: 13px Consolas, monospace; font-weight: 700; }
font: 14px/1.65 Consolas, "Microsoft YaHei UI", monospace; .config-field input { width: 100%; }
tab-size: 2; .config-field-error { grid-column: 2; margin: -4px 0 0; color: var(--red); font-size: 12px; }
outline: none; .config-field input[aria-invalid="true"] { border-color: var(--red); box-shadow: 0 0 0 2px rgba(173, 52, 45, 0.12); }
} .editor-column > .file-path { padding: 0 14px 12px; }
.editor-column > .file-path { padding: 0 14px 12px; } .publish-aside { padding: 20px; align-self: start; }
.publish-aside { padding: 20px; align-self: start; } .publish-aside h3 { padding-bottom: 14px; border-bottom: 1px solid var(--line); }
.publish-aside h3 { padding-bottom: 14px; border-bottom: 1px solid var(--line); } dl { margin: 8px 0 18px; }
dl { margin: 8px 0 18px; } dl div { display: flex; justify-content: space-between; gap: 12px; padding: 10px 0; border-bottom: 1px solid #e6ebe8; font-size: 12px; }
dl div { display: flex; justify-content: space-between; gap: 12px; padding: 10px 0; border-bottom: 1px solid #e6ebe8; font-size: 12px; } dt { color: var(--muted); }
dt { color: var(--muted); } dd { margin: 0; text-align: right; font-weight: 700; }
dd { margin: 0; text-align: right; font-weight: 700; } .result { min-height: 42px; margin-top: 14px; padding: 10px; background: #eef1ef; color: var(--muted); font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
.result { min-height: 42px; margin-top: 14px; padding: 10px; background: #eef1ef; color: var(--muted); font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; } .result[data-tone="success"] { color: var(--green-dark); background: #e2f2e9; }
.result[data-tone="success"] { color: var(--green-dark); background: #e2f2e9; } .result[data-tone="error"] { color: var(--red); background: #f8e7e5; }
.result[data-tone="error"] { color: var(--red); background: #f8e7e5; }
.management-layout { display: grid; grid-template-columns: 330px minmax(0, 1fr); gap: 18px; align-items: start; }
.management-layout { display: grid; grid-template-columns: 330px minmax(0, 1fr); gap: 18px; align-items: start; } .management-layout.equal { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.management-layout.equal { grid-template-columns: repeat(2, minmax(0, 1fr)); } .form-surface, .data-surface { background: var(--surface); border: 1px solid var(--line); }
.form-surface, .data-surface { background: var(--surface); border: 1px solid var(--line); } .form-surface { padding: 20px; display: grid; gap: 14px; }
.form-surface { padding: 20px; display: grid; gap: 14px; } .form-surface h3 { padding-bottom: 13px; border-bottom: 1px solid var(--line); }
.form-surface h3 { padding-bottom: 13px; border-bottom: 1px solid var(--line); } .form-surface label { display: grid; gap: 6px; }
.form-surface label { display: grid; gap: 6px; } .form-surface label span { color: var(--muted); font-size: 12px; font-weight: 700; }
.form-surface label span { color: var(--muted); font-size: 12px; font-weight: 700; } .form-note { color: var(--muted); font-size: 11px; line-height: 1.6; }
.form-note { color: var(--muted); font-size: 11px; line-height: 1.6; } .data-surface { min-width: 0; overflow: auto; }
.data-surface { min-width: 0; overflow: auto; } table { width: 100%; border-collapse: collapse; font-size: 12px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; } th, td { padding: 11px 13px; border-bottom: 1px solid #e4e9e6; text-align: left; vertical-align: middle; }
th, td { padding: 11px 13px; border-bottom: 1px solid #e4e9e6; text-align: left; vertical-align: middle; } th { color: var(--muted); background: #edf1ee; font-size: 11px; }
th { color: var(--muted); background: #edf1ee; font-size: 11px; } td:last-child { white-space: nowrap; }
td:last-child { white-space: nowrap; } .table-action { border: 0; background: transparent; color: var(--green); font-weight: 700; margin-right: 10px; }
.table-action { border: 0; background: transparent; color: var(--green); font-weight: 700; margin-right: 10px; } .table-action.danger { color: var(--red); }
.table-action.danger { color: var(--red); } .empty-row { padding: 30px; color: var(--muted); text-align: center; font-size: 13px; }
.empty-row { padding: 30px; color: var(--muted); text-align: center; font-size: 13px; } .detail-view { margin: 0; padding: 16px; max-height: 260px; overflow: auto; background: #18251f; color: #d9e9df; font: 12px/1.6 Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
.detail-view { margin: 0; padding: 16px; max-height: 260px; overflow: auto; background: #18251f; color: #d9e9df; font: 12px/1.6 Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
.lightbox { position: fixed; inset: 0; z-index: 20; padding: 24px; background: rgba(10, 20, 16, 0.78); }
.lightbox { position: fixed; inset: 0; z-index: 20; padding: 24px; background: rgba(10, 20, 16, 0.78); } .lightbox-shell { height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr); background: var(--surface); border: 1px solid #9aa9a1; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35); }
.lightbox-shell { height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr); background: var(--surface); border: 1px solid #9aa9a1; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35); } .lightbox-toolbar { min-height: 58px; padding: 10px 14px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); }
.lightbox-toolbar { min-height: 58px; padding: 10px 14px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); } .lightbox-actions { display: flex; align-items: center; gap: 7px; }
.lightbox-actions { display: flex; align-items: center; gap: 7px; } .lightbox-canvas { min-width: 0; min-height: 0; display: grid; place-items: center; overflow: auto; padding: 22px; background-color: #dce2de; background-image: linear-gradient(45deg, #d3dad5 25%, transparent 25%), linear-gradient(-45deg, #d3dad5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #d3dad5 75%), linear-gradient(-45deg, transparent 75%, #d3dad5 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0; }
.lightbox-canvas { min-width: 0; min-height: 0; display: grid; place-items: center; overflow: auto; padding: 22px; background-color: #dce2de; background-image: linear-gradient(45deg, #d3dad5 25%, transparent 25%), linear-gradient(-45deg, #d3dad5 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #d3dad5 75%), linear-gradient(-45deg, transparent 75%, #d3dad5 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0; } .lightbox-canvas img { display: block; max-width: none; background: white; }
.lightbox-canvas img { display: block; max-width: none; background: white; } .lightbox-canvas img.fit-image { max-width: 100%; max-height: 100%; object-fit: contain; }
.lightbox-canvas img.fit-image { max-width: 100%; max-height: 100%; object-fit: contain; }
@media (max-width: 1050px) {
@media (max-width: 1050px) { main { padding-left: 22px; padding-right: 22px; }
main { padding-left: 22px; padding-right: 22px; } .connection-band { grid-template-columns: 1fr; }
.connection-band { grid-template-columns: 1fr; } .plot-grid { grid-template-columns: 1fr; }
.plot-grid { grid-template-columns: 1fr; } .plot-stage { height: 360px; }
.plot-stage { height: 360px; } .editor-layout { grid-template-columns: minmax(0, 1fr) 240px; }
.editor-layout { grid-template-columns: minmax(0, 1fr) 240px; } .management-layout, .management-layout.equal { grid-template-columns: 1fr; }
.management-layout, .management-layout.equal { grid-template-columns: 1fr; } .lightbox { padding: 12px; }
.lightbox { padding: 12px; } .lightbox-toolbar { align-items: start; flex-direction: column; }
.lightbox-toolbar { align-items: start; flex-direction: column; }
} }
+21 -1
View File
@@ -98,8 +98,28 @@ CREATE TABLE IF NOT EXISTS volume_config_requests (
PRIMARY KEY (device_id, request_id) PRIMARY KEY (device_id, request_id)
); );
CREATE TABLE IF NOT EXISTS volume_configs (
device_id TEXT PRIMARY KEY,
file_id TEXT NOT NULL,
file_name TEXT NOT NULL,
request_id TEXT NOT NULL,
updated_at_ms BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS panel_notifications (
notification_id TEXT PRIMARY KEY,
device_id TEXT NOT NULL,
type TEXT NOT NULL,
title TEXT NOT NULL,
message TEXT NOT NULL,
request_id TEXT,
file_id TEXT,
created_at_ms BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS licenses_status_device_expiry_idx ON licenses (status, device_id, expiry_at); CREATE INDEX IF NOT EXISTS licenses_status_device_expiry_idx ON licenses (status, device_id, expiry_at);
CREATE INDEX IF NOT EXISTS file_records_folder_idx ON file_records (folder); CREATE INDEX IF NOT EXISTS file_records_folder_idx ON file_records (folder);
CREATE INDEX IF NOT EXISTS identification_files_device_upload_idx ON identification_files (device_id, upload_time DESC); CREATE INDEX IF NOT EXISTS identification_files_device_upload_idx ON identification_files (device_id, upload_time DESC);
CREATE INDEX IF NOT EXISTS identification_files_expires_idx ON identification_files (expires_at) WHERE expires_at IS NOT NULL; CREATE INDEX IF NOT EXISTS identification_files_expires_idx ON identification_files (expires_at) WHERE expires_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS identification_feedback_device_idx ON identification_feedback (device_id); CREATE INDEX IF NOT EXISTS identification_feedback_device_idx ON identification_feedback (device_id);
CREATE INDEX IF NOT EXISTS panel_notifications_device_created_idx ON panel_notifications (device_id, created_at_ms);
+1122 -1037
View File
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -41,6 +41,8 @@ class PostgresStore {
const identificationFiles = await queryable.query("SELECT file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at FROM identification_files"); const identificationFiles = await queryable.query("SELECT file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at FROM identification_files");
const feedback = await queryable.query("SELECT device_id, run_id, file_name, status, result, update_time FROM identification_feedback"); const feedback = await queryable.query("SELECT device_id, run_id, file_name, status, result, update_time FROM identification_feedback");
const requests = await queryable.query("SELECT device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time FROM volume_config_requests"); const requests = await queryable.query("SELECT device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time FROM volume_config_requests");
const volumeConfigs = await queryable.query("SELECT device_id, file_id, file_name, request_id, updated_at_ms FROM volume_configs");
const panelNotifications = await queryable.query("SELECT notification_id, device_id, type, title, message, request_id, file_id, created_at_ms FROM panel_notifications");
return { return {
...structuredClone(EMPTY_DATABASE), ...structuredClone(EMPTY_DATABASE),
companies: companies.rows.map((row) => ({ id: row.id, name: row.name, code: row.code, createdAt: asIso(row.created_at) })), companies: companies.rows.map((row) => ({ id: row.id, name: row.name, code: row.code, createdAt: asIso(row.created_at) })),
@@ -51,7 +53,9 @@ class PostgresStore {
panelInbox: panelInbox.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time) })), panelInbox: panelInbox.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time) })),
identificationFiles: identificationFiles.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time), size: Number(row.size_bytes), status: row.status, processedAt: row.processed_at && asIso(row.processed_at), expiresAt: row.expires_at && asIso(row.expires_at) })), identificationFiles: identificationFiles.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time), size: Number(row.size_bytes), status: row.status, processedAt: row.processed_at && asIso(row.processed_at), expiresAt: row.expires_at && asIso(row.expires_at) })),
identificationFeedback: feedback.rows.map((row) => ({ deviceId: row.device_id, runId: row.run_id, fileName: row.file_name, status: row.status, result: row.result, updateTime: asIso(row.update_time) })), identificationFeedback: feedback.rows.map((row) => ({ deviceId: row.device_id, runId: row.run_id, fileName: row.file_name, status: row.status, result: row.result, updateTime: asIso(row.update_time) })),
volumeConfigRequests: requests.rows.map((row) => ({ deviceId: row.device_id, requestId: row.request_id, status: row.status, createdAtMs: Number(row.created_at_ms), expiresAtMs: Number(row.expires_at_ms), configFileID: row.config_file_id, configFileName: row.config_file_name, uploadedAtMs: row.uploaded_at_ms && Number(row.uploaded_at_ms), updateTime: asIso(row.update_time) })) volumeConfigRequests: requests.rows.map((row) => ({ deviceId: row.device_id, requestId: row.request_id, status: row.status, createdAtMs: Number(row.created_at_ms), expiresAtMs: Number(row.expires_at_ms), configFileID: row.config_file_id, configFileName: row.config_file_name, uploadedAtMs: row.uploaded_at_ms && Number(row.uploaded_at_ms), updateTime: asIso(row.update_time) })),
volumeConfigs: volumeConfigs.rows.map((row) => ({ deviceId: row.device_id, fileID: row.file_id, fileName: row.file_name, requestId: row.request_id, updatedAtMs: Number(row.updated_at_ms) })),
panelNotifications: panelNotifications.rows.map((row) => ({ notificationId: row.notification_id, deviceId: row.device_id, type: row.type, title: row.title, message: row.message, requestId: row.request_id, fileID: row.file_id, createdAtMs: Number(row.created_at_ms) }))
}; };
} }
@@ -74,7 +78,7 @@ class PostgresStore {
} }
async writeDatabase(client, database) { async writeDatabase(client, database) {
await client.query("DELETE FROM volume_config_requests; DELETE FROM identification_feedback; DELETE FROM panel_inbox; DELETE FROM identification_files; DELETE FROM function_configs; DELETE FROM file_records; DELETE FROM licenses; DELETE FROM production_lines; DELETE FROM companies;"); await client.query("DELETE FROM panel_notifications; DELETE FROM volume_configs; DELETE FROM volume_config_requests; DELETE FROM identification_feedback; DELETE FROM panel_inbox; DELETE FROM identification_files; DELETE FROM function_configs; DELETE FROM file_records; DELETE FROM licenses; DELETE FROM production_lines; DELETE FROM companies;");
for (const item of database.companies) await client.query("INSERT INTO companies (id, name, code, created_at) VALUES ($1, $2, $3, $4)", [item.id, item.name, item.code, item.createdAt]); for (const item of database.companies) await client.query("INSERT INTO companies (id, name, code, created_at) VALUES ($1, $2, $3, $4)", [item.id, item.name, item.code, item.createdAt]);
for (const item of database.productionLines) await client.query("INSERT INTO production_lines (id, company_id, name, code, device_id, created_at, last_seen_at) VALUES ($1, $2, $3, $4, $5, $6, $7)", [item.id, item.companyId, item.name, item.code, item.deviceId, item.createdAt, item.lastSeenAt]); for (const item of database.productionLines) await client.query("INSERT INTO production_lines (id, company_id, name, code, device_id, created_at, last_seen_at) VALUES ($1, $2, $3, $4, $5, $6, $7)", [item.id, item.companyId, item.name, item.code, item.deviceId, item.createdAt, item.lastSeenAt]);
for (const item of database.licenses) await client.query("INSERT INTO licenses (license_id, company_id, production_line_id, device_id, customer, issued_at, expiry_at, features, license, status, created_at, revoked_at, revocation_reason) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)", [item.licenseId, item.companyId, item.productionLineId, item.deviceId, item.customer, item.issuedAt, item.expiryAt, item.features, item.license, item.status, item.createdAt, item.revokedAt, item.revocationReason]); for (const item of database.licenses) await client.query("INSERT INTO licenses (license_id, company_id, production_line_id, device_id, customer, issued_at, expiry_at, features, license, status, created_at, revoked_at, revocation_reason) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)", [item.licenseId, item.companyId, item.productionLineId, item.deviceId, item.customer, item.issuedAt, item.expiryAt, item.features, item.license, item.status, item.createdAt, item.revokedAt, item.revocationReason]);
@@ -84,6 +88,8 @@ class PostgresStore {
for (const item of database.identificationFiles) await client.query("INSERT INTO identification_files (file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.fileID, item.deviceId, item.fileName, item.mediaType, item.uploadTime, item.size, item.status, item.processedAt, item.expiresAt]); for (const item of database.identificationFiles) await client.query("INSERT INTO identification_files (file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.fileID, item.deviceId, item.fileName, item.mediaType, item.uploadTime, item.size, item.status, item.processedAt, item.expiresAt]);
for (const item of database.identificationFeedback) await client.query("INSERT INTO identification_feedback (device_id, run_id, file_name, status, result, update_time) VALUES ($1,$2,$3,$4,$5,$6)", [item.deviceId, item.runId, item.fileName, item.status, item.result, item.updateTime]); for (const item of database.identificationFeedback) await client.query("INSERT INTO identification_feedback (device_id, run_id, file_name, status, result, update_time) VALUES ($1,$2,$3,$4,$5,$6)", [item.deviceId, item.runId, item.fileName, item.status, item.result, item.updateTime]);
for (const item of database.volumeConfigRequests) await client.query("INSERT INTO volume_config_requests (device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.deviceId, item.requestId, item.status, item.createdAtMs, item.expiresAtMs, item.configFileID, item.configFileName, item.uploadedAtMs, item.updateTime]); for (const item of database.volumeConfigRequests) await client.query("INSERT INTO volume_config_requests (device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.deviceId, item.requestId, item.status, item.createdAtMs, item.expiresAtMs, item.configFileID, item.configFileName, item.uploadedAtMs, item.updateTime]);
for (const item of database.volumeConfigs) await client.query("INSERT INTO volume_configs (device_id, file_id, file_name, request_id, updated_at_ms) VALUES ($1,$2,$3,$4,$5)", [item.deviceId, item.fileID, item.fileName, item.requestId, item.updatedAtMs]);
for (const item of database.panelNotifications) await client.query("INSERT INTO panel_notifications (notification_id, device_id, type, title, message, request_id, file_id, created_at_ms) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", [item.notificationId, item.deviceId, item.type, item.title, item.message, item.requestId, item.fileID, item.createdAtMs]);
} }
createId(prefix) { createId(prefix) {
+81 -79
View File
@@ -1,80 +1,82 @@
const fs = require("node:fs"); const fs = require("node:fs");
const path = require("node:path"); const path = require("node:path");
const { randomUUID } = require("node:crypto"); const { randomUUID } = require("node:crypto");
const EMPTY_DATABASE = { const EMPTY_DATABASE = {
fileRecords: [], fileRecords: [],
functionConfigs: [], functionConfigs: [],
panelInbox: [], panelInbox: [],
identificationFiles: [], identificationFiles: [],
identificationFeedback: [], identificationFeedback: [],
volumeConfigRequests: [], volumeConfigRequests: [],
userInfo: [], volumeConfigs: [],
companies: [], panelNotifications: [],
productionLines: [], userInfo: [],
licenses: [] companies: [],
}; productionLines: [],
licenses: []
class JsonStore { };
constructor(dataDirectory) {
this.dataDirectory = dataDirectory; class JsonStore {
this.filesDirectory = path.join(dataDirectory, "files"); constructor(dataDirectory) {
this.modelsDirectory = path.join(dataDirectory, "models"); this.dataDirectory = dataDirectory;
this.databasePath = path.join(dataDirectory, "database.json"); this.filesDirectory = path.join(dataDirectory, "files");
this.writeQueue = Promise.resolve(); this.modelsDirectory = path.join(dataDirectory, "models");
} this.databasePath = path.join(dataDirectory, "database.json");
this.writeQueue = Promise.resolve();
async initialize() { }
await fs.promises.mkdir(this.filesDirectory, { recursive: true });
try { async initialize() {
await fs.promises.access(this.databasePath); await fs.promises.mkdir(this.filesDirectory, { recursive: true });
} catch { try {
await this.writeDatabase(structuredClone(EMPTY_DATABASE)); await fs.promises.access(this.databasePath);
} } catch {
} await this.writeDatabase(structuredClone(EMPTY_DATABASE));
}
async read() { }
const content = await fs.promises.readFile(this.databasePath, "utf8");
return { ...structuredClone(EMPTY_DATABASE), ...JSON.parse(content) }; async read() {
} const content = await fs.promises.readFile(this.databasePath, "utf8");
return { ...structuredClone(EMPTY_DATABASE), ...JSON.parse(content) };
async update(mutator) { }
const operation = this.writeQueue.then(async () => {
const database = await this.read(); async update(mutator) {
const result = await mutator(database); const operation = this.writeQueue.then(async () => {
await this.writeDatabase(database); const database = await this.read();
return result; const result = await mutator(database);
}); await this.writeDatabase(database);
this.writeQueue = operation.catch(() => undefined); return result;
return operation; });
} this.writeQueue = operation.catch(() => undefined);
return operation;
async writeDatabase(database) { }
await fs.promises.mkdir(this.dataDirectory, { recursive: true });
const temporaryPath = `${this.databasePath}.${process.pid}.tmp`; async writeDatabase(database) {
await fs.promises.writeFile( await fs.promises.mkdir(this.dataDirectory, { recursive: true });
temporaryPath, const temporaryPath = `${this.databasePath}.${process.pid}.tmp`;
`${JSON.stringify(database, null, 2)}\n`, await fs.promises.writeFile(
"utf8" temporaryPath,
); `${JSON.stringify(database, null, 2)}\n`,
await fs.promises.rename(temporaryPath, this.databasePath); "utf8"
} );
await fs.promises.rename(temporaryPath, this.databasePath);
createId(prefix) { }
return `${prefix}_${randomUUID()}`;
} createId(prefix) {
return `${prefix}_${randomUUID()}`;
resolveStoredFile(fileID) { }
if (typeof fileID !== "string") return null;
const isModel = fileID.startsWith("model://"); resolveStoredFile(fileID) {
if (!isModel && !fileID.startsWith("local://")) return null; if (typeof fileID !== "string") return null;
const rootDirectory = isModel ? this.modelsDirectory : this.filesDirectory; const isModel = fileID.startsWith("model://");
const relativePath = fileID.slice(isModel ? "model://".length : "local://".length).replace(/\\/g, "/"); if (!isModel && !fileID.startsWith("local://")) return null;
const absolutePath = path.resolve(rootDirectory, relativePath); const rootDirectory = isModel ? this.modelsDirectory : this.filesDirectory;
const relativeToRoot = path.relative(rootDirectory, absolutePath); const relativePath = fileID.slice(isModel ? "model://".length : "local://".length).replace(/\\/g, "/");
if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) return null; const absolutePath = path.resolve(rootDirectory, relativePath);
return absolutePath; const relativeToRoot = path.relative(rootDirectory, absolutePath);
} if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) return null;
} return absolutePath;
}
}
module.exports = { EMPTY_DATABASE, JsonStore }; module.exports = { EMPTY_DATABASE, JsonStore };
+751 -692
View File
File diff suppressed because it is too large Load Diff