domma-cms 1.80.0 → 1.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/admin/css/site-settings.css +1 -1
  3. package/admin/js/lib/site-settings-arrange.js +3 -3
  4. package/admin/js/templates/docs/usage-site-settings.html +47 -3
  5. package/admin/js/templates/settings.html +98 -8
  6. package/admin/js/views/settings.js +3 -3
  7. package/docs/DommaFeatures.md +51 -2
  8. package/docs/plans/2026-11-19-brand-kit-design.md +1 -1
  9. package/docs/plugin-development.md +6 -0
  10. package/package.json +1 -1
  11. package/plugins/_lib/telegram/bot.js +120 -0
  12. package/plugins/free-tier.lock.json +34 -9
  13. package/plugins/telegram/CHANGELOG.md +5 -0
  14. package/plugins/telegram/CLAUDE.md +77 -0
  15. package/plugins/telegram/admin/css/index.css +68 -0
  16. package/plugins/telegram/admin/lib/arrange.js +103 -0
  17. package/plugins/telegram/admin/lib/kit.js +153 -0
  18. package/plugins/telegram/admin/templates/telegram.html +1 -0
  19. package/plugins/telegram/admin/views/chats.js +223 -0
  20. package/plugins/telegram/admin/views/connection.js +90 -0
  21. package/plugins/telegram/admin/views/telegram.js +89 -0
  22. package/plugins/telegram/admin/views/test.js +84 -0
  23. package/plugins/telegram/config.js +21 -0
  24. package/plugins/telegram/docs/guide.md +87 -0
  25. package/plugins/telegram/lib/messages.js +176 -0
  26. package/plugins/telegram/lib/queue.js +72 -0
  27. package/plugins/telegram/plugin.js +490 -0
  28. package/plugins/telegram/plugin.json +71 -0
  29. package/plugins/telegram/tests/api.test.js +381 -0
  30. package/plugins/telegram/tests/arrange.test.js +41 -0
  31. package/plugins/telegram/tests/messages.test.js +110 -0
  32. package/plugins/telegram/tests/queue.test.js +47 -0
  33. package/plugins/theme-roller/CLAUDE.md +9 -0
  34. package/plugins/theme-roller/admin/lib/themes.js +49 -0
  35. package/plugins/theme-roller/admin/templates/theme-roller.html +2 -0
  36. package/plugins/theme-roller/admin/views/theme-roller-view.js +25 -2
  37. package/plugins/theme-roller/docs/guide.md +1 -0
  38. package/plugins/theme-roller/plugin.json +1 -1
  39. package/plugins/theme-roller/tests/themes.test.js +20 -0
  40. package/public/js/site.js +1 -1
  41. package/server/routes/api/brand-kit.js +55 -0
  42. package/server/routes/api/settings.js +17 -1
  43. package/server/routes/favicon.js +10 -6
  44. package/server/server.js +2 -0
  45. package/server/services/adminBrand.js +8 -3
  46. package/server/services/brandKit.js +330 -0
  47. package/server/services/chat/launcher-bridge.js +2 -1
  48. package/server/services/emailBrand.js +31 -13
  49. package/server/services/launchers.js +5 -1
  50. package/server/services/notify.js +20 -2
  51. package/server/services/plugins.js +3 -0
  52. package/server/services/renderer.js +7 -5
  53. package/server/templates/page.html +1 -1
@@ -79,6 +79,8 @@ Code was treated as the truth. Where docs disagree with it, the disagreement is
79
79
  | `support` | free | 1.3.0 | Help from Domma in the admin: Domma's email, phone and hours always to hand, and a request as a conversation with the Domma team, urgent ones first. On the Domma server, AI Assist summarises a request, suggests a reply and groups waiting requests into themes. |
80
80
  | `surveys` | paid | 1.19.2 | Targeted surveys over the Forms engine: shared audiences and Contacts groups, tokenised invites, reminders, NPS, star, smiley and number scales, quiz mode with scores, closing rules, and Results with charts, filters, Live refresh, a printable PDF report and (with AI Assist) themed summaries of free-text answers. |
81
81
  | `sweepstake` | paid (giftable) | 1.0.0 | Office, pub and club sweepstakes for any event: picks, entry fee and prizes, entrants by name with paid ticks, and one recorded, repeatable draw revealed live on the page, then who has what and the money. |
82
+ | `telegram` | free | 0.1.0 | Your own Telegram bot sends the team the site's alerts and form submissions - to a group or one person's chat, each chat choosing which alerts (how serious, from which Tools) and which forms, with the answers or the title and a link only. |
83
+ | `telegram-pro` | paid | 0.1.0 | Two-way customer chat on Telegram: an Inbox in the admin with an unread badge, an optional staff group where a reply to a copied message answers the customer, a "Message us on Telegram" button, /stop and a retention period. Needs the free Telegram Tool. |
82
84
  | `theme-roller` | paid | 1.3.0 | Make your own themes: start from any built-in theme, change its colours, fonts, spacing and borders with a live preview, and save it. Saved themes join the built-in ones everywhere a theme is chosen - the site, the admin, day and night, a region of a page. Needs Domma CMS 0.73 or later to use them. |
83
85
  | `timeline` | paid (giftable) | 1.1.0 | Put events in date order: all at once (Sort) or one at a time into a growing timeline with lives (Place). Years, months or full dates, BC too; dates stay on the server until a card is placed. Shortcode `[timeline-game]`. |
84
86
  | `treasure-hunt` | paid (giftable) | 1.1.0 | Hide 2-30 tokens across your pages and send visitors looking for them, in any order or one clue at a time. A progress chip follows players from page to page; finishers get a prize message and a code (one for all, or a unique code each). First-to-finish or fastest leaderboard. |
@@ -1143,6 +1145,8 @@ Where: `server/services/presetCollections.js` (`PRESETS`, `seedAll()`), `server/
1143
1145
  Where: `POST /api/system/notifications` (`MANAGER_SECRET`, `server/middleware/managerAuth.js`).
1144
1146
  - **Plugin API** - Plugins can raise notifications, resolve them and register their own sources through hooks: `notify()`, `resolveNotification()` and `registerNotificationSource()`, with `every: boot | 15m | hourly | daily` (daily runs at 08:00).
1145
1147
  Since: 0.80.0.
1148
+ - **`notification:raised` event** - Every stored notification (and a repeat that grew worse) is emitted on the hook bus with the stored entry, so a Tool can pass it on; the Telegram Tool sends them to linked chats by severity and source, never personal ones.
1149
+ Where: `server/services/notify.js` - Unreleased.
1146
1150
 
1147
1151
  ### In-admin documentation
1148
1152
 
@@ -1453,7 +1457,9 @@ The four Tools below were plugins until 0.67.0 and are now part of the CMS. They
1453
1457
  Where: `server/services/publicCors.js`.
1454
1458
  - **Email service** - A Nodemailer transport built from the SMTP settings in `site.json`, used for form emails, password resets and notices. With no SMTP host set, mail goes to a throwaway Ethereal test inbox, which reports success but delivers to nobody. The CMS makes this visible in Settings, in health checks and with an "Email not set up" notification. New sites ship with an SMTP host, defaulting to a local mail server on port 25 or taken from the environment.
1455
1459
  Where: `server/services/email.js`, `bin/lib/smtp-defaults.js`, `POST /api/settings/test-email` - Since: 0.55.0.
1456
- - **One email look for every automated email** - Account invitations, password resets and security alerts, form notifications, automations, call invites, bookings and calendar mail, order and account emails from the Shop, invoices and quotes, Support, Docs and signing, Waypoint, Job Board, Surveys, Onboard, Campaigns layouts, Ecards, prize and game emails, SEO reports and Wiki updates all go out in one shared, mobile-friendly frame: the site's name and logo at the top, a label for the kind of email (Your account, Bookings, Your order...), an accent line and buttons in the site's colour, and a footer with the support address and a link to the site. Every email keeps a full plain-text version. It inherits the public brand (Site Settings > Branding); **Site Settings > SMTP > Email identity** overrides it for email only - brand name, logo (PNG or JPEG; an SVG site logo falls back to the name), accent colour, support email and a footer line. The **Email preview gallery** beside it shows each kind with sample data and can send a test. Mail people write themselves (Email, Campaigns content) is never wrapped; an email already in one of Email Pro's brandings (an invoice sent in a brand) is not framed twice.
1460
+ - **Brand Kit** - one site-wide brand under **Site Settings > Branding > Brand Kit** (`site.json` `brandKit`): business name, short name and registered name; logo, logo for dark backgrounds and a square mark (Media or https); accent colour and up to four named brand colours; heading and body fonts (safe fonts and Google fonts with safe fallbacks); contact email, phone, address, website, company number and VAT number; a footer line and small print. Every empty field falls back to what the site already had (`brand.text`/`title`, `brand.logo`/`logo`, `contactEmail`/footer email, the footer address, `baseUrl`), so sites look the same until the Kit is filled in - no migration. The Kit never changes the theme (its colours are not theme tokens). Automated emails read it (below); plugins read it with `hooks.brandKit()` (resolved, fallbacks applied); anyone can read the public parts at `GET /api/brand-kit` (absolute addresses, never SMTP or private settings). An SVG logo gets a PNG copy for mail programs at `GET /api/brand-kit/logo.png` (sharp, 480x192 max, cached; needs the Site URL - Needs attention says so otherwise). **Website and sign-in defaults** (phase 3): once the Kit has been SAVED (`updatedAt`; `savedBrand()` - the Kit's own fields, no fallbacks), it fills what the site leaves empty: favicon (`site.favicon`, `brand.logo`, then Kit mark, then Kit logo; letter icon in the Kit accent with black/white ink), a completely blank navbar brand (`navBrand()`, both render paths: the Kit logo alone with its name as `alt`, else the Kit name), admin name/logo/dark logo and the sign-in screen (`adminBrandFor`: own, then Kit, then site title), chat launchers' accent/accentText and avatar (`chatBrandDefaults()` in launchers.js and the chat bridge; a character keeps its art) and og:site_name. A site with no saved Kit renders byte-for-byte the same. `GET /api/brand-kit` carries `saved`. The Theme Roller's **New theme from Brand Kit** makes a new custom theme from it on request (the Kit never changes a theme). Email Pro's read-only **Site brand** and Invoices' fallback are phase 2 (Email Pro 0.24.0, Invoices 1.11.0). Next phases (Tools, the Manager): `docs/plans/2026-11-19-brand-kit-design.md`.
1461
+ Where: `server/services/brandKit.js`, `server/routes/api/brand-kit.js`, `brandKitFromForm()` in `admin/js/lib/site-settings-arrange.js` - Since: unreleased.
1462
+ - **One email look for every automated email** - Account invitations, password resets and security alerts, form notifications, automations, call invites, bookings and calendar mail, order and account emails from the Shop, invoices and quotes, Support, Docs and signing, Waypoint, Job Board, Surveys, Onboard, Campaigns layouts, Ecards, prize and game emails, SEO reports and Wiki updates all go out in one shared, mobile-friendly frame: the site's name and logo at the top, a label for the kind of email (Your account, Bookings, Your order...), an accent line and buttons in the site's colour, and a footer with the support address and a link to the site. Every email keeps a full plain-text version. It reads the **Brand Kit** (Site Settings > Branding; the footer also carries the registered name, company and VAT numbers, address and small print, and the Kit's fonts); **Site Settings > SMTP > Email identity** overrides it for email only - brand name, logo (PNG or JPEG; an SVG site logo falls back to the name), accent colour, support email and a footer line. The **Email preview gallery** beside it shows each kind with sample data and can send a test. Mail people write themselves (Email, Campaigns content) is never wrapped; an email already in one of Email Pro's brandings (an invoice sent in a brand) is not framed twice.
1457
1463
  Where: `server/services/emailBrand.js` (`brandEmail`, `emailBrand`, `EMAIL_FAMILIES`), `sendEmail(transport, {branding: {family}})` in `server/services/email.js`, `server/services/emailExamples.js`, Settings > SMTP - Since: 1.78.0.
1458
1464
 
1459
1465
  ---
@@ -1707,7 +1713,7 @@ Handed to `plugin.js` as `options.hooks` (bound to the plugin's name where it ma
1707
1713
 
1708
1714
  Also exported from `server/services/hooks.js` but **not** handed over in `options.hooks`: `hideSidebarUrl(url)`, `unregisterCalendarSource`, `unregisterRelatedItems`, `unregisterSitemapSource`.
1709
1715
 
1710
- **Events on the bus:** `content:pageCreated`, `content:pageUpdated`, `content:pageDeleted`, `content:pageRenamed`, `content:pageViewed`, `content:mediaUploaded`, `content:mediaDeleted`, `collection:entryCreated`, `collection:entryUpdated`, `collection:entryDeleted`, `form:submitted`, `user:loggedIn`, `user:deleted`, `contact:deleted`, `note:deleted`, `auth:loginSucceeded`, `auth:loginFailed`, `auth:loggedOut`, `auth:rateLimited`, `auth:passwordChanged`, `auth:resetRequested`, `auth:resetIssued`, and `audit` (every successful POST/PUT/PATCH/DELETE under `/api/` by a signed-in user - `{actor, action, route, target, fields, status, ip}`; core stores nothing, Security Pro keeps the trail).
1716
+ **Events on the bus:** `content:pageCreated`, `content:pageUpdated`, `content:pageDeleted`, `content:pageRenamed`, `content:pageViewed`, `content:mediaUploaded`, `content:mediaDeleted`, `collection:entryCreated`, `collection:entryUpdated`, `collection:entryDeleted`, `form:submitted`, `notification:raised` (the stored notification entry, for a new one or a repeat that grew worse; unreleased), `user:loggedIn`, `user:deleted`, `contact:deleted`, `note:deleted`, `auth:loginSucceeded`, `auth:loginFailed`, `auth:loggedOut`, `auth:rateLimited`, `auth:passwordChanged`, `auth:resetRequested`, `auth:resetIssued`, and `audit` (every successful POST/PUT/PATCH/DELETE under `/api/` by a signed-in user - `{actor, action, route, target, fields, status, ip}`; core stores nothing, Security Pro keeps the trail).
1711
1717
 
1712
1718
  ```js
1713
1719
  export default async function plugin(fastify, options) {
@@ -1733,6 +1739,7 @@ Not a plugin (skipped by discovery); ships in the npm package so plugins built a
1733
1739
  - **`dataStore.js`** - `createStore(absPath)` → `read`, `write` (atomic via `.tmp` + rename), `readArray`, `appendItem` (uuid id), `updateItem`, `deleteItem`. For plugin-local JSON that does not need the collections API; single-process safe only.
1734
1740
  - **`schemaSync.js`** - `syncPluginSchemas(collectionsDir, {getCollection, updateCollection}, log)` adds fields a plugin's shipped schema has gained to already-installed collections (additive only, idempotent). Fixes "new field reaches fresh installs only".
1735
1741
  - **`admin/ui/help.js` + `help.css`** - Declarative inline help: `data-help="..."` on any element, then `scanHelp(container)`; also `helpTip`, `helpIcon`, `openHelpPanel({title, intro, sections})` for longer help.
1742
+ - **`telegram/bot.js`** - The Telegram Bot API over fetch for the Telegram Tools: `call` (8 s timeout, never throws), `sendMessage`, `tokenShape`, `esc`, `clip`, `randomCode`, `parseCommand`, `sameSecret` (timing-safe), `chatName`, `setTelegram` for tests. Unreleased.
1736
1743
  - **`admin/ui/dates.js`** - `toDate`, `fmtDate`, `fmtTime`, `fmtDateTime` (dd/mm/yyyy, 24-hour; `{utc: true}` option), usable in the browser and on the server, so plugins read dates the way core does. Needs core 0.93.0.
1737
1744
  - **`admin/ui/resizable.js`** - `makeResizable(slideover, {storageKey, defaultWidth, handleClass})`: drag handle on a slideover's leading edge, width remembered per panel (defers to the admin's central handle when present).
1738
1745
  - **`mail/` + `admin/mail/`** - The complete IMAP/SMTP mail core shared by Mail Reader (free) and Email Pro (paid): accounts with AES-256-GCM sealed passwords or a Microsoft/Google OAuth2 sign-in (`oauth.js`, `oauthRoutes.js`, `admin/mail/oauth-panel.js`; routes registered by Email Pro only), connection pool, sync, rules, send-later, snooze, templates, vacation replies, mbox export, three-pane reader, compose window, and `section-kit.js` (small DOM builders: `box`, `heading`, `note`, `formIn`, `itemCard`, `button`, `actionBar`, `richEditor`, `select`, `empty`). Mail Reader's `plugin.js` is 48 lines over it.
@@ -2541,6 +2548,39 @@ Targeted surveys on top of the Forms engine. Pick any form, choose an audience f
2541
2548
 
2542
2549
  **Where:** Admin sidebar Outreach > "Surveys" (`#/plugins/surveys`); banner actions Audience and New survey.
2543
2550
 
2551
+ ### Telegram (`telegram`)
2552
+
2553
+ Tier: free (ships in the engine) · Version: 0.1.0 (unreleased) · Requires: `plugins/_lib/telegram/bot.js` and, for alerts, the core `notification:raised` event (both in the next CMS release) · No MongoDB
2554
+
2555
+ The site's own Telegram bot sends the team its alerts and form submissions. Each linked chat - a team group or one person's private chat with the bot - has its own routing.
2556
+
2557
+ **Features**
2558
+ - Connection tab: paste the @BotFather token; the Tool checks it (getMe), refuses a bot whose webhook already points elsewhere (Takeaway, another site: "make a second bot"), sets the webhook to `/api/plugins/telegram/webhook` with its own secret, https only. The token, secret and link code are never sent to a browser. Disconnect deletes the webhook and forgets the chats.
2559
+ - Chats tab: Link a chat makes a one-time code (16 characters, 15 minutes, one chat, burnt after 5 wrong tries); `/link <code>` in the chat links it. Rows: click or Enter for "What it gets", right-click, kebab or Shift+F10 for Send a test, Pause/Resume, Unlink (the chat is told). `/unlink` in a linked chat does the same. A group that becomes a supergroup stays linked.
2560
+ - Routing per chat: alerts on/off, severities (default Warning and Critical), every Tool or chosen sources (a Tool or one of its sources); forms on/off, every form or chosen ones, and "the answers" (default) or "title and link only". Unsaved changes ask before discarding and are kept as a draft when the screen is left.
2561
+ - Never sent: notifications with a personal audience (`audience.userIds`, such as to-do reminders); form fields of type password, file, image or hidden, layout fields, fields named like password/secret/token, file values, and any posted key the form does not define. A deleted form sends title and link only.
2562
+ - Test tab: a hello, a sample alert, a sample form entry (as that chat would get it), or a real notification raised in the bell from the "Telegram test alerts" source.
2563
+ - A per-chat queue: about one message a second, Telegram's 429 waited out once, 50 waiting at most; a failure never stops the form or the notification and shows on the chat and the badge.
2564
+ - Sidebar badge: linked chats as a calm total; red when Telegram reports it cannot reach the site, the webhook points elsewhere, or a chat could not be sent to.
2565
+ - Registry `globalThis[Symbol.for('domma.telegram')]` for Telegram Pro: every update the Tool does not answer itself is offered to `onMessage` handlers.
2566
+
2567
+ **Where:** Admin sidebar "Telegram" (`#/plugins/telegram`, `/chats`, `/test`); permission `telegram` (read / manage). Guide in Documentation > Plugins.
2568
+
2569
+ ### Telegram Pro (`telegram-pro`)
2570
+
2571
+ Tier: paid (closed source) · Version: 0.1.0 (unreleased) · Requires: `telegram` · No MongoDB
2572
+
2573
+ Two-way chat with customers through the same bot.
2574
+
2575
+ **Features**
2576
+ - A customer's private message to the bot becomes a conversation (collection `telegram-conversations`, API off): name and username from Telegram, the `/start` tag they came with, text messages (a photo or file is kept as "[photo]", "[file]" and never downloaded), unread count.
2577
+ - Inbox (`#/plugins/telegram-pro`, `/<id>`): list on the left with search and unread dots, thread on the right with a reply box (Ctrl+Enter); rows have Open, Mark as read/unread, Delete (manage); refreshes every 10 s (thread 5 s); a typed reply is kept per conversation in the browser. Sidebar badge: unread conversations. A notification for each new conversation (the customer's name only, never their words).
2578
+ - Staff chat (settings cog): a group linked in Telegram › Chats gets a copy of each customer message; a staff member's Telegram reply to the copy goes to the customer and is kept as theirs. Answers from the admin are echoed there, and replying to the echo works too. Linked chats are never treated as customers.
2579
+ - `/stop` deletes the customer's conversation at once; a conversation quiet for the retention (90 days by default, 1 to 3650) is deleted by an hourly sweep.
2580
+ - `[telegram text="Message us on Telegram" tag="pricing" /]` - a t.me button with an optional start tag; nothing is shown while the bot is not connected.
2581
+
2582
+ **Where:** Admin sidebar "Telegram chats"; permission `telegram-pro` (read / reply / manage).
2583
+
2544
2584
  ### Theme Roller (`theme-roller`)
2545
2585
 
2546
2586
  Tier: paid (closed source) · Version: 1.1.3 · Requires: Domma CMS 0.73+ (`hooks.registerThemes`; stated in the description, not as a field) · Uses: nothing declared · No MongoDB
@@ -3128,6 +3168,15 @@ Later changes to these features are in the CHANGELOG (for example 0.92.1: row-le
3128
3168
  - Embedding a survey on a page with `[survey]`.
3129
3169
  - Summarising free-text answers into themes with AI Assist, and reading the answers before acting on them.
3130
3170
 
3171
+ ### Telegram (`telegram`)
3172
+
3173
+ - Your site's alerts on your phone: make a bot with @BotFather, connect it, link the team's group with /link, and choose Warning and Critical.
3174
+ - Never miss an enquiry: send one form's submissions to the sales chat with the answers, and another to a private chat as title and link only.
3175
+
3176
+ ### Telegram Pro (`telegram-pro`)
3177
+
3178
+ - Answer customers from your team's Telegram group: choose the staff chat, add a [telegram] button with a tag to the pricing page, and reply to the copies.
3179
+
3131
3180
  ### Theme Roller (`theme-roller`)
3132
3181
 
3133
3182
  - Creating a brand theme from a built-in theme and using it on the site.
@@ -1,6 +1,6 @@
1
1
  # Brand Kit - one site-wide brand (design, not built)
2
2
 
3
- Status: agreed design, 2026-11-19 (decisions below). Nothing here is implemented yet.
3
+ Status: agreed design, 2026-11-19 (decisions below). Phase 1 released (CMS 1.81.0), phase 2 released (Email Pro 0.24.0, Invoices 1.11.0), phase 3 built (feat/brand-kit-site-defaults, with the marketplace's Theme Roller and Social Media Pro); phases 4-5 not started.
4
4
 
5
5
  ## The problem
6
6
 
@@ -443,6 +443,12 @@ options.hooks.on('content:pageCreated', ({ page, urlPath }) => {
443
443
  In `data`, a file field is `{url, name, size, mime}`, a list of them when the field is `multiple`, or `''`;
444
444
  `fileRefs(value)` from `public/js/form-files.mjs` reads any of the three as a list.
445
445
 
446
+ #### Notification events
447
+
448
+ | Event | Payload | Fired when |
449
+ |-----------------------|----------------------------|------------|
450
+ | `notification:raised` | the stored entry `{ id, data, meta }` | A notification is stored by `notify()` (core or a plugin's), or a repeat with the same `dedupeKey` grows worse. Not fired for a quiet repeat, a switched-off source, a payload with no title or one held by the hourly cap. `data` has `title, body, severity, source, sourceLabel, link, audience, createdAt`. The Telegram Tool listens to it. |
451
+
446
452
  #### Auth events
447
453
 
448
454
  | Event | Payload | Fired when |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.80.0",
3
+ "version": "1.82.0",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Telegram: the Bot API over fetch (no SDK) - the parts any Tool needs.
3
+ *
4
+ * Lifted from Takeaway's lib/telegram.js (which keeps its own copy and its kitchen and customer wording) for the
5
+ * Telegram and Telegram Pro Tools. A bot is made by the site owner with @BotFather; its token is a secret the Tool
6
+ * keeps on the server and never sends back to the browser. Telegram reaches a Tool through a webhook carrying
7
+ * `X-Telegram-Bot-Api-Secret-Token` (the Tool's own random secret) - check it with `sameSecret`.
8
+ *
9
+ * Nothing here throws at the caller: every call has a timeout, and `call` answers {ok: false, description}.
10
+ * Tests swap the transport with `setTelegram()`, so no test ever reaches Telegram.
11
+ *
12
+ * @module _lib/telegram/bot
13
+ */
14
+ import {randomInt, timingSafeEqual} from 'crypto';
15
+
16
+ const API = 'https://api.telegram.org';
17
+ let transport = null;
18
+
19
+ /** Tests only: `fn(method, body, token)` answers instead of Telegram. Pass null to restore. */
20
+ export function setTelegram(fn) { transport = typeof fn === 'function' ? fn : null; }
21
+
22
+ /**
23
+ * One Bot API call.
24
+ * @param {string} token
25
+ * @param {string} method - 'getMe', 'sendMessage', 'setWebhook', …
26
+ * @param {object} [body]
27
+ * @returns {Promise<{ok: boolean, result?: any, description?: string, error_code?: number, parameters?: object}>}
28
+ */
29
+ export async function call(token, method, body = {}) {
30
+ if (!token) return {ok: false, description: 'No bot token.'};
31
+ try {
32
+ if (transport) return (await transport(method, body, token)) || {ok: false, description: 'No answer.'};
33
+ const res = await fetch(`${API}/bot${token}/${method}`, {method: 'POST', headers: {'Content-Type': 'application/json'},
34
+ body: JSON.stringify(body), signal: AbortSignal.timeout(8000)});
35
+ const json = await res.json().catch(() => ({ok: false, description: `Telegram answered ${res.status}`}));
36
+ return json && typeof json === 'object' ? json : {ok: false, description: 'Telegram sent nothing back.'};
37
+ } catch (err) {
38
+ return {ok: false, description: err?.name === 'TimeoutError' ? 'Telegram did not answer in time.' : (err?.message || String(err))};
39
+ }
40
+ }
41
+
42
+ /** A bot token's shape (123456789:AA…). */
43
+ export const tokenShape = (t) => /^\d{5,15}:[A-Za-z0-9_-]{30,60}$/.test(String(t || '').trim());
44
+
45
+ /** Telegram's HTML is a short whitelist; everything of ours is escaped. Quotes too, for attribute values. */
46
+ export const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
47
+
48
+ /**
49
+ * Telegram refuses a message over 4096 characters, and refuses the whole message when its HTML does not parse.
50
+ * So text is cut BEFORE it becomes HTML, never after: `escFit` escapes a plain string and stops while the
51
+ * escaped result still fits `max`; `fitLines` joins finished HTML lines whole, dropping the ones that do not fit.
52
+ */
53
+ export const MAX_TEXT = 4000;
54
+
55
+ /** `s` escaped, cut (with "…") so the escaped text is at most `max` characters. Never splits an entity. */
56
+ export function escFit(s, max = MAX_TEXT) {
57
+ const raw = String(s ?? '');
58
+ const whole = esc(raw);
59
+ if (whole.length <= max) return whole;
60
+ let out = '';
61
+ for (const ch of raw) {
62
+ const e = esc(ch);
63
+ if (out.length + e.length > max - 1) break;
64
+ out += e;
65
+ }
66
+ return `${out}…`;
67
+ }
68
+
69
+ /**
70
+ * Finished HTML lines joined with newlines, at most `max` characters. `keep` lines (a link, say) always stay
71
+ * at the end; the others are taken in order while they fit, and a `more` line says something was left out.
72
+ */
73
+ export function fitLines(lines, {max = MAX_TEXT, keep = [], more = '…'} = {}) {
74
+ const tail = keep.filter(Boolean);
75
+ let budget = max - tail.reduce((n, l) => n + l.length + 1, 0);
76
+ const out = [];
77
+ for (let i = 0; i < lines.length; i++) {
78
+ const l = String(lines[i] ?? '');
79
+ const room = budget - (l.length + 1);
80
+ if (room < (i < lines.length - 1 ? more.length + 1 : 0)) { out.push(more); break; }
81
+ out.push(l);
82
+ budget = room;
83
+ }
84
+ return [...out, ...tail].join('\n');
85
+ }
86
+
87
+ /** Plain text cut to `max` characters (for text that is not HTML). */
88
+ export function clip(text, max = MAX_TEXT) {
89
+ const s = String(text ?? '');
90
+ return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
91
+ }
92
+
93
+ export const sendMessage = (token, chatId, text, extra = {}) => call(token, 'sendMessage', {chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true, ...extra});
94
+
95
+ /**
96
+ * A one-time code: letters and digits only (no look-alikes), as /start payloads and typing allow. From the
97
+ * CSPRNG, never Math.random - a guessed link code would let a stranger's chat receive what the site sends.
98
+ */
99
+ const CODE_CHARS = 'abcdefghjkmnpqrstuvwxyz23456789';
100
+ export const randomCode = (n = 16) => Array.from({length: n}, () => CODE_CHARS[randomInt(CODE_CHARS.length)]).join('');
101
+
102
+ /** "/start o7xk2…" -> {command: 'start', arg: 'o7xk2…'}; also "/link@MyBot code". Not a command -> null. */
103
+ export function parseCommand(text) {
104
+ const m = /^\/([a-z_]+)(?:@\w+)?(?:\s+(\S+))?/i.exec(String(text || '').trim());
105
+ return m ? {command: m[1].toLowerCase(), arg: m[2] || ''} : null;
106
+ }
107
+
108
+ /** Timing-safe: is `given` the non-empty secret `want`? For the webhook header and link codes. */
109
+ export function sameSecret(given, want) {
110
+ const a = Buffer.from(String(given ?? ''));
111
+ const b = Buffer.from(String(want ?? ''));
112
+ return b.length > 0 && a.length === b.length && timingSafeEqual(a, b);
113
+ }
114
+
115
+ /** A chat's name for the admin: the group's title, else the person's name, else @username. */
116
+ export function chatName(chat) {
117
+ if (!chat) return '';
118
+ const s = chat.title || [chat.first_name, chat.last_name].filter(Boolean).join(' ') || (chat.username ? `@${chat.username}` : '') || 'this chat';
119
+ return String(s).slice(0, 80);
120
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "note": "Written by `make sync-free-tier` in dcms-marketplace. Do not edit these plugins here - edit them there and sync.",
3
- "source": "dcms-marketplace@5d5eabe5",
3
+ "source": "dcms-marketplace@c3d9700c",
4
4
  "plugins": {
5
5
  "blog": {
6
6
  "version": "1.11.0",
@@ -347,23 +347,48 @@
347
347
  "tests/shape.test.js": "7866c6c1d140716bf0817449937d6d711d7c3b97be1db1e1eb33bde341e36296"
348
348
  }
349
349
  },
350
+ "telegram": {
351
+ "version": "0.1.0",
352
+ "files": {
353
+ "CHANGELOG.md": "ea40431f37d2e1fad82169952197ae7a3636c8a0e16334c29af171037e13eaae",
354
+ "CLAUDE.md": "620e8133a023bf861b7f4a4b07dd47876ca0622f75f08313b07fd22d2dbbef0b",
355
+ "admin/css/index.css": "39eba0652bf8aad92296f3916d9870c4c6c682a4a6f6183d85c4045992c661e8",
356
+ "admin/lib/arrange.js": "9479d259020b58c40478e37c771efbf7932396df87829333d8cbb6d42bea5f28",
357
+ "admin/lib/kit.js": "63bb373dbb6dd082432470db9f1df155f5322f89f4586c731639c33e863beacf",
358
+ "admin/templates/telegram.html": "081efacde0d270fe8382f5d0bcfe4cac59e5015e8e2193787d0d684fa499b493",
359
+ "admin/views/chats.js": "b5d533e3a0952dbd88a323f08b7e74130e2f5ce410dac6b10f4ed22232ee8573",
360
+ "admin/views/connection.js": "d39834f2c5e3827b083cc56706cd08c87457937ea6e12706df8cea0be1ee38ba",
361
+ "admin/views/telegram.js": "ff38bddd2ae5908874f400750fab8ba8e4080c308444dce7528f12a1373a37ec",
362
+ "admin/views/test.js": "5417a8b0a7427cc1f874886dddbe56d8625652619835b864f6e968eb95c419a7",
363
+ "config.js": "eb508631684a4bf4fc9dd28f0c7837d04b6e54458d8795d01405908cae51b379",
364
+ "docs/guide.md": "c44a50c844e372bcdec9734198ea68c796048cffb6e4fcfa7f9aa874a5cb8a20",
365
+ "lib/messages.js": "5e4eb97a9e48fc8eb89c8c2ad05360e9b46aa909f9cab94147ee46ccf74bd9c5",
366
+ "lib/queue.js": "be269c6b2c4f3a6dfbe23ffd92170aefb70a1d7e27467ec7493ddb022cdebdcb",
367
+ "plugin.js": "fa1b583984b4afda03e553a5c9096ac30734f60203c48874a3631972d22ec670",
368
+ "plugin.json": "93c32b7a419e704fef4ec8791a23bc5f63e0d1bc7b963a1363126b7a8c40142c",
369
+ "tests/api.test.js": "bf1d9842adb8140f018a5ac9f7323dec01e7ee771cba0c52480e074656f87fe6",
370
+ "tests/arrange.test.js": "d90880c4566bde57f59f3a3385a0e9aabfb5b5725b954a06f94ec687a904b56b",
371
+ "tests/messages.test.js": "77b5cb5b700710766a9512a51f3b0dc2bcdb57962f5a325cdf91f68e9f98bc68",
372
+ "tests/queue.test.js": "119217c78be85739b2f4330b6d4026b7c281d7b7e81d4b1f85e13f79163dad51"
373
+ }
374
+ },
350
375
  "theme-roller": {
351
- "version": "1.3.0",
376
+ "version": "1.4.0",
352
377
  "files": {
353
- "CLAUDE.md": "c396bf316dcfe62bdfeee59d6973309aa267ac7a6b20c626f6404b18e4809e64",
378
+ "CLAUDE.md": "3f66142aa2ebe9968d63b237dc42e68bb441b67c01dd2a6d612fc7b2ab539c65",
354
379
  "admin/css/theme-roller.css": "dfb2059fb6da0e5cfaf5bd4c1e1d5da7b1918f0edbeb2a2df8a2333094bc8149",
355
380
  "admin/lib/prompt.js": "36ccd3f1536fbcfa57d69470157df633609ed7f1af41b7e351e4df13db210faf",
356
- "admin/lib/themes.js": "eb521dcd999db513e17d124591bbd4509c756756b8cc80c259bc5b502c63a344",
381
+ "admin/lib/themes.js": "66f3352e68107f698a0da84282c900cb2658293d0eee88b6e700d12a714a5aae",
357
382
  "admin/lib/view.js": "16105e216465bfb0a7a9fe838af6deb5384904327906b98099abbad898b96cdf",
358
- "admin/templates/theme-roller.html": "66fabd3819eeb08544c3ee9fd065a458c9e18d415385f9bba0c92527f96eaa0c",
359
- "admin/views/theme-roller-view.js": "be3d628901b91fd44e12981d06c5a1eb06df0c327a43f86850828cf90b332fb0",
383
+ "admin/templates/theme-roller.html": "e45837316f1f359bee96b9e55d19e61da9c3dcb298c56a0b7e211f43cf3eea92",
384
+ "admin/views/theme-roller-view.js": "f9adf76f8d8c755ac4bf87e6af46cef66375f265db6fb5c008789e581dbb67b9",
360
385
  "config.js": "450f0af4f4c1ecc4c7180f2e364c8a59bfed69dd350fb6b47bce8641c2a37786",
361
- "docs/guide.md": "ced47c67e49b3c02e1f85ab5b6da8e0dc7055fcf2688fc9994cf7b52b03881c9",
386
+ "docs/guide.md": "aaf83ff6b898c6a1aa3100076ff9ad9683933dce2d92260862f307c53db72054",
362
387
  "plugin.js": "e685064cb17b879d41428c71a3a2b072501acaa964088c322964f27f622deff2",
363
- "plugin.json": "cd19ab0a17c40b6305cc3dcd3f60f70d67ab1acd1926eda31957153bbf413b74",
388
+ "plugin.json": "89eec785e3abf8297a0d56cca825841ea3c6a2b30b76d7bbee23601ad6f1c6d5",
364
389
  "tests/api.test.js": "8ad5a76a1feebde7ad6dc3867ee49b25d4a33c3579e2149b955cd8333ab73ef0",
365
390
  "tests/prompt-values.test.js": "8cedaecea858dd76bbb92923ad49f8a7b579a368e681265b095dbe13060edc24",
366
- "tests/themes.test.js": "23071a019db49e3161956517c8bb5bb6e41312ca453819baa761ae613b1cfb67",
391
+ "tests/themes.test.js": "14fd48851788516df9a988e911640419ae10e9bddf159e1e7a3e0bb7480783f2",
367
392
  "tests/view.test.js": "24adb2c3e4f9d84dbcd8450addb134f75e2fec25667cda106ec8c80618247e94"
368
393
  }
369
394
  },
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-11-19
4
+
5
+ - **New Tool: Telegram (free).** Connect your own Telegram bot and link any number of chats - your team's group or one person's chat with the bot - with a one-time code. Each chat chooses which alerts it gets (how serious, from which Tools) and which forms; a form submission arrives with its answers, or with the form's title and a link only. Passwords, files, images and hidden fields are never sent, nor notifications meant for one person, and a chat gets only what the person who set it up may see in the admin. Tabs: Connection, Chats, Test.
@@ -0,0 +1,77 @@
1
+ # Telegram - AI Assistant Guide
2
+
3
+ Free Tool. Maintained in `dcms-marketplace/plugins/telegram`; the copy in domma-cms is made by `make sync-free-tier`
4
+ (never edit it there). Telegram Pro (`plugins/telegram-pro`, paid) builds on it through the registry below.
5
+
6
+ ## What it does
7
+
8
+ The site's own bot (made with @BotFather) sends the team alerts (`notification:raised`, CMS core) and form
9
+ submissions (`form:submitted`) to linked chats, each with its own routing. Bot API helpers are the engine's
10
+ `plugins/_lib/telegram/bot.js` (shared with Telegram Pro; Takeaway still has its own copy).
11
+
12
+ ## Files
13
+
14
+ - `plugin.js` - routes, the webhook, the listeners, the registry.
15
+ - `lib/messages.js` - PURE: routing (`cleanRouting`, `chatsForAlert`, `chatsForForm`), message text (`alertText`,
16
+ `formText`) and what is never sent (`NEVER_SENT`, `isPersonal`). Every privacy rule lives here.
17
+ - `lib/queue.js` - per-chat queue, ~1 message/s, 429 waited out once, 50 waiting max, never throws. Each message
18
+ carries the token it was queued under (a bot change never sends old messages with the new bot).
19
+ - Message text is built from whole lines with `escFit`/`fitLines` (bot.js): never cut after escaping.
20
+ - `admin/views/telegram.js` - tab shell (Connection, Chats, Test) over one `status` observable.
21
+ - `admin/views/{connection,chats,test}.js` - each `mount(root, ctx)`, domma-reactive throughout.
22
+ - `admin/lib/kit.js` - run-time admin helpers, API, `openPanel` (dirty guard), `wireRows` (menu, Shift+F10, Enter,
23
+ arrows), drafts. Telegram Pro imports it from `/plugins/telegram/admin/lib/kit.js`.
24
+ - `admin/lib/arrange.js` - PURE display strings and the routing panel's draft/body.
25
+ - `docs/guide.md` - the user guide (Documentation > Plugins). Update with behaviour.
26
+
27
+ ## Storage
28
+
29
+ `config/plugins.json` `telegram.settings` (defaults in `config.js`): `botToken`, `botName`, `secret` (webhook),
30
+ `base` (the https origin given at Connect), `linkSecret`/`linkSecretUntil` (named to match the core's secret mask),
31
+ `linkOwnerId`/`linkOwnerName` (who made the live code: the new chat's owner; a Manager staff session never owns),
32
+ `chats: [{id, chatId, name, type, linkedAt, paused, lastError, lastSentAt, alerts, forms}]`. Written only by this
33
+ Tool's routes. The token, secret and link code are never in a reply; the link code only to `manage`.
34
+
35
+ ## Routes (/api/plugins/telegram; permission `telegram`: read / manage)
36
+
37
+ | Method | Path | Who | Purpose |
38
+ |---|---|---|---|
39
+ | GET | /status | read | bot, webhook health, chats, forms, sources; link code to manage only |
40
+ | GET | /count | read | badge: linked chats (inventory), red on a webhook problem or a failed send |
41
+ | POST | /connect | manage | `{token, base}`: getMe, getWebhookInfo (refuses a bot whose webhook points elsewhere), setWebhook with a secret |
42
+ | DELETE | /connection | manage | deleteWebhook, forget token, secret and chats |
43
+ | POST | /link-code | manage | one-time code: 16 chars, 15 min, burnt after 5 wrong tries |
44
+ | PUT | /chats/:id | manage | `{name, paused, alerts, forms}` through `cleanRouting` |
45
+ | DELETE | /chats/:id | manage | unlink (the chat is told) |
46
+ | POST | /test | manage | `{kind: hello|alert|form|notification, chat, form, severity}` |
47
+ | POST | /webhook | Telegram | `X-Telegram-Bot-Api-Secret-Token` checked timing-safe, else 401 |
48
+
49
+ The webhook answers 200 at once and handles updates one at a time per chat on a promise chain (100 waiting max per chat) (`awaitUpdates: true` in
50
+ tests makes the route wait); `update_id`s are remembered (last 500), so Telegram's resends do nothing.
51
+ Webhook commands: `/link <code>`, `/unlink` (in a linked chat); without Pro also `/start` (private) and `/help`.
52
+ Wrong link codes: 5 per chat (then that chat is ignored for that code), 50 in all burn it.
53
+ `migrate_to_chat_id` moves a linked group to its supergroup id. Everything else goes to the registry handlers.
54
+
55
+ ## Registry (Telegram Pro)
56
+
57
+ `globalThis[Symbol.for('domma.telegram')]` = `{version: 1, handlers, register(name, {onMessage}), unregister(name),
58
+ services}`. `onMessage(msg, {command, linked})` resolves true when it took the update. `services`: `ready()`,
59
+ `botName()`, `base()`, `siteName()`, `chats()` (no token), `send(chatId, html, extra)` (queued, resolves to
60
+ Telegram's answer, never rejects), `esc`.
61
+
62
+ ## Gotchas
63
+
64
+ - The core bus has no `off`: the listeners are added once per process (`listening`) and call the live instance.
65
+ - Owners: a chat has `ownerId`/`ownerName` - who made its link code, then who last changed its alerts or forms.
66
+ Alerts go only if `inAudience(data.audience, owner)` (core notify.js); forms only if the owner holds
67
+ `collections.read` and `canSeeArtefact(owner, form)` (projects). Owners are read fresh (`getUserById`, 60 s cache);
68
+ a deleted or inactive owner stops the chat. `PUT /chats/:id` with forms on needs `collections.read` and keeps only
69
+ slugs the caller can see; `GET /status` lists only those forms.
70
+ - Manager-pushed and sample notifications are written straight to the store, not through `notify()`, so they never
71
+ reach `notification:raised`.
72
+ - A notification with `audience.userIds` is personal and never sent. Form fields: only those the form defines;
73
+ never `password`, `file`, `image`, `hidden`, layout types, or a name like password/secret/token; an object value
74
+ (a file ref) is never sent. A deleted form sends title and link only.
75
+ - `notification:raised` arrives with CMS core's emit (domma-cms PR, notify.js). On an older CMS alerts simply
76
+ do not arrive; forms still do. `_lib/telegram/bot.js` must be in the CMS for the Tool to load at all.
77
+ - Tests: `tests/*.test.js`, Telegram swapped by `setTelegram`; never a real call.
@@ -0,0 +1,68 @@
1
+ /* Telegram (and Telegram Pro) admin. Theme tokens only, so light, dark and Theme Roller themes all read right. */
2
+
3
+ .tg [hidden], .tg-panel [hidden] { display: none !important; }
4
+ .tg { max-width: 64rem; display: flex; flex-direction: column; gap: 1rem; }
5
+ .tg-stack { display: flex; flex-direction: column; gap: 1rem; }
6
+
7
+ /* Tabs under the banner */
8
+ .tg-nav { display: flex; flex-wrap: wrap; gap: .15rem; border-bottom: 1px solid var(--dm-border); }
9
+ .tg-nav a { display: inline-flex; align-items: center; gap: .4rem; padding: .5rem .85rem; color: var(--dm-text-secondary); text-decoration: none;
10
+ font-size: var(--dm-font-size-sm); font-weight: 500; border-bottom: 2px solid transparent; margin-bottom: -1px; }
11
+ .tg-nav a:hover { color: var(--dm-text); background: var(--dm-hover-bg); }
12
+ .tg-nav a.is-on { color: var(--dm-primary); border-bottom-color: var(--dm-primary); font-weight: 600; }
13
+
14
+ /* Cards */
15
+ .tg-card { background: var(--dm-surface); border: 1px solid var(--dm-border); border-radius: var(--dm-radius-lg); padding: 1rem 1.1rem;
16
+ display: flex; flex-direction: column; gap: .7rem; min-width: 0; }
17
+ .tg-card > header { display: flex; align-items: center; justify-content: space-between; gap: .5rem; flex-wrap: wrap; }
18
+ .tg-card h3 { margin: 0; font-size: 1.05rem; display: inline-flex; align-items: center; gap: .45rem; }
19
+ .tg-card h4 { margin: .4rem 0 0; font-size: .95rem; display: inline-flex; align-items: center; gap: .4rem; }
20
+ .tg-bar { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
21
+ .tg-spacer { flex: 1; }
22
+
23
+ .tg-note { margin: 0; color: var(--dm-text-secondary); font-size: var(--dm-font-size-sm); }
24
+ .tg-note.is-bad { color: var(--dm-danger); }
25
+ .tg-note.is-warn { color: var(--dm-text); background: color-mix(in srgb, var(--dm-warning) 14%, transparent); border-radius: var(--dm-radius-md); padding: .45rem .7rem; }
26
+ .tg-loading { color: var(--dm-text-secondary); font-size: var(--dm-font-size-sm); padding: .5rem 0; }
27
+ .tg-steps { margin: 0; padding-left: 1.3rem; display: flex; flex-direction: column; gap: .4rem; }
28
+ .tg-code { font-family: var(--dm-font-mono, monospace); padding: .1rem .4rem; border-radius: var(--dm-radius-md);
29
+ background: color-mix(in srgb, var(--dm-text-secondary) 14%, transparent); user-select: all; }
30
+ .tg-token { display: flex; gap: .5rem; flex-wrap: wrap; }
31
+ .tg-token input { flex: 1; min-width: 16rem; font-family: var(--dm-font-mono, monospace); }
32
+
33
+ .tg-chip { font-size: var(--dm-font-size-xs); font-weight: 600; padding: .12rem .55rem; border-radius: var(--dm-radius-full); white-space: nowrap;
34
+ background: color-mix(in srgb, var(--dm-text-secondary) 14%, transparent); color: var(--dm-text); }
35
+ .tg-chip.is-ok { background: color-mix(in srgb, var(--dm-success) 20%, transparent); }
36
+ .tg-chip.is-warn { background: color-mix(in srgb, var(--dm-warning) 22%, transparent); }
37
+ .tg-chip.is-bad { background: color-mix(in srgb, var(--dm-danger) 20%, transparent); }
38
+
39
+ /* Rows (chats; Pro's conversations) */
40
+ .tg-list { display: flex; flex-direction: column; }
41
+ .tg-row { display: flex; align-items: center; gap: .75rem; padding: .6rem .5rem; border-top: 1px solid var(--dm-border); cursor: pointer; border-radius: var(--dm-radius-md); }
42
+ .tg-row:first-child { border-top: 0; }
43
+ .tg-row:hover, .tg-row:focus-visible { background: var(--dm-hover-bg); outline: none; }
44
+ .tg-row.is-on { background: var(--dm-primary-light); }
45
+ .tg-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: .1rem; }
46
+ .tg-main strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
47
+ .tg-main small { color: var(--dm-text-secondary); font-size: var(--dm-font-size-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
48
+ .tg-main small.is-bad { color: var(--dm-danger); }
49
+ .tg-kebab { border: 0; background: none; color: var(--dm-text-secondary); cursor: pointer; font-size: 1.1rem; padding: 0 .35rem; border-radius: var(--dm-radius-md); }
50
+ .tg-kebab:hover { background: var(--dm-hover-bg); color: var(--dm-text); }
51
+ .tg-dot { width: .55rem; height: .55rem; border-radius: 50%; background: var(--dm-primary); flex: none; }
52
+ .tg-empty { text-align: center; padding: 2rem 1rem; color: var(--dm-text-secondary); }
53
+ .tg-empty h3 { justify-content: center; margin-bottom: .4rem; color: var(--dm-text); }
54
+
55
+ /* Panels */
56
+ .tg-panel { display: flex; flex-direction: column; gap: .55rem; padding: .25rem 0; }
57
+ .tg-panel fieldset { border: 1px solid var(--dm-border); border-radius: var(--dm-radius-md); padding: .6rem .8rem; margin: 0; display: flex; flex-direction: column; gap: .4rem; }
58
+ .tg-panel legend { font-weight: 600; padding: 0 .3rem; display: inline-flex; align-items: center; gap: .35rem; }
59
+ .tg-check { display: flex; align-items: center; gap: .45rem; font-size: var(--dm-font-size-sm); }
60
+ .tg-checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr)); gap: .25rem .8rem; max-height: 14rem; overflow: auto; }
61
+ .tg-checks small { color: var(--dm-text-secondary); }
62
+ .tg-actions { display: flex; gap: .5rem; align-items: center; margin-top: .6rem; }
63
+
64
+ /* Test */
65
+ .tg-test { display: grid; grid-template-columns: minmax(10rem, 16rem) 1fr; gap: .6rem 1rem; align-items: center; }
66
+ @media (max-width: 640px) { .tg-test { grid-template-columns: 1fr; } }
67
+
68
+ .tg .btn { display: inline-flex; align-items: center; gap: .35rem; }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Telegram admin - display strings and row shapes. PURE (no DOM, no globals), so the views hold observables,
3
+ * bindings and API calls only, and this is tested (tests/arrange.test.js).
4
+ *
5
+ * @module telegram/admin/lib/arrange
6
+ */
7
+
8
+ const SEV_LABEL = {info: 'Info', success: 'Success', warning: 'Warning', critical: 'Critical'};
9
+ const TYPE_LABEL = {private: 'Person', group: 'Group', supergroup: 'Group', channel: 'Channel'};
10
+
11
+ export const severityLabel = (s) => SEV_LABEL[s] || s;
12
+ export const typeLabel = (t) => TYPE_LABEL[t] || 'Chat';
13
+
14
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
15
+
16
+ /** "Warning and critical alerts from every Tool" / "No alerts". */
17
+ export function alertsSummary(alerts, sources = []) {
18
+ if (!alerts?.on || !alerts.severities?.length) return 'No alerts';
19
+ const sev = alerts.severities.map(severityLabel);
20
+ const list = sev.length === 4 ? 'All alerts' : `${sev.length > 1 ? `${sev.slice(0, -1).join(', ')} and ${sev.at(-1).toLowerCase()}` : sev[0]} alerts`;
21
+ if (!alerts.sources?.length) return `${list} from every Tool`;
22
+ const names = alerts.sources.map(id => sources.find(s => s.id === id)?.label || sources.find(s => s.owner === id)?.ownerLabel || id);
23
+ return `${list} from ${names.length <= 2 ? names.join(' and ') : plural(names.length, 'source')}`;
24
+ }
25
+
26
+ /** "Every form, with the answers" / "2 forms, title and link only" / "No forms". */
27
+ export function formsSummary(forms, all = []) {
28
+ if (!forms?.on || (!forms.all && !forms.slugs?.length)) return 'No forms';
29
+ const how = forms.detail === 'title' ? 'title and link only' : 'with the answers';
30
+ if (forms.all) return `Every form, ${how}`;
31
+ const names = forms.slugs.map(s => all.find(f => f.slug === s)?.title || s);
32
+ return `${names.length <= 2 ? names.join(' and ') : plural(names.length, 'form')}, ${how}`;
33
+ }
34
+
35
+ /** One row of the Chats list. */
36
+ export function chatRow(c, {sources = [], forms = []} = {}) {
37
+ return {
38
+ id: c.id,
39
+ name: c.name,
40
+ type: typeLabel(c.type),
41
+ alerts: alertsSummary(c.alerts, sources),
42
+ forms: formsSummary(c.forms, forms),
43
+ paused: Boolean(c.paused),
44
+ problem: c.lastError ? `Last message not sent: ${c.lastError}` : '',
45
+ owner: c.ownerName ? `Gets what ${c.ownerName} may see` : 'No owner - open it and save to choose what it gets',
46
+ title: `${c.name} - ${typeLabel(c.type)}`
47
+ };
48
+ }
49
+
50
+ /** The Connection tab's state, from GET /status. */
51
+ export function connectionView(st = {}) {
52
+ const w = st.webhook || null;
53
+ let hook = '';
54
+ if (st.connected && w) {
55
+ if (w.error) hook = `Telegram did not answer: ${w.error}`;
56
+ else if (!w.ours) hook = w.url ? 'The bot now sends its messages somewhere else - another Tool or site took it over. Connect it again, or use a second bot.' : 'The bot has no webhook - connect it again.';
57
+ else if (w.lastError && w.lastErrorAt && Date.now() - Date.parse(w.lastErrorAt) < 3600_000) hook = `Telegram could not reach this site: ${w.lastError}`;
58
+ }
59
+ return {
60
+ connected: Boolean(st.connected),
61
+ botAt: st.botName ? `@${st.botName}` : '',
62
+ botLink: st.botName ? `https://t.me/${st.botName}` : '',
63
+ base: st.base || '',
64
+ hookError: hook,
65
+ pending: w?.pending ? plural(w.pending, 'update') + ' waiting' : '',
66
+ chats: plural((st.chats || []).length, 'linked chat'),
67
+ manage: Boolean(st.can?.manage)
68
+ };
69
+ }
70
+
71
+ /** The "Link a chat" steps. */
72
+ export function linkView(st = {}) {
73
+ const code = st.linkCode || '';
74
+ return {code, line: code ? `/link ${code}` : '', until: st.linkCodeUntil || ''};
75
+ }
76
+
77
+ /** The routing panel's starting values, as strings and booleans the bindings can hold. */
78
+ export function routingDraft(c, {sources = [], forms = []} = {}) {
79
+ return {
80
+ name: c.name || '',
81
+ alertsOn: Boolean(c.alerts?.on),
82
+ severities: Object.fromEntries(Object.keys(SEV_LABEL).map(s => [s, (c.alerts?.severities || []).includes(s)])),
83
+ allSources: !(c.alerts?.sources || []).length,
84
+ sources: Object.fromEntries(sources.map(s => [s.id, (c.alerts?.sources || []).includes(s.id)])),
85
+ formsOn: Boolean(c.forms?.on),
86
+ allForms: Boolean(c.forms?.all),
87
+ forms: Object.fromEntries(forms.map(f => [f.slug, (c.forms?.slugs || []).includes(f.slug)])),
88
+ detail: c.forms?.detail === 'title' ? 'title' : 'fields'
89
+ };
90
+ }
91
+
92
+ /** The routing panel's values -> the PUT /chats/:id body. */
93
+ export function routingBody(d) {
94
+ const picked = (o) => Object.entries(o || {}).filter(([, v]) => v).map(([k]) => k);
95
+ return {
96
+ name: String(d.name || '').trim(),
97
+ alerts: {on: Boolean(d.alertsOn), severities: picked(d.severities), sources: d.allSources ? [] : picked(d.sources)},
98
+ forms: {on: Boolean(d.formsOn), all: Boolean(d.allForms), slugs: d.allForms ? [] : picked(d.forms), detail: d.detail === 'title' ? 'title' : 'fields'}
99
+ };
100
+ }
101
+
102
+ /** A fingerprint of routing values, to tell a changed panel from an untouched one. */
103
+ export const routingPrint = (d) => JSON.stringify(routingBody(d));