@narumitw/pi-notify 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 narumiruna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # 🔔 pi-notify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@narumitw/pi-notify)](https://www.npmjs.com/package/@narumitw/pi-notify)
4
+ [![Pi extension](https://img.shields.io/badge/Pi-extension-blue)](https://pi.dev)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
6
+
7
+ Send Telegram reminders when Pi stops automatic work, so you can return to review its result.
8
+
9
+ ## ✨ Features
10
+
11
+ - Notify private chats, groups, supergroups, and forum topics, including multiple selected destinations.
12
+ - Identify the computer, session, repository, branch, and worktree without forwarding conversations.
13
+ - Choose immediate notifications or reminders after terminal inactivity.
14
+ - Configure and test destinations through a masked, menu-first setup flow.
15
+
16
+ ## 📦 Install
17
+
18
+ Extensions run with Pi's permissions. Enable this extension only if the notification metadata may leave your computer. Bot credentials are stored in a private user settings file, not project settings.
19
+
20
+ From a local checkout, run these commands from the repository root:
21
+
22
+ ```sh
23
+ npm install
24
+ npm run build
25
+ pi -e ./packages/pi-notify
26
+ ```
27
+
28
+ After npm publication, persistent and temporary installation will be available with:
29
+
30
+ ```sh
31
+ pi install npm:@narumitw/pi-notify
32
+ pi -e npm:@narumitw/pi-notify
33
+ ```
34
+
35
+ Restart Pi or run `/reload` after persistent installation. The extension uses Pi's TypeScript loader and does not require a package-owned build. It requires Pi APIs for `agent_settled`, `getAgentDir()`, and trusted project settings, plus Node.js with native `fetch` and `AbortSignal.any()`.
36
+
37
+ ## 🚀 Quick start
38
+
39
+ Create a bot with Telegram's [BotFather](https://t.me/BotFather), then start a private conversation with it. Obtain that conversation's numeric chat ID through the [Bot API](https://core.telegram.org/bots/api#getupdates) after sending a message; keep the bot token private. For a group, add the bot and permit it to send messages. Stop any other update consumer before manually using `getUpdates`; an active webhook also prevents that method from working.
40
+
41
+ Run `/notify`, add a Telegram destination with its bot token and chat ID, and confirm its settings. The name is generated automatically; the review screen lets you change it or set an optional forum topic ID. Use Send test to preview the disclosed metadata and explicitly send a test. Choose Save and use to save the chat and select it for User notifications, or Save only to store it without selecting it. Automatic notifications are on by default, so the next eligible settled work period sends a reminder. Settings lets you pause automatic notifications or change the selected destinations. Existing Off settings and explicit Project selections are preserved.
42
+
43
+ ## 💬 Commands
44
+
45
+ `/notify` opens destination management, Settings, Status, Help, and confirmed test delivery in TUI mode. It accepts no arguments. Settings changes save immediately; closing the screen does not undo them. Destination edits remain unsaved until confirmation. Escape goes back; Ctrl+C closes the flow. Cancelling a running test closes the menu and cannot recall a message already accepted by Telegram.
46
+
47
+ RPC receives manual configuration instructions instead of a custom terminal screen. Print and JSON reject interactive setup. Automatic delivery is independent of the menu and requires no model tool or prompt changes.
48
+
49
+ ## ⚙️ Settings
50
+
51
+ User settings are stored at `<getAgentDir()>/pi-notify.json`, normally `~/.pi/agent/pi-notify.json`. Trusted project overrides use `<workspace>/.pi/pi-notify.json`. Choose User or Project scope in `/notify` Settings. Destinations and credentials are always User-scoped.
52
+
53
+ Notifications default to enabled, with immediate mode and a stored inactivity duration of 30 seconds. Loading defaults does not create a file. Successful menu saves apply immediately; manual edits take effect on session start or `/reload`.
54
+
55
+ ```json
56
+ {
57
+ "enabled": true,
58
+ "mode": "after-inactivity",
59
+ "inactivitySeconds": 30,
60
+ "targetIds": ["personal"],
61
+ "destinations": {
62
+ "personal": {
63
+ "provider": "telegram",
64
+ "label": "Personal Telegram",
65
+ "botToken": "<bot-token>",
66
+ "chatId": "123456789"
67
+ }
68
+ }
69
+ }
70
+ ```
71
+
72
+ See the bundled [settings and behavior reference](./docs/settings.md) for accepted values, inheritance, persistence, provider boundaries, failure recovery, and inactivity timing.
73
+
74
+ ## 🔒 Security and privacy
75
+
76
+ Notifications send the operating-system hostname, session name and ID, working directory, available Git repository/worktree/branch, elapsed time, and settlement timestamp to the selected Telegram chats. Paths shorten the home prefix to `~` when possible, but names and paths can still disclose private information. They describe the host running Pi, which can differ from your SSH client computer.
77
+
78
+ No prompts, assistant answers, code, tool output, Git remotes, or raw provider errors are sent. Dynamic metadata is bounded and terminal controls are removed; `@` is replaced with `@` to avoid accidental mentions. Messages use plain text with link previews disabled. Credential values never appear in preview, status, or error output. POSIX settings writes use `0600` permissions and temporary-file-plus-rename publication. JavaScript memory is not secure credential storage; revoke an exposed bot token through BotFather.
79
+
80
+ ## 🚧 Limitations
81
+
82
+ Only Telegram is implemented. The provider boundary separates transport from notification policy, but it does not load third-party plugins.
83
+
84
+ Inactivity means no input reached this extension, not proof that you are away. Pi handles fullscreen focus, mouse, scrolling, and search before extension input listeners. Those actions do not reliably cancel a reminder. Reading without typing can still produce one. Type a key that reaches the editor to cancel a pending reminder. Focus or mouse events count only if Pi forwards them; terminal support alone is not sufficient. This extension does not change Pi's listener order, enable focus reporting, or detect screen locks. RPC, print, and JSON cannot observe terminal input, so inactivity mode delivers at settlement instead.
85
+
86
+ Notification delivery is best effort with one attempt and a 10-second request timeout. There is no automatic retry, persistent queue, or replay after reload. Accepted means Telegram accepted a message, not that someone read it. Telegram rate limits can reject rapid runs; Status reports a safe error code and available retry-after time. Immediate shutdown can cancel an in-flight notification, especially in a short-lived headless session.
87
+
88
+ Manual aborts and interactive confirmation prompts do not notify. `agent_settled` means Pi will not continue automatically, not that the requested task succeeded. Preflight errors that do not produce a settled work period cannot generate a completion notification. No cooldown suppresses distinct eligible work periods.
89
+
90
+ ## 🗂️ Package layout
91
+
92
+ - `src/index.ts`: Pi entrypoint forwarding to `src/notify.ts`.
93
+ - `src/`: session coordination, metadata, settings, menu, provider contract, and Telegram transport.
94
+ - `docs/`: installed settings and behavior reference.
95
+ - `test/`: repository-only deterministic tests.
96
+
97
+ The package publishes TypeScript source, documentation, and its license. It does not publish test fixtures or credentials.
98
+
99
+ ## 🔎 Keywords
100
+
101
+ Pi coding agent, Telegram bot, completion notification, inactivity reminder, session, Git worktree.
102
+
103
+ ## 📄 License
104
+
105
+ [MIT](./LICENSE).
@@ -0,0 +1,64 @@
1
+ # Notify settings and behavior
2
+
3
+ Use `/notify` for setup or edit the canonical user JSON file. Settings load on session start, including reload and session replacement. Reads do not create files. Successful menu saves apply immediately; manual file edits need `/reload` or another session start.
4
+
5
+ ## Fields and scope
6
+
7
+ | Field | Accepted values | Default | Scope |
8
+ | --- | --- | --- | --- |
9
+ | `enabled` | Boolean | `true` | User or trusted Project |
10
+ | `mode` | `immediate`, `after-inactivity` | `immediate` | User or trusted Project |
11
+ | `inactivitySeconds` | Whole number from 1 to 86400 | `30` | User or trusted Project |
12
+ | `targetIds` | Array of unique existing destination IDs, at most 32 | Empty | User or trusted Project |
13
+ | `destinations` | Object keyed by stable IDs, at most 32 | Empty | User only |
14
+
15
+ Destination IDs contain 1–64 ASCII letters, digits, underscores, or hyphens, starting with a letter or digit; `constructor`, `prototype`, and `__proto__` are reserved. The menu creates IDs automatically.
16
+
17
+ New destinations require only a bot token and chat ID before review. The menu generates the label as `Telegram <chatId>` and leaves the forum topic unset. The review screen lets you change the label, chat ID, token, or optional topic before saving. Editing an existing destination opens that review with its current values; changing the chat ID preserves its label. Destination changes take effect only after confirmation. For a new chat, Save and use adds it to User `targetIds` in the same atomic save; Save only stores it without selecting it. Editing an existing destination preserves its selection state. Explicit Project selections and saved `enabled: false` values are unchanged. Automatic notifications default to On; Off pauses automatic delivery but still allows manual tests. No delivery occurs without a selected destination.
18
+
19
+ Each Telegram destination has `provider: "telegram"`, a nonempty `label` of at most 128 characters, `botToken`, a numeric string `chatId`, and optional positive safe-integer `messageThreadId`. A group or supergroup ID can be negative. Store IDs as strings, not JSON numbers. Forum topic IDs use Telegram's `message_thread_id` field. Other Telegram chat products with additional required fields are not supported.
20
+
21
+ Resolve defaults, User fields, then trusted Project overrides. Project arrays replace rather than merge. Project files cannot define destinations or credentials. Unknown provider IDs do not fall back to Telegram. Invalid fields, unreadable files, unsupported destinations, or missing selected IDs produce diagnostics and disable automatic delivery until repaired; no partial routing is attempted.
22
+
23
+ Project Settings show inherited values and allow restoring inheritance. Removing a destination clears its User selection atomically, but is blocked if the current trusted Project explicitly selects it. Change that Project selection first. Other projects are not edited; repair their selected IDs before enabling notifications there.
24
+
25
+ ## Persistence and recovery
26
+
27
+ Settings operations are ordered within the process, including across store instances for the same user path. Reads wait for pending writes. This is not a cross-process lock: simultaneous menu edits in different Pi processes can conflict.
28
+
29
+ Writes read the latest valid document, preserve unrelated fields and destination fields, and publish using a same-directory temporary file plus rename. Unknown provider data is retained during unrelated edits. Malformed JSON blocks writes instead of being overwritten with defaults. An existing non-object `destinations` value blocks destination changes. A non-object destination entry cannot be replaced with a new object. Repair these stored structures first; destination setup does not coerce them to empty defaults. A failed save keeps the previous file and effective state; the menu restores the previous displayed setting. A failed operation does not poison subsequent operations. Reload and shutdown await queued settings operations.
30
+
31
+ If a file is malformed, repair it manually before saving. Disable notifications in every effective scope to stop new attempts and cancel pending reminders. Unloading the extension aborts owned delivery work, but cannot recall accepted messages. Revoke exposed tokens before replacing them in User settings.
32
+
33
+ ## Inactivity timing
34
+
35
+ The activity baseline starts when the session and input observer start. It measures only input forwarded by Pi through `ctx.ui.onTerminalInput()`. Keyboard input and paste count when they reach this hook. Clicks, wheel events, and focus-gain reports also count if forwarded. Key releases, mouse motion, terminal capability replies, and focus loss do not. Unknown terminal reports are ignored; unsupported terminal keyboard encodings may therefore not count as activity.
36
+
37
+ In fullscreen mode, Pi registers its viewport listener before extension listeners. It consumes focus events, mouse events, and viewport/search keys. Wheel events can also be consumed, although a focused overlay can cause Pi to forward them. Thus returning to the window, clicking, scrolling, or using a viewport key does not reliably cancel a reminder. In regular mode, more of these events can reach the hook, but delivery still depends on earlier listeners and terminal support. The public API has no observer priority or pre-consumption hook. The extension does not read raw stdin or reorder host listeners.
38
+
39
+ For a 30-second threshold, settlement after 10 seconds without input waits another 20 seconds. Settlement after 40 seconds without input starts delivery immediately. The timestamp in the message remains the settlement time.
40
+
41
+ Observed input during the wait cancels that reminder rather than restarting its timer. New work also cancels the pending reminder; the next settlement is evaluated separately. Settings/destination changes cancel pending reminders and apply to subsequent work periods. The duration row is inactive in immediate mode. Focus reporting is optional and never enabled by the extension. A continuously focused window does not suppress reminders.
42
+
43
+ RPC, print, and JSON use immediate settlement delivery because their client activity is not observable through terminal input. This fallback does not guarantee delivery before a short-lived process exits.
44
+
45
+ ## Work periods and delivery
46
+
47
+ The coordinator observes `before_agent_start`, with `agent_start` as a fallback, and sends only at `agent_settled`. Low-level retries and continuations preserve the initial work-period start time. The final assistant stop reason identifies a terminal error without forwarding its body. An aborted settlement always suppresses notification, even if an earlier assistant error remains. Load/reload never replays past results.
48
+
49
+ Metadata is collected at settlement through bounded Git subprocesses. Missing Git information is omitted. Pending metadata work is cancelled with its reminder. Once a delivery attempt starts, new user work does not cancel it; session replacement, reload, shutdown, or explicit test cancellation does. Late results cannot replace newer per-destination status. Test delivery bypasses automatic enablement and inactivity, requires explicit confirmation, and never changes automatic arming or history.
50
+
51
+ The provider contract validates destinations and sends a provider-neutral notification with a cancellation signal. Providers do not read sessions, change settings, schedule timers, or decide notification policy. The built-in provider map contains only Telegram. Transport results distinguish accepted, failed with a safe code, and cancelled; retry-after is diagnostic, not an automatic retry instruction.
52
+
53
+ Requests use Telegram's fixed HTTPS origin, reject redirects, and do not enable paid broadcasts. Text is clipped to at most 4096 UTF-16 code units without splitting a Unicode code point. Response reads are capped at 65536 bytes. Telegram's JSON `ok` field and HTTP status are both checked. Errors expose only fixed codes, never tokens, request URLs, response bodies, or raw transport exceptions.
54
+
55
+ ## Authoritative references
56
+
57
+ - [Telegram BotFather setup](https://core.telegram.org/bots/tutorial#obtain-your-bot-token).
58
+ - [Telegram sendMessage](https://core.telegram.org/bots/api#sendmessage): chat IDs, forum topics, text limits, and link previews.
59
+ - [Telegram getUpdates](https://core.telegram.org/bots/api#getupdates): manual chat-ID discovery; incompatible with active webhooks.
60
+ - [Telegram ResponseParameters](https://core.telegram.org/bots/api#responseparameters): `retry_after` on flood control.
61
+ - [Telegram rate limits](https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this): avoid more than one message per second in a chat, 20 per minute in a group, and about 30 per second across free broadcasts.
62
+ - [Pi extension lifecycle](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md#agent_start--agent_end--agent_before_settle--agent_settled).
63
+
64
+ Input classification follows the installed Pi `ProcessTerminal` and `StdinBuffer` sequence splitting, Pi's `parseKey`/`isKeyRelease`, and `TuiAltScreen` SGR mouse handling. Pure classifier tests cover keyboard, Unicode, paste, focus, press/release, motion, wheel, legacy mouse, CSI/OSC/DCS/APC replies, and unknown input. These tests do not prove that an event reaches the extension. Installed-runtime tests also pass events through real regular/fullscreen Pi renderers and check listener order, viewport keys, and focused-overlay branches. Physical terminal and multiplexer behavior remains unverified.
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@narumitw/pi-notify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Telegram notifications when Pi settles, with optional inactivity reminders.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-extension",
10
+ "telegram",
11
+ "notifications"
12
+ ],
13
+ "files": [
14
+ "src",
15
+ "README.md",
16
+ "LICENSE",
17
+ "docs"
18
+ ],
19
+ "pi": {
20
+ "extensions": [
21
+ "./src/index.ts"
22
+ ]
23
+ },
24
+ "scripts": {
25
+ "typecheck": "tsc --noEmit"
26
+ },
27
+ "dependencies": {
28
+ "@narumitw/pi-tui-kit": "^0.65.6"
29
+ },
30
+ "peerDependencies": {
31
+ "@earendil-works/pi-coding-agent": "*",
32
+ "@earendil-works/pi-tui": "*"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "https://github.com/narumiruna/pi-extensions",
37
+ "directory": "packages/pi-notify"
38
+ }
39
+ }
@@ -0,0 +1,21 @@
1
+ import { isKeyRelease, parseKey } from "@earendil-works/pi-tui";
2
+
3
+ /** Classify forwarded input, not all terminal activity. Pi can consume events before this hook. */
4
+ export function isUserActivity(data: string): boolean {
5
+ if (!data || isKeyRelease(data)) return false;
6
+ if (data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~")) return true;
7
+ if (data === "\x1b[I") return true;
8
+ if (data === "\x1b[O") return false;
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Match the terminal's SGR protocol envelope.
10
+ const sgr = /^\x1b\[<(\d+);\d+;\d+([Mm])$/.exec(data);
11
+ if (sgr) return sgr[2] === "M" && (Number(sgr[1]) & 32) === 0;
12
+ if (data.length === 6 && data.startsWith("\x1b[M")) {
13
+ const button = data.charCodeAt(3) - 32;
14
+ return (button & 32) === 0 && (button & 3) !== 3;
15
+ }
16
+ // Keys, modified keys, Escape and control keys use Pi's authoritative parser.
17
+ if (parseKey(data) !== undefined) return true;
18
+ // Plain Unicode/pasted characters without an escape/control envelope.
19
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Capability reports are not user activity.
20
+ return !/[\x00-\x1f\x7f-\x9f]/.test(data);
21
+ }
@@ -0,0 +1,162 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { isUserActivity } from "./activity.js";
3
+ import { type Metadata, notificationMetadata } from "./metadata.js";
4
+ import { type DeliveryResult, type Destination, deliver, type Notification, type Providers } from "./provider.js";
5
+ import type { Settings } from "./settings.js";
6
+
7
+ interface Work {
8
+ id: string;
9
+ startedAt: number;
10
+ error: boolean;
11
+ revision: number;
12
+ }
13
+ interface Pending {
14
+ work: Work;
15
+ dueAt: number;
16
+ controller: AbortController;
17
+ timer?: ReturnType<typeof setTimeout>;
18
+ notification?: Notification;
19
+ }
20
+ export interface DeliveryStatus {
21
+ sequence: number;
22
+ result: DeliveryResult | { state: "sending" };
23
+ }
24
+
25
+ /** Session-owned policy. Providers receive only immutable notification data and cancellation. */
26
+ export class Coordinator {
27
+ private alive = true;
28
+ private revision = 0;
29
+ private sequence = 0;
30
+ private work?: Work;
31
+ private pending?: Pending;
32
+ private lastActivity = Date.now();
33
+ private readonly tasks = new Map<Promise<unknown>, AbortController>();
34
+ readonly statuses = new Map<string, DeliveryStatus>();
35
+ constructor(
36
+ private settings: Settings,
37
+ private readonly providers: Providers,
38
+ private readonly tui: boolean,
39
+ private readonly metadata: typeof notificationMetadata = notificationMetadata,
40
+ private readonly onFailure: () => void = () => {},
41
+ ) {}
42
+ get pendingAt(): number | undefined {
43
+ return this.pending?.dueAt;
44
+ }
45
+ observeActivity(): void {
46
+ // Loading settings can take time; do not infer absence before observation starts.
47
+ this.lastActivity = Date.now();
48
+ }
49
+ begin(replace = false): void {
50
+ if (!this.alive) return;
51
+ this.cancelPending();
52
+ if (!this.work || replace)
53
+ this.work = { id: randomUUID(), startedAt: Date.now(), error: false, revision: this.revision };
54
+ }
55
+ assistant(error: boolean): void {
56
+ if (this.work) this.work.error = error;
57
+ }
58
+ input(data: string): void {
59
+ if (this.tui && this.alive && isUserActivity(data)) {
60
+ this.lastActivity = Date.now();
61
+ this.cancelPending();
62
+ }
63
+ }
64
+ apply(settings: Settings): void {
65
+ this.cancelPending();
66
+ this.revision++;
67
+ this.settings = settings;
68
+ for (const id of this.statuses.keys()) if (!Object.hasOwn(settings.destinations, id)) this.statuses.delete(id);
69
+ }
70
+ private cancelPending(): void {
71
+ const pending = this.pending;
72
+ this.pending = undefined;
73
+ if (pending) {
74
+ clearTimeout(pending.timer);
75
+ pending.controller.abort();
76
+ }
77
+ }
78
+ settle(aborted: boolean, data: Pick<Metadata, "sessionId" | "sessionName" | "cwd">): void {
79
+ const work = this.work;
80
+ this.work = undefined;
81
+ if (
82
+ !this.alive ||
83
+ !work ||
84
+ work.revision !== this.revision ||
85
+ aborted ||
86
+ !this.settings.enabled ||
87
+ !this.settings.targetIds.length
88
+ )
89
+ return;
90
+ this.cancelPending();
91
+ const now = Date.now();
92
+ const dueAt =
93
+ this.tui && this.settings.mode === "after-inactivity"
94
+ ? Math.max(now, this.lastActivity + this.settings.inactivitySeconds * 1000)
95
+ : now;
96
+ const pending: Pending = { work, dueAt, controller: new AbortController() };
97
+ this.pending = pending;
98
+ if (dueAt > now) pending.timer = setTimeout(() => this.trySend(pending), dueAt - now);
99
+ const task = this.metadata({ ...data, ...work, settledAt: now }, pending.controller.signal)
100
+ .then((notification) => {
101
+ if (this.pending !== pending || !this.alive || pending.controller.signal.aborted) return;
102
+ pending.notification = notification;
103
+ this.trySend(pending);
104
+ })
105
+ .catch(() => {
106
+ if (this.pending === pending) this.cancelPending();
107
+ });
108
+ this.track(task, pending.controller);
109
+ }
110
+ private trySend(pending: Pending): void {
111
+ if (
112
+ !this.alive ||
113
+ this.pending !== pending ||
114
+ pending.controller.signal.aborted ||
115
+ this.work ||
116
+ Date.now() < pending.dueAt ||
117
+ !pending.notification ||
118
+ !this.settings.enabled
119
+ )
120
+ return;
121
+ this.pending = undefined;
122
+ clearTimeout(pending.timer);
123
+ const notification = pending.notification;
124
+ for (const id of this.settings.targetIds) {
125
+ const destination = this.settings.destinations[id];
126
+ if (destination) void this.send(id, destination, notification);
127
+ }
128
+ }
129
+ private track<T>(promise: Promise<T>, controller: AbortController): Promise<T> {
130
+ this.tasks.set(promise, controller);
131
+ void promise.finally(() => this.tasks.delete(promise)).catch(() => {});
132
+ return promise;
133
+ }
134
+ send(
135
+ id: string,
136
+ destination: Destination,
137
+ notification: Notification,
138
+ signal?: AbortSignal,
139
+ ): Promise<DeliveryResult> {
140
+ const controller = new AbortController();
141
+ const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
142
+ if (!this.alive) controller.abort();
143
+ const sequence = ++this.sequence;
144
+ this.statuses.set(id, { sequence, result: { state: "sending" } });
145
+ const task = deliver(this.providers, destination, notification, combined).then((result) => {
146
+ if (this.alive && this.statuses.get(id)?.sequence === sequence) {
147
+ this.statuses.set(id, { sequence, result });
148
+ if (result.state === "failed") this.onFailure();
149
+ }
150
+ return result;
151
+ });
152
+ return this.track(task, controller);
153
+ }
154
+ async close(): Promise<void> {
155
+ this.alive = false;
156
+ this.work = undefined;
157
+ this.cancelPending();
158
+ for (const controller of this.tasks.values()) controller.abort();
159
+ await Promise.allSettled(this.tasks.keys());
160
+ this.statuses.clear();
161
+ }
162
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./notify.js";