slack-term 1.47.0 → 1.49.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/ts/slack.ts CHANGED
@@ -41,7 +41,41 @@ function base(): string {
41
41
  return (process.env.SLACK_API_BASE ?? "https://slack.com/api").replace(/\/$/, "");
42
42
  }
43
43
 
44
- async function call(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
44
+ /** How long one call may spend waiting out 429s before it throws
45
+ * RateLimitError (seconds, summed over its retries). A 429 means Slack
46
+ * rejected the request unprocessed, so retrying it — even a write — cannot
47
+ * duplicate anything. One-shot commands wait (`pinlog`, `read`, `send`…);
48
+ * `slack stream` sets 0 because it schedules around Retry-After itself.
49
+ * SLACK_RATELIMIT_WAIT_SEC overrides the default. */
50
+ let rateLimitWaitSec = ((): number => {
51
+ const v = Number(process.env.SLACK_RATELIMIT_WAIT_SEC);
52
+ return Number.isFinite(v) && v >= 0 ? v : 120;
53
+ })();
54
+ export function setRateLimitWait(sec: number): void {
55
+ rateLimitWaitSec = sec;
56
+ }
57
+
58
+ /** Run `once`; while it throws RateLimitError and the budget allows, wait out
59
+ * its Retry-After (one stderr line each, method and seconds only) and retry. */
60
+ export async function withRateLimitWait<T>(once: () => Promise<T>, sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))): Promise<T> {
61
+ let waited = 0;
62
+ for (;;) {
63
+ try {
64
+ return await once();
65
+ } catch (e) {
66
+ if (!(e instanceof RateLimitError) || waited + e.retryAfter > rateLimitWaitSec) throw e;
67
+ waited += e.retryAfter;
68
+ console.error(`slack: ${e.message} — waiting`);
69
+ await sleep(e.retryAfter * 1000);
70
+ }
71
+ }
72
+ }
73
+
74
+ function call(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
75
+ return withRateLimitWait(() => callOnce(token, method, init, cookie));
76
+ }
77
+
78
+ async function callOnce(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
45
79
  cookie = token.startsWith("xoxc-") ? (cookie ?? resolveCookie()) : undefined;
46
80
  const extraHeaders: Record<string, string> = {};
47
81
  if (cookie) extraHeaders["Cookie"] = `d=${cookie}`;
@@ -95,7 +129,11 @@ async function call(token: string, method: string, init: RequestInit, cookie?: s
95
129
  // Internal Slack API caller — does NOT reject xoxc tokens.
96
130
  // Used for hidden endpoints (drafts, etc.) only accessible via session tokens.
97
131
  // cookie: raw xoxd value (without "d=" prefix); injected as Cookie header when present.
98
- async function callSession(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
132
+ function callSession(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
133
+ return withRateLimitWait(() => callSessionOnce(token, method, init, cookie));
134
+ }
135
+
136
+ async function callSessionOnce(token: string, method: string, init: RequestInit, cookie?: string): Promise<Json> {
99
137
  const extraHeaders: Record<string, string> = {};
100
138
  if (cookie) extraHeaders["Cookie"] = `d=${cookie}`;
101
139
  const res = await fetch(`${base()}/${method}`, {
package/ts/stream.ts CHANGED
@@ -136,6 +136,8 @@ export type StreamOpts = {
136
136
  selfUsers: Set<string>;
137
137
  selfBots: Set<string>;
138
138
  json: boolean;
139
+ /** Also called with every emitted match and its attachment count (`slack stream --inbox`). */
140
+ onMatch?: (rec: StreamMatch, files: number) => void;
139
141
  once: boolean;
140
142
  /** Seconds back to (re)start every channel from, overriding the saved cursor. */
141
143
  sinceSec?: number;
@@ -371,6 +373,7 @@ async function consider(
371
373
  match,
372
374
  };
373
375
  ctx.opts.json ? _internals.out(JSON.stringify(rec)) : _internals.out(humanLine(rec));
376
+ ctx.opts.onMatch?.(rec, Array.isArray(m.files) ? m.files.length : 0);
374
377
  ctx.matches++;
375
378
  return true;
376
379
  }
@@ -643,7 +646,7 @@ export async function runStream(client: StreamClient, opts: StreamOpts): Promise
643
646
  `slack stream: WARNING: polling mode (${opts.pollReason ?? "no relay configured"}) — this is the fallback, ` +
644
647
  `not the intended setup: matches arrive up to ${Math.round(opts.intervalMs / 1000)}s late (replies under older ` +
645
648
  `parents up to ${Math.round(Math.max(opts.threadScanSec ?? 180, opts.intervalMs / 1000))}s) and every cycle spends ` +
646
- `Slack API calls. For real time, deploy the relay and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${RELAY_DOCS}`,
649
+ `Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${RELAY_DOCS}`,
647
650
  );
648
651
  }
649
652
  client = paced(client, opts.callsPerMin ?? 40, opts.signal);
package/ts/tick.ts ADDED
@@ -0,0 +1,47 @@
1
+ // `slack tick`: turn a "⬜ <n>." item of a posted checklist into "✅ <n>.",
2
+ // changing nothing else (10-30: when an announced ⬜ criterion is done,
3
+ // edit the original to ✅ rather than only posting a new "done" reply).
4
+ // Slack may store the box as the shortcode, so both spellings are handled and
5
+ // the tick keeps the spelling it found.
6
+
7
+ const BOX = /(⬜️?|:white_large_square:)(\s*)(\d+)\./g;
8
+ const DONE = /(✅|:white_check_mark:)\s*(\d+)\./g;
9
+
10
+ export type TickResult =
11
+ | { kind: "ticked"; text: string; n: number }
12
+ | { kind: "already"; n: number }
13
+ | { kind: "none" }
14
+ | { kind: "ambiguous"; open: number[] }
15
+ | { kind: "missing"; n: number };
16
+
17
+ /** Tick item `n`, or — without `n` — the one open item there is. */
18
+ export function tickText(text: string, n?: number): TickResult {
19
+ const open = [...text.matchAll(BOX)].map((m) => Number(m[3]));
20
+ const done = [...text.matchAll(DONE)].map((m) => Number(m[2]));
21
+ if (n === undefined) {
22
+ if (open.length === 0) return done.length ? { kind: "already", n: done[0]! } : { kind: "none" };
23
+ if (open.length > 1) return { kind: "ambiguous", open };
24
+ n = open[0]!;
25
+ }
26
+ if (!open.includes(n)) return done.includes(n) ? { kind: "already", n } : { kind: "missing", n };
27
+ let hit = false;
28
+ const out = text.replace(BOX, (all, box: string, sp: string, num: string) => {
29
+ if (hit || Number(num) !== n) return all;
30
+ hit = true;
31
+ return `${box.startsWith(":") ? ":white_check_mark:" : "✅"}${sp}${num}.`;
32
+ });
33
+ return { kind: "ticked", text: out, n };
34
+ }
35
+
36
+ /** An edit keeps the lane tag the message was posted with (`[lane] ` or
37
+ * `[lane@host] `), so a rewrite cannot drop or change who said it. Only when
38
+ * `lanePrefix` (the scope's prefix) is the tag the original starts with. */
39
+ export function keepLanePrefix(original: string, next: string, lanePrefix: string | undefined): string {
40
+ const m = /^\[([^\]@\s]+)\]$/.exec(lanePrefix?.trim() ?? "");
41
+ if (!m) return next;
42
+ const lane = m[1]!.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
43
+ const tag = new RegExp(`^\\[${lane}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`);
44
+ const had = tag.exec(original);
45
+ if (!had) return next;
46
+ return had[0] + next.replace(tag, "");
47
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Zachary Rice
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.