@proveanything/smartlinks 2.1.46 → 2.2.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.
Files changed (136) hide show
  1. package/README.md +754 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/dpp.d.ts +99 -0
  5. package/dist/api/dpp.js +194 -0
  6. package/dist/api/index.d.ts +1 -0
  7. package/dist/api/index.js +1 -0
  8. package/dist/api/shop.d.ts +5 -1
  9. package/dist/api/shop.js +7 -7
  10. package/dist/api/subscriptions.d.ts +2 -1
  11. package/dist/api/subscriptions.js +4 -12
  12. package/dist/apiVersion.d.ts +9 -0
  13. package/dist/apiVersion.js +15 -0
  14. package/dist/baseline.css +194 -194
  15. package/dist/docs/API_SUMMARY.md +1136 -809
  16. package/dist/docs/admin-cards.md +189 -189
  17. package/dist/docs/agent-tools.md +156 -156
  18. package/dist/docs/ai-tools-and-skills.md +180 -180
  19. package/dist/docs/ai.md +1721 -1721
  20. package/dist/docs/analytics.md +39 -39
  21. package/dist/docs/api-versions.md +76 -0
  22. package/dist/docs/app-data-storage.md +277 -277
  23. package/dist/docs/app-docs.md +73 -73
  24. package/dist/docs/app-manifest.md +852 -852
  25. package/dist/docs/app-records-pattern.md +388 -388
  26. package/dist/docs/appConfig.md +550 -550
  27. package/dist/docs/assistant-apps.md +172 -172
  28. package/dist/docs/assistant-context.md +119 -119
  29. package/dist/docs/bookings.md +442 -442
  30. package/dist/docs/comms.md +686 -686
  31. package/dist/docs/connectors.md +340 -340
  32. package/dist/docs/css-baseline.md +133 -133
  33. package/dist/docs/customer-guide.md +70 -70
  34. package/dist/docs/deploying-apps.md +340 -340
  35. package/dist/docs/dpp.md +115 -0
  36. package/dist/docs/entitlements.md +90 -90
  37. package/dist/docs/files.md +69 -69
  38. package/dist/docs/host-dependency-contract.md +210 -210
  39. package/dist/docs/i18n.md +9 -9
  40. package/dist/docs/integrations.md +322 -322
  41. package/dist/docs/interactions.md +545 -545
  42. package/dist/docs/item-context.md +181 -181
  43. package/dist/docs/knowledge.md +102 -102
  44. package/dist/docs/lots.md +111 -111
  45. package/dist/docs/loyalty.md +352 -352
  46. package/dist/docs/members.md +183 -183
  47. package/dist/docs/memberships.md +149 -149
  48. package/dist/docs/mobile-admin-container.md +693 -693
  49. package/dist/docs/operations.md +281 -281
  50. package/dist/docs/overview.md +485 -484
  51. package/dist/docs/proof-comms-triggers.md +142 -142
  52. package/dist/docs/proof-ownership-transfer.md +155 -155
  53. package/dist/docs/proof-product-data-scoping.md +462 -462
  54. package/dist/docs/proof-share-grants.md +305 -305
  55. package/dist/docs/realtime.md +138 -138
  56. package/dist/docs/records-admin-pattern.md +304 -304
  57. package/dist/docs/server-functions.md +1 -1
  58. package/dist/docs/service-accounts.md +64 -64
  59. package/dist/docs/standard-query.md +187 -187
  60. package/dist/docs/tag-codes.md +97 -97
  61. package/dist/docs/theme-tokens.md +252 -252
  62. package/dist/docs/wallet-passes.md +107 -107
  63. package/dist/docs/websites.md +123 -123
  64. package/dist/http.d.ts +14 -0
  65. package/dist/http.js +65 -3
  66. package/dist/index.d.ts +2 -1
  67. package/dist/index.js +3 -1
  68. package/dist/openapi.yaml +509 -3
  69. package/dist/theme-boot.js +82 -82
  70. package/dist/theme.css +75 -75
  71. package/dist/types/dpp.d.ts +273 -0
  72. package/dist/types/dpp.js +2 -0
  73. package/dist/types/index.d.ts +1 -0
  74. package/dist/types/index.js +1 -0
  75. package/dist/utils/index.d.ts +1 -0
  76. package/dist/utils/index.js +1 -0
  77. package/dist/utils/money.d.ts +15 -0
  78. package/dist/utils/money.js +72 -0
  79. package/dist/version.d.ts +1 -0
  80. package/dist/version.js +2 -0
  81. package/docs/API_SUMMARY.md +1136 -809
  82. package/docs/admin-cards.md +189 -189
  83. package/docs/agent-tools.md +156 -156
  84. package/docs/ai-tools-and-skills.md +180 -180
  85. package/docs/ai.md +1721 -1721
  86. package/docs/analytics.md +39 -39
  87. package/docs/api-versions.md +76 -0
  88. package/docs/app-data-storage.md +277 -277
  89. package/docs/app-docs.md +73 -73
  90. package/docs/app-manifest.md +852 -852
  91. package/docs/app-records-pattern.md +388 -388
  92. package/docs/appConfig.md +550 -550
  93. package/docs/assistant-apps.md +172 -172
  94. package/docs/assistant-context.md +119 -119
  95. package/docs/bookings.md +442 -442
  96. package/docs/comms.md +686 -686
  97. package/docs/connectors.md +340 -340
  98. package/docs/css-baseline.md +133 -133
  99. package/docs/customer-guide.md +70 -70
  100. package/docs/deploying-apps.md +340 -340
  101. package/docs/dpp.md +115 -0
  102. package/docs/entitlements.md +90 -90
  103. package/docs/files.md +69 -69
  104. package/docs/host-dependency-contract.md +210 -210
  105. package/docs/i18n.md +9 -9
  106. package/docs/integrations.md +322 -322
  107. package/docs/interactions.md +545 -545
  108. package/docs/item-context.md +181 -181
  109. package/docs/knowledge.md +102 -102
  110. package/docs/lots.md +111 -111
  111. package/docs/loyalty.md +352 -352
  112. package/docs/members.md +183 -183
  113. package/docs/memberships.md +149 -149
  114. package/docs/mobile-admin-container.md +693 -693
  115. package/docs/operations.md +281 -281
  116. package/docs/overview.md +485 -484
  117. package/docs/proof-comms-triggers.md +142 -142
  118. package/docs/proof-ownership-transfer.md +155 -155
  119. package/docs/proof-product-data-scoping.md +462 -462
  120. package/docs/proof-share-grants.md +305 -305
  121. package/docs/realtime.md +138 -138
  122. package/docs/server-functions.md +1 -1
  123. package/docs/service-accounts.md +64 -64
  124. package/docs/standard-query.md +187 -187
  125. package/docs/tag-codes.md +97 -97
  126. package/docs/theme-lookbook.v1.json +120 -120
  127. package/docs/theme-tokens.md +252 -252
  128. package/docs/wallet-passes.md +107 -107
  129. package/docs/websites.md +123 -123
  130. package/openapi.yaml +509 -3
  131. package/package.json +87 -87
  132. package/scripts/headless-check.mjs +87 -87
  133. package/scripts/lib/bare-imports.mjs +57 -57
  134. package/scripts/lib/keyed-app-data.mjs +21 -21
  135. package/scripts/publish.mjs +272 -272
  136. package/scripts/register-release.mjs +91 -91
package/docs/comms.md CHANGED
@@ -1,686 +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
- ## 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 |
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 |