Skip to content

Commit b334ba1

Browse files
phasenullclaude
andcommitted
notify: say how to start when notifications or a kind are missing
A typetorch.json with no "notifications" section (templates, templates set, push) now gets a minimal ready-to-paste block naming the kind asked for, valid as it is, and a link to the docs' Kinds section; templates set on a kind that isn't declared names it and shows its stub. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cd13284 commit b334ba1

2 files changed

Lines changed: 94 additions & 5 deletions

File tree

‎src/commands/notify.ts‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
import { NOTIFY_KIND_PATTERN, NOTIFY_PARAM_NAME, NOTIFY_TEMPLATE_MAX, templatePlaceholders, validateConfig, type Project } from "../config.ts";
3838
import { ADMIN_TOKEN_VAR, registerSecret } from "../env.ts";
3939
import { setJsonPath } from "../json.ts";
40+
import { DOCS } from "../tui.ts";
4041
import { bold, dim, emitJson, info, isJson, red, warn, yellow } from "../log.ts";
4142
import type { OpenCloud } from "../opencloud.ts";
4243
import { DS_READ_SCOPE } from "../seqstore.ts";
@@ -210,10 +211,70 @@ export async function notifyCommand(args: ParsedArgs, deps: NotifyDeps = {}) {
210211
}
211212
}
212213

214+
/** Where the docs explain kinds (linked from the "how to start" errors). */
215+
export const NOTIFY_KINDS_DOCS = `${DOCS}/guides/notifications.md#kinds`;
216+
217+
/** A kind's minimal declaration: valid as it is, the text to be rewritten. */
218+
export function kindStub(): Record<string, unknown> {
219+
return { text: "Your message with a {placeholder}", priority: 50, repeat: "daily", send: "preferred_hour" };
220+
}
221+
222+
/** A minimal ready-to-paste `notifications` block with one kind (valid as it is). */
223+
export function notificationsStub(kind: string): Record<string, unknown> {
224+
return {
225+
dailyCap: 1,
226+
quietAfterLeaveMinutes: 120,
227+
lapse: [
228+
[14, 7],
229+
[30, 2],
230+
[60, 1],
231+
],
232+
unopenedBackoff: { after: 5, factor: 0.5, days: 14 },
233+
kinds: { [kind]: kindStub() },
234+
};
235+
}
236+
237+
function indent(text: string, by = " "): string {
238+
return text
239+
.split("\n")
240+
.map((line) => by + line)
241+
.join("\n");
242+
}
243+
244+
/** The error for a typetorch.json with no `notifications`: how to start, with a block to paste. */
245+
export function noNotificationsError(kind = "my_kind"): Error {
246+
// Pretty, with number pairs kept on one line ("lapse": [[14, 7], ...]).
247+
const pretty = JSON.stringify(notificationsStub(kind), null, 2).replace(/\[\s*(-?[\d.]+),\s*(-?[\d.]+)\s*\]/g, "[$1, $2]");
248+
const block = `"notifications": ${pretty.replace(/\[\s*(\[[^\]]*\](?:,\s*\[[^\]]*\])*)\s*\]/g, (_, inner: string) => `[${inner.replace(/,\s*\[/g, ", [")}]`)}`;
249+
return new Error(
250+
[
251+
`typetorch.json has no "notifications" section. Add one to start (a minimal block, valid as it is; rewrite the text):`,
252+
"",
253+
indent(block),
254+
"",
255+
`Kinds (priority, repeat, send, text and {placeholders}): ${NOTIFY_KINDS_DOCS}`,
256+
].join("\n"),
257+
);
258+
}
259+
260+
/** The error for a kind that isn't declared: its stub to paste under notifications.kinds. */
261+
export function unknownKindError(kind: string, declared: string[]): Error {
262+
const block = `"${kind}": ${JSON.stringify(kindStub())}`;
263+
return new Error(
264+
[
265+
`"${kind}" isn't a kind in typetorch.json (declared: ${declared.join(", ") || "none"}). Add it under "notifications" > "kinds" first:`,
266+
"",
267+
indent(block),
268+
"",
269+
`Kinds (priority, repeat, send, text and {placeholders}): ${NOTIFY_KINDS_DOCS}`,
270+
].join("\n"),
271+
);
272+
}
273+
213274
async function notifyPush(args: ParsedArgs, deps: NotifyDeps) {
214275
const proj = project(args);
215276
const config = proj.config.notifications;
216-
if (!config) throw new Error(`typetorch.json has no "notifications" section: declare the kinds first (docs: guides/notifications.md)`);
277+
if (!config) throw noNotificationsError();
217278
const kinds = Object.entries(config.kinds);
218279
const noTemplate = kinds.filter(([, kind]) => !kind.template).map(([name]) => name);
219280
if (flagBool(args, "dry-run")) {
@@ -356,7 +417,7 @@ export function templateRows(proj: Pick<Project, "config">): TemplateRow[] {
356417

357418
async function notifyTemplates(args: ParsedArgs) {
358419
const proj = project(args);
359-
if (!proj.config.notifications) throw new Error(`typetorch.json has no "notifications" section: declare the kinds first (docs: guides/notifications.md)`);
420+
if (!proj.config.notifications) throw noNotificationsError();
360421
const rows = templateRows(proj);
361422
const url = dashboardUrl(proj.config.universeId);
362423
if (isJson()) return emitJson({ dashboard: url, menu: "Engagement > Notifications", kinds: rows });
@@ -388,8 +449,8 @@ async function notifyTemplateSet(args: ParsedArgs, kindArg: string | undefined,
388449
if (id.length > NOTIFY_TEMPLATE_MAX || !/^[^\s{}"]+$/.test(id)) throw new UsageError(`"${id}" isn't a message id (1-${NOTIFY_TEMPLATE_MAX} characters, no spaces)`);
389450
const proj = project(args);
390451
const config = proj.config.notifications;
391-
if (!config) throw new Error(`typetorch.json has no "notifications" section`);
392-
if (!(kind in config.kinds)) throw new Error(`"${kind}" isn't a kind in typetorch.json (${Object.keys(config.kinds).join(", ") || "none"})`);
452+
if (!config) throw noNotificationsError(kind);
453+
if (!(kind in config.kinds)) throw unknownKindError(kind, Object.keys(config.kinds));
393454
const before = config.kinds[kind].template;
394455
if (before === id) {
395456
if (isJson()) return emitJson({ kind, template: id, changed: false });

‎test/notify.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { tmpdir } from "node:os";
1010
import { join } from "node:path";
1111
import { flagList, parseArgs } from "../src/args";
1212
import { notifyScopeProbe } from "../src/commands/doctor";
13-
import { dashboardUrl, haltedLines, keyFingerprintOf, paramMismatch, templateRows, newNotifyKey, notifyCommand, notifyFlags, parseData, parseParams, parseUserId } from "../src/commands/notify";
13+
import { dashboardUrl, haltedLines, keyFingerprintOf, kindStub, NOTIFY_KINDS_DOCS, notificationsStub, paramMismatch, templateRows, newNotifyKey, notifyCommand, notifyFlags, parseData, parseParams, parseUserId } from "../src/commands/notify";
1414
import { changeSettings } from "../src/commands/settings";
1515
import { templatePlaceholders, validateConfig, validateNotifications, type Project } from "../src/config";
1616
import { setJsonPath } from "../src/json";
@@ -666,6 +666,34 @@ describe("notify templates", () => {
666666
expect(readFileSync(proj.configPath, "utf8")).toBe(before);
667667
});
668668

669+
test("no notifications section / an undeclared kind: the error shows how to start, with a block to paste", async () => {
670+
const bare = project({ notifications: undefined });
671+
const before = readFileSync(bare.configPath, "utf8");
672+
const missing = (await run(bare, () => notifyCommand(notify(["templates", "set", "test", "msg-1"])))).error?.message ?? "";
673+
expect(missing).toContain('typetorch.json has no "notifications" section');
674+
expect(missing).toContain(NOTIFY_KINDS_DOCS);
675+
expect(NOTIFY_KINDS_DOCS).toEndWith("/guides/notifications.md#kinds");
676+
// The pasted block is valid as it is, and names the kind the user asked for.
677+
const pasted = JSON.parse(`{${missing.slice(missing.indexOf('"notifications": {'), missing.indexOf("\n\nKinds"))}}`);
678+
expect(Object.keys(pasted.notifications.kinds)).toEqual(["test"]);
679+
expect(pasted.notifications).toMatchObject({ dailyCap: 1, quietAfterLeaveMinutes: 120, unopenedBackoff: { after: 5 } });
680+
expect(pasted.notifications.kinds.test).toMatchObject({ priority: 50, repeat: "daily", send: "preferred_hour" });
681+
expect(validateNotifications(pasted.notifications).errors).toEqual([]);
682+
expect(validateNotifications(notificationsStub("gift_new")).errors).toEqual([]);
683+
// push and templates say the same.
684+
expect((await run(bare, () => notifyCommand(notify(["templates"])))).error?.message).toContain(NOTIFY_KINDS_DOCS);
685+
expect((await run(bare, () => notifyCommand(notify(["push"])))).error?.message).toContain('"notifications": {');
686+
expect(readFileSync(bare.configPath, "utf8")).toBe(before);
687+
688+
const proj = project({ notifications: { kinds } });
689+
const unknown = (await run(proj, () => notifyCommand(notify(["templates", "set", "test", "msg-1"])))).error?.message ?? "";
690+
expect(unknown).toContain(`"test" isn't a kind in typetorch.json (declared: ${Object.keys(kinds).join(", ")})`);
691+
expect(unknown).toContain(`"test": ${JSON.stringify(kindStub())}`);
692+
expect(unknown).toContain(NOTIFY_KINDS_DOCS);
693+
const withStub = { ...kinds, test: kindStub() };
694+
expect(validateNotifications({ kinds: withStub }).errors).toEqual([]);
695+
});
696+
669697
test("push warns about kinds with a text but no template id", async () => {
670698
const proj = project({ notifications: { kinds } });
671699
const backend = fakeBackend({ "PUT /v1/notify/config": [200, { ok: true }] });

0 commit comments

Comments
 (0)