selfping 1.1.1 → 1.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/README.md CHANGED
@@ -15,7 +15,23 @@ await sendPing("Deploy finished. 0 errors.");
15
15
  That's it. The key is read from the `SELFPING_API_KEY` environment variable, or pass it directly:
16
16
 
17
17
  ```js
18
- await sendPing("New signup: jane@example.com", { apiKey: "sp_..." });
18
+ await sendPing("New signup: jane@example.com", {
19
+ apiKey: process.env.MY_SELFPING_KEY,
20
+ });
21
+ ```
22
+
23
+ `sendPing` resolves with what the API sent back, so you can see how many texts are left:
24
+
25
+ ```js
26
+ const { remaining, truncated } = await sendPing("Backup finished in 4m12s");
27
+ ```
28
+
29
+ `remaining` is the number of texts left this month, or `null` for a key without a monthly limit. `truncated` is `true` only when a message over 1600 characters was trimmed.
30
+
31
+ Requests time out after 15 seconds. Pass `timeout` in milliseconds to change that:
32
+
33
+ ```js
34
+ await sendPing("Nightly import done", { timeout: 5000 });
19
35
  ```
20
36
 
21
37
  ## From the terminal
@@ -25,9 +41,12 @@ npx selfping login # paste your key once
25
41
  npx selfping "Deploy finished" # send a text
26
42
  some-job | npx selfping # send what you pipe in
27
43
  npx selfping run -- npm test # text me when this finishes
44
+ npx selfping --version # print the version
28
45
  ```
29
46
 
30
- `run` texts you "npm test finished in 4m12s" or "npm test FAILED in 38s (exit 1)" and exits with the command's own exit code, so it drops into scripts and CI unchanged. Add `--label deploy` to name it.
47
+ `run` texts you "npm test finished in 4m12s" or "npm test FAILED in 38s (exit 1)" and exits with the command's own exit code, so it drops into scripts and CI unchanged. Add `--label deploy` to name it. Without a key, `run` stops before starting the command.
48
+
49
+ Unknown options are rejected rather than sent as text. To send a message that starts with a dash, put `--` first: `npx selfping -- "-5 degrees and falling"`.
31
50
 
32
51
  `selfping login` saves the key to `~/.config/selfping/credentials`, readable only by you, and `selfping logout` removes it. When `SELFPING_API_KEY` is set it takes priority, which is the better fit for CI and agents. There is deliberately no `--key` flag, so your key never lands in shell history.
33
52
 
@@ -50,7 +69,13 @@ Guides: [Python and cron](https://www.selfping.com/recipes/python-cron-alert), [
50
69
 
51
70
  ## Errors
52
71
 
53
- `sendPing` resolves on success and throws `SelfPingError` otherwise. The `status` property carries the HTTP status and the message says what went wrong in plain language: bad key, out of texts for the month, or the text could not be delivered.
72
+ `sendPing` throws `SelfPingError` when a text is not sent. It carries:
73
+
74
+ - `message`: what went wrong, in plain language
75
+ - `status`: the HTTP status, or `0` when SelfPing could not be reached or the request timed out
76
+ - `code`: a stable code such as `invalid_key`, `out_of_credits`, `rate_limited` or `delivery_failed`, plus `timeout` and `network_error` for problems on the way
77
+ - `hint`: what to do next
78
+ - `retryAfter`: seconds to wait before trying again, when the API says so
54
79
 
55
80
  ```js
56
81
  import sendPing, { SelfPingError } from "selfping";
@@ -58,10 +83,17 @@ import sendPing, { SelfPingError } from "selfping";
58
83
  try {
59
84
  await sendPing("Backup finished in 4m12s");
60
85
  } catch (err) {
61
- if (err instanceof SelfPingError) console.error(err.status, err.message);
86
+ if (!(err instanceof SelfPingError)) throw err;
87
+ if (err.code === "out_of_credits") {
88
+ console.warn(`Out of texts. Retry in ${err.retryAfter} seconds.`);
89
+ } else {
90
+ console.error(err.status, err.message, err.hint);
91
+ }
62
92
  }
63
93
  ```
64
94
 
95
+ SelfPing gives the credit back when a send fails with `delivery_failed`. Every error code is listed at [selfping.com/docs#errors](https://www.selfping.com/docs#errors).
96
+
65
97
  ## One send, one credit
66
98
 
67
99
  Every send costs exactly one credit, long or short. Keep messages under 160 characters anyway: short texts read best on a lock screen. Lead with the outcome, include the numbers that matter, and say whether anything needs you.
package/cli.mjs CHANGED
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { createRequire } from "node:module";
5
6
  import { createInterface } from "node:readline";
6
7
  import { SelfPingError, sendPing } from "./index.mjs";
7
8
 
@@ -12,14 +13,21 @@ export const HELP = `selfping: text yourself from the terminal.
12
13
  selfping run -- npm test run a command, get a text when it ends
13
14
  selfping login save your API key on this computer
14
15
  selfping logout remove the saved key
16
+ selfping --version print the version
15
17
 
16
18
  Options for run:
17
19
  --label <name> name the command in the text
18
20
 
21
+ To send a text that starts with a dash, put -- before it:
22
+ selfping -- "-5 degrees and falling"
23
+
19
24
  The key comes from SELFPING_API_KEY when it is set, otherwise from
20
25
  selfping login. Get a key at https://www.selfping.com/dashboard
21
26
  `;
22
27
 
28
+ export const VERSION = createRequire(import.meta.url)("./package.json").version;
29
+ const NO_KEY_MESSAGE =
30
+ "No API key. Run `selfping login` or set SELFPING_API_KEY. Get a key at https://www.selfping.com/dashboard\n";
23
31
  const MAX_LENGTH = 1600;
24
32
  const KEY_PATTERN = /^[A-Za-z0-9_-]{16,64}$/;
25
33
 
@@ -84,6 +92,7 @@ function promptHidden(question, input, output) {
84
92
  }
85
93
 
86
94
  export function describeError(err) {
95
+ if (err instanceof SelfPingError && err.hint) return `${err.message} ${err.hint}`;
87
96
  const detail = err instanceof SelfPingError ? err.message : String(err);
88
97
  try {
89
98
  const parsed = JSON.parse(detail)?.error;
@@ -95,9 +104,7 @@ export function describeError(err) {
95
104
  async function send(message, io) {
96
105
  const apiKey = await loadKey(io.env);
97
106
  if (!apiKey) {
98
- io.stderr.write(
99
- "No API key. Run `selfping login` or set SELFPING_API_KEY. Get a key at https://www.selfping.com/dashboard\n"
100
- );
107
+ io.stderr.write(NO_KEY_MESSAGE);
101
108
  return 1;
102
109
  }
103
110
  try {
@@ -152,18 +159,37 @@ async function logout(io) {
152
159
  return 0;
153
160
  }
154
161
 
162
+ function unknownOption(option, io) {
163
+ io.stderr.write(
164
+ `selfping: unknown option ${option}. Run selfping --help to see the options.\n`
165
+ );
166
+ return 2;
167
+ }
168
+
155
169
  async function run(args, io) {
156
170
  let label = null;
157
171
  let rest = args;
158
- if (rest[0] === "--label") {
159
- label = rest[1] ?? null;
172
+ while (rest[0]?.startsWith("-")) {
173
+ if (rest[0] === "--") {
174
+ rest = rest.slice(1);
175
+ break;
176
+ }
177
+ if (rest[0] !== "--label") return unknownOption(rest[0], io);
178
+ if (!rest[1] || rest[1].startsWith("-")) {
179
+ io.stderr.write("selfping: --label needs a name, like --label deploy\n");
180
+ return 2;
181
+ }
182
+ label = rest[1];
160
183
  rest = rest.slice(2);
161
184
  }
162
- if (rest[0] === "--") rest = rest.slice(1);
163
185
  if (rest.length === 0) {
164
186
  io.stderr.write("Usage: selfping run [--label name] -- <command> [args]\n");
165
187
  return 2;
166
188
  }
189
+ if (!(await loadKey(io.env))) {
190
+ io.stderr.write(NO_KEY_MESSAGE);
191
+ return 1;
192
+ }
167
193
  const name = label || rest.join(" ").slice(0, 60);
168
194
  const started = Date.now();
169
195
  const outcome = await new Promise((resolve) => {
@@ -208,14 +234,23 @@ export async function main(argv, overrides = {}) {
208
234
  io.stdout.write(HELP);
209
235
  return 0;
210
236
  }
237
+ if (first === "-v" || first === "--version") {
238
+ io.stdout.write(`${VERSION}\n`);
239
+ return 0;
240
+ }
211
241
  if (first === "login") return login(io);
212
242
  if (first === "logout") return logout(io);
213
243
  if (first === "run") return run(rest, io);
214
244
 
215
- const message = argv.length > 0 ? argv.join(" ") : io.stdin.isTTY ? "" : await readAll(io.stdin);
245
+ const words = first === "--" ? rest : argv;
246
+ if (first !== "--" && first && first.length > 1 && first.startsWith("-")) {
247
+ return unknownOption(first, io);
248
+ }
249
+
250
+ const message = words.length > 0 ? words.join(" ") : io.stdin.isTTY ? "" : await readAll(io.stdin);
216
251
  if (!message.trim()) {
217
252
  io.stdout.write(HELP);
218
- return argv.length === 0 && io.stdin.isTTY ? 0 : 2;
253
+ return words.length === 0 && io.stdin.isTTY ? 0 : 2;
219
254
  }
220
255
  return send(message, io);
221
256
  }
package/index.cjs CHANGED
@@ -1,16 +1,39 @@
1
1
  const ENDPOINT = "https://www.selfping.com/api/sms";
2
+ const DEFAULT_TIMEOUT_MS = 15000;
2
3
 
3
4
  class SelfPingError extends Error {
4
- constructor(message, status) {
5
- super(message);
5
+ constructor(message, status, details = {}) {
6
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
6
7
  this.name = "SelfPingError";
7
8
  this.status = status;
9
+ this.code = details.code ?? null;
10
+ this.hint = details.hint ?? null;
11
+ this.retryAfter = details.retryAfter ?? null;
12
+ }
13
+ }
14
+
15
+ function parseRetryAfter(value) {
16
+ if (!value) return null;
17
+ const seconds = Number(value);
18
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds));
19
+ const at = Date.parse(value);
20
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
21
+ }
22
+
23
+ async function readBody(res) {
24
+ const text = await res.text().catch(() => "");
25
+ try {
26
+ return { text, json: JSON.parse(text) };
27
+ } catch {
28
+ return { text, json: null };
8
29
  }
9
30
  }
10
31
 
11
32
  async function sendPing(message, options = {}) {
12
33
  if (typeof message !== "string" || message.trim().length === 0) {
13
- throw new SelfPingError("message must be a non-empty string", 0);
34
+ throw new SelfPingError("message must be a non-empty string", 0, {
35
+ code: "missing_message",
36
+ });
14
37
  }
15
38
 
16
39
  const apiKey =
@@ -20,26 +43,64 @@ async function sendPing(message, options = {}) {
20
43
  if (!apiKey) {
21
44
  throw new SelfPingError(
22
45
  "No API key. Set the SELFPING_API_KEY environment variable or pass { apiKey }. Get a key at https://www.selfping.com/dashboard",
23
- 0
46
+ 0,
47
+ { code: "missing_key" }
24
48
  );
25
49
  }
26
50
 
27
- const res = await fetch(ENDPOINT, {
28
- method: "POST",
29
- headers: {
30
- "Content-Type": "application/json",
31
- Authorization: `Bearer ${apiKey}`,
32
- },
33
- body: JSON.stringify({ message }),
34
- });
51
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
52
+ if (!Number.isFinite(timeout) || timeout <= 0) {
53
+ throw new TypeError("timeout must be a positive number of milliseconds");
54
+ }
55
+
56
+ let res;
57
+ let body;
58
+ try {
59
+ res = await fetch(ENDPOINT, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/json",
63
+ Authorization: `Bearer ${apiKey}`,
64
+ },
65
+ body: JSON.stringify({ message }),
66
+ signal: AbortSignal.timeout(timeout),
67
+ });
68
+ body = await readBody(res);
69
+ } catch (err) {
70
+ if (err?.name === "TimeoutError" || err?.name === "AbortError") {
71
+ throw new SelfPingError(
72
+ `SelfPing did not answer within ${timeout / 1000}s. The text may still arrive.`,
73
+ 0,
74
+ { code: "timeout", cause: err }
75
+ );
76
+ }
77
+ throw new SelfPingError(
78
+ `Could not reach SelfPing: ${err?.message ?? String(err)}`,
79
+ 0,
80
+ { code: "network_error", cause: err }
81
+ );
82
+ }
35
83
 
36
84
  if (!res.ok) {
37
- const body = await res.text().catch(() => "");
85
+ const error = body.json?.error;
38
86
  throw new SelfPingError(
39
- body || `SelfPing request failed with status ${res.status}`,
40
- res.status
87
+ error?.message || body.text || `SelfPing request failed with status ${res.status}`,
88
+ res.status,
89
+ {
90
+ code: error?.code,
91
+ hint: error?.hint,
92
+ retryAfter: parseRetryAfter(res.headers.get("retry-after")),
93
+ }
41
94
  );
42
95
  }
96
+
97
+ const result = {
98
+ ok: true,
99
+ message: body.json?.message ?? "",
100
+ remaining: body.json?.remaining ?? null,
101
+ };
102
+ if (body.json?.truncated) result.truncated = true;
103
+ return result;
43
104
  }
44
105
 
45
106
  module.exports = sendPing;
package/index.d.ts CHANGED
@@ -1,15 +1,46 @@
1
1
  export interface SendPingOptions {
2
2
  apiKey?: string;
3
+ timeout?: number;
4
+ }
5
+
6
+ export interface SendPingResult {
7
+ ok: true;
8
+ message: string;
9
+ remaining: number | null;
10
+ truncated?: true;
11
+ }
12
+
13
+ export type SelfPingErrorCode =
14
+ | "missing_key"
15
+ | "invalid_key"
16
+ | "no_phone"
17
+ | "out_of_credits"
18
+ | "rate_limited"
19
+ | "invalid_body"
20
+ | "missing_message"
21
+ | "delivery_failed"
22
+ | "internal_error"
23
+ | "timeout"
24
+ | "network_error";
25
+
26
+ export interface SelfPingErrorDetails {
27
+ code?: SelfPingErrorCode | (string & {}) | null;
28
+ hint?: string | null;
29
+ retryAfter?: number | null;
30
+ cause?: unknown;
3
31
  }
4
32
 
5
33
  export declare class SelfPingError extends Error {
6
34
  status: number;
7
- constructor(message: string, status: number);
35
+ code: SelfPingErrorCode | (string & {}) | null;
36
+ hint: string | null;
37
+ retryAfter: number | null;
38
+ constructor(message: string, status: number, details?: SelfPingErrorDetails);
8
39
  }
9
40
 
10
41
  export declare function sendPing(
11
42
  message: string,
12
43
  options?: SendPingOptions
13
- ): Promise<void>;
44
+ ): Promise<SendPingResult>;
14
45
 
15
46
  export default sendPing;
package/index.mjs CHANGED
@@ -1,16 +1,39 @@
1
1
  const ENDPOINT = "https://www.selfping.com/api/sms";
2
+ const DEFAULT_TIMEOUT_MS = 15000;
2
3
 
3
4
  export class SelfPingError extends Error {
4
- constructor(message, status) {
5
- super(message);
5
+ constructor(message, status, details = {}) {
6
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
6
7
  this.name = "SelfPingError";
7
8
  this.status = status;
9
+ this.code = details.code ?? null;
10
+ this.hint = details.hint ?? null;
11
+ this.retryAfter = details.retryAfter ?? null;
12
+ }
13
+ }
14
+
15
+ function parseRetryAfter(value) {
16
+ if (!value) return null;
17
+ const seconds = Number(value);
18
+ if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds));
19
+ const at = Date.parse(value);
20
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - Date.now()) / 1000));
21
+ }
22
+
23
+ async function readBody(res) {
24
+ const text = await res.text().catch(() => "");
25
+ try {
26
+ return { text, json: JSON.parse(text) };
27
+ } catch {
28
+ return { text, json: null };
8
29
  }
9
30
  }
10
31
 
11
32
  export async function sendPing(message, options = {}) {
12
33
  if (typeof message !== "string" || message.trim().length === 0) {
13
- throw new SelfPingError("message must be a non-empty string", 0);
34
+ throw new SelfPingError("message must be a non-empty string", 0, {
35
+ code: "missing_message",
36
+ });
14
37
  }
15
38
 
16
39
  const apiKey =
@@ -20,26 +43,64 @@ export async function sendPing(message, options = {}) {
20
43
  if (!apiKey) {
21
44
  throw new SelfPingError(
22
45
  "No API key. Set the SELFPING_API_KEY environment variable or pass { apiKey }. Get a key at https://www.selfping.com/dashboard",
23
- 0
46
+ 0,
47
+ { code: "missing_key" }
24
48
  );
25
49
  }
26
50
 
27
- const res = await fetch(ENDPOINT, {
28
- method: "POST",
29
- headers: {
30
- "Content-Type": "application/json",
31
- Authorization: `Bearer ${apiKey}`,
32
- },
33
- body: JSON.stringify({ message }),
34
- });
51
+ const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
52
+ if (!Number.isFinite(timeout) || timeout <= 0) {
53
+ throw new TypeError("timeout must be a positive number of milliseconds");
54
+ }
55
+
56
+ let res;
57
+ let body;
58
+ try {
59
+ res = await fetch(ENDPOINT, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/json",
63
+ Authorization: `Bearer ${apiKey}`,
64
+ },
65
+ body: JSON.stringify({ message }),
66
+ signal: AbortSignal.timeout(timeout),
67
+ });
68
+ body = await readBody(res);
69
+ } catch (err) {
70
+ if (err?.name === "TimeoutError" || err?.name === "AbortError") {
71
+ throw new SelfPingError(
72
+ `SelfPing did not answer within ${timeout / 1000}s. The text may still arrive.`,
73
+ 0,
74
+ { code: "timeout", cause: err }
75
+ );
76
+ }
77
+ throw new SelfPingError(
78
+ `Could not reach SelfPing: ${err?.message ?? String(err)}`,
79
+ 0,
80
+ { code: "network_error", cause: err }
81
+ );
82
+ }
35
83
 
36
84
  if (!res.ok) {
37
- const body = await res.text().catch(() => "");
85
+ const error = body.json?.error;
38
86
  throw new SelfPingError(
39
- body || `SelfPing request failed with status ${res.status}`,
40
- res.status
87
+ error?.message || body.text || `SelfPing request failed with status ${res.status}`,
88
+ res.status,
89
+ {
90
+ code: error?.code,
91
+ hint: error?.hint,
92
+ retryAfter: parseRetryAfter(res.headers.get("retry-after")),
93
+ }
41
94
  );
42
95
  }
96
+
97
+ const result = {
98
+ ok: true,
99
+ message: body.json?.message ?? "",
100
+ remaining: body.json?.remaining ?? null,
101
+ };
102
+ if (body.json?.truncated) result.truncated = true;
103
+ return result;
43
104
  }
44
105
 
45
106
  export default sendPing;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "selfping",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "Text yourself from your code or your terminal. One function, one key, texts go only to your own verified phone number.",
5
5
  "keywords": [
6
6
  "sms",