create-heresay 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.14",
3
+ "version": "0.2.15",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.14
1
+ 0.2.15
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
7
7
  import { CLAIM_TTL_MS, LIMITS, PLATFORMS, isPlatform, } from './types.js';
8
+ import { notify } from './notifications.js';
8
9
  const json = (status, body) => ({ status, body });
9
10
  const str = (v, max) => {
10
11
  if (typeof v !== 'string')
@@ -264,6 +265,7 @@ export async function agent(p, req, deps, body, prompt, createProject, toReporte
264
265
  if (refused)
265
266
  return json(409, { error: `in progress in ${refused}`, claimed_by: refused });
266
267
  deps.log('api.brief_handed_off', { from: repoName, to, report_id: t.id });
268
+ await notify('handoff', app, t.id, deps);
267
269
  return json(200, { brief: summary(t, app, now) });
268
270
  }
269
271
  if (p[2] === 'fixed') {
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { agent, normaliseRepo, reposFor, tokens } from './agent.js';
3
+ import { notificationSettings, notify } from './notifications.js';
3
4
  import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isFramework, isPlatform, isReportType, isSignIn, toReporterView, } from './types.js';
4
5
  /**
5
6
  * Fixed windows. The public endpoint has no login, so each of these is a separate line of
@@ -137,7 +138,12 @@ async function route(req, deps) {
137
138
  return preflight(req);
138
139
  // Coding agents, with a per-repo token instead of a person's sign-in.
139
140
  if (p[0] === 'agent') {
140
- return agent(p.slice(1), req, deps, parseBody(req.body), agentPrompt, (by, body) => createProject({ email: by, role: 'member', added_at: '', added_by: null }, { ...req, body }, deps), async (project, id, note, by) => transitionRes(await deps.store.move(project.id, id, 'accepted', 'fixed', { fix_note: note, triaged_by: by, updated_at: new Date(deps.now()).toISOString() })));
141
+ return agent(p.slice(1), req, deps, parseBody(req.body), agentPrompt, (by, body) => createProject({ email: by, role: 'member', added_at: '', added_by: null }, { ...req, body }, deps), async (project, id, note, by) => {
142
+ const result = await deps.store.move(project.id, id, 'accepted', 'fixed', { fix_note: note, triaged_by: by, updated_at: new Date(deps.now()).toISOString() });
143
+ if (result.ok)
144
+ await notify('fixed', project, id, deps);
145
+ return transitionRes(result);
146
+ });
141
147
  }
142
148
  // The team, signed in to the dashboard.
143
149
  const who = await caller(req, deps);
@@ -156,6 +162,11 @@ async function route(req, deps) {
156
162
  }
157
163
  if (p[0] === 'team')
158
164
  return team(p, member, req, deps);
165
+ if (p[0] === 'notifications') {
166
+ if (member.role !== 'owner')
167
+ return json(403, { error: 'Only an owner can manage notifications.' });
168
+ return notificationSettings(p, req, deps, parseBody(req.body));
169
+ }
159
170
  if (p[0] === 'agent-tokens')
160
171
  return tokens(p, member, req, deps, parseBody(req.body));
161
172
  if (p[0] === 'projects' && p.length === 1) {
@@ -328,6 +339,7 @@ async function submit(req, deps) {
328
339
  await deps.store.updateProject(project.id, { framework: report.context.framework, framework_detected: true });
329
340
  }
330
341
  deps.log('api.report_created', { project_id: project.id, report_id: report.id, type: report.type });
342
+ await notify('new_report', project, report.id, deps);
331
343
  return json(201, { report: toReporterView(report) }, headers);
332
344
  }
333
345
  /**
@@ -532,6 +544,9 @@ async function triage(project, report_id, action, uid, req, deps) {
532
544
  return json(404, { error: 'not found' });
533
545
  }
534
546
  deps.log('api.report_triaged', { project_id: project.id, report_id, action, ok: t.ok });
547
+ if (t.ok && (action === 'accept' || action === 'fixed')) {
548
+ await notify(action === 'accept' ? 'accepted' : 'fixed', project, report_id, deps);
549
+ }
535
550
  return transitionRes(t);
536
551
  }
537
552
  //# sourceMappingURL=handler.js.map
@@ -0,0 +1,205 @@
1
+ export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
2
+ export const defaultNotifications = () => ({
3
+ events: { new_report: true, accepted: false, fixed: true, handoff: true },
4
+ telegram: { enabled: false, token: null, chat_id: '' },
5
+ cliq: { enabled: false, token: null, endpoint: '' },
6
+ });
7
+ /** Credentials never leave the server, including in save responses. */
8
+ export function notificationView(settings) {
9
+ return {
10
+ events: settings.events,
11
+ telegram: { enabled: settings.telegram.enabled, configured: !!settings.telegram.token, chat_id: settings.telegram.chat_id },
12
+ cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
13
+ };
14
+ }
15
+ class SettingsError extends Error {
16
+ }
17
+ const object = (v) => {
18
+ if (!v || typeof v !== 'object' || Array.isArray(v))
19
+ throw new SettingsError('Invalid notification settings.');
20
+ return v;
21
+ };
22
+ const field = (v, max) => {
23
+ if (typeof v !== 'string' || v.length > max)
24
+ throw new SettingsError('Invalid notification field.');
25
+ return v.trim();
26
+ };
27
+ const boolean = (v) => {
28
+ if (typeof v !== 'boolean')
29
+ throw new SettingsError('Notification switches must be true or false.');
30
+ return v;
31
+ };
32
+ /** Only Zoho's message endpoints; redirects and arbitrary webhook hosts are not allowed. */
33
+ const CLIQ_HOSTS = new Set([
34
+ 'cliq.zoho.com', 'cliq.zoho.in', 'cliq.zoho.eu', 'cliq.zoho.com.au',
35
+ 'cliq.zoho.jp', 'cliq.zohocloud.ca', 'cliq.zoho.com.cn', 'cliq.zoho.sa',
36
+ 'cliq.zoho.uk', 'cliq.zoho.ae', 'cliq.zoho.sg',
37
+ ]);
38
+ export function validCliqEndpoint(endpoint) {
39
+ try {
40
+ const u = new URL(endpoint);
41
+ return u.protocol === 'https:' && !u.username && !u.password && !u.port && !u.search && !u.hash
42
+ && CLIQ_HOSTS.has(u.hostname)
43
+ && /^\/api\/v2\/(bots|channelsbyname)\/[A-Za-z0-9_-]+\/message$/.test(u.pathname);
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /** Patch inside updateInstance: blank/omitted tokens retain the saved secret; null removes it. */
50
+ export function patchNotifications(current, body) {
51
+ const next = structuredClone(current);
52
+ if (body.events !== undefined) {
53
+ const events = object(body.events);
54
+ for (const event of NOTIFICATION_EVENTS)
55
+ if (events[event] !== undefined)
56
+ next.events[event] = boolean(events[event]);
57
+ }
58
+ for (const provider of ['telegram', 'cliq']) {
59
+ if (body[provider] === undefined)
60
+ continue;
61
+ const patch = object(body[provider]);
62
+ const target = next[provider];
63
+ if (patch.enabled !== undefined)
64
+ target.enabled = boolean(patch.enabled);
65
+ if (patch.token === null)
66
+ target.token = null;
67
+ else if (patch.token !== undefined) {
68
+ const token = field(patch.token, 512);
69
+ if (token) {
70
+ if (provider === 'telegram' ? !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
71
+ throw new SettingsError(`Invalid ${provider === 'telegram' ? 'Telegram bot' : 'Cliq webhook'} token.`);
72
+ }
73
+ target.token = token;
74
+ }
75
+ }
76
+ if (provider === 'telegram' && patch.chat_id !== undefined)
77
+ next.telegram.chat_id = field(patch.chat_id, 100);
78
+ if (provider === 'cliq' && patch.endpoint !== undefined)
79
+ next.cliq.endpoint = field(patch.endpoint, 300);
80
+ }
81
+ if (next.telegram.chat_id && !/^(?:-?\d+|@[A-Za-z][A-Za-z0-9_]{4,})$/.test(next.telegram.chat_id)) {
82
+ throw new SettingsError('Enter a Telegram chat ID or @channel username.');
83
+ }
84
+ if (next.cliq.endpoint && !validCliqEndpoint(next.cliq.endpoint)) {
85
+ throw new SettingsError('Use a Zoho Cliq bot or channel message endpoint, without a query string.');
86
+ }
87
+ if (next.telegram.enabled && (!next.telegram.token || !next.telegram.chat_id)) {
88
+ throw new SettingsError('Telegram needs a bot token and a chat ID.');
89
+ }
90
+ if (next.cliq.enabled && (!next.cliq.token || !next.cliq.endpoint)) {
91
+ throw new SettingsError('Cliq needs a webhook token and a message endpoint.');
92
+ }
93
+ return next;
94
+ }
95
+ export async function notificationSettings(p, req, deps, body) {
96
+ const json = (status, body) => ({ status, body, headers: { 'cache-control': 'no-store' } });
97
+ if (p.length === 1 && req.method === 'GET') {
98
+ const settings = (await deps.store.getInstance()).notifications ?? defaultNotifications();
99
+ return json(200, { notifications: notificationView(settings) });
100
+ }
101
+ if (p.length === 1 && req.method === 'PATCH') {
102
+ try {
103
+ const instance = await deps.store.updateInstance((cur) => ({
104
+ ...cur, notifications: patchNotifications(cur.notifications ?? defaultNotifications(), body),
105
+ }));
106
+ return json(200, { notifications: notificationView(instance.notifications) });
107
+ }
108
+ catch (error) {
109
+ // Validation messages are ours; never expose backend exceptions or credentials.
110
+ if (error instanceof SettingsError) {
111
+ return json(400, { error: error.message });
112
+ }
113
+ throw error;
114
+ }
115
+ }
116
+ if (p.length === 2 && p[1] === 'test' && req.method === 'POST') {
117
+ const provider = body.provider;
118
+ if (provider !== 'telegram' && provider !== 'cliq')
119
+ return json(400, { error: 'Choose Telegram or Cliq.' });
120
+ const settings = (await deps.store.getInstance()).notifications ?? defaultNotifications();
121
+ const target = settings[provider];
122
+ if (!target.enabled)
123
+ return json(400, { error: 'Save and enable this destination first.' });
124
+ const now = deps.now(), start = Math.floor(now / 60_000) * 60_000;
125
+ if (!await deps.store.hit(`notification-test:${provider}:${start}`, 3, start + 60_000)) {
126
+ return json(429, { error: 'Wait a minute before sending another test.' });
127
+ }
128
+ if (!deps.sendNotification)
129
+ return json(503, { error: 'Notification delivery is unavailable.' });
130
+ try {
131
+ await deps.sendNotification(provider, target, 'Heresay notifications are connected. You will receive the events selected in Notifications.');
132
+ return json(200, { ok: true });
133
+ }
134
+ catch {
135
+ return json(502, { error: 'Test could not be delivered. Check the token, destination, and bot permissions, then try again.' });
136
+ }
137
+ }
138
+ return json(404, { error: 'not found' });
139
+ }
140
+ /** Metadata only: open reports and reporter details must never flow into an integration. */
141
+ export async function notify(event, project, reportId, deps) {
142
+ try {
143
+ const settings = (await deps.store.getInstance())?.notifications;
144
+ if (!settings?.events[event] || !deps.sendNotification)
145
+ return;
146
+ const labels = {
147
+ new_report: 'A new report needs your review', accepted: 'A report was accepted for a coding agent',
148
+ fixed: 'A report was marked fixed', handoff: 'A coding agent handed off a report',
149
+ };
150
+ const origin = deps.selfOrigins?.[0];
151
+ const text = `Heresay: ${labels[event]}.\nApp: ${project.name}\nReport: ${reportId}`
152
+ + (origin ? `\n${origin}/app/#/apps/${encodeURIComponent(project.id)}` : '');
153
+ await Promise.all(['telegram', 'cliq'].map(async (provider) => {
154
+ if (!settings[provider].enabled)
155
+ return;
156
+ try {
157
+ await deps.sendNotification(provider, settings[provider], text);
158
+ deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
159
+ }
160
+ catch {
161
+ // Transport errors may contain credential-bearing URLs. Never log those errors.
162
+ deps.log('api.notification_failed', { provider, notification_event: event, project_id: project.id, report_id: reportId });
163
+ }
164
+ }));
165
+ }
166
+ catch {
167
+ // A notification outage must not turn a saved report/status change into a failed request.
168
+ deps.log('api.notification_failed', { notification_event: event, project_id: project.id, report_id: reportId });
169
+ }
170
+ }
171
+ /** Shared HTTP transport; a backend adapter supplies this to the portable core. */
172
+ export function notificationSender(http = fetch) {
173
+ return async (provider, destination, text) => {
174
+ let url, body;
175
+ if (!destination.token)
176
+ throw new Error('Notification token missing.');
177
+ if (provider === 'telegram' && 'chat_id' in destination) {
178
+ url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
179
+ body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true } };
180
+ }
181
+ else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
182
+ const u = new URL(destination.endpoint);
183
+ u.searchParams.set('zapikey', destination.token);
184
+ url = u.href;
185
+ body = { text };
186
+ }
187
+ else {
188
+ throw new Error('Invalid notification destination.');
189
+ }
190
+ // Await within the request so serverless runtimes cannot stop before delivery. Bounded,
191
+ // with no retries: report creation and triage are never rolled back by a provider outage.
192
+ const response = await http(url, {
193
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
194
+ signal: AbortSignal.timeout(5000), redirect: 'error',
195
+ });
196
+ if (!response.ok)
197
+ throw new Error('Notification provider rejected the message.');
198
+ if (provider === 'telegram') {
199
+ const result = await response.json();
200
+ if (result.ok !== true)
201
+ throw new Error('Telegram rejected the message.');
202
+ }
203
+ };
204
+ }
205
+ //# sourceMappingURL=notifications.js.map
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.14';
2
+ export const VERSION = '0.2.15';
3
3
  //# sourceMappingURL=version.js.map
@@ -8,6 +8,7 @@ import { auth, db } from './admin.js';
8
8
  import { FirestoreStore } from './firestore-store.js';
9
9
  import { handle } from '../../core/handler.js';
10
10
  import { VERSION } from '../../core/version.js';
11
+ import { notificationSender } from '../../core/notifications.js';
11
12
  const deps = {
12
13
  store: new FirestoreStore(db),
13
14
  async verifyIdToken(token) {
@@ -23,6 +24,7 @@ const deps = {
23
24
  log: (event, fields) => logger.info(event, { event, ...fields }),
24
25
  version: VERSION,
25
26
  selfOrigins: selfOrigins(),
27
+ sendNotification: notificationSender(),
26
28
  };
27
29
  function selfOrigins() {
28
30
  const id = process.env.GCLOUD_PROJECT;
@@ -9,7 +9,7 @@
9
9
  "scripts": {
10
10
  "build": "tsc -p tsconfig.json",
11
11
  "typecheck": "tsc -p tsconfig.json --noEmit",
12
- "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/store-memory.test.js'",
12
+ "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js'",
13
13
  "build:test": "tsc -p tsconfig.test.json"
14
14
  },
15
15
  "dependencies": {
@@ -44,6 +44,7 @@
44
44
  <nav class="tabs" aria-label="Main">
45
45
  <a href="#/" data-nav="apps">Apps</a>
46
46
  <a href="#/team" data-nav="team">Team</a>
47
+ <a href="#/notifications" data-nav="notifications">Notifications</a>
47
48
  </nav>
48
49
  <span class="spacer"></span>
49
50
  <span id="who" class="who"></span>
@@ -328,3 +328,17 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
328
328
  .am-titlebar i { width:11px; height:11px; border-radius:50%; background:#ff5f57; } .am-titlebar i:nth-child(2) { background:#febc2e; } .am-titlebar i:nth-child(3) { background:#28c840; }
329
329
  .am-titlebar span { flex:1; text-align:center; margin-right:40px; }
330
330
  .am-mac .am-content h3 { font-size:22px; }
331
+
332
+ /* notification settings */
333
+ .notification-form { max-width:none; }
334
+ .notification-form .notification-choice { display:flex; align-items:flex-start; gap:12px; margin:14px 0; }
335
+ .notification-choice input[type=checkbox] { width:18px; height:18px; flex:none; margin:3px 0 0; accent-color:var(--acc); }
336
+ .notification-choice .hint { display:block; margin:2px 0 0; }
337
+ .notification-form input[type=text], .notification-form input[type=password] { width:100%; min-width:0; }
338
+ .notification-form .row { margin-top:22px; }
339
+ @media (max-width:600px) {
340
+ .top { flex-wrap:wrap; gap:8px 12px; padding:12px 16px; }
341
+ .top .tabs { order:5; width:100%; }
342
+ .top .tabs a { padding:6px 10px; }
343
+ .top .who { max-width:130px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
344
+ }
@@ -200,13 +200,15 @@
200
200
  var query = new URLSearchParams(hash.split('?')[1] || '');
201
201
  var parts = hash.split('?')[0].split('/').filter(Boolean);
202
202
  document.querySelectorAll('[data-nav]').forEach(function (a) {
203
- a.setAttribute('aria-current', String((parts[0] === 'team') === (a.dataset.nav === 'team')));
203
+ var active = parts[0] === 'team' || parts[0] === 'notifications' ? parts[0] : 'apps';
204
+ a.setAttribute('aria-current', String(active === a.dataset.nav));
204
205
  });
205
206
  var view = $('view');
206
207
  view.textContent = '';
207
208
  view.appendChild(loading());
208
209
  view.classList.remove('wide');
209
210
  if (parts[0] === 'team') return teamView(view);
211
+ if (parts[0] === 'notifications') return notificationsView(view);
210
212
  if (parts[0] === 'connect') return connectView(view, query);
211
213
  if (parts[0] === 'new') return newAppView(view, parts[1], query);
212
214
  if (parts[0] === 'apps' && parts[1]) {
@@ -1536,6 +1538,117 @@
1536
1538
  repo.focus();
1537
1539
  }
1538
1540
 
1541
+ // ---- notifications ---------------------------------------------------------------------
1542
+
1543
+ function notificationsView(view) {
1544
+ view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Notifications' })]));
1545
+ view.appendChild(el('p', { class: 'mute', text: 'Know when a report needs a hearing, or when work moves forward. These settings apply to every app in this Heresay.' }));
1546
+ if (me.role !== 'owner') {
1547
+ view.appendChild(el('section', { class: 'card' }, [el('p', { text: 'An owner can connect Telegram or Zoho Cliq and choose which events your team receives.' }), el('a', { href: '#/team', text: 'See team owners' })]));
1548
+ return;
1549
+ }
1550
+ var content = el('div');
1551
+ view.appendChild(content);
1552
+ api('GET', '/notifications').then(function (b) {
1553
+ var settings = b.notifications;
1554
+ var choices = [
1555
+ ['new_report', 'New reports', 'A new report is waiting for a person to review it.'],
1556
+ ['accepted', 'Accepted reports', 'A person approved a report for a coding agent.'],
1557
+ ['fixed', 'Reports marked fixed', 'A teammate or coding agent marked a report fixed.'],
1558
+ ['handoff', 'Agent handoffs', 'An agent handed accepted work to another repo.'],
1559
+ ];
1560
+ var eventInputs = {};
1561
+ var eventsMsg = el('p', { role: 'status' });
1562
+ var eventSave = el('button', { class: 'btn primary', type: 'submit', text: 'Save events' });
1563
+ var eventsForm = el('form', { class: 'form notification-form' }, choices.map(function (choice) {
1564
+ var input = eventInputs[choice[0]] = el('input', { type: 'checkbox', name: choice[0], checked: settings.events[choice[0]] });
1565
+ return el('label', { class: 'notification-choice' }, [input, el('span', {}, [el('b', { text: choice[1] }), el('span', { class: 'hint', text: choice[2] })])]);
1566
+ }).concat([el('div', { class: 'row' }, [eventSave]), eventsMsg]));
1567
+ eventsForm.onsubmit = function (e) {
1568
+ e.preventDefault();
1569
+ var events = {};
1570
+ Object.keys(eventInputs).forEach(function (key) { events[key] = eventInputs[key].checked; eventInputs[key].disabled = true; });
1571
+ eventSave.disabled = true;
1572
+ eventsMsg.className = 'hint'; eventsMsg.textContent = 'Saving…';
1573
+ api('PATCH', '/notifications', { events: events }).then(function () {
1574
+ eventsMsg.className = 'ok-msg'; eventsMsg.textContent = 'Notification events saved.';
1575
+ }).catch(function (x) { eventsMsg.className = 'err'; eventsMsg.textContent = x.message; }).finally(function () {
1576
+ eventSave.disabled = false;
1577
+ Object.keys(eventInputs).forEach(function (key) { eventInputs[key].disabled = false; });
1578
+ });
1579
+ };
1580
+ content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
1581
+ content.appendChild(el('p', { class: 'hint', text: 'Alerts include the app name, event, report ID, and a link to the dashboard. Reporter text and contact details stay in Heresay.' }));
1582
+ destination('telegram', 'Telegram', settings.telegram);
1583
+ destination('cliq', 'Zoho Cliq', settings.cliq);
1584
+
1585
+ function destination(provider, title, saved) {
1586
+ var telegram = provider === 'telegram', dirty = false;
1587
+ var enabled = el('input', { type: 'checkbox', name: provider + '_enabled', checked: saved.enabled });
1588
+ var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
1589
+ var address = el('input', { type: 'text', name: telegram ? 'chat_id' : 'endpoint', value: telegram ? saved.chat_id : saved.endpoint, maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
1590
+ var tokenHint = el('p', { class: 'hint' });
1591
+ var message = el('p', { role: 'status' });
1592
+ var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
1593
+ var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
1594
+ var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
1595
+ var form = el('form', { class: 'form notification-form' }, [
1596
+ el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1597
+ el('label', {}, [telegram ? 'Bot token' : 'Webhook token', token]), tokenHint,
1598
+ el('label', {}, [telegram ? 'Chat ID or channel username' : 'Message endpoint', address]),
1599
+ el('p', { class: 'hint' }, telegram
1600
+ ? ['Create a bot with BotFather, start a conversation with it (or add it to your group), and enter the target chat ID. For a channel, add the bot as an administrator. ', el('a', { href: 'https://core.telegram.org/bots/tutorial', target: '_blank', rel: 'noopener noreferrer', text: 'Telegram setup guide' })]
1601
+ : ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1602
+ el('div', { class: 'row' }, [save, test, remove]), message,
1603
+ ]);
1604
+ function refresh() {
1605
+ token.placeholder = saved.configured ? 'Leave blank to keep the saved token' : 'Paste your token';
1606
+ tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Your token is saved on the server and is never displayed here.';
1607
+ test.disabled = dirty || !saved.enabled;
1608
+ remove.disabled = !saved.configured;
1609
+ }
1610
+ function busy(on) {
1611
+ form.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
1612
+ if (!on) refresh();
1613
+ }
1614
+ function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
1615
+ form.oninput = function () { dirty = true; test.disabled = true; feedback('Save your changes before sending a test.'); };
1616
+ form.onsubmit = function (e) {
1617
+ e.preventDefault();
1618
+ var patch = { enabled: enabled.checked, token: token.value.trim() };
1619
+ patch[telegram ? 'chat_id' : 'endpoint'] = address.value.trim();
1620
+ var body = {}; body[provider] = patch;
1621
+ busy(true); feedback('Saving…');
1622
+ api('PATCH', '/notifications', body).then(function (result) {
1623
+ saved = result.notifications[provider]; dirty = false; token.value = '';
1624
+ feedback(title + ' settings saved. Send a test to check delivery.');
1625
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1626
+ };
1627
+ test.onclick = function () {
1628
+ busy(true); feedback('Sending a test…');
1629
+ api('POST', '/notifications/test', { provider: provider }).then(function () {
1630
+ feedback('Test notification sent. Check ' + title + '.');
1631
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1632
+ };
1633
+ remove.onclick = function () {
1634
+ var body = {}, patch = { enabled: false, token: null };
1635
+ patch[telegram ? 'chat_id' : 'endpoint'] = '';
1636
+ body[provider] = patch;
1637
+ busy(true); feedback('Disconnecting…');
1638
+ api('PATCH', '/notifications', body).then(function (result) {
1639
+ saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
1640
+ feedback(title + ' disconnected. The saved token was removed.');
1641
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
1642
+ };
1643
+ refresh();
1644
+ content.appendChild(el('section', { class: 'card' }, [el('h2', { text: title }), form]));
1645
+ }
1646
+ }).catch(function (x) {
1647
+ content.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1648
+ content.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
1649
+ });
1650
+ }
1651
+
1539
1652
  // ---- team ------------------------------------------------------------------------------
1540
1653
 
1541
1654
  function teamView(view) {