@proveanything/smartlinks 2.1.18 → 2.1.20

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 (53) hide show
  1. package/dist/adminViews.d.ts +19 -0
  2. package/dist/adminViews.js +16 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +110 -0
  6. package/dist/api/aiGuide.js +162 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/docs/API_SUMMARY.md +510 -40
  12. package/dist/docs/admin-lists-and-pickers.md +140 -0
  13. package/dist/docs/admin-views.md +22 -0
  14. package/dist/docs/app-data-storage.md +277 -276
  15. package/dist/docs/auth-kit.md +872 -741
  16. package/dist/docs/comms.md +686 -644
  17. package/dist/docs/customer-guide.md +70 -0
  18. package/dist/docs/headless-providers.md +112 -112
  19. package/dist/docs/server-functions.md +69 -1
  20. package/dist/docs/ui-utils.md +123 -121
  21. package/dist/docs/user-groups.md +175 -168
  22. package/dist/headless.js +38 -2
  23. package/dist/http.js +4 -0
  24. package/dist/index.d.ts +2 -2
  25. package/dist/live.d.ts +88 -0
  26. package/dist/live.js +357 -0
  27. package/dist/openapi.yaml +888 -34
  28. package/dist/testing/index.d.ts +22 -0
  29. package/dist/testing/index.js +31 -0
  30. package/dist/types/appManifest.d.ts +214 -1
  31. package/dist/types/appOptions.d.ts +32 -0
  32. package/dist/types/appOptions.js +3 -0
  33. package/dist/types/authKit.d.ts +193 -4
  34. package/dist/types/comms.d.ts +41 -2
  35. package/dist/types/headless.d.ts +49 -1
  36. package/dist/types/iframeResponder.d.ts +1 -1
  37. package/dist/types/index.d.ts +1 -0
  38. package/dist/types/index.js +1 -0
  39. package/docs/API_SUMMARY.md +510 -40
  40. package/docs/admin-lists-and-pickers.md +140 -0
  41. package/docs/admin-views.md +22 -0
  42. package/docs/app-data-storage.md +277 -276
  43. package/docs/auth-kit.md +872 -741
  44. package/docs/comms.md +686 -644
  45. package/docs/customer-guide.md +70 -0
  46. package/docs/headless-providers.md +112 -112
  47. package/docs/server-functions.md +69 -1
  48. package/docs/ui-utils.md +123 -121
  49. package/docs/user-groups.md +175 -168
  50. package/openapi.yaml +888 -34
  51. package/package.json +1 -1
  52. package/scripts/doctor.mjs +454 -428
  53. package/scripts/lib/keyed-app-data.mjs +21 -0
package/docs/comms.md CHANGED
@@ -1,644 +1,686 @@
1
- # Communications (Comms & Broadcasts)
2
-
3
- This guide covers the full communications surface of the SDK: transactional sends, multi-channel broadcasts, consent management, push registration, and analytics.
4
-
5
- ---
6
-
7
- ## What You Can Do
8
-
9
- - **Transactional Send** — Fire a single targeted message to one contact without creating a broadcast record.
10
- - **Broadcasts** — Define and enqueue multi-channel campaigns (email, push, SMS, wallet); preview and test before sending.
11
- - **Comms Settings** — Configure topics and unsubscribe behaviour per collection.
12
- - **Consent & Preferences** — Record opt-ins/outs and per-subject preferences.
13
- - **Method Registration** — Register email, SMS, and Web Push contact methods.
14
- - **Analytics** — Query delivery events, recipient lists, and log custom events.
15
-
16
- ---
17
-
18
- ## Transactional Send
19
-
20
- Sends a single message to one contact using a template. No broadcast record is created. The send is logged to the contact's communication history with `sourceType: 'transactional'`.
21
-
22
- **Endpoint:** `POST /admin/collection/:collectionId/comm/send`
23
-
24
- ```typescript
25
- import { comms } from '@proveanything/smartlinks'
26
- import type { TransactionalSendRequest } from '@proveanything/smartlinks'
27
-
28
- const result = await comms.sendTransactional('collectionId', {
29
- contactId: 'e4f2a1b0-...',
30
- templateId: 'warranty-update',
31
- channel: 'preferred', // 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet' | 'preferred' (default)
32
- props: { claimRef: 'CLM-0042', decision: 'approved' },
33
- include: {
34
- productId: 'prod-abc123', // hydrate product context into template
35
- appCase: 'c9d1e2f3-...', // hydrate an app case record
36
- },
37
- ref: 'warranty-decision-notification', // arbitrary string for your own tracking
38
- appId: 'warrantyApp',
39
- })
40
-
41
- if (result.ok) {
42
- console.log(`Sent via ${result.channel}`, result.messageId)
43
- } else {
44
- console.error('Send failed:', result.error)
45
- }
46
- ```
47
-
48
- ### Request Body
49
-
50
- | Field | Type | Description |
51
- |-------|------|-------------|
52
- | `contactId` | `string` | **Required.** Contact to send to. |
53
- | `templateId` | `string` | **Required.** Template to render. |
54
- | `channel` | `'email' \| 'sms' \| 'whatsapp' \| 'push' \| 'wallet' \| 'preferred'` | Channel to send on. `'preferred'` (default) picks the contact's best available channel. |
55
- | `props` | `Record<string, unknown>` | Extra variables merged into template rendering. |
56
- | `include` | object | Hydration flags — see table below. |
57
- | `ref` | `string` | Arbitrary reference string stored with the event. |
58
- | `appId` | `string` | App identifier, used for context/logging. |
59
- | `attach` | `EmailAttachmentSpec[]` | Files on the email — see [Attachments](#attachments). |
60
-
61
- **`include` fields:**
62
-
63
- | Field | Type | Description |
64
- |-------|------|-------------|
65
- | `collection` | `boolean` | Include collection data in template context. |
66
- | `productId` | `string` | Hydrate a specific product. |
67
- | `proofId` | `string` | Hydrate a specific proof. |
68
- | `user` | `boolean` | Include the requesting user's data. |
69
- | `appCase` | `string` | Hydrate an app case record by ID. |
70
- | `appThread` | `string` | Hydrate an app thread record by ID. |
71
- | `appRecord` | `string` | Hydrate an app record by ID. |
72
-
73
- ### Response
74
-
75
- ```typescript
76
- // Success
77
- { ok: true; channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet'; messageId?: string; attachmentsLeftOut?: string[] }
78
-
79
- // Failure
80
- { ok: false; error: string }
81
- ```
82
-
83
- ### Attachments
84
-
85
- `attach` puts files on the email (email only — ignored when the send goes by text or push). At most 5
86
- files and 10 MB in all; PDF, Word / Excel / PowerPoint, images, text, CSV and calendar files.
87
-
88
- ```typescript
89
- await comms.sendTransactional(collectionId, {
90
- contactId, templateId: 'booking-confirmed', appId: 'appointment-booking',
91
- include: { booking: bookingId },
92
- attach: [
93
- 'calendar', // the booking's .ics invite (needs include.booking + appId)
94
- { asset: 'a1b2c3' }, // a file uploaded to the collection's assets
95
- { function: 'receiptPdf' }, // the app's own server function makes it
96
- { filename: 'Quote.pdf', contentType: 'application/pdf', content: base64 }, // a file you made
97
- { filename: 'Report.pdf', file: signedUrl }, // a private file you made (pdf.create return: 'signedUrl')
98
- ],
99
- })
100
- ```
101
-
102
- A malformed list is refused (`transactional.attach_invalid`). A file that can't be made at send time
103
- (a missing asset, a function that fails) is left out and listed in `attachmentsLeftOut` — the email
104
- still goes. The request body is capped at 10 MB, so for big files make a private file and pass `file`.
105
- `bookings.message` takes the same `attach` (`'calendar'` is each person's own booking).
106
-
107
- ---
108
-
109
- ## Broadcasts
110
-
111
- Broadcasts are multi-channel campaigns defined and managed under a collection. Create a broadcast record in the platform first, then use the SDK to preview, test, and enqueue.
112
-
113
- **Import:**
114
- ```typescript
115
- import { broadcasts } from '@proveanything/smartlinks'
116
- import type { BroadcastSendRequest } from '@proveanything/smartlinks'
117
- ```
118
-
119
- ### Preview
120
-
121
- Render a broadcast template for a given channel without sending.
122
-
123
- ```typescript
124
- const preview = await broadcasts.preview('collectionId', 'broadcastId', {
125
- email: 'user@example.com', // optional: override recipient email for preview
126
- channelOverride: 'push', // force a specific channel
127
- props: { productId: 'prod_123' },
128
- hydrate: true,
129
- include: { product: true, proof: true }
130
- })
131
- // preview.channel — which channel was rendered
132
- // preview.payload / preview.subject / preview.body — channel-specific render output
133
- ```
134
-
135
- ### Test Send
136
-
137
- Send a single test message to a contact.
138
-
139
- ```typescript
140
- await broadcasts.sendTest('collectionId', 'broadcastId', {
141
- contactId: 'contact_123',
142
- props: { promo: 'JAN' }
143
- })
144
- ```
145
-
146
- ### Enqueue Production Send
147
-
148
- Enqueue a background send to all recipients. When `channel` is omitted the broadcast's own mode setting drives channel selection:
149
- - `preferred` — picks the best single channel per recipient.
150
- - `channels` / `all` — sends on every enabled channel.
151
-
152
- ```typescript
153
- const body: BroadcastSendRequest = {
154
- pageSize: 200,
155
- hydrate: true,
156
- include: { product: true, proof: true, user: true }
157
- }
158
- await broadcasts.send('collectionId', 'broadcastId', body)
159
- ```
160
-
161
- ### Manual Send
162
-
163
- ```typescript
164
- await broadcasts.sendManual('collectionId', 'broadcastId', { /* overrides */ })
165
- ```
166
-
167
- ### Topic Targeting and Consent
168
-
169
- A broadcast must declare a `topic` under `broadcast.data.topic` (e.g. `newsletter`, `critical`). The topic key must match one defined in your collection's comms settings, and consent enforcement uses it at send time.
170
-
171
- Consent resolution order (per recipient, per channel):
172
- 1. `preferences._default.topicsByChannel[channel][topic]`
173
- 2. `preferences._default.channels[channel]`
174
- 3. `preferences._default.topics[topic]`
175
- 4. Subject-specific preferences (when hydrating a subject context)
176
-
177
- Minimal broadcast data shape (`attach` is optional — uploaded assets only, the same files on every email):
178
- ```json
179
- {
180
- "data": {
181
- "topic": "newsletter",
182
- "attach": [{ "asset": "a1b2c3" }],
183
- "channelSettings": {
184
- "mode": "preferred",
185
- "channels": [
186
- { "channel": "email", "enabled": true, "priority": 1, "templateId": "tmpl_newsletter_email" },
187
- { "channel": "push", "enabled": true, "priority": 2 }
188
- ]
189
- }
190
- }
191
- }
192
- ```
193
-
194
- ### Append Recipients and Events
195
-
196
- ```typescript
197
- // Append a single delivery event
198
- await broadcasts.append('collectionId', {
199
- broadcastId: 'broadcastId',
200
- contactId: 'contact_123',
201
- channel: 'email',
202
- eventType: 'delivered',
203
- outcome: 'success'
204
- })
205
-
206
- // Append bulk events
207
- await broadcasts.appendBulk('collectionId', {
208
- params: { broadcastId: 'broadcastId', channel: 'push' },
209
- ids: ['contact_1', 'contact_2'],
210
- idField: 'contactId'
211
- })
212
-
213
- // List recipients
214
- const recips = await broadcasts.recipients('collectionId', 'broadcastId', { limit: 50 })
215
- ```
216
-
217
- ---
218
-
219
- ## Admin Comms Settings
220
-
221
- Configure unsubscribe behaviour and topics per collection.
222
-
223
- **Base path:** `admin/collection/:collectionId/comm.settings`
224
-
225
- ### Get Settings
226
-
227
- ```typescript
228
- import { comms } from '@proveanything/smartlinks'
229
- const { settings } = await comms.getSettings('collectionId', { includeSecret: true })
230
- // settings.unsub — { requireToken, hasSecret }
231
- // settings.topics — map of topic key → config
232
- ```
233
-
234
- ### Patch Settings
235
-
236
- ```typescript
237
- await comms.patchSettings('collectionId', {
238
- unsub: { requireToken: true, secret: '<your-secret>' },
239
- topics: { /* ... */ }
240
- })
241
- ```
242
-
243
- To clear the unsubscribe secret, send `secret: ''`.
244
-
245
- ### Topics Config
246
-
247
- Each topic key maps to a config object:
248
-
249
- ```json
250
- {
251
- "newsletter": {
252
- "label": "Newsletter",
253
- "description": "Occasional updates and stories",
254
- "classification": "marketing",
255
- "defaults": {
256
- "policy": "opt-in",
257
- "byChannel": { "email": "opt-in", "push": "opt-in" },
258
- "channels": { "email": true, "push": true, "sms": false }
259
- },
260
- "rules": {
261
- "allowChannels": ["email", "sms", "push"],
262
- "allowUnsubscribe": true
263
- },
264
- "required": false
265
- },
266
- "critical": {
267
- "label": "Critical Notices",
268
- "classification": "transactional",
269
- "defaults": {
270
- "policy": "opt-out",
271
- "channels": { "email": true, "push": true }
272
- },
273
- "rules": { "allowChannels": ["email", "push"], "allowUnsubscribe": false },
274
- "required": true
275
- }
276
- }
277
- ```
278
-
279
- - `classification`: `'transactional'` or `'marketing'` — used by the UI when no explicit policy is set.
280
- - `defaults.policy`: `'opt-in'` or `'opt-out'` — fallback policy for channels not overridden by `byChannel`.
281
- - `required: true` and `rules.allowUnsubscribe: false` — use for critical/mandatory messages.
282
-
283
- ### Unsubscribe Tokens
284
-
285
- If `unsub.requireToken` is true, public unsubscribe calls must include a `token` query param.
286
-
287
- Token generation (topic opt-out):
288
- ```
289
- basis = "${contactId}:${topic}"
290
- token = sha256(basis + ":" + unsub.secret) // hex
291
- ```
292
-
293
- Token generation (channel opt-out):
294
- ```
295
- basis = "${contactId}:channel:${channel}"
296
- token = sha256(basis + ":" + unsub.secret)
297
- ```
298
-
299
- Browser helper:
300
- ```typescript
301
- async function sha256Hex(input: string): Promise<string> {
302
- const data = new TextEncoder().encode(input)
303
- const hash = await crypto.subtle.digest('SHA-256', data)
304
- return Array.from(new Uint8Array(hash))
305
- .map(b => b.toString(16).padStart(2, '0'))
306
- .join('')
307
- }
308
-
309
- const token = await sha256Hex(`${contactId}:${topic}:${secret}`)
310
- ```
311
-
312
- ---
313
-
314
- ## Public Comms API
315
-
316
- All public endpoints live under `public/collection/:collectionId/comm/*` and do not require an API key.
317
-
318
- ### Get Topics
319
-
320
- ```typescript
321
- const { topics } = await comms.getPublicTopics('collectionId')
322
- ```
323
-
324
- Each topic carries UI metadata:
325
- - `classification`: `'transactional'` | `'marketing'`
326
- - `defaults.policy`: `'opt-in'` | `'opt-out'`
327
- - `defaults.byChannel[channel]`: per-channel override
328
-
329
- Helper to resolve effective policy for a toggle UI:
330
- ```typescript
331
- type Policy = 'opt-in' | 'opt-out'
332
-
333
- function effectivePolicy(topic: any, channel: 'email' | 'sms' | 'push' | 'wallet'): Policy {
334
- return (
335
- topic?.defaults?.byChannel?.[channel] ??
336
- topic?.defaults?.policy ??
337
- (topic?.classification === 'marketing' ? 'opt-in' : 'opt-out')
338
- ) as Policy
339
- }
340
- ```
341
-
342
- ### Sign-up with double opt-in (newsletters)
343
-
344
- For a sign-up form — works signed out. SmartLinks emails the address a "confirm your subscription"
345
- link; nothing is consented until it's clicked. The answer is always the same, so the form can't be
346
- used to find out who's registered.
347
-
348
- ```typescript
349
- await comms.signup('collectionId', {
350
- email: 'sam@example.com',
351
- topics: ['newsletter'],
352
- templateId: config.confirmationTemplateId, // YOUR confirmation email (required)
353
- fields: { firstName: 'Sam', customFields: { favouriteStore: 'Leeds' } }, // optional
354
- appId: 'my-newsletter',
355
- })
356
- // → { ok: true, pending: true } — tell the visitor to check their inbox
357
- ```
358
-
359
- - **The confirmation email is the app's own** (emails belong to the app that runs the flow — there is
360
- no platform default): a template in the collection, created and edited in the app's admin, e.g.
361
- `SL.template.create(collectionId, { name: 'Confirm your subscription', type: 'email', engine: 'liquid',
362
- subject: 'Please confirm your subscription', body: '…<a href="{{ action_url }}">Yes, subscribe me</a>…' })`.
363
- It gets `{{ action_url }}` (the confirm link), `{{ topics }}` (labels) and `{{ contact.firstName }}`.
364
- - **Form answers** (`fields`) are applied only once the address is confirmed, and only to the
365
- contact's empty fields — a sign-up can never overwrite someone else's details.
366
-
367
- - Topics must exist in the collection's comm settings. Give a newsletter topic
368
- `defaults.policy: 'opt-in'`: broadcasts on an opt-in topic only reach people who said yes
369
- (confirmed sign-ups), never the whole contact list.
370
- - Confirming turns on the email channel and the topics, and marks the address verified.
371
- - Don't use `contact.publicUpsert` + `comms.upsertConsent` for a signed-out form: consent calls act only
372
- for the signed-in contact. `comms.signup` is the signed-out path.
373
- - Set comm settings `signup.confirmedUrl` (https) to send people to your own "thanks" page after
374
- they confirm (`?confirmed=1`, or `0` for an expired link); otherwise SmartLinks shows a short page.
375
-
376
- ### Consent (Default)
377
-
378
- Record a contact's default channel and topic opt-ins. These calls (consent, preferences, subscribe,
379
- methods, push/email/SMS registration) act for the **signed-in** contact — `contactId` may be omitted
380
- to mean "me"; only collection admins may name another contact. An email registered here is verified
381
- only if it's the one the user signed in with; any other address is sent a confirmation link.
382
-
383
- ```typescript
384
- await comms.upsertConsent('collectionId', {
385
- contactId: 'contact_123',
386
- channels: { email: true, push: true },
387
- topics: { newsletter: true, critical: true },
388
- topicsByChannel: { email: { newsletter: true }, push: { critical: true } }
389
- })
390
- ```
391
-
392
- ### Preferences (Subject-Specific)
393
-
394
- Record consent specific to a product, proof, or other subject. Omit `subject` to update defaults.
395
-
396
- ```typescript
397
- await comms.upsertPreferences('collectionId', {
398
- contactId: 'contact_123',
399
- subject: { type: 'product', id: 'prod_1' },
400
- channels: { email: true },
401
- topics: { updates: true }
402
- })
403
- ```
404
-
405
- ### Subscribe / Unsubscribe (Subject)
406
-
407
- Manage subscriptions to a specific subject (e.g. product updates, proof alerts).
408
-
409
- ```typescript
410
- // Subscribe
411
- const { subscriptionId } = await comms.subscribe('collectionId', {
412
- contactId: 'contact_123',
413
- subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
414
- subscribe: true,
415
- source: 'api'
416
- })
417
-
418
- // Unsubscribe (same call, subscribe: false)
419
- await comms.subscribe('collectionId', {
420
- contactId: 'contact_123',
421
- subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
422
- subscribe: false,
423
- source: 'api'
424
- })
425
- ```
426
-
427
- ### Check Subscription
428
-
429
- ```typescript
430
- const r = await comms.checkSubscription('collectionId', {
431
- contactId: 'contact_123',
432
- subjectType: 'proof',
433
- subjectId: 'prf_1',
434
- productId: 'prod_1'
435
- })
436
- // r.subscribed === true | false
437
- ```
438
-
439
- ### Resolve Subscriptions
440
-
441
- Find contacts that are subscribed to a subject using identity hints.
442
-
443
- ```typescript
444
- const res = await comms.resolveSubscriptions('collectionId', {
445
- subject: { type: 'product', id: 'prod_1' },
446
- hints: { userId: 'user_1', email: 'user@example.com' }
447
- })
448
- ```
449
-
450
- ### List and Register Methods
451
-
452
- ```typescript
453
- // List registered methods for a contact
454
- const { methods } = await comms.listMethods('collectionId', {
455
- contactId: 'contact_123',
456
- type: 'email' // optional filter: 'email' | 'sms' | 'push'
457
- })
458
-
459
- // Register email
460
- await comms.registerEmail('collectionId', {
461
- contactId: 'contact_123',
462
- email: 'user@example.com'
463
- })
464
-
465
- // Register SMS
466
- await comms.registerSms('collectionId', {
467
- contactId: 'contact_123',
468
- phone: '+12065550100'
469
- })
470
- ```
471
-
472
- ### Unsubscribe (Public Link / One-Click)
473
-
474
- ```typescript
475
- await comms.unsubscribe('collectionId', {
476
- contactId: 'contact_123',
477
- topic: 'newsletter',
478
- token: '<sha256-hex-when-requireToken-is-true>'
479
- })
480
- ```
481
-
482
- Omit `topic` to unsubscribe from all. Omit `channel` to apply across all channels.
483
-
484
- ---
485
-
486
- ## Push Registration
487
-
488
- Web Push requires a service worker and the browser's Push API.
489
-
490
- ### 1. Fetch the VAPID Public Key
491
-
492
- ```typescript
493
- import { comms } from '@proveanything/smartlinks'
494
- const { publicKey } = await comms.getPushVapidPublicKey('collectionId')
495
- ```
496
-
497
- ### 2. Subscribe in the Service Worker
498
-
499
- ```typescript
500
- const registration = await navigator.serviceWorker.ready
501
- const subscription = await registration.pushManager.subscribe({
502
- userVisibleOnly: true,
503
- applicationServerKey: urlBase64ToUint8Array(publicKey),
504
- })
505
- const subJson = subscription.toJSON() as any
506
- ```
507
-
508
- ### 3. Register the Method
509
-
510
- ```typescript
511
- await comms.registerPush('collectionId', {
512
- contactId: 'contact_123',
513
- endpoint: subscription.endpoint,
514
- keys: subJson?.keys,
515
- meta: { userId: 'user_1' }
516
- })
517
- ```
518
-
519
- ### VAPID Key Utility
520
-
521
- ```typescript
522
- function urlBase64ToUint8Array(base64String: string): Uint8Array {
523
- const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
524
- const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
525
- const rawData = atob(base64)
526
- const output = new Uint8Array(rawData.length)
527
- for (let i = 0; i < rawData.length; i++) output[i] = rawData.charCodeAt(i)
528
- return output
529
- }
530
- ```
531
-
532
- ---
533
-
534
- ## Analytics
535
-
536
- ### Query Events by User / Contact
537
-
538
- ```typescript
539
- const events = await comms.queryByUser('collectionId', {
540
- userId: 'user_123',
541
- limit: 100
542
- })
543
- ```
544
-
545
- ### Recipient IDs for a Source
546
-
547
- ```typescript
548
- const ids = await comms.queryRecipientIds('collectionId', {
549
- broadcastId: 'br_456'
550
- })
551
- ```
552
-
553
- ### Recipients Without an Action
554
-
555
- ```typescript
556
- const withoutOpen = await comms.queryRecipientsWithoutAction('collectionId', {
557
- broadcastId: 'br_456',
558
- actionId: 'open'
559
- })
560
- ```
561
-
562
- ### Recipients With an Action
563
-
564
- ```typescript
565
- const withClick = await comms.queryRecipientsWithAction('collectionId', {
566
- broadcastId: 'br_456',
567
- actionId: 'click',
568
- includeOutcome: true // returns RecipientWithOutcome[] instead of RecipientId[]
569
- })
570
- ```
571
-
572
- ### Log Events
573
-
574
- ```typescript
575
- // Single event
576
- await comms.logCommunicationEvent('collectionId', {
577
- eventType: 'opened',
578
- channel: 'email',
579
- contactId: 'contact_123'
580
- })
581
-
582
- // Bulk events (same params applied to all IDs)
583
- await comms.logBulkCommunicationEvents('collectionId', {
584
- params: { broadcastId: 'br_456', channel: 'email', eventType: 'delivered' },
585
- ids: ['contact_1', 'contact_2', 'contact_3'],
586
- idField: 'contactId'
587
- })
588
- ```
589
-
590
- ---
591
-
592
- ## End-to-End Admin Workflow
593
-
594
- A typical sequence from setup to delivery:
595
-
596
- ```typescript
597
- import { comms, broadcasts } from '@proveanything/smartlinks'
598
-
599
- // 1. Configure topics and unsubscribe rules
600
- await comms.patchSettings('collectionId', {
601
- unsub: { requireToken: true, secret: process.env.UNSUB_SECRET },
602
- topics: {
603
- newsletter: {
604
- label: 'Newsletter', classification: 'marketing',
605
- defaults: { policy: 'opt-in', channels: { email: true, push: true } },
606
- rules: { allowChannels: ['email', 'push', 'sms'], allowUnsubscribe: true }
607
- }
608
- }
609
- })
610
-
611
- // 2. Register contact methods (done at contact creation / profile update)
612
- await comms.registerEmail('collectionId', { contactId: 'c_123', email: 'user@example.com' })
613
-
614
- // 3. Record consent (done when user confirms opt-in)
615
- await comms.upsertConsent('collectionId', {
616
- contactId: 'c_123',
617
- channels: { email: true }, topics: { newsletter: true }
618
- })
619
-
620
- // 4a. Transactional: send a one-off triggered message
621
- const result = await comms.sendTransactional('collectionId', {
622
- contactId: 'c_123', templateId: 'order-confirmed',
623
- channel: 'email', props: { orderId: 'ORD-001' }
624
- })
625
-
626
- // 4b. Broadcast: preview → test → enqueue
627
- const preview = await broadcasts.preview('collectionId', 'br_spring', {
628
- channelOverride: 'email', hydrate: true, include: { product: true }
629
- })
630
- await broadcasts.sendTest('collectionId', 'br_spring', { contactId: 'c_123' })
631
- await broadcasts.send('collectionId', 'br_spring', { pageSize: 200, hydrate: true })
632
- ```
633
-
634
- ---
635
-
636
- ## Prerequisites
637
-
638
- | Feature | Requirement |
639
- |---------|-------------|
640
- | Email | SendGrid credentials (env or collection comms settings) |
641
- | Push | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` env vars |
642
- | SMS | Twilio credentials (env or collection comms settings) |
643
- | Wallet | Google Wallet issuer + service account |
644
- | Hydration | Set `hydrate: true` and populate `include` on broadcast/transactional sends |
1
+ # Communications (Comms & Broadcasts)
2
+
3
+ This guide covers the full communications surface of the SDK: transactional sends, multi-channel broadcasts, consent management, push registration, and analytics.
4
+
5
+ ---
6
+
7
+ ## What You Can Do
8
+
9
+ - **Transactional Send** — Fire a single targeted message to one contact without creating a broadcast record.
10
+ - **Broadcasts** — Define and enqueue multi-channel campaigns (email, push, SMS, wallet); preview and test before sending.
11
+ - **Comms Settings** — Configure topics and unsubscribe behaviour per collection.
12
+ - **Consent & Preferences** — Record opt-ins/outs and per-subject preferences.
13
+ - **Method Registration** — Register email, SMS, and Web Push contact methods.
14
+ - **Analytics** — Query delivery events, recipient lists, and log custom events.
15
+
16
+ ---
17
+
18
+ ## Transactional Send
19
+
20
+ Sends a single message to one contact using a template. No broadcast record is created. The send is logged to the contact's communication history with `sourceType: 'transactional'`.
21
+
22
+ **Endpoint:** `POST /admin/collection/:collectionId/comm/send`
23
+
24
+ ```typescript
25
+ import { comms } from '@proveanything/smartlinks'
26
+ import type { TransactionalSendRequest } from '@proveanything/smartlinks'
27
+
28
+ const result = await comms.sendTransactional('collectionId', {
29
+ contactId: 'e4f2a1b0-...',
30
+ templateId: 'warranty-update',
31
+ channel: 'preferred', // 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet' | 'preferred' (default)
32
+ props: { claimRef: 'CLM-0042', decision: 'approved' },
33
+ include: {
34
+ productId: 'prod-abc123', // hydrate product context into template
35
+ appCase: 'c9d1e2f3-...', // hydrate an app case record
36
+ },
37
+ ref: 'warranty-decision-notification', // arbitrary string for your own tracking
38
+ appId: 'warrantyApp',
39
+ })
40
+
41
+ if (result.ok) {
42
+ console.log(`Sent via ${result.channel}`, result.messageId)
43
+ } else {
44
+ console.error('Send failed:', result.error)
45
+ }
46
+ ```
47
+
48
+ ### Request Body
49
+
50
+ | Field | Type | Description |
51
+ |-------|------|-------------|
52
+ | `contactId` | `string` | **Required.** Contact to send to. |
53
+ | `templateId` | `string` | **Required.** Template to render. |
54
+ | `channel` | `'email' \| 'sms' \| 'whatsapp' \| 'push' \| 'wallet' \| 'preferred'` | Channel to send on. `'preferred'` (default) picks the contact's best available channel. |
55
+ | `props` | `Record<string, unknown>` | Extra variables merged into template rendering. |
56
+ | `include` | object | Hydration flags — see table below. |
57
+ | `ref` | `string` | Arbitrary reference string stored with the event. |
58
+ | `appId` | `string` | App identifier, used for context/logging. |
59
+ | `attach` | `EmailAttachmentSpec[]` | Files on the email — see [Attachments](#attachments). |
60
+
61
+ **`include` fields:**
62
+
63
+ | Field | Type | Description |
64
+ |-------|------|-------------|
65
+ | `collection` | `boolean` | Include collection data in template context. |
66
+ | `productId` | `string` | Hydrate a specific product. |
67
+ | `proofId` | `string` | Hydrate a specific proof. |
68
+ | `user` | `boolean` | Include the requesting user's data. |
69
+ | `appCase` | `string` | Hydrate an app case record by ID. |
70
+ | `appThread` | `string` | Hydrate an app thread record by ID. |
71
+ | `appRecord` | `string` | Hydrate an app record by ID. |
72
+
73
+ ### Response
74
+
75
+ ```typescript
76
+ // Success
77
+ { ok: true; channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet'; messageId?: string; attachmentsLeftOut?: string[] }
78
+
79
+ // Failure
80
+ { ok: false; error: string }
81
+ ```
82
+
83
+ ### Attachments
84
+
85
+ `attach` puts files on the email (email only — ignored when the send goes by text or push). At most 5
86
+ files and 10 MB in all; PDF, Word / Excel / PowerPoint, images, text, CSV and calendar files.
87
+
88
+ ```typescript
89
+ await comms.sendTransactional(collectionId, {
90
+ contactId, templateId: 'booking-confirmed', appId: 'appointment-booking',
91
+ include: { booking: bookingId },
92
+ attach: [
93
+ 'calendar', // the booking's .ics invite (needs include.booking + appId)
94
+ { asset: 'a1b2c3' }, // a file uploaded to the collection's assets
95
+ { function: 'receiptPdf' }, // the app's own server function makes it
96
+ { filename: 'Quote.pdf', contentType: 'application/pdf', content: base64 }, // a file you made
97
+ { filename: 'Report.pdf', file: signedUrl }, // a private file you made (pdf.create return: 'signedUrl')
98
+ ],
99
+ })
100
+ ```
101
+
102
+ A malformed list is refused (`transactional.attach_invalid`). A file that can't be made at send time
103
+ (a missing asset, a function that fails) is left out and listed in `attachmentsLeftOut` — the email
104
+ still goes. The request body is capped at 10 MB, so for big files make a private file and pass `file`.
105
+ `bookings.message` takes the same `attach` (`'calendar'` is each person's own booking).
106
+
107
+ ---
108
+
109
+ ## Messaging one person from an app
110
+
111
+ Every app sends through the platform: a booking reminder, a cancellation, an event update, "we got your
112
+ entry". You never set up email or SMS yourself. Each message:
113
+ - goes out on the person's preferred channel, or one you name;
114
+ - respects their opt-outs;
115
+ - is logged with your app;
116
+ - shows in the Messages app and on the contact's Activity in the CRM.
117
+
118
+ **From server code** (`sl:messages:write`):
119
+
120
+ ```js
121
+ const out = await ctx.sl.messages.send({
122
+ to: 'caller', // or contactId
123
+ templateId: 'tpl_booking_cancelled', // or message: { subject, body, sms? }
124
+ include: { booking: bookingId }, // hydrates {{ booking }}, as comm/send
125
+ about: { type: 'booking', id: bookingId, view: 'booking', params: { bookingId }, label: 'Sat 3pm' },
126
+ })
127
+ if (!out.ok) ctx.log('not sent', { reason: out.reason }) // 'opted_out' | 'no_channel' | 'no_contact' | 'template_not_found'
128
+ ```
129
+
130
+ **From an admin screen:** `SL.comms.sendTransactional(collectionId, { contactId, message | templateId, about, category: 'service', appId })`.
131
+
132
+ - **Service messages only.** A confirmation, a reminder, a cancellation or an update. Marketing goes out
133
+ as a campaign, with its opt-in and unsubscribe.
134
+ - **Someone who can't be reached is an answer, not an error.** `ctx.sl.messages.send` returns
135
+ `{ ok: false, reason }`; only a real failure throws.
136
+ - **A typed message** is plain text with Liquid (`{{ contact.firstName }}`), sent exactly like a template:
137
+ `{ subject, body, sms? }`.
138
+
139
+ ### What a message is about
140
+
141
+ `about: { appId?, type, id, view?, params?, label? }` names the record the message was sent for, and the
142
+ admin screen that shows it. `view` and `params` are one of your manifest `adminViews`
143
+ ([admin-views.md](admin-views.md)).
144
+ - **Where it shows:** the Message log shows "Bookings · Sat 3pm", and it is a link to your screen. A reply
145
+ opens a conversation that links to the same record.
146
+ - **Defaults:** `appId` defaults to your app.
147
+ - **Ids only:** never put content in it.
148
+ - **Reading it back:** the log can be filtered by it: `GET /admin/collection/:id/comm/query/events?aboutType=booking&aboutId=B-123`,
149
+ or `app=<appId>` for everything your app sent.
150
+
151
+ ## Broadcasts
152
+
153
+ Broadcasts are multi-channel campaigns defined and managed under a collection. Create a broadcast record in the platform first, then use the SDK to preview, test, and enqueue.
154
+
155
+ **Import:**
156
+ ```typescript
157
+ import { broadcasts } from '@proveanything/smartlinks'
158
+ import type { BroadcastSendRequest } from '@proveanything/smartlinks'
159
+ ```
160
+
161
+ ### Preview
162
+
163
+ Render a broadcast template for a given channel without sending.
164
+
165
+ ```typescript
166
+ const preview = await broadcasts.preview('collectionId', 'broadcastId', {
167
+ email: 'user@example.com', // optional: override recipient email for preview
168
+ channelOverride: 'push', // force a specific channel
169
+ props: { productId: 'prod_123' },
170
+ hydrate: true,
171
+ include: { product: true, proof: true }
172
+ })
173
+ // preview.channel — which channel was rendered
174
+ // preview.payload / preview.subject / preview.body — channel-specific render output
175
+ ```
176
+
177
+ ### Test Send
178
+
179
+ Send a single test message to a contact.
180
+
181
+ ```typescript
182
+ await broadcasts.sendTest('collectionId', 'broadcastId', {
183
+ contactId: 'contact_123',
184
+ props: { promo: 'JAN' }
185
+ })
186
+ ```
187
+
188
+ ### Enqueue Production Send
189
+
190
+ Enqueue a background send to all recipients. When `channel` is omitted the broadcast's own mode setting drives channel selection:
191
+ - `preferred` — picks the best single channel per recipient.
192
+ - `channels` / `all` — sends on every enabled channel.
193
+
194
+ ```typescript
195
+ const body: BroadcastSendRequest = {
196
+ pageSize: 200,
197
+ hydrate: true,
198
+ include: { product: true, proof: true, user: true }
199
+ }
200
+ await broadcasts.send('collectionId', 'broadcastId', body)
201
+ ```
202
+
203
+ ### Manual Send
204
+
205
+ ```typescript
206
+ await broadcasts.sendManual('collectionId', 'broadcastId', { /* overrides */ })
207
+ ```
208
+
209
+ ### Topic Targeting and Consent
210
+
211
+ A broadcast must declare a `topic` under `broadcast.data.topic` (e.g. `newsletter`, `critical`). The topic key must match one defined in your collection's comms settings, and consent enforcement uses it at send time.
212
+
213
+ Consent resolution order (per recipient, per channel):
214
+ 1. `preferences._default.topicsByChannel[channel][topic]`
215
+ 2. `preferences._default.channels[channel]`
216
+ 3. `preferences._default.topics[topic]`
217
+ 4. Subject-specific preferences (when hydrating a subject context)
218
+
219
+ Minimal broadcast data shape (`attach` is optional — uploaded assets only, the same files on every email):
220
+ ```json
221
+ {
222
+ "data": {
223
+ "topic": "newsletter",
224
+ "attach": [{ "asset": "a1b2c3" }],
225
+ "channelSettings": {
226
+ "mode": "preferred",
227
+ "channels": [
228
+ { "channel": "email", "enabled": true, "priority": 1, "templateId": "tmpl_newsletter_email" },
229
+ { "channel": "push", "enabled": true, "priority": 2 }
230
+ ]
231
+ }
232
+ }
233
+ }
234
+ ```
235
+
236
+ ### Append Recipients and Events
237
+
238
+ ```typescript
239
+ // Append a single delivery event
240
+ await broadcasts.append('collectionId', {
241
+ broadcastId: 'broadcastId',
242
+ contactId: 'contact_123',
243
+ channel: 'email',
244
+ eventType: 'delivered',
245
+ outcome: 'success'
246
+ })
247
+
248
+ // Append bulk events
249
+ await broadcasts.appendBulk('collectionId', {
250
+ params: { broadcastId: 'broadcastId', channel: 'push' },
251
+ ids: ['contact_1', 'contact_2'],
252
+ idField: 'contactId'
253
+ })
254
+
255
+ // List recipients
256
+ const recips = await broadcasts.recipients('collectionId', 'broadcastId', { limit: 50 })
257
+ ```
258
+
259
+ ---
260
+
261
+ ## Admin Comms Settings
262
+
263
+ Configure unsubscribe behaviour and topics per collection.
264
+
265
+ **Base path:** `admin/collection/:collectionId/comm.settings`
266
+
267
+ ### Get Settings
268
+
269
+ ```typescript
270
+ import { comms } from '@proveanything/smartlinks'
271
+ const { settings } = await comms.getSettings('collectionId', { includeSecret: true })
272
+ // settings.unsub — { requireToken, hasSecret }
273
+ // settings.topics — map of topic key → config
274
+ ```
275
+
276
+ ### Patch Settings
277
+
278
+ ```typescript
279
+ await comms.patchSettings('collectionId', {
280
+ unsub: { requireToken: true, secret: '<your-secret>' },
281
+ topics: { /* ... */ }
282
+ })
283
+ ```
284
+
285
+ To clear the unsubscribe secret, send `secret: ''`.
286
+
287
+ ### Topics Config
288
+
289
+ Each topic key maps to a config object:
290
+
291
+ ```json
292
+ {
293
+ "newsletter": {
294
+ "label": "Newsletter",
295
+ "description": "Occasional updates and stories",
296
+ "classification": "marketing",
297
+ "defaults": {
298
+ "policy": "opt-in",
299
+ "byChannel": { "email": "opt-in", "push": "opt-in" },
300
+ "channels": { "email": true, "push": true, "sms": false }
301
+ },
302
+ "rules": {
303
+ "allowChannels": ["email", "sms", "push"],
304
+ "allowUnsubscribe": true
305
+ },
306
+ "required": false
307
+ },
308
+ "critical": {
309
+ "label": "Critical Notices",
310
+ "classification": "transactional",
311
+ "defaults": {
312
+ "policy": "opt-out",
313
+ "channels": { "email": true, "push": true }
314
+ },
315
+ "rules": { "allowChannels": ["email", "push"], "allowUnsubscribe": false },
316
+ "required": true
317
+ }
318
+ }
319
+ ```
320
+
321
+ - `classification`: `'transactional'` or `'marketing'` — used by the UI when no explicit policy is set.
322
+ - `defaults.policy`: `'opt-in'` or `'opt-out'` — fallback policy for channels not overridden by `byChannel`.
323
+ - `required: true` and `rules.allowUnsubscribe: false` — use for critical/mandatory messages.
324
+
325
+ ### Unsubscribe Tokens
326
+
327
+ If `unsub.requireToken` is true, public unsubscribe calls must include a `token` query param.
328
+
329
+ Token generation (topic opt-out):
330
+ ```
331
+ basis = "${contactId}:${topic}"
332
+ token = sha256(basis + ":" + unsub.secret) // hex
333
+ ```
334
+
335
+ Token generation (channel opt-out):
336
+ ```
337
+ basis = "${contactId}:channel:${channel}"
338
+ token = sha256(basis + ":" + unsub.secret)
339
+ ```
340
+
341
+ Browser helper:
342
+ ```typescript
343
+ async function sha256Hex(input: string): Promise<string> {
344
+ const data = new TextEncoder().encode(input)
345
+ const hash = await crypto.subtle.digest('SHA-256', data)
346
+ return Array.from(new Uint8Array(hash))
347
+ .map(b => b.toString(16).padStart(2, '0'))
348
+ .join('')
349
+ }
350
+
351
+ const token = await sha256Hex(`${contactId}:${topic}:${secret}`)
352
+ ```
353
+
354
+ ---
355
+
356
+ ## Public Comms API
357
+
358
+ All public endpoints live under `public/collection/:collectionId/comm/*` and do not require an API key.
359
+
360
+ ### Get Topics
361
+
362
+ ```typescript
363
+ const { topics } = await comms.getPublicTopics('collectionId')
364
+ ```
365
+
366
+ Each topic carries UI metadata:
367
+ - `classification`: `'transactional'` | `'marketing'`
368
+ - `defaults.policy`: `'opt-in'` | `'opt-out'`
369
+ - `defaults.byChannel[channel]`: per-channel override
370
+
371
+ Helper to resolve effective policy for a toggle UI:
372
+ ```typescript
373
+ type Policy = 'opt-in' | 'opt-out'
374
+
375
+ function effectivePolicy(topic: any, channel: 'email' | 'sms' | 'push' | 'wallet'): Policy {
376
+ return (
377
+ topic?.defaults?.byChannel?.[channel] ??
378
+ topic?.defaults?.policy ??
379
+ (topic?.classification === 'marketing' ? 'opt-in' : 'opt-out')
380
+ ) as Policy
381
+ }
382
+ ```
383
+
384
+ ### Sign-up with double opt-in (newsletters)
385
+
386
+ For a sign-up form — works signed out. SmartLinks emails the address a "confirm your subscription"
387
+ link; nothing is consented until it's clicked. The answer is always the same, so the form can't be
388
+ used to find out who's registered.
389
+
390
+ ```typescript
391
+ await comms.signup('collectionId', {
392
+ email: 'sam@example.com',
393
+ topics: ['newsletter'],
394
+ templateId: config.confirmationTemplateId, // YOUR confirmation email (required)
395
+ fields: { firstName: 'Sam', customFields: { favouriteStore: 'Leeds' } }, // optional
396
+ appId: 'my-newsletter',
397
+ })
398
+ // → { ok: true, pending: true } — tell the visitor to check their inbox
399
+ ```
400
+
401
+ - **The confirmation email is the app's own** (emails belong to the app that runs the flow — there is
402
+ no platform default): a template in the collection, created and edited in the app's admin, e.g.
403
+ `SL.template.create(collectionId, { name: 'Confirm your subscription', type: 'email', engine: 'liquid',
404
+ subject: 'Please confirm your subscription', body: '…<a href="{{ action_url }}">Yes, subscribe me</a>…' })`.
405
+ It gets `{{ action_url }}` (the confirm link), `{{ topics }}` (labels) and `{{ contact.firstName }}`.
406
+ - **Form answers** (`fields`) are applied only once the address is confirmed, and only to the
407
+ contact's empty fields — a sign-up can never overwrite someone else's details.
408
+
409
+ - Topics must exist in the collection's comm settings. Give a newsletter topic
410
+ `defaults.policy: 'opt-in'`: broadcasts on an opt-in topic only reach people who said yes
411
+ (confirmed sign-ups), never the whole contact list.
412
+ - Confirming turns on the email channel and the topics, and marks the address verified.
413
+ - Don't use `contact.publicUpsert` + `comms.upsertConsent` for a signed-out form: consent calls act only
414
+ for the signed-in contact. `comms.signup` is the signed-out path.
415
+ - Set comm settings `signup.confirmedUrl` (https) to send people to your own "thanks" page after
416
+ they confirm (`?confirmed=1`, or `0` for an expired link); otherwise SmartLinks shows a short page.
417
+
418
+ ### Consent (Default)
419
+
420
+ Record a contact's default channel and topic opt-ins. These calls (consent, preferences, subscribe,
421
+ methods, push/email/SMS registration) act for the **signed-in** contact — `contactId` may be omitted
422
+ to mean "me"; only collection admins may name another contact. An email registered here is verified
423
+ only if it's the one the user signed in with; any other address is sent a confirmation link.
424
+
425
+ ```typescript
426
+ await comms.upsertConsent('collectionId', {
427
+ contactId: 'contact_123',
428
+ channels: { email: true, push: true },
429
+ topics: { newsletter: true, critical: true },
430
+ topicsByChannel: { email: { newsletter: true }, push: { critical: true } }
431
+ })
432
+ ```
433
+
434
+ ### Preferences (Subject-Specific)
435
+
436
+ Record consent specific to a product, proof, or other subject. Omit `subject` to update defaults.
437
+
438
+ ```typescript
439
+ await comms.upsertPreferences('collectionId', {
440
+ contactId: 'contact_123',
441
+ subject: { type: 'product', id: 'prod_1' },
442
+ channels: { email: true },
443
+ topics: { updates: true }
444
+ })
445
+ ```
446
+
447
+ ### Subscribe / Unsubscribe (Subject)
448
+
449
+ Manage subscriptions to a specific subject (e.g. product updates, proof alerts).
450
+
451
+ ```typescript
452
+ // Subscribe
453
+ const { subscriptionId } = await comms.subscribe('collectionId', {
454
+ contactId: 'contact_123',
455
+ subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
456
+ subscribe: true,
457
+ source: 'api'
458
+ })
459
+
460
+ // Unsubscribe (same call, subscribe: false)
461
+ await comms.subscribe('collectionId', {
462
+ contactId: 'contact_123',
463
+ subject: { type: 'proof', id: 'prf_1', productId: 'prod_1' },
464
+ subscribe: false,
465
+ source: 'api'
466
+ })
467
+ ```
468
+
469
+ ### Check Subscription
470
+
471
+ ```typescript
472
+ const r = await comms.checkSubscription('collectionId', {
473
+ contactId: 'contact_123',
474
+ subjectType: 'proof',
475
+ subjectId: 'prf_1',
476
+ productId: 'prod_1'
477
+ })
478
+ // r.subscribed === true | false
479
+ ```
480
+
481
+ ### Resolve Subscriptions
482
+
483
+ Find contacts that are subscribed to a subject using identity hints.
484
+
485
+ ```typescript
486
+ const res = await comms.resolveSubscriptions('collectionId', {
487
+ subject: { type: 'product', id: 'prod_1' },
488
+ hints: { userId: 'user_1', email: 'user@example.com' }
489
+ })
490
+ ```
491
+
492
+ ### List and Register Methods
493
+
494
+ ```typescript
495
+ // List registered methods for a contact
496
+ const { methods } = await comms.listMethods('collectionId', {
497
+ contactId: 'contact_123',
498
+ type: 'email' // optional filter: 'email' | 'sms' | 'push'
499
+ })
500
+
501
+ // Register email
502
+ await comms.registerEmail('collectionId', {
503
+ contactId: 'contact_123',
504
+ email: 'user@example.com'
505
+ })
506
+
507
+ // Register SMS
508
+ await comms.registerSms('collectionId', {
509
+ contactId: 'contact_123',
510
+ phone: '+12065550100'
511
+ })
512
+ ```
513
+
514
+ ### Unsubscribe (Public Link / One-Click)
515
+
516
+ ```typescript
517
+ await comms.unsubscribe('collectionId', {
518
+ contactId: 'contact_123',
519
+ topic: 'newsletter',
520
+ token: '<sha256-hex-when-requireToken-is-true>'
521
+ })
522
+ ```
523
+
524
+ Omit `topic` to unsubscribe from all. Omit `channel` to apply across all channels.
525
+
526
+ ---
527
+
528
+ ## Push Registration
529
+
530
+ Web Push requires a service worker and the browser's Push API.
531
+
532
+ ### 1. Fetch the VAPID Public Key
533
+
534
+ ```typescript
535
+ import { comms } from '@proveanything/smartlinks'
536
+ const { publicKey } = await comms.getPushVapidPublicKey('collectionId')
537
+ ```
538
+
539
+ ### 2. Subscribe in the Service Worker
540
+
541
+ ```typescript
542
+ const registration = await navigator.serviceWorker.ready
543
+ const subscription = await registration.pushManager.subscribe({
544
+ userVisibleOnly: true,
545
+ applicationServerKey: urlBase64ToUint8Array(publicKey),
546
+ })
547
+ const subJson = subscription.toJSON() as any
548
+ ```
549
+
550
+ ### 3. Register the Method
551
+
552
+ ```typescript
553
+ await comms.registerPush('collectionId', {
554
+ contactId: 'contact_123',
555
+ endpoint: subscription.endpoint,
556
+ keys: subJson?.keys,
557
+ meta: { userId: 'user_1' }
558
+ })
559
+ ```
560
+
561
+ ### VAPID Key Utility
562
+
563
+ ```typescript
564
+ function urlBase64ToUint8Array(base64String: string): Uint8Array {
565
+ const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
566
+ const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
567
+ const rawData = atob(base64)
568
+ const output = new Uint8Array(rawData.length)
569
+ for (let i = 0; i < rawData.length; i++) output[i] = rawData.charCodeAt(i)
570
+ return output
571
+ }
572
+ ```
573
+
574
+ ---
575
+
576
+ ## Analytics
577
+
578
+ ### Query Events by User / Contact
579
+
580
+ ```typescript
581
+ const events = await comms.queryByUser('collectionId', {
582
+ userId: 'user_123',
583
+ limit: 100
584
+ })
585
+ ```
586
+
587
+ ### Recipient IDs for a Source
588
+
589
+ ```typescript
590
+ const ids = await comms.queryRecipientIds('collectionId', {
591
+ broadcastId: 'br_456'
592
+ })
593
+ ```
594
+
595
+ ### Recipients Without an Action
596
+
597
+ ```typescript
598
+ const withoutOpen = await comms.queryRecipientsWithoutAction('collectionId', {
599
+ broadcastId: 'br_456',
600
+ actionId: 'open'
601
+ })
602
+ ```
603
+
604
+ ### Recipients With an Action
605
+
606
+ ```typescript
607
+ const withClick = await comms.queryRecipientsWithAction('collectionId', {
608
+ broadcastId: 'br_456',
609
+ actionId: 'click',
610
+ includeOutcome: true // returns RecipientWithOutcome[] instead of RecipientId[]
611
+ })
612
+ ```
613
+
614
+ ### Log Events
615
+
616
+ ```typescript
617
+ // Single event
618
+ await comms.logCommunicationEvent('collectionId', {
619
+ eventType: 'opened',
620
+ channel: 'email',
621
+ contactId: 'contact_123'
622
+ })
623
+
624
+ // Bulk events (same params applied to all IDs)
625
+ await comms.logBulkCommunicationEvents('collectionId', {
626
+ params: { broadcastId: 'br_456', channel: 'email', eventType: 'delivered' },
627
+ ids: ['contact_1', 'contact_2', 'contact_3'],
628
+ idField: 'contactId'
629
+ })
630
+ ```
631
+
632
+ ---
633
+
634
+ ## End-to-End Admin Workflow
635
+
636
+ A typical sequence from setup to delivery:
637
+
638
+ ```typescript
639
+ import { comms, broadcasts } from '@proveanything/smartlinks'
640
+
641
+ // 1. Configure topics and unsubscribe rules
642
+ await comms.patchSettings('collectionId', {
643
+ unsub: { requireToken: true, secret: process.env.UNSUB_SECRET },
644
+ topics: {
645
+ newsletter: {
646
+ label: 'Newsletter', classification: 'marketing',
647
+ defaults: { policy: 'opt-in', channels: { email: true, push: true } },
648
+ rules: { allowChannels: ['email', 'push', 'sms'], allowUnsubscribe: true }
649
+ }
650
+ }
651
+ })
652
+
653
+ // 2. Register contact methods (done at contact creation / profile update)
654
+ await comms.registerEmail('collectionId', { contactId: 'c_123', email: 'user@example.com' })
655
+
656
+ // 3. Record consent (done when user confirms opt-in)
657
+ await comms.upsertConsent('collectionId', {
658
+ contactId: 'c_123',
659
+ channels: { email: true }, topics: { newsletter: true }
660
+ })
661
+
662
+ // 4a. Transactional: send a one-off triggered message
663
+ const result = await comms.sendTransactional('collectionId', {
664
+ contactId: 'c_123', templateId: 'order-confirmed',
665
+ channel: 'email', props: { orderId: 'ORD-001' }
666
+ })
667
+
668
+ // 4b. Broadcast: preview → test → enqueue
669
+ const preview = await broadcasts.preview('collectionId', 'br_spring', {
670
+ channelOverride: 'email', hydrate: true, include: { product: true }
671
+ })
672
+ await broadcasts.sendTest('collectionId', 'br_spring', { contactId: 'c_123' })
673
+ await broadcasts.send('collectionId', 'br_spring', { pageSize: 200, hydrate: true })
674
+ ```
675
+
676
+ ---
677
+
678
+ ## Prerequisites
679
+
680
+ | Feature | Requirement |
681
+ |---------|-------------|
682
+ | Email | SendGrid credentials (env or collection comms settings) |
683
+ | Push | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` env vars |
684
+ | SMS | Twilio credentials (env or collection comms settings) |
685
+ | Wallet | Google Wallet issuer + service account |
686
+ | Hydration | Set `hydrate: true` and populate `include` on broadcast/transactional sends |