@proveanything/smartlinks 3.0.0-alpha.2 → 3.0.0-alpha.3

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 (151) hide show
  1. package/README.md +741 -741
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/bookings.d.ts +49 -2
  5. package/dist/api/bookings.js +59 -2
  6. package/dist/api/index.d.ts +1 -0
  7. package/dist/api/index.js +1 -0
  8. package/dist/api/payments.d.ts +60 -0
  9. package/dist/api/payments.js +94 -0
  10. package/dist/api/realtime.d.ts +3 -0
  11. package/dist/api/realtime.js +10 -2
  12. package/dist/baseline.css +194 -194
  13. package/dist/dataChanged.d.ts +74 -0
  14. package/dist/dataChanged.js +162 -0
  15. package/dist/docs/API_SUMMARY.md +1086 -858
  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/api-versions.md +85 -85
  21. package/dist/docs/app-data-storage.md +277 -277
  22. package/dist/docs/app-docs.md +73 -73
  23. package/dist/docs/app-manifest.md +852 -852
  24. package/dist/docs/app-records-pattern.md +388 -388
  25. package/dist/docs/appConfig.md +550 -550
  26. package/dist/docs/assistant-apps.md +172 -172
  27. package/dist/docs/assistant-context.md +119 -119
  28. package/dist/docs/bookings.md +105 -8
  29. package/dist/docs/caching.md +32 -3
  30. package/dist/docs/comms.md +689 -689
  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/data-changed.md +91 -0
  35. package/dist/docs/deploying-apps.md +340 -340
  36. package/dist/docs/dpp.md +115 -115
  37. package/dist/docs/entitlements.md +90 -90
  38. package/dist/docs/files.md +69 -69
  39. package/dist/docs/host-dependency-contract.md +252 -252
  40. package/dist/docs/iframe-responder.md +11 -0
  41. package/dist/docs/integrations.md +322 -322
  42. package/dist/docs/interactions.md +544 -544
  43. package/dist/docs/item-context.md +181 -181
  44. package/dist/docs/knowledge.md +105 -105
  45. package/dist/docs/lists.md +157 -157
  46. package/dist/docs/lots.md +112 -112
  47. package/dist/docs/loyalty.md +348 -348
  48. package/dist/docs/members.md +183 -183
  49. package/dist/docs/memberships.md +150 -150
  50. package/dist/docs/mobile-admin-container.md +693 -693
  51. package/dist/docs/operations.md +281 -281
  52. package/dist/docs/overview.md +487 -485
  53. package/dist/docs/payments.md +94 -0
  54. package/dist/docs/proof-comms-triggers.md +142 -142
  55. package/dist/docs/proof-ownership-transfer.md +155 -155
  56. package/dist/docs/proof-product-data-scoping.md +462 -462
  57. package/dist/docs/proof-share-grants.md +305 -305
  58. package/dist/docs/realtime.md +149 -139
  59. package/dist/docs/records-admin-pattern.md +304 -304
  60. package/dist/docs/service-accounts.md +64 -64
  61. package/dist/docs/standard-query.md +196 -187
  62. package/dist/docs/tag-codes.md +97 -97
  63. package/dist/docs/tag-ranges.md +106 -106
  64. package/dist/docs/theme-tokens.md +252 -252
  65. package/dist/docs/upgrading-to-3.md +550 -532
  66. package/dist/docs/wallet-passes.md +107 -107
  67. package/dist/docs/websites.md +123 -123
  68. package/dist/http.d.ts +6 -3
  69. package/dist/http.js +48 -19
  70. package/dist/iframeResponder.d.ts +7 -0
  71. package/dist/iframeResponder.js +10 -0
  72. package/dist/index.d.ts +2 -0
  73. package/dist/index.js +2 -0
  74. package/dist/openapi.yaml +426 -3
  75. package/dist/testing/bookingsMemory.d.ts +29 -1
  76. package/dist/testing/bookingsMemory.js +89 -1
  77. package/dist/testing/index.js +4 -1
  78. package/dist/theme-boot.js +82 -82
  79. package/dist/theme.css +75 -75
  80. package/dist/types/appManifest.d.ts +26 -4
  81. package/dist/types/bookings.d.ts +99 -1
  82. package/dist/types/index.d.ts +1 -0
  83. package/dist/types/index.js +1 -0
  84. package/dist/types/payments.d.ts +101 -0
  85. package/dist/types/payments.js +5 -0
  86. package/dist/types/realtime.d.ts +5 -1
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/docs/API_SUMMARY.md +1086 -858
  90. package/docs/admin-cards.md +189 -189
  91. package/docs/agent-tools.md +156 -156
  92. package/docs/ai-tools-and-skills.md +180 -180
  93. package/docs/ai.md +1721 -1721
  94. package/docs/api-versions.md +85 -85
  95. package/docs/app-data-storage.md +277 -277
  96. package/docs/app-docs.md +73 -73
  97. package/docs/app-manifest.md +852 -852
  98. package/docs/app-records-pattern.md +388 -388
  99. package/docs/appConfig.md +550 -550
  100. package/docs/assistant-apps.md +172 -172
  101. package/docs/assistant-context.md +119 -119
  102. package/docs/bookings.md +105 -8
  103. package/docs/caching.md +32 -3
  104. package/docs/comms.md +689 -689
  105. package/docs/connectors.md +340 -340
  106. package/docs/css-baseline.md +133 -133
  107. package/docs/customer-guide.md +70 -70
  108. package/docs/data-changed.md +91 -0
  109. package/docs/deploying-apps.md +340 -340
  110. package/docs/dpp.md +115 -115
  111. package/docs/entitlements.md +90 -90
  112. package/docs/files.md +69 -69
  113. package/docs/host-dependency-contract.md +252 -252
  114. package/docs/iframe-responder.md +11 -0
  115. package/docs/integrations.md +322 -322
  116. package/docs/interactions.md +544 -544
  117. package/docs/item-context.md +181 -181
  118. package/docs/knowledge.md +105 -105
  119. package/docs/lists.md +157 -157
  120. package/docs/lots.md +112 -112
  121. package/docs/loyalty.md +348 -348
  122. package/docs/members.md +183 -183
  123. package/docs/memberships.md +150 -150
  124. package/docs/mobile-admin-container.md +693 -693
  125. package/docs/operations.md +281 -281
  126. package/docs/overview.md +487 -485
  127. package/docs/payments.md +94 -0
  128. package/docs/proof-comms-triggers.md +142 -142
  129. package/docs/proof-ownership-transfer.md +155 -155
  130. package/docs/proof-product-data-scoping.md +462 -462
  131. package/docs/proof-share-grants.md +305 -305
  132. package/docs/realtime.md +149 -139
  133. package/docs/service-accounts.md +64 -64
  134. package/docs/standard-query.md +196 -187
  135. package/docs/tag-codes.md +97 -97
  136. package/docs/tag-ranges.md +106 -106
  137. package/docs/theme-lookbook.v1.json +120 -120
  138. package/docs/theme-tokens.md +252 -252
  139. package/docs/upgrading-to-3.md +550 -532
  140. package/docs/wallet-passes.md +107 -107
  141. package/docs/websites.md +123 -123
  142. package/openapi.yaml +426 -3
  143. package/package.json +91 -91
  144. package/scripts/headless-check.mjs +87 -87
  145. package/scripts/lib/bare-imports.mjs +57 -57
  146. package/scripts/lib/keyed-app-data.mjs +21 -21
  147. package/scripts/lib/upgrade.mjs +708 -668
  148. package/scripts/publish.mjs +272 -272
  149. package/scripts/register-release.mjs +91 -91
  150. package/scripts/upgrade.mjs +79 -79
  151. package/upgrade/3.json +2 -2
package/README.md CHANGED
@@ -1,742 +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
- 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, { q: 'cabernet' }) // public
140
- await products.query(collectionId, { q: '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 { jobs } from '@proveanything/smartlinks'
600
-
601
- // Enqueue an async job
602
- const queued = await jobs.enqueue('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 jobs.status('collectionId', queued.id)
611
-
612
- // List recent jobs
613
- const recent = await jobs.list('collectionId', { state: 'queued', limit: 20 })
614
-
615
- // Get a single job
616
- const job = await jobs.get('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
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, { q: 'cabernet' }) // public
140
+ await products.query(collectionId, { q: '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 { jobs } from '@proveanything/smartlinks'
600
+
601
+ // Enqueue an async job
602
+ const queued = await jobs.enqueue('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 jobs.status('collectionId', queued.id)
611
+
612
+ // List recent jobs
613
+ const recent = await jobs.list('collectionId', { state: 'queued', limit: 20 })
614
+
615
+ // Get a single job
616
+ const job = await jobs.get('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
742
742