create-heresay 0.2.16 → 0.2.18

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.16",
3
+ "version": "0.2.18",
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.16
1
+ 0.2.18
@@ -1,4 +1,6 @@
1
1
  export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
2
+ export class TelegramLookupError extends Error {
3
+ }
2
4
  export const defaultNotifications = () => ({
3
5
  events: { new_report: true, accepted: false, fixed: true, handoff: true },
4
6
  telegram: { enabled: false, token: null, chat_id: '' },
@@ -14,6 +16,7 @@ export function notificationView(settings) {
14
16
  }
15
17
  class SettingsError extends Error {
16
18
  }
19
+ const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
17
20
  const object = (v) => {
18
21
  if (!v || typeof v !== 'object' || Array.isArray(v))
19
22
  throw new SettingsError('Invalid notification settings.');
@@ -67,7 +70,7 @@ export function patchNotifications(current, body) {
67
70
  else if (patch.token !== undefined) {
68
71
  const token = field(patch.token, 512);
69
72
  if (token) {
70
- if (provider === 'telegram' ? !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
73
+ if (provider === 'telegram' ? !TELEGRAM_TOKEN.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
71
74
  throw new SettingsError(`Invalid ${provider === 'telegram' ? 'Telegram bot' : 'Cliq webhook'} token.`);
72
75
  }
73
76
  target.token = token;
@@ -113,6 +116,27 @@ export async function notificationSettings(p, req, deps, body) {
113
116
  throw error;
114
117
  }
115
118
  }
119
+ if (p.length === 3 && p[1] === 'telegram' && p[2] === 'lookup' && req.method === 'POST') {
120
+ // A pasted token, or the saved one. The token goes only to Telegram and never comes back.
121
+ const pasted = typeof body.token === 'string' ? body.token.trim() : '';
122
+ const token = pasted || ((await deps.store.getInstance()).notifications ?? defaultNotifications()).telegram.token;
123
+ if (!token)
124
+ return json(400, { error: 'Paste the bot token from BotFather first.' });
125
+ if (!TELEGRAM_TOKEN.test(token))
126
+ return json(400, { error: 'That doesn’t look like a bot token. BotFather sends one like 123456789:AAH…' });
127
+ const now = deps.now(), start = Math.floor(now / 60_000) * 60_000;
128
+ if (!await deps.store.hit(`notification-lookup:telegram:${start}`, 30, start + 60_000)) {
129
+ return json(429, { error: 'Wait a minute before looking again.' });
130
+ }
131
+ if (!deps.telegramLookup)
132
+ return json(503, { error: 'Telegram lookup is unavailable.' });
133
+ try {
134
+ return json(200, await deps.telegramLookup(token));
135
+ }
136
+ catch (error) {
137
+ return json(502, { error: error instanceof TelegramLookupError ? error.message : 'Could not reach Telegram. Try again in a moment.' });
138
+ }
139
+ }
116
140
  if (p.length === 2 && p[1] === 'test' && req.method === 'POST') {
117
141
  const provider = body.provider;
118
142
  if (provider !== 'telegram' && provider !== 'cliq')
@@ -202,4 +226,50 @@ export function notificationSender(http = fetch) {
202
226
  }
203
227
  };
204
228
  }
229
+ /**
230
+ * Telegram has no "list my chats". A bot sees the chats that wrote to it (or added it) in the
231
+ * last day, through getUpdates; that is enough to offer the right one. Read-only: no offset is
232
+ * confirmed, so nothing is consumed.
233
+ */
234
+ export function telegramLookup(http = fetch) {
235
+ const call = async (token, method, body) => {
236
+ const response = await http(`https://api.telegram.org/bot${token}/${method}`, {
237
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body ?? {}),
238
+ signal: AbortSignal.timeout(5000), redirect: 'error',
239
+ });
240
+ const result = await response.json().catch(() => ({}));
241
+ return { status: response.status, ...result };
242
+ };
243
+ return async (token) => {
244
+ const me = await call(token, 'getMe');
245
+ if (me.status === 401 || me.status === 404)
246
+ throw new TelegramLookupError('Telegram doesn’t recognise this token. Copy it again from BotFather.');
247
+ if (!me.ok)
248
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
249
+ const bot = me.result;
250
+ const updates = await call(token, 'getUpdates', { limit: 100, timeout: 0, allowed_updates: ['message', 'channel_post', 'my_chat_member'] });
251
+ if (updates.status === 409) {
252
+ throw new TelegramLookupError('This bot already sends its messages to another service (a webhook), so Heresay can’t see its chats. Enter the chat ID yourself, or use a new bot.');
253
+ }
254
+ if (!updates.ok)
255
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
256
+ const seen = new Map();
257
+ for (const u of updates.result ?? []) {
258
+ const chat = (u.message ?? u.channel_post ?? u.my_chat_member)?.chat;
259
+ if (!chat || (typeof chat.id !== 'number' && typeof chat.id !== 'string'))
260
+ continue;
261
+ const kind = String(chat.type);
262
+ if (!['private', 'group', 'supergroup', 'channel'].includes(kind))
263
+ continue;
264
+ const title = kind === 'private'
265
+ ? [chat.first_name, chat.last_name].filter((x) => typeof x === 'string').join(' ') || (typeof chat.username === 'string' ? '@' + chat.username : 'You')
266
+ : typeof chat.title === 'string' ? chat.title : 'Untitled';
267
+ seen.set(String(chat.id), { id: String(chat.id), title: title.slice(0, 120), kind });
268
+ }
269
+ return {
270
+ bot: { username: typeof bot?.username === 'string' ? bot.username : '', name: typeof bot?.first_name === 'string' ? bot.first_name.slice(0, 120) : '' },
271
+ chats: [...seen.values()].reverse(), // the latest first
272
+ };
273
+ };
274
+ }
205
275
  //# 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.16';
2
+ export const VERSION = '0.2.18';
3
3
  //# sourceMappingURL=version.js.map
@@ -8,7 +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
+ import { notificationSender, telegramLookup } from '../../core/notifications.js';
12
12
  const deps = {
13
13
  store: new FirestoreStore(db),
14
14
  async verifyIdToken(token) {
@@ -25,6 +25,7 @@ const deps = {
25
25
  version: VERSION,
26
26
  selfOrigins: selfOrigins(),
27
27
  sendNotification: notificationSender(),
28
+ telegramLookup: telegramLookup(),
28
29
  };
29
30
  function selfOrigins() {
30
31
  const id = process.env.GCLOUD_PROJECT;
@@ -10,10 +10,10 @@
10
10
  <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Figtree:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
11
11
  <link rel="stylesheet" href="/dashboard.css">
12
12
  </head>
13
- <body>
13
+ <body class="booting pending">
14
14
 
15
- <!-- Until sign-in state is known -->
16
- <div id="boot" class="loading boot" role="status" aria-label="Loading"><img src="/loader.svg" alt=""></div>
15
+ <!-- The one loader: from first paint until a page has everything it needs -->
16
+ <div id="loader" class="app-loader on" role="status" aria-label="Loading"><img src="/loader.svg" alt="" width="96" height="96"></div>
17
17
 
18
18
  <!-- Signed out -->
19
19
  <div id="gate" class="gate" hidden>
@@ -132,12 +132,19 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
132
132
  .wait.ok .btn { margin-left:auto; }
133
133
  @keyframes pulse { 0%, 100% { opacity:.25; transform:scale(.8); } 50% { opacity:1; transform:scale(1); } }
134
134
  @media (prefers-reduced-motion: reduce) { .wait::before { animation:none; } }
135
- /* loading: the Glance mark, faded in late so quick loads never flash it */
136
- .loading { display:grid; place-items:center; padding:12vh 0; animation:loading-in .2s .3s both; }
137
- .loading img { width:96px; height:96px; }
138
- .loading.boot { padding-top:30vh; }
139
- .loading:not(.boot):not(:only-child) { display:none; }
135
+ /* loading: one Glance mark, fixed in place, faded in late so quick loads never flash it */
136
+ .app-loader { position:fixed; left:50%; top:38vh; z-index:20; width:96px; height:96px; margin:-48px 0 0 -48px; pointer-events:none;
137
+ opacity:0; visibility:hidden; transition:opacity .25s ease, visibility 0s .25s; }
138
+ .app-loader.on { opacity:1; visibility:visible; transition:opacity .25s ease; }
139
+ .booting .app-loader.on { animation:loading-in .25s .3s both; }
140
+ .app-loader img { display:block; width:96px; height:96px; }
140
141
  @keyframes loading-in { from { opacity:0; } }
142
+ /* What a view still waits for. While one is alone in its box, the page stays out of sight. */
143
+ .loading { display:block; min-height:40vh; list-style:none; }
144
+ .loading:not(:only-child) { display:none; }
145
+ #app, #view { transition:opacity .25s ease; }
146
+ .booting.pending #app, .pending #view { opacity:0; visibility:hidden; transition:none; }
147
+ @media (prefers-reduced-motion: reduce) { #app, #view, .app-loader, .app-loader.on { transition:none; } }
141
148
 
142
149
  /* reports */
143
150
  .filters { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
@@ -376,6 +383,33 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
376
383
  .notification-choice .hint { display:block; margin:2px 0 0; }
377
384
  .notification-form input[type=text], .notification-form input[type=password] { width:100%; min-width:0; }
378
385
  .notification-form .row { margin-top:22px; }
386
+ /* a guided setup inside a card */
387
+ .setup-step { margin-top:22px; }
388
+ .setup-step .test-head b { font-size:16px; }
389
+ .setup-body { margin:6px 0 0 34px; }
390
+ .setup-body > .row.tight { margin-top:10px; }
391
+ .setup-body label { margin-top:14px; }
392
+ .guide { margin:6px 0 0; padding-left:20px; display:flex; flex-direction:column; gap:10px; }
393
+ .guide li { padding-left:4px; }
394
+ .guide li::marker { font-weight:700; color:var(--deep); }
395
+ .tg-step2 .seg { margin:8px 0 4px; }
396
+ .tg-step2 .wait { margin-top:16px; }
397
+ .tg-step2 .chat-list { margin-top:12px; }
398
+ .chosen-line { margin:12px 0 0; font-weight:600; }
399
+ .bot-line p { margin:8px 0 0; }
400
+ .chat-finder:empty { display:none; }
401
+ .chat-finder { margin-top:12px; }
402
+ .chat-finder p { margin:0 0 8px; }
403
+ .chat-list { display:flex; flex-direction:column; gap:6px; }
404
+ .notification-form .chat-choice { display:flex; align-items:center; gap:12px; margin:0; padding:10px 14px; border:1px solid var(--line); border-radius:12px; cursor:pointer; font-weight:400; }
405
+ .chat-choice:hover { border-color:var(--acc); }
406
+ .chat-choice:has(input:checked) { border-color:var(--acc); background:var(--mist); }
407
+ .notification-form .chat-choice input:focus { outline:none; }
408
+ .chat-choice:has(input:focus-visible) { outline:2px solid var(--acc); outline-offset:2px; }
409
+ .notification-form .chat-choice input { display:inline-block; width:auto; flex:none; accent-color:var(--acc); margin:0; }
410
+ .chat-choice b { display:block; }
411
+ .chat-choice .mute { font-size:13px; }
412
+ @media (max-width:600px) { .setup-body { margin-left:0; } }
379
413
  @media (max-width:600px) {
380
414
  .top { flex-wrap:wrap; gap:8px 12px; padding:12px 16px; }
381
415
  .top .tabs { order:5; width:100%; }
@@ -42,13 +42,34 @@
42
42
  }
43
43
 
44
44
  function show(which) {
45
- ['boot', 'gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
45
+ ['gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
46
+ syncLoader();
46
47
  }
47
48
 
48
- /** The Glance loader. It shows only while it is alone in its box, so a view's first content hides it. */
49
- function loading() {
50
- return el('div', { class: 'loading', role: 'status', 'aria-label': 'Loading' }, [el('img', { src: '/loader.svg', alt: '' })]);
49
+ /**
50
+ * One Glance loader for the whole dashboard, from the first paint until a page is ready. It is
51
+ * never recreated, so the animation never restarts. A view marks what it is still waiting for
52
+ * with loading(); while any of those is alone in its box the view stays hidden, then the page
53
+ * appears in one go.
54
+ */
55
+ var loader = $('loader'), loaderTimer = null;
56
+ function loading(tag) {
57
+ return el(tag || 'div', { class: 'loading', 'aria-hidden': 'true' });
58
+ }
59
+ function syncLoader() {
60
+ // Signed in: wait for the view. Otherwise wait until we know who this is (sign-in or blocked).
61
+ var waiting = !$('app').hidden ? !!$('view').querySelector('.loading:only-child') : $('gate').hidden && $('blocked').hidden;
62
+ document.body.classList.toggle('pending', waiting);
63
+ if (!waiting) document.body.classList.remove('booting');
64
+ if (waiting && !loader.classList.contains('on')) {
65
+ // A quick page never flashes the loader; it just appears.
66
+ if (!loaderTimer) loaderTimer = setTimeout(function () { loaderTimer = null; loader.classList.add('on'); }, 250);
67
+ } else if (!waiting) {
68
+ clearTimeout(loaderTimer); loaderTimer = null;
69
+ loader.classList.remove('on');
70
+ }
51
71
  }
72
+ new MutationObserver(syncLoader).observe($('view'), { childList: true, subtree: true });
52
73
 
53
74
  function copyButton(getText, label) {
54
75
  var b = el('button', { class: 'btn', type: 'button', text: label || 'Copy' });
@@ -157,8 +178,8 @@
157
178
  api('GET', '/me').then(function (b) {
158
179
  me = b;
159
180
  $('who').textContent = b.email;
181
+ route(); // first, so the view is already waiting when the app is shown
160
182
  show('app');
161
- route();
162
183
  checkForUpdate(b);
163
184
  }).catch(function (x) {
164
185
  show('blocked');
@@ -1272,6 +1293,11 @@
1272
1293
  reports = triageSort([].concat.apply([], sibs.map(function (x) { return ctxs[x.id].reports; })));
1273
1294
  drawPlatforms();
1274
1295
  render();
1296
+ }).catch(function (x) {
1297
+ if (reports.length) return; // a background refresh failed: keep what is on screen
1298
+ list.textContent = '';
1299
+ list.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1300
+ list.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
1275
1301
  });
1276
1302
  }
1277
1303
 
@@ -1655,7 +1681,7 @@
1655
1681
  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' })]));
1656
1682
  return;
1657
1683
  }
1658
- var content = el('div');
1684
+ var content = el('div', {}, [loading()]);
1659
1685
  view.appendChild(content);
1660
1686
  api('GET', '/notifications').then(function (b) {
1661
1687
  var settings = b.notifications;
@@ -1700,15 +1726,149 @@
1700
1726
  var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
1701
1727
  var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
1702
1728
  var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
1703
- var form = el('form', { class: 'form notification-form' }, [
1729
+ var tg = telegram ? telegramGuide() : null;
1730
+ var form = el('form', { class: 'form notification-form' }, telegram ? [
1731
+ el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1732
+ setupStep(1, 'Make a bot', [
1733
+ el('ol', { class: 'guide' }, [
1734
+ el('li', {}, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather in Telegram ↗' })]),
1735
+ el('li', {}, ['Send ', el('code', { text: '/newbot' }), '. It asks for a name (anything, like “Acme alerts”), then a username that ends in “bot” (like acme_alerts_bot).']),
1736
+ el('li', {}, ['It replies with a long token that looks like ', el('code', { text: '123456789:AAH…' }), '. Copy it and paste it here.']),
1737
+ ]),
1738
+ el('label', {}, ['Bot token', token]), tokenHint, tg.botLine,
1739
+ ]),
1740
+ setupStep(2, 'Choose where alerts go', [tg.step2]),
1741
+ setupStep(3, 'Save and test', [
1742
+ el('p', { class: 'hint', text: 'Save, then send a test. It arrives from your bot in a few seconds.' }),
1743
+ el('div', { class: 'row tight' }, [save, test, remove]), message,
1744
+ ]),
1745
+ ] : [
1704
1746
  el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1705
- el('label', {}, [telegram ? 'Bot token' : 'Webhook token', token]), tokenHint,
1706
- el('label', {}, [telegram ? 'Chat ID or channel username' : 'Message endpoint', address]),
1707
- el('p', { class: 'hint' }, telegram
1708
- ? ['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' })]
1709
- : ['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' })]),
1747
+ el('label', {}, ['Webhook token', token]), tokenHint,
1748
+ el('label', {}, ['Message endpoint', address]),
1749
+ el('p', { class: 'hint' }, ['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' })]),
1710
1750
  el('div', { class: 'row' }, [save, test, remove]), message,
1711
1751
  ]);
1752
+ /**
1753
+ * Telegram has no screen that shows a chat ID, so we never ask for one up front. Once the
1754
+ * token checks out, the person picks who gets alerts, follows two or three taps, and this
1755
+ * page watches the bot until their chat turns up, then chooses it.
1756
+ */
1757
+ function telegramGuide() {
1758
+ var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }) };
1759
+ var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null;
1760
+ var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
1761
+ var wait = el('div', { class: 'wait', role: 'status' });
1762
+ var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
1763
+ var chosen = el('p', { class: 'ok-msg chosen-line' });
1764
+ var manual = el('details', { class: 'where', open: !!saved.chat_id }, [
1765
+ el('summary', { text: 'Enter a chat ID yourself' }),
1766
+ el('label', {}, ['Chat ID or channel username', address]),
1767
+ el('p', { class: 'hint', text: 'Only if you already know it, like -1001234567890 or @yourchannel. Picking a chat above fills this in.' }),
1768
+ ]);
1769
+ var tabs = el('div', { class: 'seg', role: 'tablist', 'aria-label': 'Who gets alerts' });
1770
+ var how = el('ol', { class: 'guide' });
1771
+ var again = el('button', { class: 'btn', type: 'button', text: 'Look again', onclick: function () { watch(); } });
1772
+
1773
+ function link(href, text) { return el('a', { class: 'btn', href: href, target: '_blank', rel: 'noopener noreferrer', text: text }); }
1774
+ function drawHow() {
1775
+ var at = '@' + bot.username, url = 'https://t.me/' + encodeURIComponent(bot.username);
1776
+ how.textContent = '';
1777
+ (kind === 'private' ? [
1778
+ [link(url, 'Open ' + at + ' in Telegram ↗')],
1779
+ ['Tap ', el('b', { text: 'Start' }), ' at the bottom of the chat. No Start button? Send it any message, like “hi”.'],
1780
+ ['Come back to this page. It finds the chat by itself.'],
1781
+ ] : kind === 'group' ? [
1782
+ [link(url + '?startgroup=heresay', 'Add ' + at + ' to a group ↗')],
1783
+ ['Telegram asks which group. Pick it and confirm.'],
1784
+ ['Come back to this page. It finds the group by itself. If it doesn’t, send ', el('code', { text: '/start' + at }), ' in the group.'],
1785
+ ] : [
1786
+ ['In Telegram, open your channel and tap its name, then ', el('b', { text: 'Administrators' }), ' → ', el('b', { text: 'Add Admin' }), '.'],
1787
+ ['Search for ', el('b', { text: at }), ', add it, and leave ', el('b', { text: 'Post Messages' }), ' on.'],
1788
+ ['Post anything in the channel, then come back to this page. It finds the channel by itself.'],
1789
+ ]).forEach(function (kids) { how.appendChild(el('li', {}, kids)); });
1790
+ }
1791
+ function drawTabs() {
1792
+ tabs.textContent = '';
1793
+ [['private', 'Just me'], ['group', 'A group'], ['channel', 'A channel']].forEach(function (t) {
1794
+ tabs.appendChild(el('button', { type: 'button', role: 'tab', 'aria-selected': String(kind === t[0]), text: t[1], onclick: function () {
1795
+ kind = t[0]; drawTabs(); drawHow(); drawChats(); watch();
1796
+ } }));
1797
+ });
1798
+ }
1799
+ function sameKind(c) { return kind === 'group' ? c.kind === 'group' || c.kind === 'supergroup' : c.kind === kind; }
1800
+ function pick(c) {
1801
+ address.value = c.id;
1802
+ enabled.checked = true;
1803
+ form.dispatchEvent(new Event('input'));
1804
+ stop();
1805
+ drawChats();
1806
+ feedback('Chat chosen. Save to start sending alerts there.');
1807
+ }
1808
+ function drawChats() {
1809
+ list.textContent = '';
1810
+ var hit = chats.filter(function (c) { return c.id === address.value; })[0];
1811
+ chosen.hidden = !address.value;
1812
+ chosen.textContent = hit ? '✓ Alerts will go to ' + hit.title + ' (' + KIND[hit.kind].toLowerCase() + ').'
1813
+ : address.value ? '✓ Alerts go to chat ' + address.value + '. Pick another below to change it.' : '';
1814
+ chats.forEach(function (c) {
1815
+ var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
1816
+ radio.onchange = function () { pick(c); };
1817
+ list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] })])]));
1818
+ });
1819
+ list.hidden = !chats.length;
1820
+ }
1821
+ function drawWait(state) {
1822
+ wait.textContent = '';
1823
+ wait.className = 'wait' + (state === 'idle' ? ' ok idle' : '');
1824
+ if (state === 'waiting') wait.appendChild(document.createTextNode('Waiting for ' + (kind === 'private' ? 'your message to' : kind === 'group' ? 'a group with' : 'a channel with') + ' @' + bot.username + '…'));
1825
+ else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet. Follow the steps above, then')); wait.appendChild(again); }
1826
+ wait.hidden = state === 'none';
1827
+ }
1828
+ function stop() { clearTimeout(timer); timer = null; if (bot) drawWait(address.value ? 'none' : 'idle'); }
1829
+ function watch() {
1830
+ clearTimeout(timer);
1831
+ until = Date.now() + 5 * 60 * 1000;
1832
+ drawWait('waiting');
1833
+ poll();
1834
+ }
1835
+ function poll() {
1836
+ if (!form.isConnected) return;
1837
+ lookup(true).then(function () {
1838
+ var match = chats.filter(sameKind)[0];
1839
+ if (match && !address.value) return pick(match); // never replace a chat they already chose
1840
+ if (match) return stop();
1841
+ if (Date.now() > until) return stop();
1842
+ timer = setTimeout(poll, 6000);
1843
+ }).catch(stop);
1844
+ }
1845
+ function lookup(quiet) {
1846
+ return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
1847
+ var fresh = !bot || bot.username !== b.bot.username;
1848
+ bot = b.bot; chats = b.chats;
1849
+ g.botLine.textContent = '';
1850
+ g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
1851
+ if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [el('p', { class: 'hint', text: 'Who should get the alerts?' }), tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
1852
+ drawChats();
1853
+ }).catch(function (x) {
1854
+ if (quiet && bot) return;
1855
+ g.botLine.textContent = '';
1856
+ g.botLine.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1857
+ throw x;
1858
+ });
1859
+ }
1860
+ function check() {
1861
+ clearTimeout(checking);
1862
+ checking = setTimeout(function () {
1863
+ lookup().then(function () { if (!address.value) watch(); else stop(); }).catch(function () {});
1864
+ }, 400);
1865
+ }
1866
+ g.step2.appendChild(el('p', { class: 'hint', text: 'Paste your bot token above first. Then this step shows exactly what to tap.' }));
1867
+ g.step2.appendChild(manual);
1868
+ token.addEventListener('input', function () { if (/^\d+:[A-Za-z0-9_-]{20,}$/.test(token.value.trim())) check(); });
1869
+ if (saved.configured) check();
1870
+ return g;
1871
+ }
1712
1872
  function refresh() {
1713
1873
  token.placeholder = saved.configured ? 'Leave blank to keep the saved token' : 'Paste your token';
1714
1874
  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.';
@@ -1759,9 +1919,17 @@
1759
1919
 
1760
1920
  // ---- team ------------------------------------------------------------------------------
1761
1921
 
1922
+ /** One numbered step of a setup, in the same style as the install steps. */
1923
+ function setupStep(n, title, kids) {
1924
+ return el('div', { class: 'setup-step' }, [
1925
+ el('div', { class: 'test-head' }, [el('span', { class: 'stepnum', text: String(n) }), el('b', { text: title })]),
1926
+ el('div', { class: 'setup-body' }, kids),
1927
+ ]);
1928
+ }
1929
+
1762
1930
  function teamView(view) {
1763
1931
  var owner = me.role === 'owner';
1764
- var list = el('ul', { class: 'members' });
1932
+ var list = el('ul', { class: 'members' }, [loading('li')]);
1765
1933
  var err = el('p', { class: 'err', role: 'alert' });
1766
1934
  view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Team' })]));
1767
1935
  view.appendChild(el('p', { class: 'mute', text: 'Everyone here can read and answer reports for every app. Owners can also change the team.' }));