@proveanything/smartlinks 2.2.1 → 3.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/README.md +741 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/adminCards.d.ts +8 -0
  5. package/dist/api/adminCards.js +9 -1
  6. package/dist/api/ai.d.ts +22 -11
  7. package/dist/api/ai.js +18 -14
  8. package/dist/api/analytics.d.ts +13 -0
  9. package/dist/api/analytics.js +13 -0
  10. package/dist/api/appConfiguration.d.ts +17 -14
  11. package/dist/api/appConfiguration.js +14 -12
  12. package/dist/api/appObjects.d.ts +80 -16
  13. package/dist/api/appObjects.js +74 -11
  14. package/dist/api/asset.d.ts +55 -19
  15. package/dist/api/asset.js +52 -32
  16. package/dist/api/attestation.d.ts +3 -2
  17. package/dist/api/attestation.js +1 -1
  18. package/dist/api/attestations.d.ts +22 -7
  19. package/dist/api/attestations.js +22 -7
  20. package/dist/api/authKit.d.ts +22 -5
  21. package/dist/api/authKit.js +21 -4
  22. package/dist/api/batch.d.ts +23 -16
  23. package/dist/api/batch.js +19 -13
  24. package/dist/api/bookings.d.ts +45 -9
  25. package/dist/api/bookings.js +39 -3
  26. package/dist/api/broadcasts.d.ts +26 -6
  27. package/dist/api/broadcasts.js +22 -2
  28. package/dist/api/claimSet.d.ts +48 -13
  29. package/dist/api/claimSet.js +43 -7
  30. package/dist/api/collection.d.ts +20 -6
  31. package/dist/api/collection.js +19 -8
  32. package/dist/api/comms.d.ts +43 -12
  33. package/dist/api/comms.js +43 -13
  34. package/dist/api/conditions.d.ts +12 -2
  35. package/dist/api/conditions.js +10 -1
  36. package/dist/api/config.d.ts +15 -2
  37. package/dist/api/config.js +12 -0
  38. package/dist/api/contact.d.ts +34 -13
  39. package/dist/api/contact.js +35 -10
  40. package/dist/api/containers.d.ts +41 -23
  41. package/dist/api/containers.js +37 -21
  42. package/dist/api/crate.d.ts +9 -8
  43. package/dist/api/crate.js +8 -8
  44. package/dist/api/dpp.d.ts +58 -10
  45. package/dist/api/dpp.js +57 -15
  46. package/dist/api/facets.d.ts +71 -0
  47. package/dist/api/facets.js +71 -0
  48. package/dist/api/files.d.ts +11 -5
  49. package/dist/api/files.js +9 -1
  50. package/dist/api/form.d.ts +9 -2
  51. package/dist/api/form.js +7 -1
  52. package/dist/api/index.d.ts +0 -1
  53. package/dist/api/index.js +0 -1
  54. package/dist/api/integrations.d.ts +82 -27
  55. package/dist/api/integrations.js +63 -7
  56. package/dist/api/interactions.d.ts +42 -6
  57. package/dist/api/interactions.js +41 -5
  58. package/dist/api/jobs.d.ts +9 -2
  59. package/dist/api/jobs.js +6 -0
  60. package/dist/api/journeys.d.ts +13 -2
  61. package/dist/api/journeys.js +10 -1
  62. package/dist/api/journeysAnalytics.d.ts +12 -3
  63. package/dist/api/journeysAnalytics.js +9 -1
  64. package/dist/api/knowledge.d.ts +43 -10
  65. package/dist/api/knowledge.js +37 -5
  66. package/dist/api/location.d.ts +10 -3
  67. package/dist/api/location.js +7 -1
  68. package/dist/api/lots.d.ts +40 -13
  69. package/dist/api/lots.js +38 -8
  70. package/dist/api/loyalty.d.ts +70 -12
  71. package/dist/api/loyalty.js +60 -3
  72. package/dist/api/nfc.d.ts +8 -2
  73. package/dist/api/nfc.js +6 -1
  74. package/dist/api/order.d.ts +51 -160
  75. package/dist/api/order.js +46 -208
  76. package/dist/api/partner.d.ts +41 -8
  77. package/dist/api/partner.js +36 -4
  78. package/dist/api/products.d.ts +41 -8
  79. package/dist/api/products.js +33 -4
  80. package/dist/api/proof.d.ts +50 -13
  81. package/dist/api/proof.js +43 -7
  82. package/dist/api/realtime.d.ts +1 -11
  83. package/dist/api/realtime.js +1 -22
  84. package/dist/api/secrets.d.ts +25 -5
  85. package/dist/api/secrets.js +21 -2
  86. package/dist/api/segments.d.ts +26 -6
  87. package/dist/api/segments.js +22 -2
  88. package/dist/api/serviceAccounts.d.ts +8 -1
  89. package/dist/api/serviceAccounts.js +8 -1
  90. package/dist/api/shop.d.ts +41 -13
  91. package/dist/api/shop.js +35 -4
  92. package/dist/api/subscriptions.d.ts +47 -12
  93. package/dist/api/subscriptions.js +40 -4
  94. package/dist/api/tags.d.ts +40 -19
  95. package/dist/api/tags.js +38 -18
  96. package/dist/api/template.d.ts +31 -3
  97. package/dist/api/template.js +27 -0
  98. package/dist/api/translations.d.ts +17 -2
  99. package/dist/api/translations.js +14 -0
  100. package/dist/api/userGroups.d.ts +35 -9
  101. package/dist/api/userGroups.js +30 -5
  102. package/dist/api/variant.d.ts +11 -3
  103. package/dist/api/variant.js +9 -2
  104. package/dist/api/wallet.d.ts +23 -10
  105. package/dist/api/wallet.js +20 -2
  106. package/dist/apiVersion.d.ts +1 -1
  107. package/dist/apiVersion.js +1 -1
  108. package/dist/baseline.css +194 -194
  109. package/dist/docs/API_SUMMARY.md +1389 -2298
  110. package/dist/docs/PRODUCT_FACETS_SDK.md +10 -15
  111. package/dist/docs/admin-cards.md +189 -189
  112. package/dist/docs/admin-lists-and-pickers.md +1 -1
  113. package/dist/docs/agent-tools.md +156 -156
  114. package/dist/docs/ai-tools-and-skills.md +180 -180
  115. package/dist/docs/ai.md +1721 -1721
  116. package/dist/docs/analytics.md +3 -2
  117. package/dist/docs/api-versions.md +85 -76
  118. package/dist/docs/app-data-storage.md +277 -277
  119. package/dist/docs/app-docs.md +73 -73
  120. package/dist/docs/app-manifest.md +852 -852
  121. package/dist/docs/app-objects.md +38 -50
  122. package/dist/docs/app-records-pattern.md +388 -388
  123. package/dist/docs/appConfig.md +550 -550
  124. package/dist/docs/assets.md +17 -3
  125. package/dist/docs/assistant-apps.md +172 -172
  126. package/dist/docs/assistant-context.md +119 -119
  127. package/dist/docs/attestations.md +5 -4
  128. package/dist/docs/auth-kit.md +1 -1
  129. package/dist/docs/bookings.md +442 -442
  130. package/dist/docs/comms.md +689 -686
  131. package/dist/docs/connectors.md +340 -340
  132. package/dist/docs/contact-search.md +4 -3
  133. package/dist/docs/container-tracking.md +7 -7
  134. package/dist/docs/css-baseline.md +133 -133
  135. package/dist/docs/customer-guide.md +70 -70
  136. package/dist/docs/deploying-apps.md +340 -340
  137. package/dist/docs/dpp.md +115 -115
  138. package/dist/docs/entitlements.md +90 -90
  139. package/dist/docs/executor.md +1 -1
  140. package/dist/docs/files.md +69 -69
  141. package/dist/docs/forms.md +1 -1
  142. package/dist/docs/headless-providers.md +3 -3
  143. package/dist/docs/host-dependency-contract.md +252 -210
  144. package/dist/docs/integrations.md +322 -322
  145. package/dist/docs/interactions.md +544 -545
  146. package/dist/docs/item-context.md +181 -181
  147. package/dist/docs/knowledge.md +105 -102
  148. package/dist/docs/lists.md +114 -0
  149. package/dist/docs/lots.md +112 -111
  150. package/dist/docs/loyalty.md +348 -352
  151. package/dist/docs/members.md +183 -183
  152. package/dist/docs/memberships.md +150 -149
  153. package/dist/docs/mobile-admin-container.md +693 -693
  154. package/dist/docs/operations.md +281 -281
  155. package/dist/docs/overview.md +485 -485
  156. package/dist/docs/proof-claiming-methods.md +6 -6
  157. package/dist/docs/proof-comms-triggers.md +142 -142
  158. package/dist/docs/proof-ownership-transfer.md +155 -155
  159. package/dist/docs/proof-product-data-scoping.md +462 -462
  160. package/dist/docs/proof-share-grants.md +305 -305
  161. package/dist/docs/realtime.md +139 -138
  162. package/dist/docs/records-admin-pattern.md +304 -304
  163. package/dist/docs/server-functions.md +2 -2
  164. package/dist/docs/service-accounts.md +64 -64
  165. package/dist/docs/shop.md +4 -2
  166. package/dist/docs/site-seo.md +2 -1
  167. package/dist/docs/standard-query.md +187 -187
  168. package/dist/docs/tag-codes.md +97 -97
  169. package/dist/docs/tag-ranges.md +106 -106
  170. package/dist/docs/theme-tokens.md +252 -252
  171. package/dist/docs/translations.md +6 -1
  172. package/dist/docs/upgrading-to-3.md +430 -0
  173. package/dist/docs/user-groups.md +4 -4
  174. package/dist/docs/utils.md +1 -1
  175. package/dist/docs/wallet-passes.md +107 -107
  176. package/dist/docs/websites.md +123 -123
  177. package/dist/headless.d.ts +1 -1
  178. package/dist/headless.js +2 -2
  179. package/dist/http.d.ts +15 -2
  180. package/dist/http.js +60 -2
  181. package/dist/index.d.ts +7 -8
  182. package/dist/index.js +2 -0
  183. package/dist/list.d.ts +24 -0
  184. package/dist/list.js +80 -0
  185. package/dist/mobile-admin/types.d.ts +0 -16
  186. package/dist/openapi.yaml +290 -2723
  187. package/dist/shared-dependencies.d.ts +3 -3
  188. package/dist/shared-dependencies.js +13 -5
  189. package/dist/site.d.ts +1 -7
  190. package/dist/site.js +1 -14
  191. package/dist/theme-boot.js +82 -82
  192. package/dist/theme.css +75 -75
  193. package/dist/types/adminCards.d.ts +6 -3
  194. package/dist/types/ai.d.ts +0 -6
  195. package/dist/types/analytics.d.ts +5 -8
  196. package/dist/types/appManifest.d.ts +4 -5
  197. package/dist/types/appObjects.d.ts +14 -18
  198. package/dist/types/appObjects.js +0 -1
  199. package/dist/types/appOptions.d.ts +18 -0
  200. package/dist/types/asset.d.ts +3 -22
  201. package/dist/types/attestations.d.ts +7 -10
  202. package/dist/types/batch.d.ts +6 -14
  203. package/dist/types/bookings.d.ts +22 -4
  204. package/dist/types/broadcasts.d.ts +5 -13
  205. package/dist/types/broadcasts.js +0 -1
  206. package/dist/types/claimSet.d.ts +0 -5
  207. package/dist/types/comms.d.ts +11 -9
  208. package/dist/types/contact.d.ts +5 -29
  209. package/dist/types/contact.js +0 -13
  210. package/dist/types/containers.d.ts +15 -26
  211. package/dist/types/crate.d.ts +4 -12
  212. package/dist/types/dpp.d.ts +3 -3
  213. package/dist/types/dpp.js +0 -1
  214. package/dist/types/error.d.ts +8 -5
  215. package/dist/types/error.js +12 -5
  216. package/dist/types/facets.d.ts +15 -15
  217. package/dist/types/index.d.ts +1 -0
  218. package/dist/types/index.js +1 -0
  219. package/dist/types/integrations.d.ts +3 -28
  220. package/dist/types/interaction.d.ts +3 -9
  221. package/dist/types/jobs.d.ts +3 -8
  222. package/dist/types/jobs.js +0 -1
  223. package/dist/types/journeys.d.ts +3 -8
  224. package/dist/types/journeys.js +0 -1
  225. package/dist/types/journeysAnalytics.d.ts +0 -1
  226. package/dist/types/list.d.ts +24 -0
  227. package/dist/types/list.js +2 -0
  228. package/dist/types/location.d.ts +0 -4
  229. package/dist/types/lots.d.ts +0 -9
  230. package/dist/types/loyalty.d.ts +0 -9
  231. package/dist/types/order.d.ts +7 -134
  232. package/dist/types/product.d.ts +11 -24
  233. package/dist/types/proof.d.ts +16 -0
  234. package/dist/types/realtime.d.ts +0 -29
  235. package/dist/types/segments.d.ts +5 -13
  236. package/dist/types/segments.js +0 -1
  237. package/dist/types/serviceAccounts.d.ts +3 -2
  238. package/dist/types/serviceAccounts.js +0 -1
  239. package/dist/types/shop.d.ts +5 -12
  240. package/dist/types/shop.js +0 -4
  241. package/dist/types/subscriptions.d.ts +18 -0
  242. package/dist/types/subscriptions.js +0 -8
  243. package/dist/types/tags.d.ts +6 -16
  244. package/dist/types/tags.js +0 -7
  245. package/dist/types/translations.d.ts +3 -9
  246. package/dist/types/variant.d.ts +0 -2
  247. package/dist/version.d.ts +1 -1
  248. package/dist/version.js +1 -1
  249. package/docs/API_SUMMARY.md +1389 -2298
  250. package/docs/PRODUCT_FACETS_SDK.md +10 -15
  251. package/docs/admin-cards.md +189 -189
  252. package/docs/admin-lists-and-pickers.md +1 -1
  253. package/docs/agent-tools.md +156 -156
  254. package/docs/ai-tools-and-skills.md +180 -180
  255. package/docs/ai.md +1721 -1721
  256. package/docs/analytics.md +3 -2
  257. package/docs/api-versions.md +85 -76
  258. package/docs/app-data-storage.md +277 -277
  259. package/docs/app-docs.md +73 -73
  260. package/docs/app-manifest.md +852 -852
  261. package/docs/app-objects.md +38 -50
  262. package/docs/app-records-pattern.md +388 -388
  263. package/docs/appConfig.md +550 -550
  264. package/docs/assets.md +17 -3
  265. package/docs/assistant-apps.md +172 -172
  266. package/docs/assistant-context.md +119 -119
  267. package/docs/attestations.md +5 -4
  268. package/docs/auth-kit.md +1 -1
  269. package/docs/bookings.md +442 -442
  270. package/docs/comms.md +689 -686
  271. package/docs/connectors.md +340 -340
  272. package/docs/contact-search.md +4 -3
  273. package/docs/container-tracking.md +7 -7
  274. package/docs/css-baseline.md +133 -133
  275. package/docs/customer-guide.md +70 -70
  276. package/docs/deploying-apps.md +340 -340
  277. package/docs/dpp.md +115 -115
  278. package/docs/entitlements.md +90 -90
  279. package/docs/executor.md +1 -1
  280. package/docs/files.md +69 -69
  281. package/docs/forms.md +1 -1
  282. package/docs/headless-providers.md +3 -3
  283. package/docs/host-dependency-contract.md +252 -210
  284. package/docs/integrations.md +322 -322
  285. package/docs/interactions.md +544 -545
  286. package/docs/item-context.md +181 -181
  287. package/docs/knowledge.md +105 -102
  288. package/docs/lists.md +114 -0
  289. package/docs/lots.md +112 -111
  290. package/docs/loyalty.md +348 -352
  291. package/docs/members.md +183 -183
  292. package/docs/memberships.md +150 -149
  293. package/docs/mobile-admin-container.md +693 -693
  294. package/docs/operations.md +281 -281
  295. package/docs/overview.md +485 -485
  296. package/docs/proof-claiming-methods.md +6 -6
  297. package/docs/proof-comms-triggers.md +142 -142
  298. package/docs/proof-ownership-transfer.md +155 -155
  299. package/docs/proof-product-data-scoping.md +462 -462
  300. package/docs/proof-share-grants.md +305 -305
  301. package/docs/realtime.md +139 -138
  302. package/docs/server-functions.md +2 -2
  303. package/docs/service-accounts.md +64 -64
  304. package/docs/shop.md +4 -2
  305. package/docs/site-seo.md +2 -1
  306. package/docs/standard-query.md +187 -187
  307. package/docs/tag-codes.md +97 -97
  308. package/docs/tag-ranges.md +106 -106
  309. package/docs/theme-lookbook.v1.json +120 -120
  310. package/docs/theme-tokens.md +252 -252
  311. package/docs/translations.md +6 -1
  312. package/docs/upgrading-to-3.md +430 -0
  313. package/docs/user-groups.md +4 -4
  314. package/docs/utils.md +1 -1
  315. package/docs/wallet-passes.md +107 -107
  316. package/docs/websites.md +123 -123
  317. package/openapi.yaml +290 -2723
  318. package/package.json +8 -4
  319. package/scripts/headless-check.mjs +87 -87
  320. package/scripts/lib/bare-imports.mjs +57 -57
  321. package/scripts/lib/keyed-app-data.mjs +21 -21
  322. package/scripts/lib/upgrade.mjs +512 -0
  323. package/scripts/publish.mjs +272 -272
  324. package/scripts/register-release.mjs +91 -91
  325. package/scripts/upgrade.mjs +56 -0
  326. package/upgrade/3.json +2213 -0
package/README.md CHANGED
@@ -1,755 +1,742 @@
1
- # @proveanything/smartlinks
2
-
3
- Official JavaScript/TypeScript SDK for the Smartlinks API.
4
-
5
- Build Smartlinks-powered apps in Node.js or the browser: list collections and products, authenticate users, manage assets and attestations, and call admin endpoints with a clean, typed API.
6
-
7
- • TypeScript-first types and intellisense
8
- • Works in Node.js and modern browsers
9
- • Simple auth helpers (login, verify token, request admin/public JWTs)
10
- • Rich resources: collections, products, proofs, assets, attestations, batches, variants, AI, and more
11
- • Optional iframe proxy mode for embedded apps
12
-
13
- ## Start here
14
-
15
- If you're new to the SDK, this is the easiest path:
16
-
17
- 1. Initialize the SDK with your SmartLinks API base URL.
18
- 2. Pick the guide that matches what you're building.
19
- 3. Copy one of the working examples and adapt it to your collection/product IDs.
20
-
21
- ### Pick a guide
22
-
23
- - [docs/ai.md](docs/ai.md) — AI responses, chat, RAG, voice, streaming, and product assistants
24
- - [docs/analytics.md](docs/analytics.md) — fire-and-forget web analytics, tag scan telemetry, and dashboard queries
25
- - [docs/proof-share-grants.md](docs/proof-share-grants.md) — delegated, scoped, revocable share links for a proof (album sharing, guest comments, proof-of-ownership)
26
- - [docs/assets.md](docs/assets.md) — asset uploads, including resumable uploads for large files (video)
27
- - [docs/files.md](docs/files.md) — temporary files, fetching web pages and documents once, and extracting text, Markdown, OCR or fields from them
28
- - [docs/app-objects.md](docs/app-objects.md) — cases, threads (comments), and records
29
- - [docs/translations.md](docs/translations.md) — runtime translation lookup, browser-side caching, and translation admin flows
30
- - [docs/widgets.md](docs/widgets.md) — embeddable React components
31
- - [docs/realtime.md](docs/realtime.md) — subscriptions and live updates
32
- - [docs/admin-cards.md](docs/admin-cards.md) — cards on the collection's Studio dashboard
33
- - [docs/iframe-responder.md](docs/iframe-responder.md) — iframe integration and parent/child messaging
34
- - [docs/utils.md](docs/utils.md) — helper utilities and portal path generation
35
-
36
- ### Most common use cases
37
-
38
- - **Build an AI assistant** → start with [docs/ai.md](docs/ai.md)
39
- - **Track page views, clicks, or tag scans** → start with [docs/analytics.md](docs/analytics.md)
40
- - **Translate dynamic content with local browser caching** → start with [docs/translations.md](docs/translations.md)
41
- - **Share a proof / album by link, or add guest comments** → start with [docs/proof-share-grants.md](docs/proof-share-grants.md)
42
- - **Upload large video with resume-on-reconnect** → see [Resumable uploads](docs/assets.md#resumable-uploads-large-files-eg-video)
43
- - **Fetch collections/products** → see [Quick start](README.md#quick-start)
44
- - **Authenticate admins or end users** → see [Authentication](README.md#authentication)
45
- - **Upload and manage files** → see [Assets](README.md#assets)
46
- - **Browse the full surface area** → use [API_SUMMARY.md](docs/API_SUMMARY.md) as reference
47
-
48
- For the full list of functions and types, see the API summary:
49
- → [API Summary](docs/API_SUMMARY.md)
50
-
51
- **Documentation:**
52
- - [AI & Chat Completions](docs/ai.md) - Chat completions, RAG, voice integration
53
- - [Analytics](docs/analytics.md) - Fire-and-forget analytics tracking, tag scans, and dashboard queries
54
- - [Proof Share Grants](docs/proof-share-grants.md) - Delegated, revocable share links; guest comments; proof-of-ownership
55
- - [Assets](docs/assets.md) - Uploads, resumable large-file uploads, token uploads, replace/versioning
56
- - [App Objects](docs/app-objects.md) - Cases, threads (comments), records
57
- - [Translations](docs/translations.md) - Runtime translation lookup, browser-side IndexedDB caching, and admin translation management
58
- - [Widgets](docs/widgets.md) - Embeddable React components
59
- - [Realtime](docs/realtime.md) - Realtime data updates
60
- - [iframe Responder](docs/iframe-responder.md) - iframe integration
61
- - [Utilities](docs/utils.md) - Helper functions for paths, URLs, and common tasks
62
-
63
- ## Install
64
-
65
- ```bash
66
- npm install @proveanything/smartlinks
67
- ```
68
-
69
- ## Quick start
70
-
71
- Initialize once at app startup with your API base URL. Trailing slashes are optional (normalized). In Node, you can also provide an API key for server-to-server calls. You can enable an ngrok header or supply custom headers.
72
-
73
- ```ts
74
- import { initializeApi } from '@proveanything/smartlinks'
75
-
76
- initializeApi({
77
- baseURL: 'https://smartlinks.app/api/v1', // or 'https://smartlinks.app/api/v1/'
78
- // logger: console, // optional: verbose logging of requests/responses and proxy messages
79
- // apiKey: process.env.SMARTLINKS_API_KEY, // Node/server only (optional)
80
- // ngrokSkipBrowserWarning: true, // adds 'ngrok-skip-browser-warning: true'
81
- // extraHeaders: { 'X-Debug': '1' } // merged into every request
82
- })
83
- ```
84
-
85
- List public collections and fetch products:
86
-
87
- ```ts
88
- import { collection, products } from '@proveanything/smartlinks'
89
-
90
- const collections = await collection.list(false) // public endpoint
91
- const first = collections[0]
92
- if (first) {
93
- const items = await products.list(first.id, false) // public endpoint
94
- console.log('First product:', items[0])
95
- }
96
- ```
97
-
98
- ### Quick start by scenario
99
-
100
- **Public storefront or portal experience**
101
-
102
- ```ts
103
- import { initializeApi, collection, products } from '@proveanything/smartlinks'
104
-
105
- initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
106
-
107
- const collections = await collection.list(false)
108
- const items = await products.list('collectionId', false)
109
- ```
110
-
111
- **Server-side admin scripts or back office tools**
112
-
113
- ```ts
114
- import { initializeApi, products } from '@proveanything/smartlinks'
115
-
116
- initializeApi({
117
- baseURL: 'https://smartlinks.app/api/v1',
118
- apiKey: process.env.SMARTLINKS_API_KEY,
119
- })
120
-
121
- const created = await products.create('collectionId', { name: 'New product' })
122
- console.log(created.id)
123
- ```
124
-
125
- ### Product API migration: use products (plural)
126
-
127
- The SDK keeps `product` (singular) for backward compatibility, but it is deprecated.
128
- For all new integrations, use `products` (plural).
129
-
130
- ```ts
131
- // Preferred
132
- import { products } from '@proveanything/smartlinks'
133
-
134
- await products.get(collectionId, productId, false)
135
- await products.list(collectionId, false)
136
- await products.query(collectionId, { query: { search: 'cabernet' } }) // public
137
- await products.query(collectionId, { query: { search: 'cabernet' } }, true) // admin
138
- ```
139
-
140
- Quick mapping:
141
-
142
- - `product.get` -> `products.get`
143
- - `product.list` -> `products.list`
144
- - `product.create` -> `products.create`
145
- - `product.update` -> `products.update`
146
- - `product.remove` -> `products.remove`
147
- - `product.find` / `product.publicFind` -> `products.query` / `products.get`
148
-
149
- **AI-powered assistant or setup flow**
150
-
151
- ```ts
152
- import { initializeApi, ai } from '@proveanything/smartlinks'
153
-
154
- initializeApi({
155
- baseURL: 'https://smartlinks.app/api/v1',
156
- apiKey: process.env.SMARTLINKS_API_KEY,
157
- })
158
-
159
- const response = await ai.chat.responses.create('collectionId', {
160
- input: 'Write a concise onboarding checklist for a new product launch.'
161
- })
162
-
163
- console.log(response.output_text)
164
- ```
165
-
166
- ## Authentication
167
-
168
- Use the built-in helpers to log in and verify tokens. After a successful login, the SDK stores the bearer token for subsequent calls.
169
-
170
- ```ts
171
- import { initializeApi } from '@proveanything/smartlinks'
172
- import { auth } from '@proveanything/smartlinks'
173
-
174
- initializeApi({ baseURL: 'https://smartlinks.app/api/v1/' }) // trailing slash OK
175
-
176
- // Email + password login (browser or Node)
177
- const user = await auth.login('user@example.com', 'password')
178
- console.log('Hello,', user.name)
179
-
180
- // Verify an existing token (and set it if valid)
181
- const verified = await auth.verifyToken(user.bearerToken)
182
- console.log('Token valid?', verified.valid)
183
-
184
- // Later, clear token
185
- auth.logout()
186
- ```
187
-
188
- Admin flows:
189
-
190
- ```ts
191
- // Request an admin JWT for a collection (requires prior auth)
192
- const jwt = await auth.requestAdminJWT('collectionId')
193
-
194
- // Or request a public JWT authorized for a collection/product/proof
195
- const publicJwt = await auth.requestPublicJWT('collectionId', 'productId', 'proofId')
196
- ```
197
-
198
- ## Error Handling
199
-
200
- The SDK throws `SmartlinksApiError` for all API errors, providing structured access to:
201
- - **HTTP status code** (`statusCode` / `code`) - Numeric HTTP status (400, 401, 500, etc.)
202
- - **Server error code** (`errorCode`) - String identifier ("NOT_AUTHORIZED", "broadcasts.topic.invalid", etc.)
203
- - **Error message** (`message`) - Human-readable description
204
- - **Additional details** (`details`) - Server-specific fields
205
-
206
- ### Automatic Error Normalization
207
-
208
- The SDK automatically normalizes various server error response formats into a consistent structure:
209
-
210
- ```ts
211
- // Server may return errors in different formats:
212
- // { errorText: "...", errorCode: "..." }
213
- // { error: "...", message: "..." }
214
- // { ok: false, error: "..." }
215
- // { error: "..." }
216
-
217
- // All are normalized to SmartlinksApiError with consistent access:
218
- import { SmartlinksApiError, products } from '@proveanything/smartlinks'
219
-
220
- try {
221
- const item = await products.get('collectionId', 'productId', false)
222
- } catch (error) {
223
- if (error instanceof SmartlinksApiError) {
224
- console.error({
225
- message: error.message, // "Error 404: Product not found"
226
- statusCode: error.statusCode, // 404 (HTTP status)
227
- code: error.code, // 404 (same as statusCode)
228
- errorCode: error.errorCode, // "NOT_FOUND" (server error code string)
229
- details: error.details, // Additional server details
230
- url: error.url, // Failed URL
231
- })
232
-
233
- // Handle specific server error codes (primary identifier)
234
- switch (error.errorCode) {
235
- case 'NOT_AUTHORIZED':
236
- // Invalid credentials
237
- break
238
- case 'broadcasts.topic.invalid':
239
- // Invalid broadcast topic
240
- break
241
- default:
242
- // Fall back to HTTP status code
243
- if (error.isNotFound()) {
244
- // Handle 404
245
- } else if (error.isAuthError()) {
246
- // Handle 401/403 - redirect to login
247
- }
248
- }
249
-
250
- // Use helper methods for HTTP status-based handling
251
- if (error.isRateLimited()) {
252
- // Handle 429 - implement retry logic
253
- } else if (error.isServerError()) {
254
- // Handle 5xx - show maintenance message
255
- }
256
- }
257
- }
258
- ```
259
-
260
- ### Helper Methods
261
-
262
- - `error.isClientError()` - 4xx status codes
263
- - `error.isServerError()` - 5xx status codes
264
- - `error.isAuthError()` - 401 or 403
265
- - `error.isNotFound()` - 404
266
- - `error.isRateLimited()` - 429
267
- - `error.toJSON()` - Serializable object for logging
268
-
269
- For comprehensive error handling examples and migration guidance, see [examples/error-handling-demo.ts](examples/error-handling-demo.ts).
270
-
271
- ## Utility Functions
272
-
273
- The SDK includes a simple utility for building portal URLs. Pass in objects and it extracts what it needs:
274
-
275
- ### Build Portal Paths
276
-
277
- ```ts
278
- import { utils } from '@proveanything/smartlinks'
279
-
280
- // Pass in objects - extracts shortId, portalUrl, product ID, GTIN, etc.
281
- const url = utils.buildPortalPath({
282
- collection: myCollection,
283
- product: myProduct // reads ownGtin from product
284
- })
285
- // Returns: https://portal.smartlinks.io/c/abc123/prod1
286
-
287
- // With proof object
288
- const withProof = utils.buildPortalPath({
289
- collection: myCollection,
290
- product: myProduct,
291
- proof: myProof
292
- })
293
- // Returns: https://portal.smartlinks.io/c/abc123/prod1/proof1
294
-
295
- // GTIN path (ownGtin read from product.ownGtin)
296
- const gtinPath = utils.buildPortalPath({
297
- collection: myCollection,
298
- product: myProduct, // if product.ownGtin is true, uses /01/ format
299
- batch: myBatch, // extracts batch ID and expiry date
300
- variant: myVariant
301
- })
302
- // Returns: https://portal.smartlinks.io/01/1234567890123/10/batch1/22/var1?17=260630
303
-
304
- // Or pass just IDs if you don't have full objects
305
- const simple = utils.buildPortalPath({
306
- collection: { shortId: 'abc123' },
307
- productId: 'prod1',
308
- batchId: 'batch1', // just string, no expiry
309
- queryParams: { utm_source: 'email' }
310
- })
311
- // Returns: /c/abc123/prod1?utm_source=email
312
- ```
313
-
314
- Pass objects where you have them (collection, product, batch, variant, proof) and the function extracts the needed properties. Or pass just IDs (productId, batchId) for simpler cases.
315
-
316
- For complete documentation, see [docs/utils.md](docs/utils.md).
317
-
318
- ## Common tasks
319
-
320
- ### Products
321
-
322
- ```ts
323
- import { products } from '@proveanything/smartlinks'
324
-
325
- // Public fetch
326
- const item = await products.get('collectionId', 'productId', false)
327
-
328
- // Admin create/update/delete (requires auth)
329
- await products.create('collectionId', { name: 'New product' })
330
- await products.update('collectionId', 'productId', { description: 'Updated' })
331
- await products.remove('collectionId', 'productId')
332
- ```
333
-
334
- ### Assets
335
-
336
- Upload, list, get, and remove assets within a scope (collection/product/proof).
337
-
338
- #### Upload (new)
339
-
340
- ```ts
341
- import { asset } from '@proveanything/smartlinks'
342
-
343
- const uploaded = await asset.upload({
344
- file, // File from an <input type="file">
345
- scope: { type: 'proof', collectionId, productId, proofId },
346
- name: 'hero.png',
347
- metadata: { description: 'Uploaded via SDK' },
348
- onProgress: (p) => console.log(`Upload: ${p}%`),
349
- // appId: 'microapp-123' // optional
350
- })
351
- console.log('Uploaded asset:', uploaded)
352
- ```
353
-
354
- Deprecated upload helper (wraps to the new `upload` internally):
355
-
356
- ```ts
357
- // @deprecated Use asset.upload(options)
358
- const legacy = await asset.uploadAsset(collectionId, productId, proofId, file)
359
- ```
360
-
361
- #### List
362
-
363
- ```ts
364
- // Collection assets, first 20 images
365
- const list1 = await asset.list({
366
- scope: { type: 'collection', collectionId },
367
- mimeTypePrefix: 'image/',
368
- limit: 20,
369
- })
370
-
371
- // Product assets, filter by appId
372
- const list2 = await asset.list({
373
- scope: { type: 'product', collectionId, productId },
374
- appId: 'microapp-123',
375
- })
376
- ```
377
-
378
- #### Get (scoped)
379
-
380
- ```ts
381
- const a = await asset.get({
382
- assetId,
383
- scope: { type: 'proof', collectionId, productId, proofId },
384
- })
385
- ```
386
-
387
- #### Remove (scoped, admin)
388
-
389
- ```ts
390
- await asset.remove({
391
- assetId,
392
- scope: { type: 'product', collectionId, productId },
393
- })
394
- ```
395
-
396
- #### Asset response example
397
-
398
- ```json
399
- {
400
- "id": "aBcDeFgHiJkLmNoPqRsT",
401
- "collectionId": "acme-demo",
402
- "site": "acme-demo",
403
- "productId": null,
404
- "proofId": null,
405
- "appId": null,
406
- "name": "product-hero-shot",
407
- "cleanName": "product-hero-shot",
408
- "assetType": "Image",
409
- "fileType": "png",
410
- "type": "png",
411
- "url": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123.png",
412
- "thumbnail": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123_thumb.webp",
413
- "mimeType": "image/png",
414
- "contentType": "image/png",
415
- "size": 204800,
416
- "width": 1440,
417
- "height": 900,
418
- "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
419
- "labels": [],
420
- "metadata": {},
421
- "versions": [],
422
- "uploadedBy": "uid_mock0001",
423
- "uploaderContactId": null,
424
- "uploadTokenId": null,
425
- "uploaderIp": null,
426
- "status": "active",
427
- "createdAt": "2025-01-15T10:00:00Z",
428
- "updatedAt": "2025-01-15T10:00:00Z",
429
- "deletedAt": null
430
- }
431
- ```
432
-
433
- #### Proxy mode and uploads
434
-
435
- When `initializeApi({ proxyMode: true })` is active (e.g., SDK runs inside an iframe and the parent performs API calls), the SDK serializes `FormData` for upload into a proxy-safe shape and posts a message to the parent window. The parent proxy handler should detect this payload and reconstruct a native `FormData` before performing the actual HTTP request.
436
-
437
- - SDK proxy message body shape for uploads:
438
- - `{ _isFormData: true, entries: Array<[name: string, value: string | File]> }`
439
- - Each entry’s value is either a string or a `File` object (structured-cloneable).
440
- - Direct XHR uploads are only used when NOT in proxy mode. In proxy mode, the SDK uses the proxy channel and `postMessage`.
441
-
442
- Progress support in proxy mode:
443
-
444
- - If you pass `onProgress`, the SDK uses an enhanced upload protocol with chunked messages and progress events.
445
- - Unified envelope protocol (single message shape):
446
- - Iframe → Parent
447
- - `{ _smartlinksProxyUpload: true, phase: 'start', id, path, method: 'POST', headers, fields, fileInfo }`
448
- - `{ _smartlinksProxyUpload: true, phase: 'chunk', id, seq, chunk: ArrayBuffer }`
449
- - `{ _smartlinksProxyUpload: true, phase: 'end', id }`
450
- - Parent → Iframe
451
- - `{ _smartlinksProxyUpload: true, phase: 'ack', id, seq }` (reply via `event.source.postMessage`)
452
- - `{ _smartlinksProxyUpload: true, phase: 'progress', id, percent }` (reply via `event.source.postMessage`)
453
- - `{ _smartlinksProxyUpload: true, phase: 'done', id, ok, data? | error? }` (reply via `event.source.postMessage`)
454
-
455
- Example parent handler (buffered, simple):
456
-
457
- ```html
458
- <script>
459
- const uploads = new Map();
460
- window.addEventListener('message', async (e) => {
461
- const m = e.data;
462
- if (!m || m._smartlinksProxyUpload !== true) return;
463
- const target = e.source; // reply to the sender iframe
464
- const origin = e.origin; // consider validating and passing a strict origin
465
- switch (m.phase) {
466
- case 'start': {
467
- uploads.set(m.id, { chunks: [], fields: m.fields, fileInfo: m.fileInfo, path: m.path, headers: m.headers });
468
- break;
469
- }
470
- case 'chunk': {
471
- const u = uploads.get(m.id);
472
- if (!u) break;
473
- u.chunks.push(new Uint8Array(m.chunk));
474
- target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'ack', id: m.id, seq: m.seq }, origin);
475
- break;
476
- }
477
- case 'end': {
478
- const u = uploads.get(m.id);
479
- if (!u) break;
480
- const blob = new Blob(u.chunks, { type: u.fileInfo.type || 'application/octet-stream' });
481
- const fd = new FormData();
482
- for (const [k, v] of u.fields) fd.append(k, v);
483
- fd.append(u.fileInfo.key || 'file', blob, u.fileInfo.name || 'upload.bin');
484
-
485
- const xhr = new XMLHttpRequest();
486
- xhr.open('POST', (window.SMARTLINKS_API_BASEURL || '') + u.path);
487
- for (const [k, v] of Object.entries(u.headers || {})) xhr.setRequestHeader(k, v);
488
- xhr.upload.onprogress = (ev) => {
489
- if (ev.lengthComputable) {
490
- const pct = Math.round((ev.loaded / ev.total) * 100);
491
- target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'progress', id: m.id, percent: pct }, origin);
492
- }
493
- };
494
- xhr.onload = () => {
495
- const ok = xhr.status >= 200 && xhr.status < 300;
496
- try {
497
- const data = JSON.parse(xhr.responseText);
498
- target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok, data, error: ok ? undefined : data?.message }, origin);
499
- } catch (err) {
500
- target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Invalid server response' }, origin);
501
- }
502
- };
503
- xhr.onerror = () => target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Network error' }, origin);
504
- xhr.send(fd);
505
- uploads.delete(m.id);
506
- break;
507
- }
508
- }
509
- });
510
- </script>
511
- ```
512
-
513
- If you maintain the parent proxy, ensure its handler for `_smartlinksProxyRequest`:
514
- - Detects `body._isFormData === true` and rebuilds `const fd = new FormData(); for (const [k,v] of body.entries) fd.append(k, v);`
515
- - Issues the HTTP request with that `FormData` and returns the parsed JSON response back to the iframe.
516
-
517
- ### AI helpers
518
-
519
- ```ts
520
- import { ai } from '@proveanything/smartlinks'
521
-
522
- const content = await ai.generateContent('collectionId', {
523
- contents: 'Write a friendly product blurb for our coffee beans.',
524
- responseMimeType: 'text/plain',
525
- provider: 'openai',
526
- model: 'gpt-4o'
527
- })
528
- console.log(content)
529
- ```
530
-
531
- ### Analytics (Actions & Broadcasts)
532
-
533
- Track user actions and broadcast deliveries per collection. These endpoints live under admin and require valid auth (API key or bearer token).
534
-
535
- ```ts
536
- import { actions, broadcasts } from '@proveanything/smartlinks'
537
-
538
- // List action events for a user
539
- const actionEvents = await actions.byUser('collectionId', {
540
- userId: 'user_123',
541
- from: '2025-01-01T00:00:00Z',
542
- to: '2025-12-31T23:59:59Z',
543
- limit: 100,
544
- })
545
-
546
- // Outcome counts, optionally deduping latest per actor
547
- const counts = await actions.countsByOutcome('collectionId', {
548
- actionId: 'click',
549
- dedupeLatest: true,
550
- idField: 'userId',
551
- })
552
-
553
- // Append a single action event
554
- await actions.append('collectionId', {
555
- userId: 'user_123',
556
- actionId: 'click',
557
- outcome: 'success',
558
- })
559
-
560
- // Broadcast recipients and filters
561
- const recipients = await broadcasts.recipientIds('collectionId', {
562
- broadcastId: 'br_456',
563
- idField: 'contactId',
564
- })
565
-
566
- // Append broadcast recipients in bulk (preferred shape)
567
- await broadcasts.appendBulk('collectionId', {
568
- params: { broadcastId: 'br_456', channel: 'email' },
569
- ids: ['contact_1','contact_2'],
570
- idField: 'contactId',
571
- })
572
- ```
573
-
574
- ### Broadcast sending and previews
575
-
576
- ```ts
577
- import { broadcasts } from '@proveanything/smartlinks'
578
-
579
- // Preview a broadcast (HTML)
580
- const preview = await broadcasts.preview('collectionId', 'broadcastId', {
581
- contactId: 'contact_123',
582
- props: { firstName: 'Sam' },
583
- })
584
-
585
- // Send a test email
586
- await broadcasts.sendTest('collectionId', 'broadcastId', {
587
- to: 'test@example.com',
588
- subject: 'Test subject',
589
- props: { foo: 'bar' },
590
- })
591
-
592
- // Enqueue broadcast sending (background)
593
- await broadcasts.send('collectionId', 'broadcastId', {
594
- pageSize: 100,
595
- sharedContext: { campaign: 'summer' },
596
- })
597
-
598
- // Manual page send (for testing/UX)
599
- const manual = await broadcasts.sendManual('collectionId', 'broadcastId', {
600
- limit: 50,
601
- dryRun: true,
602
- })
603
- ```
604
-
605
- ## Communications Overview
606
-
607
- End-to-end explainer covering comms settings (unsubscribe, types), Web Push registration, and multi-channel broadcasts with SDK examples: [src/docs/smartlinks/comms-explainer.md](src/docs/smartlinks/comms-explainer.md)
608
-
609
- ### Async jobs
610
-
611
- ```ts
612
- import { async as slAsync, jobs } from '@proveanything/smartlinks'
613
-
614
- // Enqueue an async job
615
- const queued = await slAsync.enqueueAsyncJob('collectionId', {
616
- task: 'email:daily-digest',
617
- payload: { segmentId: 'seg_1' },
618
- priority: 5,
619
- key: 'digest:seg_1',
620
- })
621
-
622
- // Check job status
623
- const status = await slAsync.getAsyncJobStatus('collectionId', queued.id)
624
-
625
- // List recent jobs
626
- const recent = await jobs.listJobs('collectionId', { state: 'queued', limit: 20 })
627
-
628
- // Get a single job
629
- const job = await jobs.getJob('collectionId', queued.id)
630
- ```
631
-
632
- ## Browser and React
633
-
634
- The SDK works in modern browsers. Initialize once and call public endpoints without an API key; authenticate to access protected/admin endpoints.
635
-
636
- ```ts
637
- import { initializeApi } from '@proveanything/smartlinks'
638
- import { collection } from '@proveanything/smartlinks'
639
-
640
- initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
641
- const collections = await collection.list(false)
642
- ```
643
-
644
- For a fuller UI example, see `examples/react-demo.tsx`.
645
-
646
- ## Iframe Integration
647
-
648
- When embedding Smartlinks inside an iframe (set `proxyMode: true` in `initializeApi` if you need parent-proxy API calls), you can also send UI/control messages to the parent window. The SDK provides lightweight helpers in `iframe.ts`:
649
-
650
- ```ts
651
- import { enableAutoIframeResize, disableAutoIframeResize, redirectParent, sendParentCustom, isIframe } from '@proveanything/smartlinks'
652
-
653
- // Automatically push height changes to parent so it can resize the iframe.
654
- enableAutoIframeResize({ intervalMs: 150 })
655
-
656
- // Later disable if not needed:
657
- disableAutoIframeResize()
658
-
659
- // Redirect parent window to a URL (e.g. after login):
660
- redirectParent('https://app.example.com/dashboard')
661
-
662
- // Send any custom event + payload:
663
- sendParentCustom('smartlinks:navigate', { url: '/profile' })
664
-
665
- if (isIframe()) {
666
- console.log('Running inside an iframe')
667
- }
668
- ```
669
-
670
- Parent page can listen for these messages:
671
-
672
- ```ts
673
- window.addEventListener('message', (e) => {
674
- const msg = e.data
675
- if (!msg || !msg._smartlinksIframeMessage) return
676
- switch (msg.type) {
677
- case 'smartlinks:resize':
678
- // adjust iframe height
679
- const iframeEl = document.getElementById('smartlinks-frame') as HTMLIFrameElement
680
- if (iframeEl) iframeEl.style.height = msg.payload.height + 'px'
681
- break
682
- case 'smartlinks:redirect':
683
- window.location.href = msg.payload.url
684
- break
685
- case 'smartlinks:navigate':
686
- // Custom example
687
- console.log('Navigate request:', msg.payload.url)
688
- break
689
- }
690
- })
691
- ```
692
-
693
- Notes:
694
- - Auto-resize uses `ResizeObserver` when available, falling back to `MutationObserver` + polling.
695
- - In non-browser or Node environments these helpers safely no-op.
696
- - Use `sendParentCustom` for any domain-specific integration events.
697
-
698
- ## Configuration reference
699
-
700
- ```ts
701
- initializeApi({
702
- baseURL: string, // with or without trailing slash
703
- apiKey?: string, // Node/server only
704
- bearerToken?: string, // optional at init; set by auth.login/verifyToken
705
- proxyMode?: boolean // set true if running inside an iframe and using parent proxy
706
- ngrokSkipBrowserWarning?: boolean // forces header 'ngrok-skip-browser-warning: true'
707
- extraHeaders?: Record<string,string> // custom headers merged in each request
708
- iframeAutoResize?: boolean // default true when embedded in an iframe
709
- logger?: Function | { debug?: Function; info?: Function; warn?: Function; error?: Function; log?: Function } // optional verbose logging
710
- })
711
-
712
- // Auto-detection: If baseURL contains '.ngrok.io' or '.ngrok-free.dev' the header is added automatically
713
- // unless you explicitly set ngrokSkipBrowserWarning: false.
714
- // Auto iframe resize: When in an iframe, resize messages are sent by default unless iframeAutoResize: false.
715
- // Verbose logging: Pass a logger (e.g. console) to log outbound requests/responses and proxy postMessages.
716
- ```
717
-
718
- When embedding the SDK in an iframe with `proxyMode: true`, you can also use:
719
-
720
- ```ts
721
- import { sendCustomProxyMessage } from '@proveanything/smartlinks'
722
- const data = await sendCustomProxyMessage('my-action', { foo: 'bar' })
723
-
724
- // Toggle ngrok header or update custom headers later:
725
- import { setNgrokSkipBrowserWarning, setExtraHeaders } from '@proveanything/smartlinks'
726
- setNgrokSkipBrowserWarning(true)
727
- setExtraHeaders({ 'X-Debug': '1' })
728
- ```
729
-
730
- ## Full API surface
731
-
732
- Explore every function, parameter, and type here:
733
-
734
- - [API_SUMMARY.md](docs/API_SUMMARY.md) - Complete API reference
735
-
736
- ## Additional Documentation
737
-
738
- The SDK includes comprehensive guides for advanced features:
739
-
740
- - **[Liquid Templates](docs/liquid-templates.md)** - Dynamic templating for emails and notifications with personalized data
741
- - **[Real-Time Messaging](docs/realtime.md)** - Ably integration for live chat, presence, and real-time updates
742
- - **[Theme System](docs/theme.system.md)** - Dynamic theming for iframe apps with CSS variables and postMessage
743
- - **[Theme Defaults](docs/theme-defaults.md)** - Default theme configuration reference
744
- - **[Widgets](docs/widgets.md)** - React widget system for embeddable components
745
- - **[Internationalization](docs/i18n.md)** - Multi-language support and localization
746
-
747
- ## Requirements
748
-
749
- - Node.js 16+ or modern browsers
750
- - TypeScript 4.9+ (if using TS)
751
-
752
- ## License
753
-
754
- MIT © Prove Anything
1
+ # @proveanything/smartlinks
2
+
3
+ Official JavaScript/TypeScript SDK for the Smartlinks API.
4
+
5
+ Build Smartlinks-powered apps in Node.js or the browser: list collections and products, authenticate users, manage assets and attestations, and call admin endpoints with a clean, typed API.
6
+
7
+ • TypeScript-first types and intellisense
8
+ • Works in Node.js and modern browsers
9
+ • Simple auth helpers (login, verify token, request admin/public JWTs)
10
+ • Rich resources: collections, products, proofs, assets, attestations, batches, variants, AI, and more
11
+ • Optional iframe proxy mode for embedded apps
12
+
13
+ ## Start here
14
+
15
+ If you're new to the SDK, this is the easiest path:
16
+
17
+ 1. Initialize the SDK with your SmartLinks API base URL.
18
+ 2. Pick the guide that matches what you're building.
19
+ 3. Copy one of the working examples and adapt it to your collection/product IDs.
20
+
21
+ ### Pick a guide
22
+
23
+ - [docs/ai.md](docs/ai.md) — AI responses, chat, RAG, voice, streaming, and product assistants
24
+ - [docs/analytics.md](docs/analytics.md) — fire-and-forget web analytics, tag scan telemetry, and dashboard queries
25
+ - [docs/proof-share-grants.md](docs/proof-share-grants.md) — delegated, scoped, revocable share links for a proof (album sharing, guest comments, proof-of-ownership)
26
+ - [docs/assets.md](docs/assets.md) — asset uploads, including resumable uploads for large files (video)
27
+ - [docs/files.md](docs/files.md) — temporary files, fetching web pages and documents once, and extracting text, Markdown, OCR or fields from them
28
+ - [docs/app-objects.md](docs/app-objects.md) — cases, threads (comments), and records
29
+ - [docs/translations.md](docs/translations.md) — runtime translation lookup, browser-side caching, and translation admin flows
30
+ - [docs/widgets.md](docs/widgets.md) — embeddable React components
31
+ - [docs/realtime.md](docs/realtime.md) — subscriptions and live updates
32
+ - [docs/admin-cards.md](docs/admin-cards.md) — cards on the collection's Studio dashboard
33
+ - [docs/iframe-responder.md](docs/iframe-responder.md) — iframe integration and parent/child messaging
34
+ - [docs/utils.md](docs/utils.md) — helper utilities and portal path generation
35
+
36
+ ### Most common use cases
37
+
38
+ - **Build an AI assistant** → start with [docs/ai.md](docs/ai.md)
39
+ - **Track page views, clicks, or tag scans** → start with [docs/analytics.md](docs/analytics.md)
40
+ - **Translate dynamic content with local browser caching** → start with [docs/translations.md](docs/translations.md)
41
+ - **Share a proof / album by link, or add guest comments** → start with [docs/proof-share-grants.md](docs/proof-share-grants.md)
42
+ - **Upload large video with resume-on-reconnect** → see [Resumable uploads](docs/assets.md#resumable-uploads-large-files-eg-video)
43
+ - **Fetch collections/products** → see [Quick start](README.md#quick-start)
44
+ - **Authenticate admins or end users** → see [Authentication](README.md#authentication)
45
+ - **Upload and manage files** → see [Assets](README.md#assets)
46
+ - **Browse the full surface area** → use [API_SUMMARY.md](docs/API_SUMMARY.md) as reference
47
+
48
+ For the full list of functions and types, see the API summary:
49
+ → [API Summary](docs/API_SUMMARY.md)
50
+
51
+ **Documentation:**
52
+ - [AI & Chat Completions](docs/ai.md) - Chat completions, RAG, voice integration
53
+ - [Analytics](docs/analytics.md) - Fire-and-forget analytics tracking, tag scans, and dashboard queries
54
+ - [Proof Share Grants](docs/proof-share-grants.md) - Delegated, revocable share links; guest comments; proof-of-ownership
55
+ - [Assets](docs/assets.md) - Uploads, resumable large-file uploads, token uploads, replace/versioning
56
+ - [App Objects](docs/app-objects.md) - Cases, threads (comments), records
57
+ - [Translations](docs/translations.md) - Runtime translation lookup, browser-side IndexedDB caching, and admin translation management
58
+ - [Widgets](docs/widgets.md) - Embeddable React components
59
+ - [Realtime](docs/realtime.md) - Realtime data updates
60
+ - [iframe Responder](docs/iframe-responder.md) - iframe integration
61
+ - [Utilities](docs/utils.md) - Helper functions for paths, URLs, and common tasks
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ npm install @proveanything/smartlinks
67
+ ```
68
+
69
+ ## Quick start
70
+
71
+ Initialize once at app startup with your API base URL. Trailing slashes are optional (normalized). In Node, you can also provide an API key for server-to-server calls. You can enable an ngrok header or supply custom headers.
72
+
73
+ ```ts
74
+ import { initializeApi } from '@proveanything/smartlinks'
75
+
76
+ initializeApi({
77
+ baseURL: 'https://smartlinks.app/api/v1', // or 'https://smartlinks.app/api/v1/'
78
+ // logger: console, // optional: verbose logging of requests/responses and proxy messages
79
+ // apiKey: process.env.SMARTLINKS_API_KEY, // Node/server only (optional)
80
+ // ngrokSkipBrowserWarning: true, // adds 'ngrok-skip-browser-warning: true'
81
+ // extraHeaders: { 'X-Debug': '1' } // merged into every request
82
+ })
83
+ ```
84
+
85
+ Read a collection and list its products:
86
+
87
+ ```ts
88
+ import { collection, products } from '@proveanything/smartlinks'
89
+
90
+ const site = await collection.get('collectionId') // public endpoint
91
+ const { items } = await products.list('collectionId') // public endpoint
92
+ console.log(site.title, 'first product:', items[0])
93
+ ```
94
+
95
+ Every list answers the same way: `{ items, nextCursor, count? }`. Pass `nextCursor` back as `cursor` for
96
+ the next page, or let `each` / `all` walk the pages for you (see [docs/lists.md](docs/lists.md)).
97
+
98
+ ### Quick start by scenario
99
+
100
+ **Public storefront or portal experience**
101
+
102
+ ```ts
103
+ import { initializeApi, collection, products } from '@proveanything/smartlinks'
104
+
105
+ initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
106
+
107
+ const site = await collection.get('collectionId')
108
+ const { items } = await products.list('collectionId')
109
+ ```
110
+
111
+ **Server-side admin scripts or back office tools**
112
+
113
+ ```ts
114
+ import { initializeApi, products } from '@proveanything/smartlinks'
115
+
116
+ initializeApi({
117
+ baseURL: 'https://smartlinks.app/api/v1',
118
+ apiKey: process.env.SMARTLINKS_API_KEY,
119
+ })
120
+
121
+ const created = await products.create('collectionId', { name: 'New product' })
122
+ console.log(created.id)
123
+ ```
124
+
125
+ ### Moving from SDK 2
126
+
127
+ SDK 3 asks for API version `2027-01`: every list returns `{ items, nextCursor, count? }` and pages with
128
+ `limit` and `cursor`, errors have one shape, and the calls that were marked deprecated in SDK 2 are gone
129
+ (the old `product` namespace among them: use `products`). SDK 2 keeps working against the API as it is.
130
+
131
+ - [docs/upgrading-to-3.md](docs/upgrading-to-3.md): what changed and how to move each call
132
+ - `upgrade/3.json` in this package: the same changes as data, for scripts and AI agents
133
+
134
+ ```ts
135
+ import { products } from '@proveanything/smartlinks'
136
+
137
+ await products.get(collectionId, productId)
138
+ const { items } = await products.list(collectionId)
139
+ await products.query(collectionId, { query: { search: 'cabernet' } }) // public
140
+ await products.query(collectionId, { query: { search: 'cabernet' } }, true) // admin
141
+ ```
142
+
143
+ **AI-powered assistant or setup flow**
144
+
145
+ ```ts
146
+ import { initializeApi, ai } from '@proveanything/smartlinks'
147
+
148
+ initializeApi({
149
+ baseURL: 'https://smartlinks.app/api/v1',
150
+ apiKey: process.env.SMARTLINKS_API_KEY,
151
+ })
152
+
153
+ const response = await ai.chat.responses.create('collectionId', {
154
+ input: 'Write a concise onboarding checklist for a new product launch.'
155
+ })
156
+
157
+ console.log(response.output_text)
158
+ ```
159
+
160
+ ## Authentication
161
+
162
+ Use the built-in helpers to log in and verify tokens. After a successful login, the SDK stores the bearer token for subsequent calls.
163
+
164
+ ```ts
165
+ import { initializeApi } from '@proveanything/smartlinks'
166
+ import { auth } from '@proveanything/smartlinks'
167
+
168
+ initializeApi({ baseURL: 'https://smartlinks.app/api/v1/' }) // trailing slash OK
169
+
170
+ // Email + password login (browser or Node)
171
+ const user = await auth.login('user@example.com', 'password')
172
+ console.log('Hello,', user.name)
173
+
174
+ // Verify an existing token (and set it if valid)
175
+ const verified = await auth.verifyToken(user.bearerToken)
176
+ console.log('Token valid?', verified.valid)
177
+
178
+ // Later, clear token
179
+ auth.logout()
180
+ ```
181
+
182
+ Admin flows:
183
+
184
+ ```ts
185
+ // Request an admin JWT for a collection (requires prior auth)
186
+ const jwt = await auth.requestAdminJWT('collectionId')
187
+
188
+ // Or request a public JWT authorized for a collection/product/proof
189
+ const publicJwt = await auth.requestPublicJWT('collectionId', 'productId', 'proofId')
190
+ ```
191
+
192
+ ## Error Handling
193
+
194
+ The SDK throws `SmartlinksApiError` for all API errors, providing structured access to:
195
+ - **HTTP status code** (`statusCode` / `code`) - Numeric HTTP status (400, 401, 500, etc.)
196
+ - **Server error code** (`errorCode`) - String identifier ("NOT_AUTHORIZED", "broadcasts.topic.invalid", etc.)
197
+ - **Error message** (`message`) - Human-readable description
198
+ - **Additional details** (`details`) - Server-specific fields
199
+
200
+ ### Automatic Error Normalization
201
+
202
+ The SDK automatically normalizes various server error response formats into a consistent structure:
203
+
204
+ ```ts
205
+ // Server may return errors in different formats:
206
+ // { errorText: "...", errorCode: "..." }
207
+ // { error: "...", message: "..." }
208
+ // { ok: false, error: "..." }
209
+ // { error: "..." }
210
+
211
+ // All are normalized to SmartlinksApiError with consistent access:
212
+ import { SmartlinksApiError, products } from '@proveanything/smartlinks'
213
+
214
+ try {
215
+ const item = await products.get('collectionId', 'productId', false)
216
+ } catch (error) {
217
+ if (error instanceof SmartlinksApiError) {
218
+ console.error({
219
+ message: error.message, // "Error 404: Product not found"
220
+ statusCode: error.statusCode, // 404 (HTTP status)
221
+ code: error.code, // 404 (same as statusCode)
222
+ errorCode: error.errorCode, // "NOT_FOUND" (server error code string)
223
+ details: error.details, // Additional server details
224
+ url: error.url, // Failed URL
225
+ })
226
+
227
+ // Handle specific server error codes (primary identifier)
228
+ switch (error.errorCode) {
229
+ case 'NOT_AUTHORIZED':
230
+ // Invalid credentials
231
+ break
232
+ case 'broadcasts.topic.invalid':
233
+ // Invalid broadcast topic
234
+ break
235
+ default:
236
+ // Fall back to HTTP status code
237
+ if (error.isNotFound()) {
238
+ // Handle 404
239
+ } else if (error.isAuthError()) {
240
+ // Handle 401/403 - redirect to login
241
+ }
242
+ }
243
+
244
+ // Use helper methods for HTTP status-based handling
245
+ if (error.isRateLimited()) {
246
+ // Handle 429 - implement retry logic
247
+ } else if (error.isServerError()) {
248
+ // Handle 5xx - show maintenance message
249
+ }
250
+ }
251
+ }
252
+ ```
253
+
254
+ ### Helper Methods
255
+
256
+ - `error.isClientError()` - 4xx status codes
257
+ - `error.isServerError()` - 5xx status codes
258
+ - `error.isAuthError()` - 401 or 403
259
+ - `error.isNotFound()` - 404
260
+ - `error.isRateLimited()` - 429
261
+ - `error.toJSON()` - Serializable object for logging
262
+
263
+ For comprehensive error handling examples and migration guidance, see [examples/error-handling-demo.ts](examples/error-handling-demo.ts).
264
+
265
+ ## Utility Functions
266
+
267
+ The SDK includes a simple utility for building portal URLs. Pass in objects and it extracts what it needs:
268
+
269
+ ### Build Portal Paths
270
+
271
+ ```ts
272
+ import { utils } from '@proveanything/smartlinks'
273
+
274
+ // Pass in objects - extracts shortId, portalUrl, product ID, GTIN, etc.
275
+ const url = utils.buildPortalPath({
276
+ collection: myCollection,
277
+ product: myProduct // reads ownGtin from product
278
+ })
279
+ // Returns: https://portal.smartlinks.io/c/abc123/prod1
280
+
281
+ // With proof object
282
+ const withProof = utils.buildPortalPath({
283
+ collection: myCollection,
284
+ product: myProduct,
285
+ proof: myProof
286
+ })
287
+ // Returns: https://portal.smartlinks.io/c/abc123/prod1/proof1
288
+
289
+ // GTIN path (ownGtin read from product.ownGtin)
290
+ const gtinPath = utils.buildPortalPath({
291
+ collection: myCollection,
292
+ product: myProduct, // if product.ownGtin is true, uses /01/ format
293
+ batch: myBatch, // extracts batch ID and expiry date
294
+ variant: myVariant
295
+ })
296
+ // Returns: https://portal.smartlinks.io/01/1234567890123/10/batch1/22/var1?17=260630
297
+
298
+ // Or pass just IDs if you don't have full objects
299
+ const simple = utils.buildPortalPath({
300
+ collection: { shortId: 'abc123' },
301
+ productId: 'prod1',
302
+ batchId: 'batch1', // just string, no expiry
303
+ queryParams: { utm_source: 'email' }
304
+ })
305
+ // Returns: /c/abc123/prod1?utm_source=email
306
+ ```
307
+
308
+ Pass objects where you have them (collection, product, batch, variant, proof) and the function extracts the needed properties. Or pass just IDs (productId, batchId) for simpler cases.
309
+
310
+ For complete documentation, see [docs/utils.md](docs/utils.md).
311
+
312
+ ## Common tasks
313
+
314
+ ### Products
315
+
316
+ ```ts
317
+ import { products } from '@proveanything/smartlinks'
318
+
319
+ // Public fetch
320
+ const item = await products.get('collectionId', 'productId', false)
321
+
322
+ // Admin create/update/delete (requires auth)
323
+ await products.create('collectionId', { name: 'New product' })
324
+ await products.update('collectionId', 'productId', { description: 'Updated' })
325
+ await products.remove('collectionId', 'productId')
326
+ ```
327
+
328
+ ### Assets
329
+
330
+ Upload, list, get, and remove assets within a scope (collection/product/proof).
331
+
332
+ #### Upload (new)
333
+
334
+ ```ts
335
+ import { asset } from '@proveanything/smartlinks'
336
+
337
+ const uploaded = await asset.upload({
338
+ file, // File from an <input type="file">
339
+ scope: { type: 'proof', collectionId, productId, proofId },
340
+ name: 'hero.png',
341
+ metadata: { description: 'Uploaded via SDK' },
342
+ onProgress: (p) => console.log(`Upload: ${p}%`),
343
+ // appId: 'microapp-123' // optional
344
+ })
345
+ console.log('Uploaded asset:', uploaded)
346
+ ```
347
+
348
+ #### List
349
+
350
+ ```ts
351
+ // A collection's assets
352
+ const { items } = await asset.list({
353
+ scope: { type: 'collection', collectionId },
354
+ })
355
+ const images = items.filter((a) => a.mimeType?.startsWith('image/'))
356
+
357
+ // Product assets, only those an app added
358
+ const { items: appAssets } = await asset.list({
359
+ scope: { type: 'product', collectionId, productId },
360
+ appId: 'microapp-123',
361
+ })
362
+
363
+ // Admin: every asset in the collection, a page at a time, with a total
364
+ const page = await asset.listAdmin({ collectionId, assetType: 'Image', limit: 50 })
365
+ console.log(page.items.length, 'of', page.count, 'next:', page.nextCursor)
366
+ ```
367
+
368
+ #### Get (scoped)
369
+
370
+ ```ts
371
+ const a = await asset.get({
372
+ assetId,
373
+ scope: { type: 'proof', collectionId, productId, proofId },
374
+ })
375
+ ```
376
+
377
+ #### Remove (scoped, admin)
378
+
379
+ ```ts
380
+ await asset.remove({
381
+ assetId,
382
+ scope: { type: 'product', collectionId, productId },
383
+ })
384
+ ```
385
+
386
+ #### Asset response example
387
+
388
+ ```json
389
+ {
390
+ "id": "aBcDeFgHiJkLmNoPqRsT",
391
+ "collectionId": "acme-demo",
392
+ "site": "acme-demo",
393
+ "productId": null,
394
+ "proofId": null,
395
+ "appId": null,
396
+ "name": "product-hero-shot",
397
+ "cleanName": "product-hero-shot",
398
+ "assetType": "Image",
399
+ "fileType": "png",
400
+ "type": "png",
401
+ "url": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123.png",
402
+ "thumbnail": "https://cdn.smartlinks.app/sites%2Facme-demo%2Fimages%2F2025%2F1%2Fproduct-hero-shot-1234567890123_thumb.webp",
403
+ "mimeType": "image/png",
404
+ "contentType": "image/png",
405
+ "size": 204800,
406
+ "width": 1440,
407
+ "height": 900,
408
+ "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
409
+ "labels": [],
410
+ "metadata": {},
411
+ "versions": [],
412
+ "uploadedBy": "uid_mock0001",
413
+ "uploaderContactId": null,
414
+ "uploadTokenId": null,
415
+ "uploaderIp": null,
416
+ "status": "active",
417
+ "createdAt": "2025-01-15T10:00:00Z",
418
+ "updatedAt": "2025-01-15T10:00:00Z",
419
+ "deletedAt": null
420
+ }
421
+ ```
422
+
423
+ #### Proxy mode and uploads
424
+
425
+ When `initializeApi({ proxyMode: true })` is active (e.g., SDK runs inside an iframe and the parent performs API calls), the SDK serializes `FormData` for upload into a proxy-safe shape and posts a message to the parent window. The parent proxy handler should detect this payload and reconstruct a native `FormData` before performing the actual HTTP request.
426
+
427
+ - SDK proxy message body shape for uploads:
428
+ - `{ _isFormData: true, entries: Array<[name: string, value: string | File]> }`
429
+ - Each entry’s value is either a string or a `File` object (structured-cloneable).
430
+ - Direct XHR uploads are only used when NOT in proxy mode. In proxy mode, the SDK uses the proxy channel and `postMessage`.
431
+
432
+ Progress support in proxy mode:
433
+
434
+ - If you pass `onProgress`, the SDK uses an enhanced upload protocol with chunked messages and progress events.
435
+ - Unified envelope protocol (single message shape):
436
+ - Iframe → Parent
437
+ - `{ _smartlinksProxyUpload: true, phase: 'start', id, path, method: 'POST', headers, fields, fileInfo }`
438
+ - `{ _smartlinksProxyUpload: true, phase: 'chunk', id, seq, chunk: ArrayBuffer }`
439
+ - `{ _smartlinksProxyUpload: true, phase: 'end', id }`
440
+ - Parent → Iframe
441
+ - `{ _smartlinksProxyUpload: true, phase: 'ack', id, seq }` (reply via `event.source.postMessage`)
442
+ - `{ _smartlinksProxyUpload: true, phase: 'progress', id, percent }` (reply via `event.source.postMessage`)
443
+ - `{ _smartlinksProxyUpload: true, phase: 'done', id, ok, data? | error? }` (reply via `event.source.postMessage`)
444
+
445
+ Example parent handler (buffered, simple):
446
+
447
+ ```html
448
+ <script>
449
+ const uploads = new Map();
450
+ window.addEventListener('message', async (e) => {
451
+ const m = e.data;
452
+ if (!m || m._smartlinksProxyUpload !== true) return;
453
+ const target = e.source; // reply to the sender iframe
454
+ const origin = e.origin; // consider validating and passing a strict origin
455
+ switch (m.phase) {
456
+ case 'start': {
457
+ uploads.set(m.id, { chunks: [], fields: m.fields, fileInfo: m.fileInfo, path: m.path, headers: m.headers });
458
+ break;
459
+ }
460
+ case 'chunk': {
461
+ const u = uploads.get(m.id);
462
+ if (!u) break;
463
+ u.chunks.push(new Uint8Array(m.chunk));
464
+ target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'ack', id: m.id, seq: m.seq }, origin);
465
+ break;
466
+ }
467
+ case 'end': {
468
+ const u = uploads.get(m.id);
469
+ if (!u) break;
470
+ const blob = new Blob(u.chunks, { type: u.fileInfo.type || 'application/octet-stream' });
471
+ const fd = new FormData();
472
+ for (const [k, v] of u.fields) fd.append(k, v);
473
+ fd.append(u.fileInfo.key || 'file', blob, u.fileInfo.name || 'upload.bin');
474
+
475
+ const xhr = new XMLHttpRequest();
476
+ xhr.open('POST', (window.SMARTLINKS_API_BASEURL || '') + u.path);
477
+ for (const [k, v] of Object.entries(u.headers || {})) xhr.setRequestHeader(k, v);
478
+ xhr.upload.onprogress = (ev) => {
479
+ if (ev.lengthComputable) {
480
+ const pct = Math.round((ev.loaded / ev.total) * 100);
481
+ target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'progress', id: m.id, percent: pct }, origin);
482
+ }
483
+ };
484
+ xhr.onload = () => {
485
+ const ok = xhr.status >= 200 && xhr.status < 300;
486
+ try {
487
+ const data = JSON.parse(xhr.responseText);
488
+ target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok, data, error: ok ? undefined : data?.message }, origin);
489
+ } catch (err) {
490
+ target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Invalid server response' }, origin);
491
+ }
492
+ };
493
+ xhr.onerror = () => target && target.postMessage({ _smartlinksProxyUpload: true, phase: 'done', id: m.id, ok: false, error: 'Network error' }, origin);
494
+ xhr.send(fd);
495
+ uploads.delete(m.id);
496
+ break;
497
+ }
498
+ }
499
+ });
500
+ </script>
501
+ ```
502
+
503
+ If you maintain the parent proxy, ensure its handler for `_smartlinksProxyRequest`:
504
+ - Detects `body._isFormData === true` and rebuilds `const fd = new FormData(); for (const [k,v] of body.entries) fd.append(k, v);`
505
+ - Issues the HTTP request with that `FormData` and returns the parsed JSON response back to the iframe.
506
+
507
+ ### AI helpers
508
+
509
+ ```ts
510
+ import { ai } from '@proveanything/smartlinks'
511
+
512
+ const reply = await ai.chat.completions.create('collectionId', {
513
+ messages: [{ role: 'user', content: 'Write a friendly product blurb for our coffee beans.' }],
514
+ })
515
+ console.log(reply.choices[0].message.content)
516
+ ```
517
+
518
+ ### Analytics (Actions & Broadcasts)
519
+
520
+ Track user actions and broadcast deliveries per collection. These endpoints live under admin and require valid auth (API key or bearer token).
521
+
522
+ ```ts
523
+ import { actions, broadcasts } from '@proveanything/smartlinks'
524
+
525
+ // List action events for a user
526
+ const actionEvents = await actions.byUser('collectionId', {
527
+ userId: 'user_123',
528
+ from: '2025-01-01T00:00:00Z',
529
+ to: '2025-12-31T23:59:59Z',
530
+ limit: 100,
531
+ })
532
+
533
+ // Outcome counts, optionally deduping latest per actor
534
+ const counts = await actions.countsByOutcome('collectionId', {
535
+ actionId: 'click',
536
+ dedupeLatest: true,
537
+ idField: 'userId',
538
+ })
539
+
540
+ // Append a single action event
541
+ await actions.append('collectionId', {
542
+ userId: 'user_123',
543
+ actionId: 'click',
544
+ outcome: 'success',
545
+ })
546
+
547
+ // Broadcast recipients and filters
548
+ const recipients = await broadcasts.recipientIds('collectionId', {
549
+ broadcastId: 'br_456',
550
+ idField: 'contactId',
551
+ })
552
+
553
+ // Append broadcast recipients in bulk (preferred shape)
554
+ await broadcasts.appendBulk('collectionId', {
555
+ params: { broadcastId: 'br_456', channel: 'email' },
556
+ ids: ['contact_1','contact_2'],
557
+ idField: 'contactId',
558
+ })
559
+ ```
560
+
561
+ ### Broadcast sending and previews
562
+
563
+ ```ts
564
+ import { broadcasts } from '@proveanything/smartlinks'
565
+
566
+ // Preview a broadcast (HTML)
567
+ const preview = await broadcasts.preview('collectionId', 'broadcastId', {
568
+ contactId: 'contact_123',
569
+ props: { firstName: 'Sam' },
570
+ })
571
+
572
+ // Send a test email
573
+ await broadcasts.sendTest('collectionId', 'broadcastId', {
574
+ to: 'test@example.com',
575
+ subject: 'Test subject',
576
+ props: { foo: 'bar' },
577
+ })
578
+
579
+ // Enqueue broadcast sending (background)
580
+ await broadcasts.send('collectionId', 'broadcastId', {
581
+ pageSize: 100,
582
+ sharedContext: { campaign: 'summer' },
583
+ })
584
+
585
+ // Manual page send (for testing/UX)
586
+ const manual = await broadcasts.sendManual('collectionId', 'broadcastId', {
587
+ limit: 50,
588
+ dryRun: true,
589
+ })
590
+ ```
591
+
592
+ ## Communications Overview
593
+
594
+ End-to-end explainer covering comms settings (unsubscribe, types), Web Push registration, and multi-channel broadcasts with SDK examples: [src/docs/smartlinks/comms-explainer.md](src/docs/smartlinks/comms-explainer.md)
595
+
596
+ ### Async jobs
597
+
598
+ ```ts
599
+ import { async as slAsync, jobs } from '@proveanything/smartlinks'
600
+
601
+ // Enqueue an async job
602
+ const queued = await slAsync.enqueueAsyncJob('collectionId', {
603
+ task: 'email:daily-digest',
604
+ payload: { segmentId: 'seg_1' },
605
+ priority: 5,
606
+ key: 'digest:seg_1',
607
+ })
608
+
609
+ // Check job status
610
+ const status = await slAsync.getAsyncJobStatus('collectionId', queued.id)
611
+
612
+ // List recent jobs
613
+ const recent = await jobs.listJobs('collectionId', { state: 'queued', limit: 20 })
614
+
615
+ // Get a single job
616
+ const job = await jobs.getJob('collectionId', queued.id)
617
+ ```
618
+
619
+ ## Browser and React
620
+
621
+ The SDK works in modern browsers. Initialize once and call public endpoints without an API key; authenticate to access protected/admin endpoints.
622
+
623
+ ```ts
624
+ import { initializeApi } from '@proveanything/smartlinks'
625
+ import { collection } from '@proveanything/smartlinks'
626
+
627
+ initializeApi({ baseURL: 'https://smartlinks.app/api/v1' })
628
+ const collections = await collection.list(false)
629
+ ```
630
+
631
+ For a fuller UI example, see `examples/react-demo.tsx`.
632
+
633
+ ## Iframe Integration
634
+
635
+ When embedding Smartlinks inside an iframe (set `proxyMode: true` in `initializeApi` if you need parent-proxy API calls), you can also send UI/control messages to the parent window. The SDK provides lightweight helpers in `iframe.ts`:
636
+
637
+ ```ts
638
+ import { enableAutoIframeResize, disableAutoIframeResize, redirectParent, sendParentCustom, isIframe } from '@proveanything/smartlinks'
639
+
640
+ // Automatically push height changes to parent so it can resize the iframe.
641
+ enableAutoIframeResize({ intervalMs: 150 })
642
+
643
+ // Later disable if not needed:
644
+ disableAutoIframeResize()
645
+
646
+ // Redirect parent window to a URL (e.g. after login):
647
+ redirectParent('https://app.example.com/dashboard')
648
+
649
+ // Send any custom event + payload:
650
+ sendParentCustom('smartlinks:navigate', { url: '/profile' })
651
+
652
+ if (isIframe()) {
653
+ console.log('Running inside an iframe')
654
+ }
655
+ ```
656
+
657
+ Parent page can listen for these messages:
658
+
659
+ ```ts
660
+ window.addEventListener('message', (e) => {
661
+ const msg = e.data
662
+ if (!msg || !msg._smartlinksIframeMessage) return
663
+ switch (msg.type) {
664
+ case 'smartlinks:resize':
665
+ // adjust iframe height
666
+ const iframeEl = document.getElementById('smartlinks-frame') as HTMLIFrameElement
667
+ if (iframeEl) iframeEl.style.height = msg.payload.height + 'px'
668
+ break
669
+ case 'smartlinks:redirect':
670
+ window.location.href = msg.payload.url
671
+ break
672
+ case 'smartlinks:navigate':
673
+ // Custom example
674
+ console.log('Navigate request:', msg.payload.url)
675
+ break
676
+ }
677
+ })
678
+ ```
679
+
680
+ Notes:
681
+ - Auto-resize uses `ResizeObserver` when available, falling back to `MutationObserver` + polling.
682
+ - In non-browser or Node environments these helpers safely no-op.
683
+ - Use `sendParentCustom` for any domain-specific integration events.
684
+
685
+ ## Configuration reference
686
+
687
+ ```ts
688
+ initializeApi({
689
+ baseURL: string, // with or without trailing slash
690
+ apiKey?: string, // Node/server only
691
+ bearerToken?: string, // optional at init; set by auth.login/verifyToken
692
+ proxyMode?: boolean // set true if running inside an iframe and using parent proxy
693
+ ngrokSkipBrowserWarning?: boolean // forces header 'ngrok-skip-browser-warning: true'
694
+ extraHeaders?: Record<string,string> // custom headers merged in each request
695
+ iframeAutoResize?: boolean // default true when embedded in an iframe
696
+ logger?: Function | { debug?: Function; info?: Function; warn?: Function; error?: Function; log?: Function } // optional verbose logging
697
+ })
698
+
699
+ // Auto-detection: If baseURL contains '.ngrok.io' or '.ngrok-free.dev' the header is added automatically
700
+ // unless you explicitly set ngrokSkipBrowserWarning: false.
701
+ // Auto iframe resize: When in an iframe, resize messages are sent by default unless iframeAutoResize: false.
702
+ // Verbose logging: Pass a logger (e.g. console) to log outbound requests/responses and proxy postMessages.
703
+ ```
704
+
705
+ When embedding the SDK in an iframe with `proxyMode: true`, you can also use:
706
+
707
+ ```ts
708
+ import { sendCustomProxyMessage } from '@proveanything/smartlinks'
709
+ const data = await sendCustomProxyMessage('my-action', { foo: 'bar' })
710
+
711
+ // Toggle ngrok header or update custom headers later:
712
+ import { setNgrokSkipBrowserWarning, setExtraHeaders } from '@proveanything/smartlinks'
713
+ setNgrokSkipBrowserWarning(true)
714
+ setExtraHeaders({ 'X-Debug': '1' })
715
+ ```
716
+
717
+ ## Full API surface
718
+
719
+ Explore every function, parameter, and type here:
720
+
721
+ - [API_SUMMARY.md](docs/API_SUMMARY.md) - Complete API reference
722
+
723
+ ## Additional Documentation
724
+
725
+ The SDK includes comprehensive guides for advanced features:
726
+
727
+ - **[Liquid Templates](docs/liquid-templates.md)** - Dynamic templating for emails and notifications with personalized data
728
+ - **[Real-Time Messaging](docs/realtime.md)** - Ably integration for live chat, presence, and real-time updates
729
+ - **[Theme System](docs/theme.system.md)** - Dynamic theming for iframe apps with CSS variables and postMessage
730
+ - **[Theme Defaults](docs/theme-defaults.md)** - Default theme configuration reference
731
+ - **[Widgets](docs/widgets.md)** - React widget system for embeddable components
732
+ - **[Internationalization](docs/i18n.md)** - Multi-language support and localization
733
+
734
+ ## Requirements
735
+
736
+ - Node.js 16+ or modern browsers
737
+ - TypeScript 4.9+ (if using TS)
738
+
739
+ ## License
740
+
741
+ MIT © Prove Anything
755
742