workers-start 0.8.0 → 0.10.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/src/mail.ts ADDED
@@ -0,0 +1,227 @@
1
+ /**
2
+ * One way to send mail from a Worker, over Cloudflare Email Sending (the
3
+ * `send_email` binding) or Resend, with a recording fake for tests. Every
4
+ * message carries both a plain text and an HTML body: some clients show only
5
+ * one, and a message with only HTML scores worse with spam filters.
6
+ */
7
+
8
+ export type MailAddress = string | { email: string; name?: string };
9
+
10
+ export interface MailAttachment {
11
+ filename: string;
12
+ /** Base64. */
13
+ content: string;
14
+ contentType?: string;
15
+ }
16
+
17
+ export interface MailMessage {
18
+ from: MailAddress;
19
+ to: string | string[];
20
+ subject: string;
21
+ text: string;
22
+ html: string;
23
+ replyTo?: MailAddress;
24
+ /** Extra headers, such as `In-Reply-To`. */
25
+ headers?: Record<string, string>;
26
+ /** Adds `List-Unsubscribe` and one-click `List-Unsubscribe-Post`, for bulk and marketing mail. */
27
+ listUnsubscribeUrl?: string;
28
+ /** Resend only: repeating a send with the same key within 24 hours sends once. */
29
+ idempotencyKey?: string;
30
+ attachments?: MailAttachment[];
31
+ }
32
+
33
+ export interface MailResult {
34
+ /** The provider's message id. */
35
+ id?: string;
36
+ }
37
+
38
+ export interface Mailer {
39
+ send(message: MailMessage): Promise<MailResult>;
40
+ }
41
+
42
+ /** A send that failed. `permanent` is true when repeating it cannot help (a 4xx other than 409 and 429). */
43
+ export class MailError extends Error {
44
+ override readonly name = "MailError";
45
+ constructor(
46
+ message: string,
47
+ readonly status?: number,
48
+ readonly body?: unknown,
49
+ ) {
50
+ super(message);
51
+ }
52
+ get permanent(): boolean {
53
+ return (
54
+ this.status !== undefined &&
55
+ this.status >= 400 &&
56
+ this.status < 500 &&
57
+ this.status !== 409 &&
58
+ this.status !== 429
59
+ );
60
+ }
61
+ }
62
+
63
+ /** Throws unless the message has recipients, a subject and both bodies. */
64
+ export function checkMessage(message: MailMessage): void {
65
+ const to = Array.isArray(message.to) ? message.to : [message.to];
66
+ if (to.length === 0 || to.some((t) => !t.trim()))
67
+ throw new MailError("A message needs at least one recipient.");
68
+ if (!message.subject.trim())
69
+ throw new MailError("A message needs a subject.");
70
+ if (!message.text.trim() || !message.html.trim())
71
+ throw new MailError("A message needs both a text and an HTML body.");
72
+ }
73
+
74
+ function headersFor(message: MailMessage): Record<string, string> {
75
+ const headers = { ...message.headers };
76
+ if (message.listUnsubscribeUrl) {
77
+ headers["List-Unsubscribe"] = `<${message.listUnsubscribeUrl}>`;
78
+ headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
79
+ }
80
+ return headers;
81
+ }
82
+
83
+ const formatAddress = (a: MailAddress) =>
84
+ typeof a === "string"
85
+ ? a
86
+ : a.name
87
+ ? `${a.name.replace(/["\\]/g, "")} <${a.email}>`
88
+ : a.email;
89
+
90
+ /** The `send_email` binding, structurally, so this module needs no Workers types. */
91
+ export interface SendEmailBinding {
92
+ // biome-ignore lint/suspicious/noExplicitAny: the binding's builder type lives in @cloudflare/workers-types.
93
+ send(message: any): Promise<{ messageId?: string } | undefined | void>;
94
+ }
95
+
96
+ /** Sends through Cloudflare Email Sending. Senders and recipients must be allowed in the binding's wrangler config. */
97
+ export function cloudflareMailer(binding: SendEmailBinding): Mailer {
98
+ return {
99
+ async send(message) {
100
+ checkMessage(message);
101
+ const headers = headersFor(message);
102
+ const from =
103
+ typeof message.from === "string"
104
+ ? message.from
105
+ : { email: message.from.email, name: message.from.name ?? "" };
106
+ try {
107
+ const result = await binding.send({
108
+ from,
109
+ to: message.to,
110
+ subject: message.subject,
111
+ text: message.text,
112
+ html: message.html,
113
+ ...(message.replyTo
114
+ ? {
115
+ replyTo:
116
+ typeof message.replyTo === "string"
117
+ ? message.replyTo
118
+ : {
119
+ email: message.replyTo.email,
120
+ name: message.replyTo.name ?? "",
121
+ },
122
+ }
123
+ : {}),
124
+ ...(Object.keys(headers).length ? { headers } : {}),
125
+ ...(message.attachments?.length
126
+ ? {
127
+ attachments: message.attachments.map((a) => ({
128
+ disposition: "attachment",
129
+ filename: a.filename,
130
+ type: a.contentType ?? "application/octet-stream",
131
+ content: a.content,
132
+ })),
133
+ }
134
+ : {}),
135
+ });
136
+ return result?.messageId ? { id: result.messageId } : {};
137
+ } catch (err) {
138
+ throw new MailError(
139
+ `Email Sending failed: ${err instanceof Error ? err.message : String(err)}`,
140
+ );
141
+ }
142
+ },
143
+ };
144
+ }
145
+
146
+ export interface ResendOptions {
147
+ apiKey: string | undefined;
148
+ fetch?: (url: string, init?: RequestInit) => Promise<Response>;
149
+ /** Default 10 seconds. */
150
+ timeoutMs?: number;
151
+ }
152
+
153
+ /** Sends through the Resend API with `fetch`, no SDK. */
154
+ export function resendMailer(options: ResendOptions): Mailer {
155
+ const fetcher = options.fetch ?? ((url, init) => fetch(url, init));
156
+ return {
157
+ async send(message) {
158
+ checkMessage(message);
159
+ if (!options.apiKey) throw new MailError("RESEND_API_KEY is not set.");
160
+ const headers = headersFor(message);
161
+ const body: Record<string, unknown> = {
162
+ from: formatAddress(message.from),
163
+ to: message.to,
164
+ subject: message.subject,
165
+ text: message.text,
166
+ html: message.html,
167
+ };
168
+ if (message.replyTo) body.reply_to = formatAddress(message.replyTo);
169
+ if (Object.keys(headers).length) body.headers = headers;
170
+ if (message.attachments?.length) {
171
+ body.attachments = message.attachments.map((a) => ({
172
+ filename: a.filename,
173
+ content: a.content,
174
+ ...(a.contentType ? { content_type: a.contentType } : {}),
175
+ }));
176
+ }
177
+ const res = await fetcher("https://api.resend.com/emails", {
178
+ method: "POST",
179
+ headers: {
180
+ authorization: `Bearer ${options.apiKey}`,
181
+ "content-type": "application/json",
182
+ ...(message.idempotencyKey
183
+ ? { "idempotency-key": message.idempotencyKey }
184
+ : {}),
185
+ },
186
+ body: JSON.stringify(body),
187
+ signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
188
+ });
189
+ const json = (await res.json().catch(() => null)) as {
190
+ id?: string;
191
+ message?: string;
192
+ } | null;
193
+ if (!res.ok) {
194
+ throw new MailError(
195
+ `Resend failed (${res.status}): ${json?.message ?? res.statusText}`,
196
+ res.status,
197
+ json,
198
+ );
199
+ }
200
+ return json?.id ? { id: json.id } : {};
201
+ },
202
+ };
203
+ }
204
+
205
+ /** A mailer that records what it would send, for tests. It applies the same checks as the real ones. */
206
+ export function recordingMailer(): Mailer & { sent: MailMessage[] } {
207
+ const sent: MailMessage[] = [];
208
+ return {
209
+ sent,
210
+ async send(message) {
211
+ checkMessage(message);
212
+ sent.push(message);
213
+ return { id: `test-${sent.length}` };
214
+ },
215
+ };
216
+ }
217
+
218
+ /** Escapes text for an HTML body. */
219
+ export function escapeHtml(text: string): string {
220
+ return text.replace(
221
+ /[&<>"']/g,
222
+ (c) =>
223
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
224
+ c
225
+ ] ?? c,
226
+ );
227
+ }
package/src/sentry.ts ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Sentry options for a Worker and its pages, without importing an SDK: the
3
+ * objects here go straight into `withSentry` from `@sentry/cloudflare` and
4
+ * `Sentry.init` from a browser SDK.
5
+ *
6
+ * What every app had written for itself: no DSN means no SDK traffic, events
7
+ * from a local server (`wrangler dev`, `vite preview`) never reach the
8
+ * production project, and in the browser the noise that is not the app's to
9
+ * fix (requests that never left the device, extension and injected wallet
10
+ * scripts, users declining a wallet prompt) is dropped. The Worker side gets
11
+ * no message filters: browser wording describes nothing workerd says, so a
12
+ * filter there could only hide a real failure.
13
+ *
14
+ * Release and environment are left unset unless given, so
15
+ * `@sentry/cloudflare` reads `SENTRY_RELEASE` (or `CF_VERSION_METADATA`) and
16
+ * `SENTRY_ENVIRONMENT` from the Worker's env itself.
17
+ */
18
+
19
+ /** The part of a Sentry event the filters read. */
20
+ export interface SentryEventLike {
21
+ request?: { url?: string };
22
+ exception?: { values?: { value?: string; type?: string }[] };
23
+ }
24
+
25
+ // biome-ignore lint/suspicious/noExplicitAny: each SDK types its events differently; these options must be assignable to all of them.
26
+ type AnyEvent = any;
27
+ type BeforeSend = (event: AnyEvent, hint: AnyEvent) => AnyEvent;
28
+
29
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
30
+
31
+ /** Whether the event's request was served from this machine. An event with no request (a cron run, a workflow step) is not local. */
32
+ export function isLocalEvent(event: SentryEventLike): boolean {
33
+ const url = event.request?.url;
34
+ if (!url) return false;
35
+ try {
36
+ const host = new URL(url).hostname;
37
+ return LOCAL_HOSTS.has(host) || host.endsWith(".localhost");
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /** A `beforeSend` that drops local events and keeps the rest. */
44
+ export function dropLocalEvents<T extends SentryEventLike>(event: T): T | null {
45
+ return isLocalEvent(event) ? null : event;
46
+ }
47
+
48
+ /** Browser wording for a request that never left the device: Chrome, Safari, Firefox. */
49
+ export const NETWORK_ERROR = /failed to fetch|load failed|networkerror/i;
50
+ /** Errors thrown by extension content scripts and injected wallets. */
51
+ export const EXTENSION_ERROR =
52
+ /func \w+ not found|tronlink|trap returned falsish|origin not allowed|object captured as promise rejection with keys: code, (data, )?message/i;
53
+ /** A person declining a wallet prompt. */
54
+ export const USER_REJECTION = /user rejected|user denied|rejected the request/i;
55
+
56
+ /** Scripts other people inject into the page: extensions, wallets and Google Translate's proxy. */
57
+ export const BROWSER_DENY_URLS: readonly RegExp[] = [
58
+ /\/_\/translate_http\//i,
59
+ /injected\.js/i,
60
+ /inpage\.js/i,
61
+ /contentscript/i,
62
+ /chrome-extension:\/\//i,
63
+ /moz-extension:\/\//i,
64
+ /safari-(web-)?extension:\/\//i,
65
+ ];
66
+
67
+ /** Whether a browser event is noise that is not the app's to fix. `extra` adds patterns matched against the message. */
68
+ export function isBrowserNoise(
69
+ event: SentryEventLike,
70
+ extra: readonly RegExp[] = [],
71
+ ): boolean {
72
+ const message = event.exception?.values?.[0]?.value ?? "";
73
+ return [NETWORK_ERROR, EXTENSION_ERROR, USER_REJECTION, ...extra].some((re) =>
74
+ re.test(message),
75
+ );
76
+ }
77
+
78
+ /** A DSN worth using: an `https://` URL. Anything else (empty, `off`, a placeholder) turns Sentry off. */
79
+ export function validDsn(dsn: string | null | undefined): string | undefined {
80
+ const value = dsn?.trim();
81
+ return value?.startsWith("https://") ? value : undefined;
82
+ }
83
+
84
+ function chain(...steps: (BeforeSend | undefined)[]): BeforeSend {
85
+ return (event, hint) => {
86
+ let current = event;
87
+ for (const step of steps) {
88
+ if (!step || current === null) continue;
89
+ current = step(current, hint);
90
+ }
91
+ return current;
92
+ };
93
+ }
94
+
95
+ interface CommonOptions {
96
+ /** Overrides the DSN read from the env. */
97
+ dsn?: string | undefined;
98
+ /** Default 0: no tracing. */
99
+ tracesSampleRate?: number;
100
+ /** Runs after the built-in filters. */
101
+ beforeSend?: BeforeSend;
102
+ /** Tags set on every event, such as `{ runtime: "worker", worker: "api" }`. */
103
+ tags?: Record<string, string>;
104
+ release?: string;
105
+ environment?: string;
106
+ }
107
+
108
+ export interface WorkerSentryOptions {
109
+ dsn: string | undefined;
110
+ enabled: boolean;
111
+ tracesSampleRate: number;
112
+ beforeSend: BeforeSend;
113
+ beforeSendTransaction: BeforeSend;
114
+ initialScope?: { tags: Record<string, string> };
115
+ release?: string;
116
+ environment?: string;
117
+ }
118
+
119
+ /**
120
+ * Options for `withSentry`, `instrumentWorkflowWithSentry` and
121
+ * `instrumentDurableObjectWithSentry`. Reads `SENTRY_DSN` from the env;
122
+ * spread the result and add anything app-specific (integrations, samplers).
123
+ */
124
+ export function workerSentryOptions(
125
+ env: { SENTRY_DSN?: string | undefined },
126
+ options: CommonOptions = {},
127
+ ): WorkerSentryOptions {
128
+ const dsn = validDsn(options.dsn ?? env.SENTRY_DSN);
129
+ const out: WorkerSentryOptions = {
130
+ dsn,
131
+ enabled: dsn !== undefined,
132
+ tracesSampleRate: options.tracesSampleRate ?? 0,
133
+ beforeSend: chain(dropLocalEvents, options.beforeSend),
134
+ beforeSendTransaction: dropLocalEvents,
135
+ };
136
+ if (options.tags) out.initialScope = { tags: options.tags };
137
+ if (options.release) out.release = options.release;
138
+ if (options.environment) out.environment = options.environment;
139
+ return out;
140
+ }
141
+
142
+ export interface BrowserSentryOptions extends WorkerSentryOptions {
143
+ denyUrls: RegExp[];
144
+ }
145
+
146
+ /**
147
+ * Options for a browser SDK's `Sentry.init`. Pass the DSN (from the build),
148
+ * and `enabled: false` for dev builds, which the browser cannot tell from
149
+ * the env.
150
+ */
151
+ export function browserSentryOptions(
152
+ options: CommonOptions & {
153
+ enabled?: boolean;
154
+ /** More script URLs to ignore. */
155
+ denyUrls?: readonly RegExp[];
156
+ /** More messages that are noise. */
157
+ noise?: readonly RegExp[];
158
+ } = {},
159
+ ): BrowserSentryOptions {
160
+ const dsn = validDsn(options.dsn);
161
+ const noise = options.noise ?? [];
162
+ const out: BrowserSentryOptions = {
163
+ dsn,
164
+ enabled: dsn !== undefined && options.enabled !== false,
165
+ tracesSampleRate: options.tracesSampleRate ?? 0,
166
+ denyUrls: [...BROWSER_DENY_URLS, ...(options.denyUrls ?? [])],
167
+ beforeSend: chain(
168
+ (event) =>
169
+ isLocalEvent(event) || isBrowserNoise(event, noise) ? null : event,
170
+ options.beforeSend,
171
+ ),
172
+ beforeSendTransaction: dropLocalEvents,
173
+ };
174
+ if (options.tags) out.initialScope = { tags: options.tags };
175
+ if (options.release) out.release = options.release;
176
+ if (options.environment) out.environment = options.environment;
177
+ return out;
178
+ }