@growth-labs/push 0.2.0 → 0.4.1

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 (41) hide show
  1. package/README.md +6 -2
  2. package/dist/db/schema.d.ts +24 -10
  3. package/dist/db/schema.d.ts.map +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +8 -3
  6. package/dist/index.js.map +1 -1
  7. package/dist/types.d.ts +28 -0
  8. package/dist/types.d.ts.map +1 -1
  9. package/dist/utils/index.d.ts +1 -1
  10. package/dist/utils/index.d.ts.map +1 -1
  11. package/dist/utils/index.js +1 -1
  12. package/dist/utils/index.js.map +1 -1
  13. package/dist/utils/queue.d.ts +18 -2
  14. package/dist/utils/queue.d.ts.map +1 -1
  15. package/dist/utils/queue.js +43 -9
  16. package/dist/utils/queue.js.map +1 -1
  17. package/dist/utils/scheduled.d.ts +1 -0
  18. package/dist/utils/scheduled.d.ts.map +1 -1
  19. package/dist/utils/scheduled.js +1 -1
  20. package/dist/utils/scheduled.js.map +1 -1
  21. package/package.json +13 -7
  22. package/src/db/schema.ts +14 -0
  23. package/src/index.ts +69 -0
  24. package/src/middleware/push.ts +10 -0
  25. package/src/options.ts +45 -0
  26. package/src/routes/subscribe.ts +82 -0
  27. package/src/routes/unsubscribe.ts +29 -0
  28. package/src/types.ts +129 -0
  29. package/src/utils/analytics.ts +96 -0
  30. package/src/utils/cleanup.ts +28 -0
  31. package/src/utils/composer.ts +141 -0
  32. package/src/utils/index.ts +38 -0
  33. package/src/utils/queue.ts +173 -0
  34. package/src/utils/scheduled.ts +152 -0
  35. package/src/utils/send.ts +140 -0
  36. package/src/utils/subscriptions.ts +124 -0
  37. package/src/utils/turnstile.ts +25 -0
  38. package/src/utils/vapid.ts +28 -0
  39. package/src/client/push-sw.d.ts.map +0 -1
  40. package/src/client/push-sw.js +0 -25
  41. package/src/client/push-sw.js.map +0 -1
package/src/options.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod'
2
+
3
+ export const pushOptionsSchema = z.object({
4
+ vapidPublicKey: z.string().min(1),
5
+ vapidPrivateKey: z.string().min(1),
6
+ vapidSubject: z.string().min(1),
7
+
8
+ d1Binding: z.string().default('SITE_DB'),
9
+ queueBinding: z.string().default('PUSH_QUEUE'),
10
+
11
+ defaults: z
12
+ .object({
13
+ icon: z.string().optional(),
14
+ ttl: z.number().int().positive().default(86400),
15
+ urgency: z.enum(['very-low', 'low', 'normal', 'high']).default('normal'),
16
+ })
17
+ .default({}),
18
+
19
+ queue: z
20
+ .object({
21
+ batchSize: z.number().int().positive().default(100),
22
+ maxRetries: z.number().int().nonnegative().default(3),
23
+ })
24
+ .default({}),
25
+
26
+ turnstile: z.object({
27
+ secretKey: z.string().min(1),
28
+ }),
29
+
30
+ routes: z
31
+ .object({
32
+ subscribe: z.string().default('/api/push/subscribe'),
33
+ unsubscribe: z.string().default('/api/push/unsubscribe'),
34
+ })
35
+ .default({}),
36
+
37
+ cleanup: z
38
+ .object({
39
+ staleAfterDays: z.number().int().positive().default(90),
40
+ })
41
+ .default({}),
42
+ })
43
+
44
+ export type PushOptions = z.input<typeof pushOptionsSchema>
45
+ export type ResolvedPushOptions = z.output<typeof pushOptionsSchema>
@@ -0,0 +1,82 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import config from 'virtual:growth-labs/push/config'
3
+ import type { APIRoute } from 'astro'
4
+ import { trackPushSubscription } from '../utils/analytics.js'
5
+ import { findSubscriptionByEndpoint, saveSubscription } from '../utils/subscriptions.js'
6
+ import { verifyTurnstile } from '../utils/turnstile.js'
7
+
8
+ export const POST: APIRoute = async ({ request }) => {
9
+ const body = (await request.json()) as Record<string, unknown>
10
+
11
+ const turnstileToken = body.turnstileToken as string | undefined
12
+ if (!turnstileToken) {
13
+ return new Response(JSON.stringify({ error: 'Missing Turnstile token' }), {
14
+ status: 400,
15
+ headers: { 'Content-Type': 'application/json' },
16
+ })
17
+ }
18
+
19
+ const envMap = env as Record<string, unknown>
20
+ const turnstileSecret =
21
+ (envMap[config.turnstile.secretKey] as string) ?? (envMap.TURNSTILE_SECRET as string)
22
+ const turnstileValid = await verifyTurnstile(
23
+ turnstileToken,
24
+ turnstileSecret,
25
+ request.headers.get('CF-Connecting-IP'),
26
+ )
27
+ if (!turnstileValid) {
28
+ return new Response(JSON.stringify({ error: 'Bot detected' }), {
29
+ status: 403,
30
+ headers: { 'Content-Type': 'application/json' },
31
+ })
32
+ }
33
+
34
+ const sub = (body.subscription ?? {}) as Record<string, unknown>
35
+ const endpoint = sub.endpoint as string | undefined
36
+ const keys = sub.keys as Record<string, string> | undefined
37
+ if (!endpoint || !keys?.p256dh || !keys?.auth) {
38
+ return new Response(JSON.stringify({ error: 'Invalid subscription' }), {
39
+ status: 400,
40
+ headers: { 'Content-Type': 'application/json' },
41
+ })
42
+ }
43
+
44
+ const db = envMap[config.d1Binding] as D1Database
45
+ const existing = await findSubscriptionByEndpoint(db, endpoint)
46
+ if (existing) {
47
+ await saveSubscription(db, {
48
+ ...existing,
49
+ keyP256dh: keys.p256dh,
50
+ keyAuth: keys.auth,
51
+ failureCount: 0,
52
+ lastDeliveryAt: null,
53
+ })
54
+ return new Response(JSON.stringify({ ok: true, updated: true }), {
55
+ status: 200,
56
+ headers: { 'Content-Type': 'application/json' },
57
+ })
58
+ }
59
+
60
+ await saveSubscription(db, {
61
+ id: crypto.randomUUID(),
62
+ endpoint,
63
+ keyP256dh: keys.p256dh,
64
+ keyAuth: keys.auth,
65
+ topics: null,
66
+ createdAt: Math.floor(Date.now() / 1000),
67
+ lastDeliveryAt: null,
68
+ failureCount: 0,
69
+ userAgent: request.headers.get('User-Agent'),
70
+ country: request.headers.get('CF-IPCountry') ?? null,
71
+ })
72
+
73
+ trackPushSubscription('subscribed', {
74
+ country: request.headers.get('CF-IPCountry') ?? undefined,
75
+ userAgent: request.headers.get('User-Agent') ?? undefined,
76
+ }).catch(() => {})
77
+
78
+ return new Response(JSON.stringify({ ok: true, created: true }), {
79
+ status: 201,
80
+ headers: { 'Content-Type': 'application/json' },
81
+ })
82
+ }
@@ -0,0 +1,29 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import config from 'virtual:growth-labs/push/config'
3
+ import type { APIRoute } from 'astro'
4
+ import { trackPushSubscription } from '../utils/analytics.js'
5
+ import { deleteSubscriptionByEndpoint } from '../utils/subscriptions.js'
6
+
7
+ export const POST: APIRoute = async ({ request }) => {
8
+ const body = (await request.json()) as Record<string, unknown>
9
+ const endpoint = body.endpoint as string | undefined
10
+
11
+ if (!endpoint) {
12
+ return new Response(JSON.stringify({ error: 'Missing endpoint' }), {
13
+ status: 400,
14
+ headers: { 'Content-Type': 'application/json' },
15
+ })
16
+ }
17
+
18
+ const db = (env as Record<string, unknown>)[config.d1Binding] as D1Database
19
+ const deleted = await deleteSubscriptionByEndpoint(db, endpoint)
20
+
21
+ if (deleted) {
22
+ trackPushSubscription('unsubscribed').catch(() => {})
23
+ }
24
+
25
+ return new Response(JSON.stringify({ ok: true, deleted }), {
26
+ status: 200,
27
+ headers: { 'Content-Type': 'application/json' },
28
+ })
29
+ }
package/src/types.ts ADDED
@@ -0,0 +1,129 @@
1
+ /** Push notification payload — what the user sees */
2
+ export interface PushPayload {
3
+ title: string
4
+ body: string
5
+ icon?: string
6
+ image?: string
7
+ url: string
8
+ action?: {
9
+ title: string
10
+ url: string
11
+ }
12
+ tag?: string
13
+ }
14
+
15
+ /** Per-notification delivery options */
16
+ export interface PushSendOptions {
17
+ ttl?: number
18
+ urgency?: 'very-low' | 'low' | 'normal' | 'high'
19
+ }
20
+
21
+ /** A push subscription as stored in D1 / received from the browser */
22
+ export interface PushSubscriptionRecord {
23
+ id: string
24
+ endpoint: string
25
+ keyP256dh: string
26
+ keyAuth: string
27
+ topics: string | null
28
+ createdAt: number
29
+ lastDeliveryAt: number | null
30
+ failureCount: number
31
+ userAgent: string | null
32
+ country: string | null
33
+ }
34
+
35
+ /**
36
+ * Queue message shape for batch sends.
37
+ *
38
+ * VAPID credentials are NOT included. The Queue consumer Worker reads them
39
+ * from its own env bindings (Cloudflare Secrets). This keeps the private key
40
+ * in exactly one place and avoids serializing it into every Queue message.
41
+ *
42
+ * `siteId` identifies which site enqueued the message. The realm consumer
43
+ * uses it with `siteConfigLookup` to apply per-site overrides (icon URL,
44
+ * VAPID identity, etc.). Sites in single-tenant mode can pass any string.
45
+ */
46
+ export interface PushQueueMessage {
47
+ siteId: string
48
+ subscriptions: PushSubscriptionRecord[]
49
+ payload: PushPayload
50
+ options: PushSendOptions
51
+ }
52
+
53
+ /**
54
+ * Per-site config override applied at consumer time. Returned from
55
+ * SitePushConfigLookup. All fields are optional — only the ones present
56
+ * will override the consumer context for that message.
57
+ */
58
+ export interface SitePushConfig {
59
+ defaults?: {
60
+ icon?: string
61
+ ttl?: number
62
+ urgency?: 'very-low' | 'low' | 'normal' | 'high'
63
+ }
64
+ vapid?: {
65
+ subject?: string
66
+ publicKey?: string
67
+ privateKey?: string
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Per-message lookup. The realm consumer calls it with the message's
73
+ * `siteId`. Returns the per-site config to apply, or `null` to skip the
74
+ * override and use the consumer's context as-is.
75
+ */
76
+ export type SitePushConfigLookup = (
77
+ siteId: string,
78
+ env: Record<string, unknown>,
79
+ ) => Promise<SitePushConfig | null>
80
+
81
+ /** Result of a single push send attempt */
82
+ export interface PushSendResult {
83
+ subscriptionId: string
84
+ success: boolean
85
+ statusCode?: number
86
+ error?: string
87
+ expired?: boolean
88
+ }
89
+
90
+ /** Batch send result */
91
+ export interface PushBatchResult {
92
+ sent: number
93
+ failed: number
94
+ expired: number
95
+ results: PushSendResult[]
96
+ }
97
+
98
+ /** What the middleware puts on context.locals */
99
+ export interface PushLocals {
100
+ push: {
101
+ vapidPublicKey: string
102
+ }
103
+ }
104
+
105
+ /** Serializable config exported by the virtual module */
106
+ export interface PushConfig {
107
+ vapidPublicKey: string
108
+ d1Binding: string
109
+ queueBinding: string
110
+ defaults: {
111
+ icon?: string
112
+ ttl: number
113
+ urgency: 'very-low' | 'low' | 'normal' | 'high'
114
+ }
115
+ queue: {
116
+ batchSize: number
117
+ maxRetries: number
118
+ }
119
+ turnstile: {
120
+ secretKey: string
121
+ }
122
+ routes: {
123
+ subscribe: string
124
+ unsubscribe: string
125
+ }
126
+ cleanup: {
127
+ staleAfterDays: number
128
+ }
129
+ }
@@ -0,0 +1,96 @@
1
+ import type { PushBatchResult, PushPayload } from '../types.js'
2
+
3
+ /** Module name kept in a variable so TypeScript doesn't try to resolve it at compile time */
4
+ const ANALYTICS_MODULE = '@growth-labs/analytics'
5
+
6
+ /**
7
+ * Server-side analytics helper for push events.
8
+ *
9
+ * Uses optional peer dependency on @growth-labs/analytics.
10
+ * If analytics is not installed, events are silently dropped.
11
+ * This follows the project convention: optional peer dependency + dynamic import with try/catch.
12
+ */
13
+ export async function trackPushEvent(
14
+ eventName: string,
15
+ data: Record<string, unknown>,
16
+ ): Promise<void> {
17
+ try {
18
+ const analytics = (await import(/* @vite-ignore */ ANALYTICS_MODULE)) as Record<string, unknown>
19
+ if (analytics && typeof analytics.trackServerEvent === 'function') {
20
+ await (
21
+ analytics.trackServerEvent as (name: string, data: Record<string, unknown>) => Promise<void>
22
+ )(eventName, data)
23
+ }
24
+ } catch {
25
+ // @growth-labs/analytics not installed — silently skip
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Track a push notification send completion.
31
+ * Call after a batch send completes (in queue consumer or direct send).
32
+ */
33
+ export async function trackPushSend(payload: PushPayload, result: PushBatchResult): Promise<void> {
34
+ await trackPushEvent('push_notification_sent', {
35
+ title: payload.title,
36
+ tag: payload.tag,
37
+ url: payload.url,
38
+ sent: result.sent,
39
+ failed: result.failed,
40
+ expired: result.expired,
41
+ })
42
+ }
43
+
44
+ /**
45
+ * Track a push subscription event (subscribe or unsubscribe).
46
+ * Call from route handlers after successful subscription changes.
47
+ */
48
+ export async function trackPushSubscription(
49
+ action: 'subscribed' | 'unsubscribed',
50
+ metadata: { endpoint?: string; country?: string; userAgent?: string } = {},
51
+ ): Promise<void> {
52
+ await trackPushEvent(`push_${action}`, {
53
+ country: metadata.country,
54
+ userAgent: metadata.userAgent,
55
+ })
56
+ }
57
+
58
+ /**
59
+ * Track a push cleanup event.
60
+ * Call after subscription cleanup runs.
61
+ */
62
+ export async function trackPushCleanup(removed: number): Promise<void> {
63
+ await trackPushEvent('push_cleanup', { removed })
64
+ }
65
+
66
+ /**
67
+ * Emit a client-side analytics event using the gl:* CustomEvent pattern.
68
+ * This is meant to be called from browser-side code (service worker or page).
69
+ *
70
+ * Packages emit CustomEvent on document with gl: prefix. These are local
71
+ * browser signals; consumers call window.glAnalytics.track(...) when an event
72
+ * should be persisted to WAE.
73
+ *
74
+ * Usage in service worker notificationclick handler:
75
+ * ```javascript
76
+ * // In the page after notification click navigation
77
+ * document.dispatchEvent(new CustomEvent('gl:push_notification_clicked', {
78
+ * detail: { tag: 'article-123', url: '/articles/123' }
79
+ * }))
80
+ * ```
81
+ *
82
+ * This function is a convenience wrapper for use in page scripts.
83
+ */
84
+ export function emitPushAnalyticsEvent(
85
+ eventName: string,
86
+ detail: Record<string, unknown> = {},
87
+ ): void {
88
+ // Check for browser environment — this function is a no-op on the server
89
+ const doc =
90
+ typeof globalThis !== 'undefined'
91
+ ? (globalThis as unknown as { document?: { dispatchEvent(event: Event): boolean } }).document
92
+ : undefined
93
+ if (doc) {
94
+ doc.dispatchEvent(new CustomEvent(`gl:${eventName}`, { detail }))
95
+ }
96
+ }
@@ -0,0 +1,28 @@
1
+ interface CleanupResult {
2
+ removed: number
3
+ }
4
+
5
+ /**
6
+ * Remove stale or high-failure subscriptions.
7
+ * Call from a cron trigger or maintenance script.
8
+ */
9
+ export async function cleanupStaleSubscriptions(
10
+ db: D1Database,
11
+ options: { staleAfterDays: number },
12
+ ): Promise<CleanupResult> {
13
+ const cutoff = Math.floor(Date.now() / 1000) - options.staleAfterDays * 86400
14
+
15
+ const result = await db
16
+ .prepare(
17
+ `DELETE FROM gl_push_subscriptions
18
+ WHERE (last_delivery_at IS NOT NULL AND last_delivery_at < ?)
19
+ OR (last_delivery_at IS NULL AND created_at < ?)
20
+ OR failure_count >= 10`,
21
+ )
22
+ .bind(cutoff, cutoff)
23
+ .run()
24
+
25
+ return {
26
+ removed: result.meta?.changes ?? 0,
27
+ }
28
+ }
@@ -0,0 +1,141 @@
1
+ import type { PushPayload } from '../types.js'
2
+
3
+ /**
4
+ * A push notification template with placeholder support.
5
+ * Placeholders use {{key}} syntax and are replaced at compose time.
6
+ */
7
+ export interface PushTemplate {
8
+ /** Template name for identification */
9
+ name: string
10
+ /** Title with optional {{placeholders}} */
11
+ title: string
12
+ /** Body with optional {{placeholders}} */
13
+ body: string
14
+ /** Default icon URL (can be overridden at compose time) */
15
+ icon?: string
16
+ /** Default image URL with optional {{placeholders}} */
17
+ image?: string
18
+ /** URL pattern with optional {{placeholders}} */
19
+ url: string
20
+ /** Optional action button */
21
+ action?: {
22
+ title: string
23
+ url: string
24
+ }
25
+ /** Optional dedup tag with {{placeholders}} */
26
+ tag?: string
27
+ }
28
+
29
+ /** Variables to interpolate into a template */
30
+ export type TemplateVariables = Record<string, string>
31
+
32
+ /**
33
+ * Replace {{key}} placeholders in a string with values from the variables map.
34
+ * Unknown placeholders are left as-is.
35
+ */
36
+ function interpolate(template: string, variables: TemplateVariables): string {
37
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key: string) => {
38
+ return key in variables ? variables[key] : match
39
+ })
40
+ }
41
+
42
+ /**
43
+ * Compose a PushPayload from a template and variables.
44
+ *
45
+ * Templates define the structure with {{placeholder}} tokens.
46
+ * Variables fill in the dynamic parts at send time.
47
+ *
48
+ * ```typescript
49
+ * const template: PushTemplate = {
50
+ * name: 'new-article',
51
+ * title: 'New on {{siteName}}',
52
+ * body: '{{articleTitle}}',
53
+ * url: 'https://{{domain}}/articles/{{slug}}',
54
+ * icon: '/icons/notification-192.png',
55
+ * tag: 'article-{{slug}}',
56
+ * action: {
57
+ * title: 'Read article',
58
+ * url: 'https://{{domain}}/articles/{{slug}}',
59
+ * },
60
+ * }
61
+ *
62
+ * const payload = composePushPayload(template, {
63
+ * siteName: 'FEDweek',
64
+ * domain: 'fedweek.com',
65
+ * articleTitle: 'Federal Pay Freeze Announced',
66
+ * slug: 'pay-freeze-2026',
67
+ * })
68
+ * ```
69
+ */
70
+ export function composePushPayload(
71
+ template: PushTemplate,
72
+ variables: TemplateVariables = {},
73
+ overrides: Partial<PushPayload> = {},
74
+ ): PushPayload {
75
+ const payload: PushPayload = {
76
+ title: interpolate(template.title, variables),
77
+ body: interpolate(template.body, variables),
78
+ url: interpolate(template.url, variables),
79
+ }
80
+
81
+ if (template.icon) {
82
+ payload.icon = interpolate(template.icon, variables)
83
+ }
84
+
85
+ if (template.image) {
86
+ payload.image = interpolate(template.image, variables)
87
+ }
88
+
89
+ if (template.tag) {
90
+ payload.tag = interpolate(template.tag, variables)
91
+ }
92
+
93
+ if (template.action) {
94
+ payload.action = {
95
+ title: interpolate(template.action.title, variables),
96
+ url: interpolate(template.action.url, variables),
97
+ }
98
+ }
99
+
100
+ return { ...payload, ...overrides }
101
+ }
102
+
103
+ /**
104
+ * Built-in templates for common notification patterns.
105
+ * Consumers can use these directly or define their own.
106
+ */
107
+ export const templates = {
108
+ /** New content published notification */
109
+ newContent: {
110
+ name: 'new-content',
111
+ title: 'New on {{siteName}}',
112
+ body: '{{contentTitle}}',
113
+ url: '{{contentUrl}}',
114
+ tag: 'content-{{contentId}}',
115
+ action: {
116
+ title: 'Read now',
117
+ url: '{{contentUrl}}',
118
+ },
119
+ },
120
+
121
+ /** Breaking news / high-urgency notification */
122
+ breaking: {
123
+ name: 'breaking',
124
+ title: 'Breaking: {{headline}}',
125
+ body: '{{summary}}',
126
+ url: '{{contentUrl}}',
127
+ tag: 'breaking-{{contentId}}',
128
+ action: {
129
+ title: 'Read more',
130
+ url: '{{contentUrl}}',
131
+ },
132
+ },
133
+
134
+ /** Generic notification with just title and body */
135
+ generic: {
136
+ name: 'generic',
137
+ title: '{{title}}',
138
+ body: '{{body}}',
139
+ url: '{{url}}',
140
+ },
141
+ } as const satisfies Record<string, PushTemplate>
@@ -0,0 +1,38 @@
1
+ export {
2
+ emitPushAnalyticsEvent,
3
+ trackPushCleanup,
4
+ trackPushEvent,
5
+ trackPushSend,
6
+ trackPushSubscription,
7
+ } from './analytics.js'
8
+ export { cleanupStaleSubscriptions } from './cleanup.js'
9
+ export {
10
+ composePushPayload,
11
+ type PushTemplate,
12
+ type TemplateVariables,
13
+ templates,
14
+ } from './composer.js'
15
+ export { enqueuePushBatch, enqueuePushBatchAll } from './queue.js'
16
+ export {
17
+ handleScheduledPush,
18
+ type ScheduledContentProvider,
19
+ type ScheduledPushContext,
20
+ type ScheduledPushResult,
21
+ } from './scheduled.js'
22
+ export {
23
+ type SendContext,
24
+ sendPushBatch,
25
+ sendPushNotification,
26
+ } from './send.js'
27
+ export {
28
+ countSubscriptions,
29
+ deleteSubscriptionByEndpoint,
30
+ deleteSubscriptionById,
31
+ findSubscriptionByEndpoint,
32
+ getAllSubscriptions,
33
+ incrementFailureCount,
34
+ markDelivered,
35
+ saveSubscription,
36
+ } from './subscriptions.js'
37
+ export { verifyTurnstile } from './turnstile.js'
38
+ export { generateVapidKeys } from './vapid.js'