nomadro/src/lib/ntfy.ts
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

54 lines
1.7 KiB
TypeScript

/**
* Publish to self-hosted ntfy (https://ntfy.nomadro.cn).
* Env: NTFY_BASE_URL, NTFY_TOPIC, NTFY_TOKEN (optional Bearer).
*/
export type NtfyPublishInput = {
title: string;
message: string;
priority?: "min" | "low" | "default" | "high" | "urgent" | number;
tags?: string;
topic?: string;
};
export function ntfyConfigured(): boolean {
const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").trim();
const topic = (process.env.NTFY_TOPIC || "nomadro").trim();
return Boolean(base && topic);
}
export async function publishNtfy(input: NtfyPublishInput): Promise<{
ok: boolean;
skipped?: boolean;
status?: number;
error?: string;
}> {
const base = (process.env.NTFY_BASE_URL || "https://ntfy.nomadro.cn").replace(/\/$/, "");
const topic = (input.topic || process.env.NTFY_TOPIC || "nomadro").replace(/^\/+|\/+$/g, "");
if (!base || !topic) {
return { ok: false, skipped: true, error: "ntfy not configured" };
}
const headers: Record<string, string> = {
Title: input.title.slice(0, 200),
Priority: String(input.priority ?? "default"),
};
if (input.tags) headers.Tags = input.tags;
const token = (process.env.NTFY_TOKEN || "").trim();
if (token) headers.Authorization = `Bearer ${token}`;
try {
const res = await fetch(`${base}/${topic}`, {
method: "POST",
headers,
body: input.message.slice(0, 4000),
cache: "no-store",
});
if (!res.ok) {
return { ok: false, status: res.status, error: await res.text().then((t) => t.slice(0, 200)) };
}
return { ok: true, status: res.status };
} catch (e) {
return { ok: false, error: e instanceof Error ? e.message : String(e) };
}
}