@alexsun-top/opencode-chat-room 0.8.2 → 0.8.3

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +466 -188
  5. package/package.json +8 -5
  6. package/packages/chat-room-channeld/README.md +25 -3
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +5 -0
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +17 -2
  11. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  12. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  13. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  14. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  15. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  16. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  17. package/packages/chat-room-channeld/src/protocol.ts +1 -0
  18. package/packages/chat-room-channeld/src/state.ts +73 -97
  19. package/packages/chat-room-channeld/src/stats.ts +140 -109
  20. package/server/assets/base.css +3 -1
  21. package/server/assets/chat/admin-badge.js +32 -30
  22. package/server/assets/chat/admin.js +198 -161
  23. package/server/assets/chat/announcements.js +295 -208
  24. package/server/assets/chat/attachment-store.js +106 -75
  25. package/server/assets/chat/attachments.js +686 -441
  26. package/server/assets/chat/chat-background.js +185 -156
  27. package/server/assets/chat/clipboard.js +44 -25
  28. package/server/assets/chat/confirm-dialog.js +36 -33
  29. package/server/assets/chat/copy-action.js +40 -40
  30. package/server/assets/chat/create-room-dialog.js +50 -47
  31. package/server/assets/chat/diagram-viewer.js +293 -234
  32. package/server/assets/chat/doc-preview.js +507 -441
  33. package/server/assets/chat/editor.js +423 -335
  34. package/server/assets/chat/events.js +637 -510
  35. package/server/assets/chat/files.js +476 -430
  36. package/server/assets/chat/history-loader.js +79 -73
  37. package/server/assets/chat/icons.js +9 -11
  38. package/server/assets/chat/image-zoom.js +239 -176
  39. package/server/assets/chat/index.js +2 -3
  40. package/server/assets/chat/install-prompt.js +86 -66
  41. package/server/assets/chat/integration-account-schema.js +88 -86
  42. package/server/assets/chat/integration-editor.js +162 -153
  43. package/server/assets/chat/integration-values.js +109 -100
  44. package/server/assets/chat/integrations.js +689 -622
  45. package/server/assets/chat/join-requests.js +408 -358
  46. package/server/assets/chat/locales/de.js +193 -194
  47. package/server/assets/chat/locales/es.js +193 -194
  48. package/server/assets/chat/locales/fr.js +193 -194
  49. package/server/assets/chat/locales/index.js +1 -2
  50. package/server/assets/chat/locales/it.js +193 -194
  51. package/server/assets/chat/locales/ja.js +193 -193
  52. package/server/assets/chat/locales/ko.js +193 -193
  53. package/server/assets/chat/markdown-footnotes.js +134 -102
  54. package/server/assets/chat/markdown.js +547 -403
  55. package/server/assets/chat/members.js +236 -197
  56. package/server/assets/chat/mentions.js +157 -133
  57. package/server/assets/chat/message-cache.js +40 -33
  58. package/server/assets/chat/message-polling.js +280 -227
  59. package/server/assets/chat/message-window.js +74 -55
  60. package/server/assets/chat/messages.js +552 -480
  61. package/server/assets/chat/office-preview.js +46 -45
  62. package/server/assets/chat/palette.js +450 -417
  63. package/server/assets/chat/panels.js +94 -78
  64. package/server/assets/chat/pwa.js +144 -73
  65. package/server/assets/chat/questions.js +372 -302
  66. package/server/assets/chat/recall.js +320 -273
  67. package/server/assets/chat/receipts.js +149 -121
  68. package/server/assets/chat/reminders.js +331 -214
  69. package/server/assets/chat/replies.js +165 -130
  70. package/server/assets/chat/resource-format.js +59 -62
  71. package/server/assets/chat/room-list.js +58 -55
  72. package/server/assets/chat/room-watcher.js +72 -50
  73. package/server/assets/chat/rooms.js +623 -500
  74. package/server/assets/chat/search.js +136 -114
  75. package/server/assets/chat/settings.js +223 -200
  76. package/server/assets/chat/shiki.js +61 -62
  77. package/server/assets/chat/shortcuts.js +212 -187
  78. package/server/assets/chat/side-pane.js +160 -150
  79. package/server/assets/chat/state.js +849 -735
  80. package/server/assets/chat/system-events.js +45 -43
  81. package/server/assets/chat/system-messages.js +57 -56
  82. package/server/assets/chat/task-form.js +178 -182
  83. package/server/assets/chat/task-row.js +158 -155
  84. package/server/assets/chat/tasks.js +653 -587
  85. package/server/assets/chat/viewport.js +32 -29
  86. package/server/assets/chat/window-controls.js +32 -32
  87. package/server/assets/conversation.css +10 -4
  88. package/server/chat-server.ts +9 -1
  89. package/server/chat.html +2 -1
  90. package/server/routes/pages.ts +7 -5
  91. package/server/sw.js +346 -268
  92. package/src/web/integration-rules-editor.ts +2 -0
@@ -4,645 +4,712 @@ import { iconNode } from "./icons.js";
4
4
  import { readAccountSchema, renderAccountSchema } from "./integration-account-schema.js";
5
5
  import { checkInbound, checkRules, knownPlugins, normalizeAccount, parseInbound, parseRules } from "./integration-values.js";
6
6
  import { accountBody, cleanError, stateLabel } from "./integration-values.js";
7
-
8
7
  const MAX_SOURCE = 256 * 1024;
9
8
  const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
10
9
  const PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs|ts)$/;
11
10
  const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
-
13
11
  const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
14
-
15
12
  export function initIntegrations(app) {
16
- const $ = app.$;
17
- const panel = $("#settingsPanelIntegrations"); if (!panel) return;
18
- const enabledInput = $("#inIntegrationsEnabled"), statusText = $("#integrationStatus");
19
- const integrationBody = $("#integrationBody"), disabledHint = $("#integrationDisabledHint");
20
- const panelError = $("#integrationError"), accountsList = $("#integrationAccounts");
21
- const externalNotice = $("#integrationExternalNotice"), addAccountButton = $("#btnAddIntegrationAccount");
22
- const uploadPluginButton = $("#btnUploadPlugin");
23
- const accountsEmpty = $("#integrationAccountsEmpty"), pluginsList = $("#integrationPlugins");
24
- const pluginsEmpty = $("#integrationPluginsEmpty");
25
- const rulesError = $("#integrationRulesError"), saveButton = $("#btnSaveIntegrations");
26
- const accountDialog = $("#integrationAccountDialog"), accountForm = $("#integrationAccountForm");
27
- const accountError = $("#integrationAccountError"), accountId = $("#integrationAccountId");
28
- const accountPlugin = $("#integrationAccountPlugin");
29
- const accountSchema = $("#integrationAccountSchema"), accountSchemaField = $("#integrationAccountSchemaField"), accountAdvanced = $("#integrationAccountAdvanced");
30
- const accountEnv = $("#integrationAccountEnv"), accountEnvNote = $("#integrationAccountEnvNote");
31
- const accountClear = $("#btnClearAccountEnv"), accountAddEnv = $("#btnAddAccountEnv");
32
- const pluginDialog = $("#integrationPluginDialog"), pluginForm = $("#integrationPluginForm");
33
- const pluginError = $("#integrationPluginError"), pluginFile = $("#integrationPluginFile");
34
- let data = { enabled: false, source: "managed", editable: true, accounts: [], rules: [], inbound: [], plugins: [] };
35
- let initialInbound = "[]";
36
- let loaded = false, loading = false, saving = false, accountDraft = null, clearEnv = false;
37
- let pluginUploadSource = "", pluginUploadName = "";
38
-
39
- const text = (key, values) => app.t(key, values);
40
- const clean = (error) => cleanError(error, text("integrationsLoadFailed"));
41
- const showPanelError = (error) => { panelError.textContent = clean(error); panelError.hidden = false; };
42
- const hidePanelError = () => { panelError.hidden = true; };
43
- const showStatus = (value) => { statusText.textContent = value; };
44
- const showAccountError = (error) => { accountError.textContent = clean(error); accountError.hidden = false; };
45
- const hideAccountError = () => { accountError.hidden = true; };
46
- const showPluginError = (error) => { pluginError.textContent = clean(error); pluginError.hidden = false; };
47
- const hidePluginError = () => { pluginError.hidden = true; };
48
- const showRulesError = (value) => { rulesError.textContent = value; rulesError.hidden = false; };
49
- const hideRulesError = () => { rulesError.hidden = true; };
50
- const rulesSection = initIntegrationEditor(app, {
51
- kind: "rules",
52
- editor: "#integrationRulesEditor",
53
- textarea: "#integrationRules",
54
- fallback: "#integrationRulesFallback",
55
- error: "#integrationRulesError",
56
- errors: "#integrationRulesErrorList",
57
- formats: "#integrationRulesFormat",
58
- getValue: () => data.rules,
59
- getAccounts: () => data.accounts,
60
- });
61
- const inboundSection = initIntegrationEditor(app, {
62
- kind: "inbound",
63
- editor: "#integrationInboundEditor",
64
- textarea: "#integrationInbound",
65
- fallback: "#integrationInboundFallback",
66
- error: "#integrationInboundError",
67
- errors: "#integrationInboundErrorList",
68
- formats: "#integrationInboundFormat",
69
- getValue: () => data.inbound,
70
- getAccounts: () => data.accounts,
71
- });
72
-
73
- function applyEditableState() {
74
- const editable = data.editable !== false;
75
- if (externalNotice) externalNotice.hidden = editable;
76
- saveButton.disabled = saving || !editable;
77
- if (addAccountButton) addAccountButton.disabled = !editable;
78
- if (uploadPluginButton) uploadPluginButton.disabled = !editable;
79
- rulesSection.setEditable(editable);
80
- inboundSection.setEditable(editable);
81
- }
82
-
83
- function applyEnabledState() {
84
- const enabled = enabledInput.checked;
85
- integrationBody.hidden = !enabled;
86
- disabledHint.hidden = enabled;
87
- }
88
-
89
- const pluginNameOf = (pluginId) => knownPlugins(data).find((plugin) => plugin.pluginId === pluginId)?.name || pluginId;
90
-
91
- function adopt(snapshot) {
92
- const raw = isRecord(snapshot) ? snapshot : {};
93
- data = {
94
- enabled: raw.enabled === true,
95
- source: typeof raw.source === "string" ? raw.source : "managed",
96
- editable: raw.editable !== false,
97
- accounts: Array.isArray(raw.accounts) ? raw.accounts.filter(isRecord).map(normalizeAccount) : [],
98
- rules: Array.isArray(raw.rules) ? raw.rules : [],
99
- inbound: Array.isArray(raw.inbound) ? raw.inbound : data.inbound,
100
- plugins: Array.isArray(raw.plugins)
101
- ? raw.plugins.filter((plugin) => isRecord(plugin) && typeof plugin.pluginId === "string" && typeof plugin.name === "string" && typeof plugin.platform === "string")
102
- : data.plugins,
103
- };
104
- initialInbound = JSON.stringify(data.inbound);
105
- loaded = true;
106
- }
107
-
108
- function renderAccounts() {
109
- accountsList.textContent = "";
110
- for (const account of data.accounts) {
111
- const row = document.createElement("li");
112
- row.className = "integration-account";
113
- const main = document.createElement("div");
114
- main.className = "integration-account-main";
115
- const head = document.createElement("p");
116
- head.className = "integration-account-head";
117
- const id = document.createElement("span");
118
- id.className = "integration-account-id";
119
- id.textContent = account.id;
120
- const platform = document.createElement("span");
121
- platform.className = "integration-platform";
122
- platform.textContent = account.platform;
123
- const state = document.createElement("span");
124
- state.className = "integration-state";
125
- state.dataset.state = account.state;
126
- state.textContent = stateLabel(account.state, text);
127
- head.append(id, platform, state);
128
- const meta = document.createElement("p");
129
- meta.className = "integration-account-meta";
130
- const env = account.envClear ? "—" : account.envKeys.length ? account.envKeys.join(", ") : "—";
131
- meta.textContent = `${text("integrationsPlugin")}: ${pluginNameOf(account.pluginId)} · ${text("integrationsEnv")}: ${env}`;
132
- main.append(head, meta);
133
- if (account.lastError) {
134
- const error = document.createElement("p");
135
- error.className = "integration-account-error";
136
- error.textContent = `${text("integrationsLastError")}: ${clean(account.lastError)}`;
137
- main.append(error);
138
- }
139
- const actions = document.createElement("div");
140
- actions.className = "integration-account-actions";
141
- const edit = document.createElement("button");
142
- edit.type = "button"; edit.className = "btn ghost small"; edit.textContent = text("integrationsEdit");
143
- edit.setAttribute("aria-label", `${text("integrationsEdit")}: ${account.id}`);
144
- edit.disabled = data.editable === false;
145
- edit.addEventListener("click", () => openAccount(account));
146
- const remove = document.createElement("button");
147
- remove.type = "button"; remove.className = "btn ghost small danger-text"; remove.textContent = text("integrationsRemove");
148
- remove.setAttribute("aria-label", `${text("integrationsRemove")}: ${account.id}`);
149
- remove.disabled = data.editable === false;
150
- remove.addEventListener("click", async () => {
151
- if (data.editable === false) return;
152
- if (!(await app.confirmAction(text("integrationsRemoveAccountConfirm", { id: account.id })))) return;
153
- data.accounts = data.accounts.filter((item) => item.id !== account.id);
13
+ const $ = app.$;
14
+ const panel = $("#settingsPanelIntegrations");
15
+ if (!panel)
16
+ return;
17
+ const enabledInput = $("#inIntegrationsEnabled"), statusText = $("#integrationStatus");
18
+ const integrationBody = $("#integrationBody"), disabledHint = $("#integrationDisabledHint");
19
+ const panelError = $("#integrationError"), accountsList = $("#integrationAccounts");
20
+ const externalNotice = $("#integrationExternalNotice"), addAccountButton = $("#btnAddIntegrationAccount");
21
+ const uploadPluginButton = $("#btnUploadPlugin");
22
+ const accountsEmpty = $("#integrationAccountsEmpty"), pluginsList = $("#integrationPlugins");
23
+ const pluginsEmpty = $("#integrationPluginsEmpty");
24
+ const rulesError = $("#integrationRulesError"), saveButton = $("#btnSaveIntegrations");
25
+ const accountDialog = $("#integrationAccountDialog"), accountForm = $("#integrationAccountForm");
26
+ const accountError = $("#integrationAccountError"), accountId = $("#integrationAccountId");
27
+ const accountPlugin = $("#integrationAccountPlugin");
28
+ const accountSchema = $("#integrationAccountSchema"), accountSchemaField = $("#integrationAccountSchemaField"), accountAdvanced = $("#integrationAccountAdvanced");
29
+ const accountEnv = $("#integrationAccountEnv"), accountEnvNote = $("#integrationAccountEnvNote");
30
+ const accountClear = $("#btnClearAccountEnv"), accountAddEnv = $("#btnAddAccountEnv");
31
+ const pluginDialog = $("#integrationPluginDialog"), pluginForm = $("#integrationPluginForm");
32
+ const pluginError = $("#integrationPluginError"), pluginFile = $("#integrationPluginFile");
33
+ let data = { enabled: false, source: "managed", editable: true, accounts: [], rules: [], inbound: [], plugins: [] };
34
+ let initialInbound = "[]";
35
+ let loaded = false, loading = false, saving = false, accountDraft = null, clearEnv = false;
36
+ let pluginUploadSource = "", pluginUploadName = "";
37
+ const text = (key, values) => app.t(key, values);
38
+ const clean = (error) => cleanError(error, text("integrationsLoadFailed"));
39
+ const showPanelError = (error) => { panelError.textContent = clean(error); panelError.hidden = false; };
40
+ const hidePanelError = () => { panelError.hidden = true; };
41
+ const showStatus = (value) => { statusText.textContent = value; };
42
+ const showAccountError = (error) => { accountError.textContent = clean(error); accountError.hidden = false; };
43
+ const hideAccountError = () => { accountError.hidden = true; };
44
+ const showPluginError = (error) => { pluginError.textContent = clean(error); pluginError.hidden = false; };
45
+ const hidePluginError = () => { pluginError.hidden = true; };
46
+ const showRulesError = (value) => { rulesError.textContent = value; rulesError.hidden = false; };
47
+ const hideRulesError = () => { rulesError.hidden = true; };
48
+ const rulesSection = initIntegrationEditor(app, {
49
+ kind: "rules",
50
+ editor: "#integrationRulesEditor",
51
+ textarea: "#integrationRules",
52
+ fallback: "#integrationRulesFallback",
53
+ error: "#integrationRulesError",
54
+ errors: "#integrationRulesErrorList",
55
+ formats: "#integrationRulesFormat",
56
+ getValue: () => data.rules,
57
+ getAccounts: () => data.accounts,
58
+ });
59
+ const inboundSection = initIntegrationEditor(app, {
60
+ kind: "inbound",
61
+ editor: "#integrationInboundEditor",
62
+ textarea: "#integrationInbound",
63
+ fallback: "#integrationInboundFallback",
64
+ error: "#integrationInboundError",
65
+ errors: "#integrationInboundErrorList",
66
+ formats: "#integrationInboundFormat",
67
+ getValue: () => data.inbound,
68
+ getAccounts: () => data.accounts,
69
+ });
70
+ function applyEditableState() {
71
+ const editable = data.editable !== false;
72
+ if (externalNotice)
73
+ externalNotice.hidden = editable;
74
+ saveButton.disabled = saving || !editable;
75
+ if (addAccountButton)
76
+ addAccountButton.disabled = !editable;
77
+ if (uploadPluginButton)
78
+ uploadPluginButton.disabled = !editable;
79
+ rulesSection.setEditable(editable);
80
+ inboundSection.setEditable(editable);
81
+ }
82
+ function applyEnabledState() {
83
+ const enabled = enabledInput.checked;
84
+ integrationBody.hidden = !enabled;
85
+ disabledHint.hidden = enabled;
86
+ }
87
+ const pluginNameOf = (pluginId) => knownPlugins(data).find((plugin) => plugin.pluginId === pluginId)?.name || pluginId;
88
+ function adopt(snapshot) {
89
+ const raw = isRecord(snapshot) ? snapshot : {};
90
+ data = {
91
+ enabled: raw.enabled === true,
92
+ source: typeof raw.source === "string" ? raw.source : "managed",
93
+ editable: raw.editable !== false,
94
+ accounts: Array.isArray(raw.accounts) ? raw.accounts.filter(isRecord).map(normalizeAccount) : [],
95
+ rules: Array.isArray(raw.rules) ? raw.rules : [],
96
+ inbound: Array.isArray(raw.inbound) ? raw.inbound : data.inbound,
97
+ plugins: Array.isArray(raw.plugins)
98
+ ? raw.plugins.filter((plugin) => isRecord(plugin) && typeof plugin.pluginId === "string" && typeof plugin.name === "string" && typeof plugin.platform === "string")
99
+ : data.plugins,
100
+ };
101
+ initialInbound = JSON.stringify(data.inbound);
102
+ loaded = true;
103
+ }
104
+ function renderAccounts() {
105
+ accountsList.textContent = "";
106
+ for (const account of data.accounts) {
107
+ const row = document.createElement("li");
108
+ row.className = "integration-account";
109
+ const main = document.createElement("div");
110
+ main.className = "integration-account-main";
111
+ const head = document.createElement("p");
112
+ head.className = "integration-account-head";
113
+ const id = document.createElement("span");
114
+ id.className = "integration-account-id";
115
+ id.textContent = account.id;
116
+ const platform = document.createElement("span");
117
+ platform.className = "integration-platform";
118
+ platform.textContent = account.platform;
119
+ const state = document.createElement("span");
120
+ state.className = "integration-state";
121
+ state.dataset.state = account.state;
122
+ state.textContent = stateLabel(account.state, text);
123
+ head.append(id, platform, state);
124
+ const meta = document.createElement("p");
125
+ meta.className = "integration-account-meta";
126
+ const env = account.envClear ? "—" : account.envKeys.length ? account.envKeys.join(", ") : "—";
127
+ meta.textContent = `${text("integrationsPlugin")}: ${pluginNameOf(account.pluginId)} · ${text("integrationsEnv")}: ${env}`;
128
+ main.append(head, meta);
129
+ if (account.lastError) {
130
+ const error = document.createElement("p");
131
+ error.className = "integration-account-error";
132
+ error.textContent = `${text("integrationsLastError")}: ${clean(account.lastError)}`;
133
+ main.append(error);
134
+ }
135
+ const actions = document.createElement("div");
136
+ actions.className = "integration-account-actions";
137
+ const edit = document.createElement("button");
138
+ edit.type = "button";
139
+ edit.className = "btn ghost small";
140
+ edit.textContent = text("integrationsEdit");
141
+ edit.setAttribute("aria-label", `${text("integrationsEdit")}: ${account.id}`);
142
+ edit.disabled = data.editable === false;
143
+ edit.addEventListener("click", () => openAccount(account));
144
+ const remove = document.createElement("button");
145
+ remove.type = "button";
146
+ remove.className = "btn ghost small danger-text";
147
+ remove.textContent = text("integrationsRemove");
148
+ remove.setAttribute("aria-label", `${text("integrationsRemove")}: ${account.id}`);
149
+ remove.disabled = data.editable === false;
150
+ remove.addEventListener("click", async () => {
151
+ if (data.editable === false)
152
+ return;
153
+ if (!(await app.confirmAction(text("integrationsRemoveAccountConfirm", { id: account.id }))))
154
+ return;
155
+ data.accounts = data.accounts.filter((item) => item.id !== account.id);
156
+ renderAccounts();
157
+ showStatus(text("integrationsAccountRemoved"));
158
+ });
159
+ actions.append(edit, remove);
160
+ row.append(main, actions);
161
+ accountsList.append(row);
162
+ }
163
+ accountsEmpty.hidden = data.accounts.length > 0;
164
+ rulesSection.setAccounts(data.accounts);
165
+ inboundSection.setAccounts(data.accounts);
166
+ }
167
+ function renderPlugins() {
168
+ const plugins = knownPlugins(data);
169
+ pluginsList.textContent = "";
170
+ for (const plugin of plugins) {
171
+ const row = document.createElement("li");
172
+ row.className = "integration-plugin";
173
+ const name = document.createElement("span");
174
+ name.className = "integration-plugin-name";
175
+ name.textContent = plugin.name;
176
+ const platform = document.createElement("span");
177
+ platform.className = "integration-platform";
178
+ platform.textContent = plugin.platform;
179
+ const download = document.createElement("button");
180
+ download.type = "button";
181
+ download.className = "btn ghost small integration-plugin-download";
182
+ download.title = text("integrationsDownloadPlugin", { name: plugin.name });
183
+ download.setAttribute("aria-label", download.title);
184
+ download.append(iconNode("arrow_download"));
185
+ download.addEventListener("click", () => void downloadPlugin(plugin, download));
186
+ row.append(name, platform, download);
187
+ pluginsList.append(row);
188
+ }
189
+ pluginsEmpty.hidden = plugins.length > 0;
190
+ }
191
+ async function downloadPlugin(plugin, button) {
192
+ if (button.disabled)
193
+ return;
194
+ button.disabled = true;
195
+ try {
196
+ const blob = await app.apiBlob(`/channeld/plugins/${encodeURIComponent(plugin.pluginId)}/download`);
197
+ const href = URL.createObjectURL(blob);
198
+ const anchor = document.createElement("a");
199
+ anchor.href = href;
200
+ anchor.download = plugin.name;
201
+ document.body.append(anchor);
202
+ anchor.click();
203
+ anchor.remove();
204
+ setTimeout(() => URL.revokeObjectURL(href), 1000);
205
+ }
206
+ catch (error) {
207
+ showPanelError(error);
208
+ }
209
+ finally {
210
+ button.disabled = false;
211
+ }
212
+ }
213
+ function renderRules() {
214
+ rulesSection.refresh();
215
+ inboundSection.refresh();
216
+ rulesSection.setAccounts(data.accounts);
217
+ inboundSection.setAccounts(data.accounts);
218
+ hideRulesError();
219
+ }
220
+ function renderAll() {
221
+ enabledInput.checked = data.enabled;
154
222
  renderAccounts();
155
- showStatus(text("integrationsAccountRemoved"));
156
- });
157
- actions.append(edit, remove);
158
- row.append(main, actions);
159
- accountsList.append(row);
223
+ renderPlugins();
224
+ renderRules();
225
+ applyEnabledState();
226
+ applyEditableState();
160
227
  }
161
- accountsEmpty.hidden = data.accounts.length > 0;
162
- rulesSection.setAccounts(data.accounts);
163
- inboundSection.setAccounts(data.accounts);
164
- }
165
-
166
- function renderPlugins() {
167
- const plugins = knownPlugins(data);
168
- pluginsList.textContent = "";
169
- for (const plugin of plugins) {
170
- const row = document.createElement("li");
171
- row.className = "integration-plugin";
172
- const name = document.createElement("span");
173
- name.className = "integration-plugin-name";
174
- name.textContent = plugin.name;
175
- const platform = document.createElement("span");
176
- platform.className = "integration-platform";
177
- platform.textContent = plugin.platform;
178
- const download = document.createElement("button");
179
- download.type = "button";
180
- download.className = "btn ghost small integration-plugin-download";
181
- download.title = text("integrationsDownloadPlugin", { name: plugin.name });
182
- download.setAttribute("aria-label", download.title);
183
- download.append(iconNode("arrow_download"));
184
- download.addEventListener("click", () => void downloadPlugin(plugin, download));
185
- row.append(name, platform, download);
186
- pluginsList.append(row);
228
+ async function load(force = false) {
229
+ if (loading || loaded && !force)
230
+ return;
231
+ loading = true;
232
+ void rulesSection.ensure();
233
+ void inboundSection.ensure();
234
+ hidePanelError();
235
+ showStatus(text("integrationsLoading"));
236
+ try {
237
+ adopt(await app.api("/channeld/integration", { cache: "no-store" }));
238
+ renderAll();
239
+ showStatus("");
240
+ }
241
+ catch (error) {
242
+ showStatus("");
243
+ showPanelError(error);
244
+ }
245
+ finally {
246
+ loading = false;
247
+ }
248
+ }
249
+ app.loadIntegrations = () => { void load(true); };
250
+ function setSaving(busy) {
251
+ saving = busy;
252
+ saveButton.disabled = busy || data.editable === false;
253
+ enabledInput.disabled = busy;
254
+ }
255
+ let envMenuSerial = 0;
256
+ function envFields() {
257
+ const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
258
+ return (plugin?.account?.env ?? []).filter((field) => ENV_KEY.test(field.key));
187
259
  }
188
- pluginsEmpty.hidden = plugins.length > 0;
189
- }
190
-
191
- async function downloadPlugin(plugin, button) {
192
- if (button.disabled) return;
193
- button.disabled = true;
194
- try {
195
- const blob = await app.apiBlob(`/channeld/plugins/${encodeURIComponent(plugin.pluginId)}/download`);
196
- const href = URL.createObjectURL(blob);
197
- const anchor = document.createElement("a");
198
- anchor.href = href;
199
- anchor.download = plugin.name;
200
- document.body.append(anchor);
201
- anchor.click();
202
- anchor.remove();
203
- setTimeout(() => URL.revokeObjectURL(href), 1000);
204
- } catch (error) {
205
- showPanelError(error);
206
- } finally { button.disabled = false; }
207
- }
208
-
209
- function renderRules() {
210
- rulesSection.refresh();
211
- inboundSection.refresh();
212
- rulesSection.setAccounts(data.accounts);
213
- inboundSection.setAccounts(data.accounts);
214
- hideRulesError();
215
- }
216
-
217
- function renderAll() {
218
- enabledInput.checked = data.enabled;
219
- renderAccounts();
220
- renderPlugins();
221
- renderRules();
222
- applyEnabledState();
223
- applyEditableState();
224
- }
225
-
226
- async function load(force = false) {
227
- if (loading || loaded && !force) return;
228
- loading = true;
229
- void rulesSection.ensure();
230
- void inboundSection.ensure();
231
- hidePanelError();
232
- showStatus(text("integrationsLoading"));
233
- try {
234
- adopt(await app.api("/channeld/integration", { cache: "no-store" }));
235
- renderAll();
236
- showStatus("");
237
- } catch (error) {
238
- showStatus("");
239
- showPanelError(error);
240
- } finally { loading = false; }
241
- }
242
- app.loadIntegrations = () => { void load(true); };
243
-
244
- function setSaving(busy) {
245
- saving = busy;
246
- saveButton.disabled = busy || data.editable === false;
247
- enabledInput.disabled = busy;
248
- }
249
-
250
- let envMenuSerial = 0;
251
-
252
- function envFields() {
253
- const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
254
- return (plugin?.account?.env ?? []).filter((field) => ENV_KEY.test(field.key));
255
- }
256
-
257
- function closeEnvMenus(except) {
258
- for (const menu of accountEnv.querySelectorAll(".integration-env-menu")) {
259
- if (menu === except) continue;
260
- menu.hidden = true;
261
- menu.parentElement?.querySelector(".integration-env-key")?.setAttribute("aria-expanded", "false");
260
+ function closeEnvMenus(except) {
261
+ for (const menu of accountEnv.querySelectorAll(".integration-env-menu")) {
262
+ if (menu === except)
263
+ continue;
264
+ menu.hidden = true;
265
+ menu.parentElement?.querySelector(".integration-env-key")?.setAttribute("aria-expanded", "false");
266
+ }
262
267
  }
263
- }
264
-
265
- function addEnvRow(container, entry = {}, existing = false, onRemove = null) {
266
- const row = document.createElement("div");
267
- row.className = `integration-env-row${existing ? " is-stored" : ""}`;
268
- const key = document.createElement("input");
269
- key.className = "input integration-env-key";
270
- key.value = entry.key || "";
271
- key.readOnly = existing;
272
- key.placeholder = text("integrationsEnvKey");
273
- key.setAttribute("aria-label", text("integrationsEnvKey"));
274
- key.autocomplete = "off";
275
- const value = document.createElement("input");
276
- value.className = "input integration-env-value";
277
- value.type = "password";
278
- value.value = "";
279
- value.placeholder = existing ? text("integrationsLeaveBlank") : "";
280
- value.setAttribute("aria-label", text("integrationsEnvValue"));
281
- value.autocomplete = "new-password";
282
- let keyControl = key;
283
- if (!existing) {
284
- const combo = document.createElement("div");
285
- combo.className = "integration-env-combo";
286
- const menu = document.createElement("div");
287
- menu.className = "integration-env-menu";
288
- menu.id = `integrationEnvMenu-${++envMenuSerial}`;
289
- menu.role = "listbox";
290
- menu.hidden = true;
291
- key.setAttribute("role", "combobox");
292
- key.setAttribute("aria-autocomplete", "list");
293
- key.setAttribute("aria-expanded", "false");
294
- key.setAttribute("aria-controls", menu.id);
295
- const hide = () => {
296
- menu.hidden = true;
297
- key.setAttribute("aria-expanded", "false");
298
- };
299
- const choose = (option) => {
300
- key.value = option.dataset.key;
301
- hide();
302
- value.focus();
303
- };
304
- const renderMenu = () => {
305
- closeEnvMenus(menu);
306
- const used = new Set([...container.querySelectorAll(".integration-env-key")]
307
- .map((input) => input.value.trim())
308
- .filter(Boolean));
309
- const query = key.value.trim().toLowerCase();
310
- const matches = envFields().filter((field) => !used.has(field.key)).filter((field) => {
311
- if (!query) return true;
312
- return [field.key, field.label, field.description]
313
- .some((text) => String(text ?? "").toLowerCase().includes(query));
268
+ function addEnvRow(container, entry = {}, existing = false, onRemove = null) {
269
+ const row = document.createElement("div");
270
+ row.className = `integration-env-row${existing ? " is-stored" : ""}`;
271
+ const key = document.createElement("input");
272
+ key.className = "input integration-env-key";
273
+ key.value = entry.key || "";
274
+ key.readOnly = existing;
275
+ key.placeholder = text("integrationsEnvKey");
276
+ key.setAttribute("aria-label", text("integrationsEnvKey"));
277
+ key.autocomplete = "off";
278
+ const value = document.createElement("input");
279
+ value.className = "input integration-env-value";
280
+ value.type = "password";
281
+ value.value = "";
282
+ value.placeholder = existing ? text("integrationsLeaveBlank") : "";
283
+ value.setAttribute("aria-label", text("integrationsEnvValue"));
284
+ value.autocomplete = "new-password";
285
+ let keyControl = key;
286
+ if (!existing) {
287
+ const combo = document.createElement("div");
288
+ combo.className = "integration-env-combo";
289
+ const menu = document.createElement("div");
290
+ menu.className = "integration-env-menu";
291
+ menu.id = `integrationEnvMenu-${++envMenuSerial}`;
292
+ menu.role = "listbox";
293
+ menu.hidden = true;
294
+ key.setAttribute("role", "combobox");
295
+ key.setAttribute("aria-autocomplete", "list");
296
+ key.setAttribute("aria-expanded", "false");
297
+ key.setAttribute("aria-controls", menu.id);
298
+ const hide = () => {
299
+ menu.hidden = true;
300
+ key.setAttribute("aria-expanded", "false");
301
+ };
302
+ const choose = (option) => {
303
+ key.value = option.dataset.key;
304
+ hide();
305
+ value.focus();
306
+ };
307
+ const renderMenu = () => {
308
+ closeEnvMenus(menu);
309
+ const used = new Set([...container.querySelectorAll(".integration-env-key")]
310
+ .map((input) => input.value.trim())
311
+ .filter(Boolean));
312
+ const query = key.value.trim().toLowerCase();
313
+ const matches = envFields().filter((field) => !used.has(field.key)).filter((field) => {
314
+ if (!query)
315
+ return true;
316
+ return [field.key, field.label, field.description]
317
+ .some((text) => String(text ?? "").toLowerCase().includes(query));
318
+ });
319
+ menu.replaceChildren(...matches.map((field) => {
320
+ const option = document.createElement("button");
321
+ option.type = "button";
322
+ option.className = "integration-env-option";
323
+ option.dataset.key = field.key;
324
+ option.tabIndex = -1;
325
+ option.setAttribute("role", "option");
326
+ const name = document.createElement("span");
327
+ name.className = "integration-env-option-key";
328
+ name.textContent = field.key;
329
+ option.append(name);
330
+ const detail = [field.label, field.description].filter(Boolean).join(" · ");
331
+ if (detail) {
332
+ const description = document.createElement("span");
333
+ description.className = "integration-env-option-desc";
334
+ description.textContent = detail;
335
+ option.append(description);
336
+ }
337
+ option.addEventListener("mousedown", (event) => event.preventDefault());
338
+ option.addEventListener("click", () => choose(option));
339
+ option.addEventListener("keydown", (event) => {
340
+ const options = [...menu.querySelectorAll(".integration-env-option")];
341
+ const index = options.indexOf(option);
342
+ if (event.key === "ArrowDown") {
343
+ event.preventDefault();
344
+ options[(index + 1) % options.length]?.focus();
345
+ }
346
+ else if (event.key === "ArrowUp") {
347
+ event.preventDefault();
348
+ options[(index - 1 + options.length) % options.length]?.focus();
349
+ }
350
+ else if (event.key === "Escape") {
351
+ event.preventDefault();
352
+ hide();
353
+ key.focus();
354
+ }
355
+ else if (event.key === "Enter") {
356
+ event.preventDefault();
357
+ choose(option);
358
+ }
359
+ });
360
+ return option;
361
+ }));
362
+ menu.hidden = matches.length === 0;
363
+ key.setAttribute("aria-expanded", String(!menu.hidden));
364
+ };
365
+ key.addEventListener("focus", renderMenu);
366
+ key.addEventListener("click", renderMenu);
367
+ key.addEventListener("input", renderMenu);
368
+ key.addEventListener("keydown", (event) => {
369
+ if (event.key === "ArrowDown") {
370
+ event.preventDefault();
371
+ if (menu.hidden)
372
+ renderMenu();
373
+ menu.querySelector(".integration-env-option")?.focus();
374
+ }
375
+ else if (event.key === "Escape") {
376
+ hide();
377
+ }
378
+ });
379
+ key.addEventListener("blur", () => {
380
+ setTimeout(() => { if (!combo.contains(document.activeElement))
381
+ hide(); }, 0);
382
+ });
383
+ combo.append(key, menu);
384
+ keyControl = combo;
385
+ }
386
+ const remove = document.createElement("button");
387
+ remove.type = "button";
388
+ remove.className = "btn ghost small integration-env-remove";
389
+ remove.append(iconNode("subtract"));
390
+ remove.setAttribute("aria-label", text("integrationsRemove"));
391
+ remove.setAttribute("title", text("integrationsRemove"));
392
+ remove.addEventListener("click", () => {
393
+ const currentKey = key.value.trim();
394
+ row.remove();
395
+ onRemove?.(currentKey, existing);
314
396
  });
315
- menu.replaceChildren(...matches.map((field) => {
316
- const option = document.createElement("button");
317
- option.type = "button";
318
- option.className = "integration-env-option";
319
- option.dataset.key = field.key;
320
- option.tabIndex = -1;
321
- option.setAttribute("role", "option");
322
- const name = document.createElement("span");
323
- name.className = "integration-env-option-key";
324
- name.textContent = field.key;
325
- option.append(name);
326
- const detail = [field.label, field.description].filter(Boolean).join(" · ");
327
- if (detail) {
328
- const description = document.createElement("span");
329
- description.className = "integration-env-option-desc";
330
- description.textContent = detail;
331
- option.append(description);
332
- }
333
- option.addEventListener("mousedown", (event) => event.preventDefault());
334
- option.addEventListener("click", () => choose(option));
335
- option.addEventListener("keydown", (event) => {
336
- const options = [...menu.querySelectorAll(".integration-env-option")];
337
- const index = options.indexOf(option);
338
- if (event.key === "ArrowDown") {
339
- event.preventDefault();
340
- options[(index + 1) % options.length]?.focus();
341
- } else if (event.key === "ArrowUp") {
342
- event.preventDefault();
343
- options[(index - 1 + options.length) % options.length]?.focus();
344
- } else if (event.key === "Escape") {
345
- event.preventDefault();
346
- hide();
347
- key.focus();
348
- } else if (event.key === "Enter") {
349
- event.preventDefault();
350
- choose(option);
351
- }
352
- });
353
- return option;
354
- }));
355
- menu.hidden = matches.length === 0;
356
- key.setAttribute("aria-expanded", String(!menu.hidden));
357
- };
358
- key.addEventListener("focus", renderMenu);
359
- key.addEventListener("click", renderMenu);
360
- key.addEventListener("input", renderMenu);
361
- key.addEventListener("keydown", (event) => {
362
- if (event.key === "ArrowDown") {
363
- event.preventDefault();
364
- if (menu.hidden) renderMenu();
365
- menu.querySelector(".integration-env-option")?.focus();
366
- } else if (event.key === "Escape") {
367
- hide();
368
- }
369
- });
370
- key.addEventListener("blur", () => {
371
- setTimeout(() => { if (!combo.contains(document.activeElement)) hide(); }, 0);
372
- });
373
- combo.append(key, menu);
374
- keyControl = combo;
397
+ row.append(keyControl, value, remove);
398
+ container.append(row);
399
+ return row;
375
400
  }
376
- const remove = document.createElement("button");
377
- remove.type = "button";
378
- remove.className = "btn ghost small integration-env-remove";
379
- remove.append(iconNode("subtract"));
380
- remove.setAttribute("aria-label", text("integrationsRemove"));
381
- remove.setAttribute("title", text("integrationsRemove"));
382
- remove.addEventListener("click", () => {
383
- const currentKey = key.value.trim();
384
- row.remove();
385
- onRemove?.(currentKey, existing);
386
- });
387
- row.append(keyControl, value, remove);
388
- container.append(row);
389
- return row;
390
- }
391
-
392
- function readEnv(container) {
393
- const values = {};
394
- for (const row of container.querySelectorAll(".integration-env-row")) {
395
- const key = row.querySelector(".integration-env-key").value.trim();
396
- const value = row.querySelector(".integration-env-value").value;
397
- if (!key && !value) continue;
398
- if (!ENV_KEY.test(key) || Object.hasOwn(values, key)) throw new Error(text("integrationsEnvInvalid"));
399
- if (value !== "") values[key] = value;
401
+ function readEnv(container) {
402
+ const values = {};
403
+ for (const row of container.querySelectorAll(".integration-env-row")) {
404
+ const key = row.querySelector(".integration-env-key").value.trim();
405
+ const value = row.querySelector(".integration-env-value").value;
406
+ if (!key && !value)
407
+ continue;
408
+ if (!ENV_KEY.test(key) || Object.hasOwn(values, key))
409
+ throw new Error(text("integrationsEnvInvalid"));
410
+ if (value !== "")
411
+ values[key] = value;
412
+ }
413
+ return values;
400
414
  }
401
- return values;
402
- }
403
-
404
- function fillPlugins(selected) {
405
- accountPlugin.textContent = "";
406
- const plugins = knownPlugins(data);
407
- if (!plugins.length) {
408
- const option = document.createElement("option");
409
- option.value = ""; option.textContent = text("integrationsPluginFirst");
410
- accountPlugin.append(option);
415
+ function fillPlugins(selected) {
416
+ accountPlugin.textContent = "";
417
+ const plugins = knownPlugins(data);
418
+ if (!plugins.length) {
419
+ const option = document.createElement("option");
420
+ option.value = "";
421
+ option.textContent = text("integrationsPluginFirst");
422
+ accountPlugin.append(option);
423
+ }
424
+ for (const plugin of plugins) {
425
+ const option = document.createElement("option");
426
+ option.value = plugin.pluginId;
427
+ option.textContent = `${plugin.name} · ${plugin.platform}`;
428
+ accountPlugin.append(option);
429
+ }
430
+ accountPlugin.value = plugins.some((plugin) => plugin.pluginId === selected) ? selected : plugins[0]?.pluginId || "";
411
431
  }
412
- for (const plugin of plugins) {
413
- const option = document.createElement("option");
414
- option.value = plugin.pluginId;
415
- option.textContent = `${plugin.name} · ${plugin.platform}`;
416
- accountPlugin.append(option);
432
+ /** Stable once saved; a blank ID is only a convenience for new accounts. */
433
+ function newAccountId(plugin) {
434
+ const prefix = String(plugin?.platform || "account").replace(/[^A-Za-z0-9._-]/g, "") || "account";
435
+ const bytes = crypto.getRandomValues(new Uint8Array(4));
436
+ return `${prefix}-${[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
417
437
  }
418
- accountPlugin.value = plugins.some((plugin) => plugin.pluginId === selected) ? selected : plugins[0]?.pluginId || "";
419
- }
420
-
421
- /** Stable once saved; a blank ID is only a convenience for new accounts. */
422
- function newAccountId(plugin) {
423
- const prefix = String(plugin?.platform || "account").replace(/[^A-Za-z0-9._-]/g, "") || "account";
424
- const bytes = crypto.getRandomValues(new Uint8Array(4));
425
- return `${prefix}-${[...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
426
- }
427
-
428
- function setClearEnv(next) {
429
- clearEnv = next;
430
- accountClear.textContent = text(next ? "integrationsKeepEnv" : "integrationsClearEnv");
431
- accountEnvNote.hidden = !next;
432
- accountEnvNote.textContent = next ? text("integrationsClearEnvActive") : "";
433
- accountAddEnv.disabled = next;
434
- for (const control of accountEnv.querySelectorAll("input, button")) control.disabled = next;
435
- for (const control of accountSchema.querySelectorAll("input, select, button")) control.disabled = next;
436
- }
437
-
438
- function removeStoredKey(key) {
439
- if (!key || !accountDraft) return;
440
- if ((accountDraft.storedKeys || []).includes(key) && !accountDraft.envDelete.includes(key)) {
441
- accountDraft.envDelete.push(key);
438
+ function setClearEnv(next) {
439
+ clearEnv = next;
440
+ accountClear.textContent = text(next ? "integrationsKeepEnv" : "integrationsClearEnv");
441
+ accountEnvNote.hidden = !next;
442
+ accountEnvNote.textContent = next ? text("integrationsClearEnvActive") : "";
443
+ accountAddEnv.disabled = next;
444
+ for (const control of accountEnv.querySelectorAll("input, button"))
445
+ control.disabled = next;
446
+ for (const control of accountSchema.querySelectorAll("input, select, button"))
447
+ control.disabled = next;
442
448
  }
443
- accountDraft.envKeys = (accountDraft.envKeys || []).filter((item) => item !== key);
444
- if (accountDraft.envSet) delete accountDraft.envSet[key];
445
- }
446
-
447
- function syncAccountSchema() {
448
- const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
449
- closeEnvMenus();
450
- renderAccountSchema(accountSchema, plugin, accountDraft?.id ? accountDraft : null, text);
451
- accountSchemaField.hidden = accountSchema.hidden;
452
- // Without a declared schema the raw env rows are the only way to configure
453
- // the account, so keep them open; schema-backed plugins can collapse them.
454
- accountAdvanced.open = accountSchema.hidden;
455
- }
456
-
457
- function openAccount(account = null, presetPlugin = "") {
458
- if (data.editable === false) return;
459
- if (!knownPlugins(data).length) { showPanelError(text("integrationsPluginFirst")); return; }
460
- accountDraft = account ? {
461
- ...account,
462
- storedKeys: [...(account.storedKeys || account.envKeys || [])],
463
- envSet: { ...(account.envSet || {}) },
464
- envDelete: [...(account.envDelete || [])],
465
- } : { id: "", platform: "", pluginId: presetPlugin, envKeys: [], storedKeys: [], envSet: {}, envDelete: [], envClear: false, state: "unknown", lastError: "" };
466
- accountId.value = account?.id || "";
467
- accountId.readOnly = Boolean(account);
468
- hideAccountError();
469
- fillPlugins(account?.pluginId || presetPlugin);
470
- syncAccountSchema();
471
- accountEnv.textContent = "";
472
- const keys = account?.envClear ? account.storedKeys : account?.envKeys || [];
473
- for (const key of keys) addEnvRow(accountEnv, { key }, true, removeStoredKey);
474
- if (!keys.length) addEnvRow(accountEnv);
475
- setClearEnv(Boolean(account?.envClear));
476
- accountDialog.showModal();
477
- accountPlugin.focus();
478
- }
479
-
480
- function closeAccount() {
481
- if (accountDialog.open) accountDialog.close();
482
- accountDraft = null;
483
- }
484
-
485
- accountForm.addEventListener("submit", (event) => {
486
- event.preventDefault();
487
- if (!accountDraft) return;
488
- hideAccountError();
489
- const pluginId = accountPlugin.value;
490
- const plugin = knownPlugins(data).find((item) => item.pluginId === pluginId);
491
- if (!plugin) return showAccountError(text("integrationsAccountInvalid"));
492
- const id = accountDraft.id || accountId.value.trim() || newAccountId(plugin);
493
- if (!IDENTIFIER.test(id)) return showAccountError(text("integrationsAccountInvalid"));
494
- if (data.accounts.some((item) => item.id === id && item.id !== accountDraft.id)) {
495
- return showAccountError(text("integrationsDuplicateAccount"));
449
+ function removeStoredKey(key) {
450
+ if (!key || !accountDraft)
451
+ return;
452
+ if ((accountDraft.storedKeys || []).includes(key) && !accountDraft.envDelete.includes(key)) {
453
+ accountDraft.envDelete.push(key);
454
+ }
455
+ accountDraft.envKeys = (accountDraft.envKeys || []).filter((item) => item !== key);
456
+ if (accountDraft.envSet)
457
+ delete accountDraft.envSet[key];
496
458
  }
497
- let values;
498
- try { values = clearEnv ? {} : readEnv(accountEnv); }
499
- catch (error) { return showAccountError(error); }
500
- let schema;
501
- try { schema = readAccountSchema(accountSchema, text); }
502
- catch (error) { return showAccountError(error); }
503
- // A schema field and a free-form env row can name the same key: the schema wins.
504
- for (const key of schema.keys) delete values[key];
505
- const schemaValues = clearEnv ? {} : schema.values;
506
- const envSet = clearEnv ? {} : { ...(accountDraft.envSet || {}), ...values, ...schemaValues };
507
- const deleted = new Set(clearEnv ? [] : accountDraft.envDelete || []);
508
- for (const key of Object.keys(values)) deleted.delete(key);
509
- for (const key of Object.keys(schemaValues)) deleted.delete(key);
510
- const remaining = (accountDraft.envKeys || []).filter((key) => !deleted.has(key));
511
- const next = {
512
- id,
513
- platform: plugin.platform,
514
- pluginId: plugin.pluginId,
515
- state: accountDraft.state,
516
- lastError: accountDraft.lastError,
517
- envKeys: clearEnv ? [] : [...new Set([...remaining, ...Object.keys(envSet)])],
518
- storedKeys: accountDraft.storedKeys || [],
519
- envSet,
520
- envDelete: clearEnv ? [] : [...deleted].filter((key) => !Object.hasOwn(envSet, key)),
521
- envClear: clearEnv,
522
- };
523
- data.accounts = accountDraft.id
524
- ? data.accounts.map((item) => item.id === accountDraft.id ? next : item)
525
- : [...data.accounts, next];
526
- renderAccounts();
527
- renderPlugins();
528
- closeAccount();
529
- showStatus(text("integrationsAccountSaved"));
530
- });
531
-
532
- async function save() {
533
- if (saving || data.editable === false) return;
534
- if (data.enabled && !enabledInput.checked && !(await app.confirmAction(text("integrationsDisableConfirm")))) {
535
- enabledInput.checked = true;
536
- applyEnabledState();
537
- return;
459
+ function syncAccountSchema() {
460
+ const plugin = knownPlugins(data).find((item) => item.pluginId === accountPlugin.value);
461
+ closeEnvMenus();
462
+ renderAccountSchema(accountSchema, plugin, accountDraft?.id ? accountDraft : null, text);
463
+ accountSchemaField.hidden = accountSchema.hidden;
464
+ // Without a declared schema the raw env rows are the only way to configure
465
+ // the account, so keep them open; schema-backed plugins can collapse them.
466
+ accountAdvanced.open = accountSchema.hidden;
538
467
  }
539
- hidePanelError();
540
- hideRulesError();
541
- if (!data.accounts.length) return showPanelError(text("integrationsNeedAccount"));
542
- const rulesState = rulesSection.current();
543
- let rules;
544
- if (rulesState.editor) {
545
- if (rulesState.errors.length) return;
546
- try { rules = checkRules(rulesState.value, data.accounts, text); }
547
- catch (error) { return rulesSection.showMessage(error.message); }
548
- } else {
549
- try { rules = parseRules(rulesState.text, data.accounts, text); }
550
- catch (error) { return showRulesError(error.message); }
468
+ function openAccount(account = null, presetPlugin = "") {
469
+ if (data.editable === false)
470
+ return;
471
+ if (!knownPlugins(data).length) {
472
+ showPanelError(text("integrationsPluginFirst"));
473
+ return;
474
+ }
475
+ accountDraft = account ? {
476
+ ...account,
477
+ storedKeys: [...(account.storedKeys || account.envKeys || [])],
478
+ envSet: { ...(account.envSet || {}) },
479
+ envDelete: [...(account.envDelete || [])],
480
+ } : { id: "", platform: "", pluginId: presetPlugin, envKeys: [], storedKeys: [], envSet: {}, envDelete: [], envClear: false, state: "unknown", lastError: "" };
481
+ accountId.value = account?.id || "";
482
+ accountId.readOnly = Boolean(account);
483
+ hideAccountError();
484
+ fillPlugins(account?.pluginId || presetPlugin);
485
+ syncAccountSchema();
486
+ accountEnv.textContent = "";
487
+ const keys = account?.envClear ? account.storedKeys : account?.envKeys || [];
488
+ for (const key of keys)
489
+ addEnvRow(accountEnv, { key }, true, removeStoredKey);
490
+ if (!keys.length)
491
+ addEnvRow(accountEnv);
492
+ setClearEnv(Boolean(account?.envClear));
493
+ accountDialog.showModal();
494
+ accountPlugin.focus();
551
495
  }
552
- const inboundState = inboundSection.current();
553
- let inbound;
554
- if (inboundState.editor) {
555
- if (inboundState.errors.length) return;
556
- try { inbound = checkInbound(inboundState.value, data.accounts); }
557
- catch (error) { return inboundSection.showMessage(error.message); }
558
- } else {
559
- try { inbound = parseInbound(inboundState.text, data.accounts, text); }
560
- catch (error) { return inboundSection.showMessage(error.message); }
496
+ function closeAccount() {
497
+ if (accountDialog.open)
498
+ accountDialog.close();
499
+ accountDraft = null;
561
500
  }
562
- const inboundChanged = JSON.stringify(inbound) !== initialInbound;
563
- setSaving(true);
564
- try {
565
- adopt(await app.api("/channeld/integration", {
566
- method: "PUT",
567
- body: JSON.stringify({
568
- enabled: enabledInput.checked,
569
- accounts: data.accounts.map(accountBody),
570
- rules,
571
- ...(inboundChanged ? { inbound } : {}),
572
- }),
573
- }));
574
- const enabled = data.enabled;
575
- await load(true);
576
- if (panelError.hidden) showStatus(text(enabled ? "integrationsSavedEnabled" : "integrationsSavedDisabled"));
577
- } catch (error) { showPanelError(error); }
578
- finally { setSaving(false); }
579
- }
580
-
581
- function openUpload() {
582
- if (data.editable === false) return;
583
- pluginForm.reset();
584
- pluginUploadSource = "";
585
- pluginUploadName = "";
586
- hidePluginError();
587
- pluginDialog.showModal();
588
- pluginFile.focus();
589
- }
590
-
591
- pluginFile.addEventListener("change", async () => {
592
- const file = pluginFile.files?.[0];
593
- pluginUploadSource = "";
594
- pluginUploadName = "";
595
- if (!file) return;
596
- if (file.size > MAX_SOURCE) return showPluginError(text("integrationsSourceTooLarge"));
597
- try {
598
- pluginUploadSource = await file.text();
599
- pluginUploadName = file.name;
600
- hidePluginError();
601
- } catch (error) { showPluginError(error); }
602
- });
603
-
604
- pluginForm.addEventListener("submit", async (event) => {
605
- event.preventDefault();
606
- hidePluginError();
607
- const name = pluginUploadName || "plugin.js", source = pluginUploadSource;
608
- if (!PLUGIN_NAME.test(name)) return showPluginError(text("integrationsNameRequired"));
609
- if (!source.trim()) return showPluginError(text("integrationsSourceRequired"));
610
- if (new TextEncoder().encode(source).length > MAX_SOURCE) return showPluginError(text("integrationsSourceTooLarge"));
611
- const submit = $("#btnSaveIntegrationPlugin");
612
- submit.disabled = true;
613
- try {
614
- const result = await app.api("/channeld/plugins", {
615
- method: "POST",
616
- body: JSON.stringify({ name, source }),
617
- });
618
- const plugin = {
619
- pluginId: result.pluginId,
620
- name: result.name,
621
- platform: result.platform,
622
- ...(result.displayName ? { displayName: result.displayName } : {}),
623
- ...(result.account ? { account: result.account } : {}),
624
- };
625
- data.plugins = [...data.plugins.filter((item) => item.pluginId !== plugin.pluginId), plugin];
626
- renderPlugins();
627
- pluginDialog.close();
628
- showStatus(text("integrationsUploaded"));
629
- openAccount(null, plugin.pluginId);
630
- } catch (error) { showPluginError(error); }
631
- finally { submit.disabled = false; }
632
- });
633
-
634
- $("#btnAddAccountEnv").addEventListener("click", () => addEnvRow(accountEnv).querySelector(".integration-env-key").focus());
635
- accountPlugin.addEventListener("change", syncAccountSchema);
636
- accountClear.addEventListener("click", () => setClearEnv(!clearEnv));
637
- enabledInput.addEventListener("change", applyEnabledState);
638
- addAccountButton.addEventListener("click", () => openAccount(null));
639
- uploadPluginButton.addEventListener("click", openUpload);
640
- $("#btnRefreshIntegrations").addEventListener("click", () => void load(true));
641
- saveButton.addEventListener("click", () => void save());
642
- $("#btnCloseIntegrationAccount").addEventListener("click", closeAccount);
643
- $("#btnCancelIntegrationAccount").addEventListener("click", closeAccount);
644
- accountDialog.addEventListener("cancel", (event) => { event.preventDefault(); closeAccount(); });
645
- $("#btnCloseIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
646
- $("#btnCancelIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
647
- pluginDialog.addEventListener("cancel", (event) => { event.preventDefault(); pluginDialog.close(); });
648
- }
501
+ accountForm.addEventListener("submit", (event) => {
502
+ event.preventDefault();
503
+ if (!accountDraft)
504
+ return;
505
+ hideAccountError();
506
+ const pluginId = accountPlugin.value;
507
+ const plugin = knownPlugins(data).find((item) => item.pluginId === pluginId);
508
+ if (!plugin)
509
+ return showAccountError(text("integrationsAccountInvalid"));
510
+ const id = accountDraft.id || accountId.value.trim() || newAccountId(plugin);
511
+ if (!IDENTIFIER.test(id))
512
+ return showAccountError(text("integrationsAccountInvalid"));
513
+ if (data.accounts.some((item) => item.id === id && item.id !== accountDraft.id)) {
514
+ return showAccountError(text("integrationsDuplicateAccount"));
515
+ }
516
+ let values;
517
+ try {
518
+ values = clearEnv ? {} : readEnv(accountEnv);
519
+ }
520
+ catch (error) {
521
+ return showAccountError(error);
522
+ }
523
+ let schema;
524
+ try {
525
+ schema = readAccountSchema(accountSchema, text);
526
+ }
527
+ catch (error) {
528
+ return showAccountError(error);
529
+ }
530
+ // A schema field and a free-form env row can name the same key: the schema wins.
531
+ for (const key of schema.keys)
532
+ delete values[key];
533
+ const schemaValues = clearEnv ? {} : schema.values;
534
+ const envSet = clearEnv ? {} : { ...(accountDraft.envSet || {}), ...values, ...schemaValues };
535
+ const deleted = new Set(clearEnv ? [] : accountDraft.envDelete || []);
536
+ for (const key of Object.keys(values))
537
+ deleted.delete(key);
538
+ for (const key of Object.keys(schemaValues))
539
+ deleted.delete(key);
540
+ const remaining = (accountDraft.envKeys || []).filter((key) => !deleted.has(key));
541
+ const next = {
542
+ id,
543
+ platform: plugin.platform,
544
+ pluginId: plugin.pluginId,
545
+ state: accountDraft.state,
546
+ lastError: accountDraft.lastError,
547
+ envKeys: clearEnv ? [] : [...new Set([...remaining, ...Object.keys(envSet)])],
548
+ storedKeys: accountDraft.storedKeys || [],
549
+ envSet,
550
+ envDelete: clearEnv ? [] : [...deleted].filter((key) => !Object.hasOwn(envSet, key)),
551
+ envClear: clearEnv,
552
+ };
553
+ data.accounts = accountDraft.id
554
+ ? data.accounts.map((item) => item.id === accountDraft.id ? next : item)
555
+ : [...data.accounts, next];
556
+ renderAccounts();
557
+ renderPlugins();
558
+ closeAccount();
559
+ showStatus(text("integrationsAccountSaved"));
560
+ });
561
+ async function save() {
562
+ if (saving || data.editable === false)
563
+ return;
564
+ if (data.enabled && !enabledInput.checked && !(await app.confirmAction(text("integrationsDisableConfirm")))) {
565
+ enabledInput.checked = true;
566
+ applyEnabledState();
567
+ return;
568
+ }
569
+ hidePanelError();
570
+ hideRulesError();
571
+ if (!data.accounts.length)
572
+ return showPanelError(text("integrationsNeedAccount"));
573
+ const rulesState = rulesSection.current();
574
+ let rules;
575
+ if (rulesState.editor) {
576
+ if (rulesState.errors.length)
577
+ return;
578
+ try {
579
+ rules = checkRules(rulesState.value, data.accounts, text);
580
+ }
581
+ catch (error) {
582
+ return rulesSection.showMessage(error.message);
583
+ }
584
+ }
585
+ else {
586
+ try {
587
+ rules = parseRules(rulesState.text, data.accounts, text);
588
+ }
589
+ catch (error) {
590
+ return showRulesError(error.message);
591
+ }
592
+ }
593
+ const inboundState = inboundSection.current();
594
+ let inbound;
595
+ if (inboundState.editor) {
596
+ if (inboundState.errors.length)
597
+ return;
598
+ try {
599
+ inbound = checkInbound(inboundState.value, data.accounts);
600
+ }
601
+ catch (error) {
602
+ return inboundSection.showMessage(error.message);
603
+ }
604
+ }
605
+ else {
606
+ try {
607
+ inbound = parseInbound(inboundState.text, data.accounts, text);
608
+ }
609
+ catch (error) {
610
+ return inboundSection.showMessage(error.message);
611
+ }
612
+ }
613
+ const inboundChanged = JSON.stringify(inbound) !== initialInbound;
614
+ setSaving(true);
615
+ try {
616
+ adopt(await app.api("/channeld/integration", {
617
+ method: "PUT",
618
+ body: JSON.stringify({
619
+ enabled: enabledInput.checked,
620
+ accounts: data.accounts.map(accountBody),
621
+ rules,
622
+ ...(inboundChanged ? { inbound } : {}),
623
+ }),
624
+ }));
625
+ const enabled = data.enabled;
626
+ await load(true);
627
+ if (panelError.hidden)
628
+ showStatus(text(enabled ? "integrationsSavedEnabled" : "integrationsSavedDisabled"));
629
+ }
630
+ catch (error) {
631
+ showPanelError(error);
632
+ }
633
+ finally {
634
+ setSaving(false);
635
+ }
636
+ }
637
+ function openUpload() {
638
+ if (data.editable === false)
639
+ return;
640
+ pluginForm.reset();
641
+ pluginUploadSource = "";
642
+ pluginUploadName = "";
643
+ hidePluginError();
644
+ pluginDialog.showModal();
645
+ pluginFile.focus();
646
+ }
647
+ pluginFile.addEventListener("change", async () => {
648
+ const file = pluginFile.files?.[0];
649
+ pluginUploadSource = "";
650
+ pluginUploadName = "";
651
+ if (!file)
652
+ return;
653
+ if (file.size > MAX_SOURCE)
654
+ return showPluginError(text("integrationsSourceTooLarge"));
655
+ try {
656
+ pluginUploadSource = await file.text();
657
+ pluginUploadName = file.name;
658
+ hidePluginError();
659
+ }
660
+ catch (error) {
661
+ showPluginError(error);
662
+ }
663
+ });
664
+ pluginForm.addEventListener("submit", async (event) => {
665
+ event.preventDefault();
666
+ hidePluginError();
667
+ const name = pluginUploadName || "plugin.js", source = pluginUploadSource;
668
+ if (!PLUGIN_NAME.test(name))
669
+ return showPluginError(text("integrationsNameRequired"));
670
+ if (!source.trim())
671
+ return showPluginError(text("integrationsSourceRequired"));
672
+ if (new TextEncoder().encode(source).length > MAX_SOURCE)
673
+ return showPluginError(text("integrationsSourceTooLarge"));
674
+ const submit = $("#btnSaveIntegrationPlugin");
675
+ submit.disabled = true;
676
+ try {
677
+ const result = await app.api("/channeld/plugins", {
678
+ method: "POST",
679
+ body: JSON.stringify({ name, source }),
680
+ });
681
+ const plugin = {
682
+ pluginId: result.pluginId,
683
+ name: result.name,
684
+ platform: result.platform,
685
+ ...(result.displayName ? { displayName: result.displayName } : {}),
686
+ ...(result.account ? { account: result.account } : {}),
687
+ };
688
+ data.plugins = [...data.plugins.filter((item) => item.pluginId !== plugin.pluginId), plugin];
689
+ renderPlugins();
690
+ pluginDialog.close();
691
+ showStatus(text("integrationsUploaded"));
692
+ openAccount(null, plugin.pluginId);
693
+ }
694
+ catch (error) {
695
+ showPluginError(error);
696
+ }
697
+ finally {
698
+ submit.disabled = false;
699
+ }
700
+ });
701
+ $("#btnAddAccountEnv").addEventListener("click", () => addEnvRow(accountEnv).querySelector(".integration-env-key").focus());
702
+ accountPlugin.addEventListener("change", syncAccountSchema);
703
+ accountClear.addEventListener("click", () => setClearEnv(!clearEnv));
704
+ enabledInput.addEventListener("change", applyEnabledState);
705
+ addAccountButton.addEventListener("click", () => openAccount(null));
706
+ uploadPluginButton.addEventListener("click", openUpload);
707
+ $("#btnRefreshIntegrations").addEventListener("click", () => void load(true));
708
+ saveButton.addEventListener("click", () => void save());
709
+ $("#btnCloseIntegrationAccount").addEventListener("click", closeAccount);
710
+ $("#btnCancelIntegrationAccount").addEventListener("click", closeAccount);
711
+ accountDialog.addEventListener("cancel", (event) => { event.preventDefault(); closeAccount(); });
712
+ $("#btnCloseIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
713
+ $("#btnCancelIntegrationPlugin").addEventListener("click", () => pluginDialog.close());
714
+ pluginDialog.addEventListener("cancel", (event) => { event.preventDefault(); pluginDialog.close(); });
715
+ }