@hamur/notifications 0.0.0-stage → 0.0.2

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.
Files changed (45) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/index.js +235 -0
  4. package/dist/src/server/index.js +282 -0
  5. package/dist/src/test.js +32 -0
  6. package/dist/types/src/build/scan.d.ts +27 -0
  7. package/dist/types/src/build/setup.d.ts +4 -0
  8. package/dist/types/src/index.d.ts +11 -0
  9. package/dist/types/src/module.d.ts +3 -0
  10. package/dist/types/src/options.d.ts +9 -0
  11. package/dist/types/src/server/broadcast.d.ts +6 -0
  12. package/dist/types/src/server/deliver.d.ts +27 -0
  13. package/dist/types/src/server/inbox.d.ts +23 -0
  14. package/dist/types/src/server/index.d.ts +17 -0
  15. package/dist/types/src/server/notify.d.ts +20 -0
  16. package/dist/types/src/server/queue.d.ts +7 -0
  17. package/dist/types/src/server/recipient.d.ts +2 -0
  18. package/dist/types/src/server/record.d.ts +3 -0
  19. package/dist/types/src/server/runtime.d.ts +6 -0
  20. package/dist/types/src/server/task.d.ts +4 -0
  21. package/dist/types/src/server/topic.d.ts +3 -0
  22. package/dist/types/src/server/webhook.d.ts +10 -0
  23. package/dist/types/src/test.d.ts +5 -0
  24. package/dist/types/src/types.d.ts +87 -0
  25. package/package.json +51 -4
  26. package/src/build/scan.ts +119 -0
  27. package/src/build/setup.ts +111 -0
  28. package/src/env.d.ts +26 -0
  29. package/src/index.ts +13 -0
  30. package/src/module.ts +11 -0
  31. package/src/options.ts +52 -0
  32. package/src/server/broadcast.ts +9 -0
  33. package/src/server/deliver.ts +57 -0
  34. package/src/server/inbox.ts +121 -0
  35. package/src/server/index.ts +74 -0
  36. package/src/server/notify.ts +127 -0
  37. package/src/server/queue.ts +22 -0
  38. package/src/server/recipient.ts +10 -0
  39. package/src/server/record.ts +16 -0
  40. package/src/server/runtime.ts +42 -0
  41. package/src/server/task.ts +14 -0
  42. package/src/server/topic.ts +18 -0
  43. package/src/server/webhook.ts +71 -0
  44. package/src/test.ts +35 -0
  45. package/src/types.ts +93 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 productdevbook
4
+ Copyright (c) 2019 Material-UI SAS
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @hamur/notifications
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
+ The first-party notifications module for [Hamur](https://github.com/productdevbook/hamur), a full-stack web framework for Bun. It has no dependency.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @hamur/notifications
9
+ ```
10
+
11
+ Add it to `modules` in `hamur.config.ts` and set the `notifications` key.
12
+
13
+ ## Docs
14
+
15
+ [Documentation](https://docs.productdevbook.com/) and the [API reference](https://docs.productdevbook.com/api-reference/notifications). MIT license.
@@ -0,0 +1,235 @@
1
+ // packages/notifications/src/module.ts
2
+ import { defineModule } from "hamur/kit";
3
+
4
+ // packages/notifications/src/build/setup.ts
5
+ import { rmSync } from "node:fs";
6
+ import { dirname, join as join2, relative as relative2 } from "node:path";
7
+ import {
8
+ addTask,
9
+ addTemplate,
10
+ addTypeTemplate,
11
+ createResolver,
12
+ DiagnosticError as DiagnosticError2,
13
+ hasModule,
14
+ useInstalledModules
15
+ } from "hamur/kit";
16
+
17
+ // packages/notifications/src/build/scan.ts
18
+ import { readdirSync, readFileSync } from "node:fs";
19
+ import { isAbsolute, join, relative, sep } from "node:path";
20
+ import { DiagnosticError } from "hamur/kit";
21
+ import { defaultCallKeys } from "hamur/server/internal";
22
+
23
+ // packages/notifications/src/types.ts
24
+ var CHANNELS = ["mail", "database", "broadcast", "webhook"];
25
+
26
+ // packages/notifications/src/build/scan.ts
27
+ var IGNORED = /\.(?:test|spec|d)\.ts$/;
28
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
29
+ var slashes = (path) => path.split(sep).join("/");
30
+ function filesOf(dir, prefix) {
31
+ let entries;
32
+ try {
33
+ entries = readdirSync(dir, { withFileTypes: true });
34
+ } catch {
35
+ return [];
36
+ }
37
+ return entries.filter(({ name }) => !/^[_.]/.test(name)).flatMap((entry) => {
38
+ const file = join(dir, entry.name);
39
+ if (entry.isDirectory())
40
+ return filesOf(file, `${prefix}${entry.name}:`);
41
+ if (!entry.isFile() || !entry.name.endsWith(".ts") || IGNORED.test(entry.name))
42
+ return [];
43
+ return [{ name: prefix + entry.name.slice(0, -".ts".length), file }];
44
+ });
45
+ }
46
+ function scanNotifications(serverDirs) {
47
+ const found = new Map;
48
+ for (const dir of serverDirs)
49
+ for (const entry of filesOf(join(dir, "notifications"), ""))
50
+ if (!found.has(entry.name))
51
+ found.set(entry.name, entry);
52
+ return [...found.values()].sort((a, b) => a.name < b.name ? -1 : 1);
53
+ }
54
+ function readNotifications(files, rootDir, support) {
55
+ return files.map(({ name, file }) => {
56
+ const path = relative(rootDir, file);
57
+ const shown = slashes(path.startsWith("..") || isAbsolute(path) ? file : path);
58
+ const bad = name.split(":").find((segment) => !SEGMENT.test(segment));
59
+ if (bad !== undefined)
60
+ throw new DiagnosticError("HAMUR_E6807", `${shown}: a notification name segment holds A-Z, a-z, 0-9, _ and - (got ${JSON.stringify(bad)})`);
61
+ const keys = defaultCallKeys(readFileSync(file, "utf8"), "defineNotification");
62
+ if (!keys)
63
+ throw new DiagnosticError("HAMUR_E6802", `${shown} must default-export defineNotification({ ... })`);
64
+ if (keys.includes("..."))
65
+ throw new DiagnosticError("HAMUR_E6808", `${shown}: the options of defineNotification are written out (the build reads them)`);
66
+ const channels = CHANNELS.filter((channel) => keys.includes(channel));
67
+ if (!channels.length)
68
+ throw new DiagnosticError("HAMUR_E6803", `${shown} has no channel: give it mail, database, broadcast or webhook`);
69
+ if (channels.includes("mail") && !support.mail)
70
+ throw new DiagnosticError("HAMUR_E6804", `${shown}: the mail channel needs @hamur/mail in modules`);
71
+ if (channels.includes("database") && !support.db)
72
+ throw new DiagnosticError("HAMUR_E6805", `${shown}: the database channel needs @hamur/db and the table ${JSON.stringify(support.inbox.table)} in db ${JSON.stringify(support.inbox.connection)}; add a migration that creates it`);
73
+ if (channels.includes("broadcast") && !support.publish)
74
+ throw new DiagnosticError("HAMUR_E6806", `${shown}: the broadcast channel needs a preset that publishes (bun, node, cloudflare)`);
75
+ if (channels.includes("broadcast") && !support.topics)
76
+ throw new DiagnosticError("HAMUR_E6806", `${shown}: the broadcast channel needs cloudflare.websocket: "durable"`);
77
+ return { name, file, channels };
78
+ });
79
+ }
80
+ function notificationTypes(files, typesDir) {
81
+ if (!files.length)
82
+ return `export {};
83
+ `;
84
+ return [
85
+ `type NotificationTypes<T> = T extends { readonly "~types"?: infer Types } ? NonNullable<Types> : never;`,
86
+ "",
87
+ `declare module "@hamur/notifications" {`,
88
+ " interface HamurNotifications {",
89
+ ...files.map(({ name, file }) => ` ${JSON.stringify(name)}: NotificationTypes<typeof import(${JSON.stringify(slashes(relative(typesDir, file)))}).default>;`),
90
+ " }",
91
+ "}",
92
+ "",
93
+ "export {};",
94
+ ""
95
+ ].join(`
96
+ `);
97
+ }
98
+
99
+ // packages/notifications/src/build/setup.ts
100
+ var SERVER = "@hamur/notifications/server";
101
+ var PUBLISH = new Set(["bun", "node", "cloudflare"]);
102
+ var COLUMNS = ["id", "recipient_type", "recipient_id", "notification", "data", "read_at", "created_at"];
103
+ var uses = (notifications, channel) => notifications.some(({ channels }) => channels.includes(channel));
104
+ function setupNotifications(options, hamur) {
105
+ const { dev, preset, cloudflare, rootDir, buildDir } = hamur.options;
106
+ const testBuild = process.env.HAMUR_TEST_BUILD === "1";
107
+ const recordFile = join2(buildDir, "notifications.jsonl");
108
+ if (testBuild)
109
+ rmSync(recordFile, { force: true });
110
+ const protection = hamur.options.build.importProtection;
111
+ const client = protection.client ??= {};
112
+ (client.deny ??= []).push(SERVER);
113
+ const r = createResolver(new URL("../../src/build/setup.ts", import.meta.url).href);
114
+ addTask({ name: "notifications:deliver", file: r.resolve("../server/task.ts") });
115
+ const serverDirs = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)];
116
+ const { table, connection } = options;
117
+ const support = {
118
+ mail: false,
119
+ db: false,
120
+ publish: dev || PUBLISH.has(preset),
121
+ topics: dev || preset !== "cloudflare" || cloudflare.websocket !== "worker",
122
+ inbox: { table, connection }
123
+ };
124
+ let dbDir = rootDir;
125
+ hamur.hooks.hook("modules:done", () => {
126
+ support.mail = hasModule("@hamur/mail");
127
+ support.db = hasModule("@hamur/db");
128
+ const file = useInstalledModules().find(({ name }) => name === "db")?.file;
129
+ if (file !== undefined)
130
+ dbDir = dirname(file);
131
+ });
132
+ const read = (found = support) => readNotifications(scanNotifications(serverDirs), rootDir, found);
133
+ hamur.hooks.hook("build:before", async () => {
134
+ if (!uses(read(), "database"))
135
+ return;
136
+ const { tableProblem } = await import(Bun.resolveSync("@hamur/db/cli", dbDir));
137
+ if (await tableProblem(hamur, { connection, table, columns: [] }))
138
+ read({ ...support, db: false });
139
+ const problem = await tableProblem(hamur, { connection, table, columns: COLUMNS });
140
+ if (problem)
141
+ throw new DiagnosticError2("HAMUR_E6809", `@hamur/notifications: ${problem}`);
142
+ });
143
+ hamur.hooks.hook("dev:change", (change) => {
144
+ if (serverDirs.some((dir) => !relative2(join2(dir, "notifications"), change.file).startsWith("..")))
145
+ change.rebuildServer = true;
146
+ });
147
+ addTypeTemplate({
148
+ filename: "notifications.d.ts",
149
+ getContents: () => notificationTypes(scanNotifications(serverDirs), join2(buildDir, "types"))
150
+ });
151
+ addTemplate({
152
+ filename: "notifications/database",
153
+ getContents: () => support.db ? `import { cursorQuery, useDatabase } from ${JSON.stringify(Bun.resolveSync("@hamur/db/server", dbDir))};
154
+ import { createInbox } from ${JSON.stringify(r.resolve("../server/inbox.ts"))};
155
+ export const inbox = createInbox(() => useDatabase(${JSON.stringify(connection)}), cursorQuery, ${JSON.stringify(table)});
156
+ ` : `export {};
157
+ `
158
+ });
159
+ addTemplate({
160
+ filename: "notifications/config",
161
+ getContents: () => {
162
+ const notifications = read();
163
+ const entries = notifications.map(({ name, file }) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),
164
+ `);
165
+ return [
166
+ `export const queue = ${options.queue};`,
167
+ `export const webhook = ${JSON.stringify(options.webhook)};`,
168
+ `export const notifications = {
169
+ ${entries.join("")}};`,
170
+ `export const loadMail = ${uses(notifications, "mail") ? `() => import("#hamur/mail/deliver")` : "undefined"};`,
171
+ `export const loadDatabase = ${uses(notifications, "database") ? `() => import("#hamur/notifications/database")` : "undefined"};`,
172
+ `export const loadBroadcast = ${uses(notifications, "broadcast") ? `() => import(${JSON.stringify(r.resolve("../server/broadcast.ts"))})` : "undefined"};`,
173
+ `export const loadRecord = ${testBuild ? `() => import(${JSON.stringify(r.resolve("../server/record.ts"))})` : "undefined"};`,
174
+ `export const recordFile = ${JSON.stringify(testBuild ? recordFile : "")};`,
175
+ ""
176
+ ].join(`
177
+ `);
178
+ }
179
+ });
180
+ }
181
+
182
+ // packages/notifications/src/options.ts
183
+ import { DiagnosticError as DiagnosticError3, isEnvRef } from "hamur/kit";
184
+ import { urlProblem } from "hamur/server/internal";
185
+ var KEYS = ["queue", "webhook", "table", "connection"];
186
+ var WEBHOOK_KEYS = ["url", "secret"];
187
+ var TABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
188
+ function fail(message) {
189
+ throw new DiagnosticError3("HAMUR_E6801", message);
190
+ }
191
+ var shown = (value) => typeof value === "function" ? "a function" : String(JSON.stringify(value));
192
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
193
+ function checkKeys(label, value, keys) {
194
+ for (const key of Object.keys(value))
195
+ if (!keys.includes(key))
196
+ fail(`${label} has no ${JSON.stringify(key)} (it takes: ${keys.join(", ")})`);
197
+ }
198
+ function resolveWebhook(input) {
199
+ if (!isObject(input))
200
+ fail(`notifications.webhook must be an object with url and secret (got ${shown(input)})`);
201
+ checkKeys("notifications.webhook", input, WEBHOOK_KEYS);
202
+ const { url, secret } = input;
203
+ if (typeof url !== "string")
204
+ fail(`notifications.webhook.url must be an https: URL (got ${shown(url)})`);
205
+ const problem = urlProblem(url);
206
+ if (problem !== undefined)
207
+ fail(`notifications.webhook.url cannot be used: ${problem}`);
208
+ if (!isEnvRef(secret))
209
+ fail('notifications.webhook.secret must be env("NAME"); a secret in the config file ends up in the repository');
210
+ return { url, secret };
211
+ }
212
+ function resolveOptions(input = {}) {
213
+ if (!isObject(input))
214
+ fail(`notifications must be an object (got ${shown(input)})`);
215
+ checkKeys("notifications", input, KEYS);
216
+ const { queue = true, webhook, table = "notifications", connection = "default" } = input;
217
+ if (typeof queue !== "boolean")
218
+ fail(`notifications.queue must be a boolean (got ${shown(queue)})`);
219
+ if (typeof table !== "string" || !TABLE.test(table))
220
+ fail(`notifications.table must be a table name of A-Z, a-z, 0-9 and _ (got ${shown(table)})`);
221
+ if (typeof connection !== "string")
222
+ fail(`notifications.connection must be a string (got ${shown(connection)})`);
223
+ return { queue, table, connection, ...webhook === undefined ? {} : { webhook: resolveWebhook(webhook) } };
224
+ }
225
+
226
+ // packages/notifications/src/module.ts
227
+ var module_default = defineModule({
228
+ meta: { name: "notifications", configKey: "notifications" },
229
+ setup(input, hamur) {
230
+ setupNotifications(resolveOptions(input), hamur);
231
+ }
232
+ });
233
+ export {
234
+ module_default as default
235
+ };
@@ -0,0 +1,282 @@
1
+ // @bun
2
+ // packages/notifications/src/server/index.ts
3
+ import { queue } from "#hamur/notifications/config";
4
+ import { useEvent, useLogger, useSiteConfig } from "hamur/server";
5
+ import { prepareEnqueue } from "hamur/server/internal";
6
+
7
+ // packages/notifications/src/types.ts
8
+ var CHANNELS = ["mail", "database", "broadcast", "webhook"];
9
+
10
+ // packages/notifications/src/server/deliver.ts
11
+ var shownDelivery = ({ channel, to }) => `${channel} to ${to.type}::${JSON.stringify(to.id)}`;
12
+ async function deliver(deps, { id, name, channel, to, input, site, webhook = deps.webhook }, queued, log) {
13
+ const payload = await (await deps.load(name))[channel]?.(input, to);
14
+ if (payload === undefined)
15
+ throw new TypeError(`${channel}() of the notification gave nothing to send`);
16
+ await deps.record?.({ name, channel, recipient: { type: to.type, id: to.id }, payload });
17
+ if (channel === "mail") {
18
+ const message = { ...payload, to: to.email };
19
+ return deps.deliverMail(message, { id, queued, ...site === undefined ? {} : { site } }, log);
20
+ }
21
+ if (channel === "database") {
22
+ await deps.storeRow({ id, name, to, payload });
23
+ return;
24
+ }
25
+ if (deps.record)
26
+ return;
27
+ if (channel === "broadcast") {
28
+ const send = await deps.openTopic(to);
29
+ await send({ notification: name, data: payload });
30
+ return;
31
+ }
32
+ if (!webhook)
33
+ throw new Error("the recipient has no webhook");
34
+ await deps.postWebhook(webhook, id, JSON.stringify(payload));
35
+ return;
36
+ }
37
+
38
+ // packages/notifications/src/server/notify.ts
39
+ var recipientOf = ({ type, id, email, prefs }) => ({
40
+ type,
41
+ id,
42
+ ...email === undefined ? {} : { email },
43
+ ...prefs === undefined ? {} : { prefs }
44
+ });
45
+ var textOf = (error) => error instanceof Error ? error.message : String(error);
46
+ function uuidV7() {
47
+ const time = Date.now().toString(16).padStart(12, "0");
48
+ return `${time.slice(0, 8)}-${time.slice(8)}-7${crypto.randomUUID().slice(15)}`;
49
+ }
50
+ async function prepareAll(deps, deliveries, label) {
51
+ const packed = await Promise.all(deliveries.map(deps.pack));
52
+ return packed.map((delivery) => {
53
+ try {
54
+ return deps.prepare(delivery);
55
+ } catch (error) {
56
+ throw new Error(`${label}: ${shownDelivery(delivery)}: ${textOf(error)}`, { cause: error });
57
+ }
58
+ });
59
+ }
60
+ function createNotify(deps) {
61
+ return async function notify(to, name, input, options = {}) {
62
+ const label = `notify(${JSON.stringify(name)})`;
63
+ const site = deps.site();
64
+ const definition = await deps.load(name);
65
+ const result = await definition.input["~standard"].validate(input);
66
+ if (result.issues) {
67
+ const { message, path = [] } = result.issues[0];
68
+ const at = path.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
69
+ throw new Error(`${label}: the input is refused by its schema: ${message}${at ? ` at ${at}` : ""}`);
70
+ }
71
+ const log = deps.log();
72
+ const defined = CHANNELS.filter((channel) => definition[channel]);
73
+ const deliveries = new Map;
74
+ for (const given of Array.isArray(to) ? to : [to]) {
75
+ const recipient = recipientOf(given);
76
+ for (const channel of definition.via?.(recipient, result.value) ?? defined) {
77
+ const delivery = {
78
+ id: uuidV7(),
79
+ name,
80
+ channel,
81
+ to: recipient,
82
+ input: result.value,
83
+ ...channel === "webhook" && given.webhook ? { webhook: given.webhook } : {},
84
+ ...channel === "mail" && site !== undefined ? { site } : {}
85
+ };
86
+ const shown = `${recipient.type}::${JSON.stringify(recipient.id)}`;
87
+ if (!defined.includes(channel)) {
88
+ log.warn(`${label}: via() names the channel ${JSON.stringify(channel)}, which the notification does not have`);
89
+ } else if (channel === "mail" && recipient.email === undefined) {
90
+ log.warn(`${label}: ${shown} has no email; the mail channel skipped it`);
91
+ } else if (channel === "webhook" && !given.webhook && !deps.webhook) {
92
+ log.warn(`${label}: ${shown} has no webhook; the webhook channel skipped it`);
93
+ } else if (!deliveries.has(shownDelivery(delivery))) {
94
+ if (channel === "broadcast")
95
+ await deps.openTopic(recipient);
96
+ deliveries.set(shownDelivery(delivery), delivery);
97
+ }
98
+ }
99
+ }
100
+ const list = [...deliveries.values()];
101
+ const queued = options.queue ?? deps.queue;
102
+ const runs = queued && !deps.record ? await prepareAll(deps, list, label) : undefined;
103
+ const settled = await Promise.allSettled(runs ? runs.map((run) => run()) : list.map(async (delivery) => {
104
+ const unconfirmed = await deliver(deps, delivery, queued, log);
105
+ if (unconfirmed)
106
+ throw unconfirmed;
107
+ }));
108
+ const failures = settled.flatMap((entry, at) => entry.status === "rejected" ? [{ delivery: list[at], error: entry.reason }] : []);
109
+ if (!failures.length)
110
+ return;
111
+ const texts = failures.map(({ delivery, error }) => `${shownDelivery(delivery)}: ${textOf(error)}`);
112
+ throw new Error(`${label}: ${failures.length} of ${list.length} deliveries failed: ${texts.join("; ")}`, {
113
+ cause: failures[0].error
114
+ });
115
+ };
116
+ }
117
+
118
+ // packages/notifications/src/server/queue.ts
119
+ import { sealFor, unsealFor } from "hamur/server/internal";
120
+ var PURPOSE = "hamur-notifications";
121
+ async function packDelivery({ webhook, ...delivery }) {
122
+ if (!webhook)
123
+ return delivery;
124
+ const { url, secret } = webhook;
125
+ return { ...delivery, webhook: await sealFor({ url, secret }, { purpose: PURPOSE }) };
126
+ }
127
+
128
+ // packages/notifications/src/server/runtime.ts
129
+ import {
130
+ loadBroadcast,
131
+ loadDatabase,
132
+ loadMail,
133
+ loadRecord,
134
+ notifications,
135
+ recordFile,
136
+ webhook
137
+ } from "#hamur/notifications/config";
138
+
139
+ // packages/notifications/src/server/webhook.ts
140
+ import { pinnedFetch, readSecret, reasonPhrase, urlProblem } from "hamur/server/internal";
141
+ var TIMEOUT = 1e4;
142
+ var PREFIX = "whsec_";
143
+ var encoder = new TextEncoder;
144
+ function keyOf(secret) {
145
+ try {
146
+ const bytes = secret.startsWith(PREFIX) ? atob(secret.slice(PREFIX.length)) : "";
147
+ if (bytes !== "")
148
+ return Uint8Array.from(bytes, (char) => char.charCodeAt(0));
149
+ } catch {}
150
+ throw new Error("the webhook secret must be whsec_ followed by the base64 of the key");
151
+ }
152
+ async function signWebhook(secret, id, timestamp, body) {
153
+ const key = await crypto.subtle.importKey("raw", keyOf(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
154
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(`${id}.${timestamp}.${body}`));
155
+ return `v1,${btoa(String.fromCharCode(...new Uint8Array(signature)))}`;
156
+ }
157
+ function reasonOf(error) {
158
+ const {
159
+ name,
160
+ message,
161
+ code = error.cause?.code
162
+ } = error;
163
+ if (name === "TimeoutError" || name === "AbortError")
164
+ return `no answer in ${TIMEOUT / 1000} s`;
165
+ if (typeof code === "string")
166
+ return `the request failed (${code})`;
167
+ return message && !message.includes("://") ? message : "the request failed";
168
+ }
169
+ async function postWebhook(target, id, body, { send = pinnedFetch() ?? fetch, now = Date.now } = {}) {
170
+ const problem = urlProblem(target.url);
171
+ if (problem !== undefined)
172
+ throw new Error(`the webhook URL is refused: ${problem}`);
173
+ const timestamp = Math.floor(now() / 1000);
174
+ const signature = await signWebhook(readSecret(target.secret, "the webhook channel's secret"), id, timestamp, body);
175
+ let response;
176
+ try {
177
+ response = await send(target.url, {
178
+ method: "POST",
179
+ redirect: "manual",
180
+ signal: AbortSignal.timeout(TIMEOUT),
181
+ headers: {
182
+ "content-type": "application/json",
183
+ "webhook-id": id,
184
+ "webhook-timestamp": String(timestamp),
185
+ "webhook-signature": signature
186
+ },
187
+ body
188
+ });
189
+ } catch (error) {
190
+ throw new Error(reasonOf(error));
191
+ }
192
+ await response.body?.cancel().catch(() => {
193
+ return;
194
+ });
195
+ if (!response.ok)
196
+ throw new Error(`${response.status} ${reasonPhrase(response.status)}`.trim());
197
+ }
198
+
199
+ // packages/notifications/src/server/runtime.ts
200
+ async function useInbox(caller) {
201
+ if (!loadDatabase)
202
+ throw new Error(`${caller} needs a notification with the database channel`);
203
+ return (await loadDatabase()).inbox;
204
+ }
205
+ var deliverDeps = {
206
+ async load(name) {
207
+ if (!Object.hasOwn(notifications, name))
208
+ throw new Error(`Notification ${JSON.stringify(name)} not found (notifications: ${Object.keys(notifications).join(", ") || "none"})`);
209
+ return (await notifications[name]()).default;
210
+ },
211
+ async deliverMail(message, delivery, log) {
212
+ if (!loadMail)
213
+ throw new Error("the mail channel needs @hamur/mail in modules");
214
+ return (await loadMail()).deliverMail(message, delivery, log);
215
+ },
216
+ storeRow: async (delivery) => (await useInbox("The delivery")).add(delivery),
217
+ openTopic: async (to) => (await loadBroadcast()).openTopic(to),
218
+ ...webhook ? { webhook } : {},
219
+ postWebhook,
220
+ ...loadRecord ? { record: async (delivery) => (await loadRecord()).record(recordFile, delivery) } : {}
221
+ };
222
+
223
+ // packages/notifications/src/server/recipient.ts
224
+ var isText = (value) => typeof value === "string" && value !== "";
225
+ function checkRecipient({ type, id }) {
226
+ if (!isText(type) || !isText(id))
227
+ throw new TypeError(`A notification recipient needs type and id, both non-empty strings (got ${JSON.stringify({ type, id })})`);
228
+ }
229
+
230
+ // packages/notifications/src/server/topic.ts
231
+ var MAX_LENGTH = 256;
232
+ function notificationTopic(to) {
233
+ checkRecipient(to);
234
+ const type = to.type.replaceAll("%", "%25").replaceAll(":", "%3A");
235
+ const topic = `hamur:notifications:${type}:${to.id}`;
236
+ if (topic.length > MAX_LENGTH || !topic.isWellFormed())
237
+ throw new TypeError(`The topic of a notification recipient is well-formed text of at most ${MAX_LENGTH} characters (got ${JSON.stringify(topic)})`);
238
+ return topic;
239
+ }
240
+
241
+ // packages/notifications/src/server/index.ts
242
+ var TASK = "notifications:deliver";
243
+ var KEYS = ["input", "via", "mail", "database", "broadcast", "webhook"];
244
+ function requestSite() {
245
+ try {
246
+ return useSiteConfig(useEvent()).url;
247
+ } catch {
248
+ return;
249
+ }
250
+ }
251
+ var send = createNotify({
252
+ ...deliverDeps,
253
+ queue,
254
+ pack: packDelivery,
255
+ prepare: (delivery) => prepareEnqueue(TASK, delivery),
256
+ site: requestSite,
257
+ log: useLogger
258
+ });
259
+ function defineNotification(options) {
260
+ for (const key of Object.keys(options))
261
+ if (!KEYS.includes(key))
262
+ throw new TypeError(`defineNotification has no ${JSON.stringify(key)}; it takes ${KEYS.join(", ")}`);
263
+ if (typeof options.input?.["~standard"]?.validate !== "function")
264
+ throw new TypeError("defineNotification input must be a Standard Schema");
265
+ return options;
266
+ }
267
+ function notify(to, name, input, options) {
268
+ return send(to, name, input, options);
269
+ }
270
+ async function listNotifications(to, options) {
271
+ return (await useInbox("listNotifications")).list(to, options);
272
+ }
273
+ async function markNotificationsRead(to, ids) {
274
+ return (await useInbox("markNotificationsRead")).markRead(to, ids);
275
+ }
276
+ export {
277
+ defineNotification,
278
+ listNotifications,
279
+ markNotificationsRead,
280
+ notificationTopic,
281
+ notify
282
+ };
@@ -0,0 +1,32 @@
1
+ // @bun
2
+ // packages/notifications/src/test.ts
3
+ import { readFile } from "fs/promises";
4
+ import { dirname, join } from "path";
5
+ import { useTestContext } from "hamur/test";
6
+ import { useTestLoader } from "hamur/test/internal";
7
+ async function recordFile() {
8
+ try {
9
+ return join(dirname(useTestContext().outputDir), ".hamur", "notifications.jsonl");
10
+ } catch {}
11
+ try {
12
+ return join((await useTestLoader()).hamur.options.buildDir, "notifications.jsonl");
13
+ } catch (error) {
14
+ throw new Error("@hamur/notifications/test: no deliveries to read; call setup() from hamur/test in this file or run the tests with the hamur/test/preload", { cause: error });
15
+ }
16
+ }
17
+ async function sentNotifications(options = {}) {
18
+ let text;
19
+ try {
20
+ text = await readFile(await recordFile(), "utf8");
21
+ } catch (error) {
22
+ if (error.code === "ENOENT")
23
+ return [];
24
+ throw error;
25
+ }
26
+ const deliveries = text.split(`
27
+ `).filter(Boolean).map((line) => JSON.parse(line));
28
+ return options.name === undefined ? deliveries : deliveries.filter(({ name }) => name === options.name);
29
+ }
30
+ export {
31
+ sentNotifications
32
+ };
@@ -0,0 +1,27 @@
1
+ import { type NotificationChannel } from "../types.ts";
2
+ export interface NotificationFile {
3
+ name: string;
4
+ file: string;
5
+ }
6
+ export interface NotificationRecord extends NotificationFile {
7
+ channels: NotificationChannel[];
8
+ }
9
+ /** What the channels of a notification need of the build. */
10
+ export interface ChannelSupport {
11
+ mail: boolean;
12
+ db: boolean;
13
+ publish: boolean;
14
+ /** False with `cloudflare.websocket: "worker"`, where `publish` always rejects. */
15
+ topics: boolean;
16
+ /** Where the database channel keeps its rows. */
17
+ inbox: {
18
+ table: string;
19
+ connection: string;
20
+ };
21
+ }
22
+ /** `notifications/**` of the app's server folder, then each layer's; the first of a name wins. */
23
+ export declare function scanNotifications(serverDirs: readonly string[]): NotificationFile[];
24
+ /** Each notification's channels, read without running it, or the build error of the first file that is wrong. */
25
+ export declare function readNotifications(files: readonly NotificationFile[], rootDir: string, support: ChannelSupport): NotificationRecord[];
26
+ /** `.hamur/types/notifications.d.ts`, the input each notification takes in `HamurNotifications`. */
27
+ export declare function notificationTypes(files: readonly NotificationFile[], typesDir: string): string;
@@ -0,0 +1,4 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { ResolvedNotificationsOptions } from "../options.ts";
3
+ /** The import guard, the task, the types, the build checks and `#hamur/notifications/config`. */
4
+ export declare function setupNotifications(options: ResolvedNotificationsOptions, hamur: HamurContext): void;
@@ -0,0 +1,11 @@
1
+ import type { NotificationsConfig } from "./types.ts";
2
+ export { default } from "./module.ts";
3
+ export type { NotificationName, NotificationRow, NotificationsConfig, Recipient } from "./types.ts";
4
+ /** Filled in by typegen from `server/notifications/`: each notification's name and the input `notify` takes. */
5
+ export interface HamurNotifications {
6
+ }
7
+ declare module "hamur" {
8
+ interface HamurModuleOptions {
9
+ notifications?: NotificationsConfig;
10
+ }
11
+ }
@@ -0,0 +1,3 @@
1
+ import type { NotificationsConfig } from "./types.ts";
2
+ declare const _default: import("hamur/kit").HamurModule<NotificationsConfig>;
3
+ export default _default;
@@ -0,0 +1,9 @@
1
+ import type { NotificationsConfig } from "./types.ts";
2
+ export interface ResolvedNotificationsOptions {
3
+ queue: boolean;
4
+ table: string;
5
+ connection: string;
6
+ webhook?: NonNullable<NotificationsConfig["webhook"]>;
7
+ }
8
+ /** The checked options, or the load error of the first value that is wrong. */
9
+ export declare function resolveOptions(input?: unknown): ResolvedNotificationsOptions;
@@ -0,0 +1,6 @@
1
+ import type { Recipient } from "../types.ts";
2
+ /** What publishes to the topic of `to`. */
3
+ export declare function openTopic(to: Recipient): (message: {
4
+ notification: string;
5
+ data: unknown;
6
+ }) => Promise<void>;