@proveanything/smartlinks 2.1.47 → 2.2.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 (133) hide show
  1. package/README.md +754 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/dpp.d.ts +6 -0
  5. package/dist/api/dpp.js +12 -0
  6. package/dist/api/shop.d.ts +5 -1
  7. package/dist/api/shop.js +7 -7
  8. package/dist/api/subscriptions.d.ts +2 -1
  9. package/dist/api/subscriptions.js +4 -12
  10. package/dist/apiVersion.d.ts +9 -0
  11. package/dist/apiVersion.js +15 -0
  12. package/dist/baseline.css +194 -194
  13. package/dist/docs/API_SUMMARY.md +821 -811
  14. package/dist/docs/admin-cards.md +189 -189
  15. package/dist/docs/agent-tools.md +156 -156
  16. package/dist/docs/ai-tools-and-skills.md +180 -180
  17. package/dist/docs/ai.md +1721 -1721
  18. package/dist/docs/analytics.md +39 -39
  19. package/dist/docs/api-versions.md +76 -0
  20. package/dist/docs/app-data-storage.md +277 -277
  21. package/dist/docs/app-docs.md +73 -73
  22. package/dist/docs/app-manifest.md +852 -852
  23. package/dist/docs/app-records-pattern.md +388 -388
  24. package/dist/docs/appConfig.md +550 -550
  25. package/dist/docs/assistant-apps.md +172 -172
  26. package/dist/docs/assistant-context.md +119 -119
  27. package/dist/docs/bookings.md +442 -442
  28. package/dist/docs/comms.md +686 -686
  29. package/dist/docs/connectors.md +340 -340
  30. package/dist/docs/css-baseline.md +133 -133
  31. package/dist/docs/customer-guide.md +70 -70
  32. package/dist/docs/deploying-apps.md +340 -340
  33. package/dist/docs/dpp.md +115 -99
  34. package/dist/docs/entitlements.md +90 -90
  35. package/dist/docs/files.md +69 -69
  36. package/dist/docs/host-dependency-contract.md +210 -210
  37. package/dist/docs/i18n.md +46 -292
  38. package/dist/docs/integrations.md +322 -322
  39. package/dist/docs/interactions.md +545 -545
  40. package/dist/docs/item-context.md +181 -181
  41. package/dist/docs/knowledge.md +102 -102
  42. package/dist/docs/lots.md +111 -111
  43. package/dist/docs/loyalty.md +352 -352
  44. package/dist/docs/members.md +183 -183
  45. package/dist/docs/memberships.md +149 -149
  46. package/dist/docs/mobile-admin-container.md +693 -693
  47. package/dist/docs/operations.md +281 -281
  48. package/dist/docs/overview.md +485 -485
  49. package/dist/docs/proof-comms-triggers.md +142 -142
  50. package/dist/docs/proof-ownership-transfer.md +155 -155
  51. package/dist/docs/proof-product-data-scoping.md +462 -462
  52. package/dist/docs/proof-share-grants.md +305 -305
  53. package/dist/docs/realtime.md +138 -138
  54. package/dist/docs/records-admin-pattern.md +304 -304
  55. package/dist/docs/server-functions.md +1 -1
  56. package/dist/docs/service-accounts.md +64 -64
  57. package/dist/docs/standard-query.md +187 -187
  58. package/dist/docs/tag-codes.md +97 -97
  59. package/dist/docs/theme-tokens.md +252 -252
  60. package/dist/docs/wallet-passes.md +107 -107
  61. package/dist/docs/websites.md +123 -123
  62. package/dist/http.d.ts +14 -0
  63. package/dist/http.js +65 -3
  64. package/dist/i18n.d.ts +14 -2
  65. package/dist/i18n.js +23 -6
  66. package/dist/index.d.ts +2 -1
  67. package/dist/index.js +3 -1
  68. package/dist/openapi.yaml +6 -3
  69. package/dist/theme-boot.js +82 -82
  70. package/dist/theme.css +75 -75
  71. package/dist/types/dpp.d.ts +14 -5
  72. package/dist/utils/index.d.ts +1 -0
  73. package/dist/utils/index.js +1 -0
  74. package/dist/utils/money.d.ts +15 -0
  75. package/dist/utils/money.js +72 -0
  76. package/dist/version.d.ts +1 -0
  77. package/dist/version.js +2 -0
  78. package/docs/API_SUMMARY.md +821 -811
  79. package/docs/admin-cards.md +189 -189
  80. package/docs/agent-tools.md +156 -156
  81. package/docs/ai-tools-and-skills.md +180 -180
  82. package/docs/ai.md +1721 -1721
  83. package/docs/analytics.md +39 -39
  84. package/docs/api-versions.md +76 -0
  85. package/docs/app-data-storage.md +277 -277
  86. package/docs/app-docs.md +73 -73
  87. package/docs/app-manifest.md +852 -852
  88. package/docs/app-records-pattern.md +388 -388
  89. package/docs/appConfig.md +550 -550
  90. package/docs/assistant-apps.md +172 -172
  91. package/docs/assistant-context.md +119 -119
  92. package/docs/bookings.md +442 -442
  93. package/docs/comms.md +686 -686
  94. package/docs/connectors.md +340 -340
  95. package/docs/css-baseline.md +133 -133
  96. package/docs/customer-guide.md +70 -70
  97. package/docs/deploying-apps.md +340 -340
  98. package/docs/dpp.md +115 -99
  99. package/docs/entitlements.md +90 -90
  100. package/docs/files.md +69 -69
  101. package/docs/host-dependency-contract.md +210 -210
  102. package/docs/i18n.md +46 -292
  103. package/docs/integrations.md +322 -322
  104. package/docs/interactions.md +545 -545
  105. package/docs/item-context.md +181 -181
  106. package/docs/knowledge.md +102 -102
  107. package/docs/lots.md +111 -111
  108. package/docs/loyalty.md +352 -352
  109. package/docs/members.md +183 -183
  110. package/docs/memberships.md +149 -149
  111. package/docs/mobile-admin-container.md +693 -693
  112. package/docs/operations.md +281 -281
  113. package/docs/overview.md +485 -485
  114. package/docs/proof-comms-triggers.md +142 -142
  115. package/docs/proof-ownership-transfer.md +155 -155
  116. package/docs/proof-product-data-scoping.md +462 -462
  117. package/docs/proof-share-grants.md +305 -305
  118. package/docs/realtime.md +138 -138
  119. package/docs/server-functions.md +1 -1
  120. package/docs/service-accounts.md +64 -64
  121. package/docs/standard-query.md +187 -187
  122. package/docs/tag-codes.md +97 -97
  123. package/docs/theme-lookbook.v1.json +120 -120
  124. package/docs/theme-tokens.md +252 -252
  125. package/docs/wallet-passes.md +107 -107
  126. package/docs/websites.md +123 -123
  127. package/openapi.yaml +6 -3
  128. package/package.json +87 -87
  129. package/scripts/headless-check.mjs +87 -87
  130. package/scripts/lib/bare-imports.mjs +57 -57
  131. package/scripts/lib/keyed-app-data.mjs +21 -21
  132. package/scripts/publish.mjs +272 -272
  133. package/scripts/register-release.mjs +91 -91
@@ -1,107 +1,107 @@
1
- # Wallet passes
2
-
3
- Put an **event ticket**, a **booking**, a **membership card** or a **loyalty card** in the person's Apple Wallet or
4
- Google Wallet. SmartLinks is the issuer and signs the passes. Each pass is branded from your site's name, logo and
5
- colour, and your app decides what it says.
6
-
7
- - **Who gets one:** only someone the business knows. A pass is issued to the signed-in owner of what it's for, or
8
- by your app's own server function.
9
- - **What the phone does:** the pass shows its QR code offline, appears near the time (and place, if you give
10
- `venue.lat` / `lng`), and updates when you change it.
11
- - **Bookings look after themselves:** when a booking is moved its pass shows the new time, and when it's cancelled
12
- the pass is voided.
13
-
14
- ## In a page: "Add to Wallet"
15
-
16
- ```typescript
17
- import { wallet } from '@proveanything/smartlinks'
18
-
19
- // The signed-in person's booking, membership card, or a pass your app issued them
20
- const { pass } = await wallet.addLinks(collectionId, { type: 'booking', id: booking.id })
21
- // pass.links.apple → opens the .pkpass on an iPhone
22
- // pass.links.google → opens Google's "Save to Google Wallet" page
23
- ```
24
-
25
- - `{ type: 'booking', id }` and `{ type: 'contact', id: 'me' }` are made on first ask:
26
- - a booking pass, from the booking's date and time
27
- - a membership card, from the person's `level` and `memberUntil` fields
28
- - For anything else (an event ticket with your own title, a loyalty card with points), issue the pass in your server
29
- function first. `addLinks` then returns that pass for its owner.
30
- - Show the official "Add to Apple Wallet" and "Add to Google Wallet" badges, and only the one that suits the
31
- device. A wallet that isn't set up yet is left out of `links`.
32
- - `wallet.mine(collectionId)` lists the person's passes.
33
-
34
- ## In a server function: issue, change, void, message
35
-
36
- Declare `sl:wallet:write` in the function's capabilities.
37
-
38
- ```typescript
39
- // An event ticket
40
- const pass = await ctx.sl.wallet.issue({
41
- ref: { type: 'booking', id: booking.id }, // what it's for; issuing again changes the same pass
42
- pass: {
43
- kind: 'event',
44
- title: 'Jazz on the Terrace',
45
- start: '2026-12-24T19:00:00Z', end: '2026-12-24T22:00:00Z', timezone: 'Europe/London',
46
- venue: { name: 'The Terrace', address: '1 High St, Bath', lat: 51.38, lng: -2.36 },
47
- holder: 'Sam Lee', number: 'T-0042',
48
- fields: [{ label: 'Seat', value: 'Table 6' }],
49
- },
50
- })
51
- return { links: pass.links } // hand these to the page
52
-
53
- // A loyalty card, kept up to date
54
- await ctx.sl.wallet.issue({ ref: { type: 'loyalty', id: accountId }, pass: { kind: 'loyalty', title: 'Bloom Rewards', points: 120, holder: 'Sam' } })
55
- await ctx.sl.wallet.update(passId, { points: 145 })
56
-
57
- await ctx.sl.wallet.void(passId, 'refunded')
58
- await ctx.sl.wallet.message(passId, { header: 'Doors open', body: 'Doors open at 7pm. See you soon!' })
59
- // Everyone holding a ticket for this event
60
- await ctx.sl.wallet.messageAll({ type: 'event', id: eventId }, { header: 'Running late', body: 'We start at 7:30 tonight.' })
61
- ```
62
-
63
- - **Contact:** `contactId` defaults to the caller's contact.
64
- - **Reading:** `ctx.sl.wallet.get(passId)`, `forRef(ref)`, `byCode(code)` and `mine()` need only `sl:wallet:read`.
65
- - **Messages:** you can also send a message to wallet with `ctx.sl.messages` and `channel: 'wallet'`. It goes to the
66
- person's passes about the message's `about`, otherwise to your app's own passes for them. It's worded from the
67
- template's push version.
68
-
69
- ## Knowing who added it
70
-
71
- Every pass belongs to a known person, so you can tell who has actually put it in their wallet:
72
-
73
- - **Apple:** the phone registers the pass with SmartLinks when it's added, and unregisters it when it's removed.
74
- - **Google:** Google sends a signed "saved" or "deleted" notice.
75
-
76
- The pass's `inWallet` shows `{ apple: { saved, savedAt }, google: { saved, savedAt } }`. Each change raises an
77
- event for the pass holder, so a flow in your app's blueprint can react, for example by sending a "see you there"
78
- email when someone adds their ticket:
79
-
80
- | Event | When |
81
- |---|---|
82
- | `wallet.pass_added` | the person added the pass to Apple or Google Wallet |
83
- | `wallet.pass_removed` | they removed it |
84
-
85
- Google's notices are best-effort, so treat them as a good signal rather than a guarantee.
86
-
87
- ## Checking a pass at the door
88
-
89
- The QR holds the pass's own code, never an id. Scan it, then:
90
-
91
- ```typescript
92
- const { pass, valid } = await wallet.byCode(collectionId, scanned) // admin
93
- // or in a function: await ctx.sl.wallet.byCode(scanned)
94
- ```
95
-
96
- ## What a pass can show
97
-
98
- | Field | Use |
99
- |---|---|
100
- | `kind` | `event`, `booking`, `membership` or `loyalty` |
101
- | `title` / `subtitle` | the main line and a second line |
102
- | `start` / `end` / `timezone` | when; the pass surfaces near `start` |
103
- | `venue` | `name`, `address`, and `lat` / `lng` for the lock screen nearby |
104
- | `holder`, `number`, `level`, `points`, `validUntil` | the person, a reference or member number, a level, a balance, an end date |
105
- | `fields` (up to 4), `back` | extra lines on the front and the back |
106
- | `image`, `url` | https only: a picture, a link back to your site |
107
- | `barcode` | your own QR value, instead of the pass's code |
1
+ # Wallet passes
2
+
3
+ Put an **event ticket**, a **booking**, a **membership card** or a **loyalty card** in the person's Apple Wallet or
4
+ Google Wallet. SmartLinks is the issuer and signs the passes. Each pass is branded from your site's name, logo and
5
+ colour, and your app decides what it says.
6
+
7
+ - **Who gets one:** only someone the business knows. A pass is issued to the signed-in owner of what it's for, or
8
+ by your app's own server function.
9
+ - **What the phone does:** the pass shows its QR code offline, appears near the time (and place, if you give
10
+ `venue.lat` / `lng`), and updates when you change it.
11
+ - **Bookings look after themselves:** when a booking is moved its pass shows the new time, and when it's cancelled
12
+ the pass is voided.
13
+
14
+ ## In a page: "Add to Wallet"
15
+
16
+ ```typescript
17
+ import { wallet } from '@proveanything/smartlinks'
18
+
19
+ // The signed-in person's booking, membership card, or a pass your app issued them
20
+ const { pass } = await wallet.addLinks(collectionId, { type: 'booking', id: booking.id })
21
+ // pass.links.apple → opens the .pkpass on an iPhone
22
+ // pass.links.google → opens Google's "Save to Google Wallet" page
23
+ ```
24
+
25
+ - `{ type: 'booking', id }` and `{ type: 'contact', id: 'me' }` are made on first ask:
26
+ - a booking pass, from the booking's date and time
27
+ - a membership card, from the person's `level` and `memberUntil` fields
28
+ - For anything else (an event ticket with your own title, a loyalty card with points), issue the pass in your server
29
+ function first. `addLinks` then returns that pass for its owner.
30
+ - Show the official "Add to Apple Wallet" and "Add to Google Wallet" badges, and only the one that suits the
31
+ device. A wallet that isn't set up yet is left out of `links`.
32
+ - `wallet.mine(collectionId)` lists the person's passes.
33
+
34
+ ## In a server function: issue, change, void, message
35
+
36
+ Declare `sl:wallet:write` in the function's capabilities.
37
+
38
+ ```typescript
39
+ // An event ticket
40
+ const pass = await ctx.sl.wallet.issue({
41
+ ref: { type: 'booking', id: booking.id }, // what it's for; issuing again changes the same pass
42
+ pass: {
43
+ kind: 'event',
44
+ title: 'Jazz on the Terrace',
45
+ start: '2026-12-24T19:00:00Z', end: '2026-12-24T22:00:00Z', timezone: 'Europe/London',
46
+ venue: { name: 'The Terrace', address: '1 High St, Bath', lat: 51.38, lng: -2.36 },
47
+ holder: 'Sam Lee', number: 'T-0042',
48
+ fields: [{ label: 'Seat', value: 'Table 6' }],
49
+ },
50
+ })
51
+ return { links: pass.links } // hand these to the page
52
+
53
+ // A loyalty card, kept up to date
54
+ await ctx.sl.wallet.issue({ ref: { type: 'loyalty', id: accountId }, pass: { kind: 'loyalty', title: 'Bloom Rewards', points: 120, holder: 'Sam' } })
55
+ await ctx.sl.wallet.update(passId, { points: 145 })
56
+
57
+ await ctx.sl.wallet.void(passId, 'refunded')
58
+ await ctx.sl.wallet.message(passId, { header: 'Doors open', body: 'Doors open at 7pm. See you soon!' })
59
+ // Everyone holding a ticket for this event
60
+ await ctx.sl.wallet.messageAll({ type: 'event', id: eventId }, { header: 'Running late', body: 'We start at 7:30 tonight.' })
61
+ ```
62
+
63
+ - **Contact:** `contactId` defaults to the caller's contact.
64
+ - **Reading:** `ctx.sl.wallet.get(passId)`, `forRef(ref)`, `byCode(code)` and `mine()` need only `sl:wallet:read`.
65
+ - **Messages:** you can also send a message to wallet with `ctx.sl.messages` and `channel: 'wallet'`. It goes to the
66
+ person's passes about the message's `about`, otherwise to your app's own passes for them. It's worded from the
67
+ template's push version.
68
+
69
+ ## Knowing who added it
70
+
71
+ Every pass belongs to a known person, so you can tell who has actually put it in their wallet:
72
+
73
+ - **Apple:** the phone registers the pass with SmartLinks when it's added, and unregisters it when it's removed.
74
+ - **Google:** Google sends a signed "saved" or "deleted" notice.
75
+
76
+ The pass's `inWallet` shows `{ apple: { saved, savedAt }, google: { saved, savedAt } }`. Each change raises an
77
+ event for the pass holder, so a flow in your app's blueprint can react, for example by sending a "see you there"
78
+ email when someone adds their ticket:
79
+
80
+ | Event | When |
81
+ |---|---|
82
+ | `wallet.pass_added` | the person added the pass to Apple or Google Wallet |
83
+ | `wallet.pass_removed` | they removed it |
84
+
85
+ Google's notices are best-effort, so treat them as a good signal rather than a guarantee.
86
+
87
+ ## Checking a pass at the door
88
+
89
+ The QR holds the pass's own code, never an id. Scan it, then:
90
+
91
+ ```typescript
92
+ const { pass, valid } = await wallet.byCode(collectionId, scanned) // admin
93
+ // or in a function: await ctx.sl.wallet.byCode(scanned)
94
+ ```
95
+
96
+ ## What a pass can show
97
+
98
+ | Field | Use |
99
+ |---|---|
100
+ | `kind` | `event`, `booking`, `membership` or `loyalty` |
101
+ | `title` / `subtitle` | the main line and a second line |
102
+ | `start` / `end` / `timezone` | when; the pass surfaces near `start` |
103
+ | `venue` | `name`, `address`, and `lat` / `lng` for the lock screen nearby |
104
+ | `holder`, `number`, `level`, `points`, `validUntil` | the person, a reference or member number, a level, a balance, an end date |
105
+ | `fields` (up to 4), `back` | extra lines on the front and the back |
106
+ | `image`, `url` | https only: a picture, a link back to your site |
107
+ | `barcode` | your own QR value, instead of the pass's code |
@@ -1,123 +1,123 @@
1
- # Websites: server-rendered on the SmartLinks site runtime
2
-
3
- A website built on SmartLinks is an app whose public side is a **server-rendered site** at its own
4
- address: an automatic `*.smartlinks.host` name, a chosen name, or the business's own domain. Every
5
- page arrives as finished HTML, so search engines, AI crawlers and link previews see the real
6
- content, and visitors see it before any JavaScript runs.
7
-
8
- ## How a request is served
9
-
10
- ```
11
- visitor / crawler / agent
12
- └─► SmartLinks site router (edge)
13
- ├─ /robots.txt, /sitemap.xml, /llms.txt made by the platform (site-seo.md)
14
- ├─ a file in your build (has an extension) served from the build, cached at the edge
15
- └─ anything else your site's server renders it
16
- • runs in an isolated worker, close to the SmartLinks API
17
- • may call the SmartLinks API and the hosts you declare, nothing else
18
- • request header x-sl-site says which site it is (SL.site.fromRequest)
19
- ```
20
-
21
- The router also adds the canonical or noindex header, the security headers, and
22
- `window.__SMARTLINKS_SITE__` to every HTML page (read in the browser with `SL.site.current()` or
23
- `SL.readContext()`).
24
-
25
- ## The build
26
-
27
- The website template (TanStack Start) produces this; you don't write it by hand.
28
-
29
- ```
30
- dist/
31
- ├── index.html? / assets/… the client build (hashed files: cached for a year)
32
- ├── sitemap-paths.txt your pages, "<path> [Title]" per line (site-seo.md)
33
- ├── _server/ the server bundle: one ES module entry + its chunks
34
- │ └── index.mjs exports default { fetch(request, env, ctx) } (WinterTC)
35
- └── app.manifest.json
36
- ```
37
-
38
- Manifest:
39
-
40
- ```jsonc
41
- "site": {
42
- "server": {
43
- "main": "_server/index.mjs", // the server entry, inside the build
44
- "compatibilityFlags": ["nodejs_compat"] // allowed: nodejs_compat, nodejs_compat_v2, nodejs_als
45
- },
46
- "network": ["api.example-weather.com"] // other hosts the server may call (optional)
47
- }
48
- ```
49
-
50
- On publish, the server folder becomes the site's server for that channel. Promote copies the same
51
- bytes. `_server/` is never served to visitors.
52
-
53
- ## The server's rules
54
-
55
- - **Which site:** `const site = SL.site.fromRequest(request)` gives `{ host, collectionId, appId,
56
- channel, canonicalHost }`. One build serves every site it's installed on, so always take the
57
- collection from here, never from a constant.
58
- - **Data:** call the SmartLinks API with the SDK as you would in the browser. The server reads what
59
- an anonymous visitor could read on that site, and only that collection. It holds no keys and no
60
- signed-in user.
61
- - **Writes** (contact forms, entries, sign-ups) go to your app's **server functions**
62
- (server-functions.md), called from the browser as today. Their capabilities, secrets and limits
63
- apply.
64
- - **Other hosts:** only those in `site.network`. Anything else is refused (`403 Blocked`).
65
- - **Limits per request:** a CPU-time budget and a cap on outgoing calls. A page that needs more is
66
- doing work that belongs in a server function or a scheduled job.
67
- - **No secrets** in the server bundle and no Node built-ins beyond `nodejs_compat`.
68
-
69
- ## Using another app's pages
70
-
71
- Some apps do a job a site shouldn't rebuild: a booking journey holds the time rules, the clash
72
- handling and the confirmation; "my bookings" holds who may change what. Those apps declare their pages
73
- in `linkable` (app-manifest.md), each with a stable `id`, a `path` and the params it `accepts`. A site
74
- embeds one with **`IframeResponder`** (iframe-responder.md), from the browser:
75
-
76
- ```typescript
77
- const site = SL.site.current()
78
- const responder = new SL.IframeResponder({
79
- collectionId: site.collectionId,
80
- appId: 'appointments', // the app's id on this collection
81
- initialPath: '/my-bookings', // the page's `path`
82
- params: { service: 'svc_123' }, // what the page `accepts`
83
- autoHeight: { minHeight: 480 }, // the iframe is as tall as the page: your page scrolls, never the iframe
84
- })
85
- iframe.src = await responder.attach(iframe)
86
- ```
87
-
88
- - **Size it with `autoHeight`, not by hand.** The responder sets the iframe's height from the page's own
89
- height and counts the iframe's border and padding, so there's nothing left to scroll. Setting
90
- `iframe.style.height` from `onResize` yourself goes wrong in a site: `onResize` also fires on every
91
- window resize with "the window below the iframe" (for a full-screen host), and a bordered iframe
92
- (Tailwind's border-box) ends up a few pixels short — a scrollbar inside the frame.
93
-
94
- - **The visitor's session goes with it.** The page's API calls are proxied through the site, so it
95
- acts as whoever is signed in to the site (or as a guest). Never pass a token in the URL.
96
- - **The app must be installed** on the site's collection; its address comes from there.
97
- - **Show the app's content natively where you can** (its `headless` data: services, staff, events)
98
- for your own design and SEO, and embed the page only for the part that does the work.
99
- - Pages render on the client, after load: they aren't part of the server-rendered HTML.
100
-
101
- ## Caching
102
-
103
- The router keeps a rendered page at the edge when your response says it may:
104
-
105
- | Your response | At the edge |
106
- |---|---|
107
- | `Cache-Control: public, s-maxage=300` (the template's default for pages) | kept up to 5 minutes |
108
- | `private`, `no-store`, `no-cache`, or a `Set-Cookie` | never kept |
109
- | no `Cache-Control` | never kept |
110
-
111
- Cached pages are keyed by the release and the collection's **content generation**: when products,
112
- public app records, app settings or the collection change, the generation moves and every page of
113
- the collection's sites re-renders on its next visit (within about 30 seconds). Publishing a release
114
- does the same. Tracking parameters (`utm_*`, `gclid`, `fbclid`…) don't create separate entries.
115
-
116
- Keep pages the same for every visitor. Anything personal (a signed-in owner's products, a basket)
117
- renders in the browser after load.
118
-
119
- ## Locally
120
-
121
- `npm run dev` runs the site with your dev collection (`.env`: `VITE_SL_COLLECTION_ID`), because
122
- there's no router to say which site it is: `SL.site.fromRequest()` is null, so fall back to it.
123
- Forge's preview runs the same server code the site runtime does.
1
+ # Websites: server-rendered on the SmartLinks site runtime
2
+
3
+ A website built on SmartLinks is an app whose public side is a **server-rendered site** at its own
4
+ address: an automatic `*.smartlinks.host` name, a chosen name, or the business's own domain. Every
5
+ page arrives as finished HTML, so search engines, AI crawlers and link previews see the real
6
+ content, and visitors see it before any JavaScript runs.
7
+
8
+ ## How a request is served
9
+
10
+ ```
11
+ visitor / crawler / agent
12
+ └─► SmartLinks site router (edge)
13
+ ├─ /robots.txt, /sitemap.xml, /llms.txt made by the platform (site-seo.md)
14
+ ├─ a file in your build (has an extension) served from the build, cached at the edge
15
+ └─ anything else your site's server renders it
16
+ • runs in an isolated worker, close to the SmartLinks API
17
+ • may call the SmartLinks API and the hosts you declare, nothing else
18
+ • request header x-sl-site says which site it is (SL.site.fromRequest)
19
+ ```
20
+
21
+ The router also adds the canonical or noindex header, the security headers, and
22
+ `window.__SMARTLINKS_SITE__` to every HTML page (read in the browser with `SL.site.current()` or
23
+ `SL.readContext()`).
24
+
25
+ ## The build
26
+
27
+ The website template (TanStack Start) produces this; you don't write it by hand.
28
+
29
+ ```
30
+ dist/
31
+ ├── index.html? / assets/… the client build (hashed files: cached for a year)
32
+ ├── sitemap-paths.txt your pages, "<path> [Title]" per line (site-seo.md)
33
+ ├── _server/ the server bundle: one ES module entry + its chunks
34
+ │ └── index.mjs exports default { fetch(request, env, ctx) } (WinterTC)
35
+ └── app.manifest.json
36
+ ```
37
+
38
+ Manifest:
39
+
40
+ ```jsonc
41
+ "site": {
42
+ "server": {
43
+ "main": "_server/index.mjs", // the server entry, inside the build
44
+ "compatibilityFlags": ["nodejs_compat"] // allowed: nodejs_compat, nodejs_compat_v2, nodejs_als
45
+ },
46
+ "network": ["api.example-weather.com"] // other hosts the server may call (optional)
47
+ }
48
+ ```
49
+
50
+ On publish, the server folder becomes the site's server for that channel. Promote copies the same
51
+ bytes. `_server/` is never served to visitors.
52
+
53
+ ## The server's rules
54
+
55
+ - **Which site:** `const site = SL.site.fromRequest(request)` gives `{ host, collectionId, appId,
56
+ channel, canonicalHost }`. One build serves every site it's installed on, so always take the
57
+ collection from here, never from a constant.
58
+ - **Data:** call the SmartLinks API with the SDK as you would in the browser. The server reads what
59
+ an anonymous visitor could read on that site, and only that collection. It holds no keys and no
60
+ signed-in user.
61
+ - **Writes** (contact forms, entries, sign-ups) go to your app's **server functions**
62
+ (server-functions.md), called from the browser as today. Their capabilities, secrets and limits
63
+ apply.
64
+ - **Other hosts:** only those in `site.network`. Anything else is refused (`403 Blocked`).
65
+ - **Limits per request:** a CPU-time budget and a cap on outgoing calls. A page that needs more is
66
+ doing work that belongs in a server function or a scheduled job.
67
+ - **No secrets** in the server bundle and no Node built-ins beyond `nodejs_compat`.
68
+
69
+ ## Using another app's pages
70
+
71
+ Some apps do a job a site shouldn't rebuild: a booking journey holds the time rules, the clash
72
+ handling and the confirmation; "my bookings" holds who may change what. Those apps declare their pages
73
+ in `linkable` (app-manifest.md), each with a stable `id`, a `path` and the params it `accepts`. A site
74
+ embeds one with **`IframeResponder`** (iframe-responder.md), from the browser:
75
+
76
+ ```typescript
77
+ const site = SL.site.current()
78
+ const responder = new SL.IframeResponder({
79
+ collectionId: site.collectionId,
80
+ appId: 'appointments', // the app's id on this collection
81
+ initialPath: '/my-bookings', // the page's `path`
82
+ params: { service: 'svc_123' }, // what the page `accepts`
83
+ autoHeight: { minHeight: 480 }, // the iframe is as tall as the page: your page scrolls, never the iframe
84
+ })
85
+ iframe.src = await responder.attach(iframe)
86
+ ```
87
+
88
+ - **Size it with `autoHeight`, not by hand.** The responder sets the iframe's height from the page's own
89
+ height and counts the iframe's border and padding, so there's nothing left to scroll. Setting
90
+ `iframe.style.height` from `onResize` yourself goes wrong in a site: `onResize` also fires on every
91
+ window resize with "the window below the iframe" (for a full-screen host), and a bordered iframe
92
+ (Tailwind's border-box) ends up a few pixels short — a scrollbar inside the frame.
93
+
94
+ - **The visitor's session goes with it.** The page's API calls are proxied through the site, so it
95
+ acts as whoever is signed in to the site (or as a guest). Never pass a token in the URL.
96
+ - **The app must be installed** on the site's collection; its address comes from there.
97
+ - **Show the app's content natively where you can** (its `headless` data: services, staff, events)
98
+ for your own design and SEO, and embed the page only for the part that does the work.
99
+ - Pages render on the client, after load: they aren't part of the server-rendered HTML.
100
+
101
+ ## Caching
102
+
103
+ The router keeps a rendered page at the edge when your response says it may:
104
+
105
+ | Your response | At the edge |
106
+ |---|---|
107
+ | `Cache-Control: public, s-maxage=300` (the template's default for pages) | kept up to 5 minutes |
108
+ | `private`, `no-store`, `no-cache`, or a `Set-Cookie` | never kept |
109
+ | no `Cache-Control` | never kept |
110
+
111
+ Cached pages are keyed by the release and the collection's **content generation**: when products,
112
+ public app records, app settings or the collection change, the generation moves and every page of
113
+ the collection's sites re-renders on its next visit (within about 30 seconds). Publishing a release
114
+ does the same. Tracking parameters (`utm_*`, `gclid`, `fbclid`…) don't create separate entries.
115
+
116
+ Keep pages the same for every visitor. Anything personal (a signed-in owner's products, a basket)
117
+ renders in the browser after load.
118
+
119
+ ## Locally
120
+
121
+ `npm run dev` runs the site with your dev collection (`.env`: `VITE_SL_COLLECTION_ID`), because
122
+ there's no router to say which site it is: `SL.site.fromRequest()` is null, so fall back to it.
123
+ Forge's preview runs the same server code the site runtime does.
package/dist/http.d.ts CHANGED
@@ -1,3 +1,7 @@
1
+ /** The identity headers for this client: API version, SDK release and (in an app) the app. */
2
+ export declare function getClientHeaders(): Record<string, string>;
3
+ /** The API version this client asks for (the SDK's own, unless `initializeApi({ apiVersion })` set another). */
4
+ export declare function getApiVersion(): string;
1
5
  type Logger = {
2
6
  debug?: (...args: any[]) => void;
3
7
  info?: (...args: any[]) => void;
@@ -56,6 +60,16 @@ export declare function initializeApi(options: {
56
60
  * Preserved across re-initialization when not supplied.
57
61
  */
58
62
  appId?: string;
63
+ /**
64
+ * The app's own version (its manifest `meta.version`). With `appId`, it tells SmartLinks which release of
65
+ * which app is calling (the `SmartLinks-App` header), so an old route is never retired under an app still using it.
66
+ */
67
+ appVersion?: string;
68
+ /**
69
+ * The API version to ask for, as year-month (for example `"2026-11"`). Defaults to the version this SDK
70
+ * release was built for (`API_VERSION`), which is what you want unless you are pinning an older contract.
71
+ */
72
+ apiVersion?: string;
59
73
  /**
60
74
  * The release channel this build is running as ('dev' | 'alpha' | 'beta' | 'stable'). Normally
61
75
  * left unset — hosts that run a non-production build (Forge preview of a Test build) pass
package/dist/http.js CHANGED
@@ -25,6 +25,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
25
25
  function reject(value) { resume("throw", value); }
26
26
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
27
27
  };
28
+ import { API_VERSION, API_VERSION_HEADER, SDK_HEADER, APP_HEADER, SDK_VERSION } from "./apiVersion.js";
28
29
  import { SmartlinksApiError, SmartlinksOfflineError } from "./types/error.js";
29
30
  import { idbGet, idbSet, idbClear } from './persistentCache.js';
30
31
  let baseURL = null;
@@ -37,6 +38,29 @@ let proxyMode = false;
37
38
  let proxyTimeoutMs = 90000;
38
39
  let ngrokSkipBrowserWarning = false;
39
40
  let extraHeadersGlobal = {};
41
+ // Which API contract this client was built for, and who it is (see ./apiVersion). Sent on every request
42
+ // the SDK makes itself, and passed to the host when the app runs in a frame. NOT part of getApiHeaders():
43
+ // a host uses that to make calls on a framed app's behalf, and must send the APP's version, not its own.
44
+ let apiVersionSent = API_VERSION;
45
+ let clientAppVersion = null;
46
+ /** The identity headers for this client: API version, SDK release and (in an app) the app. */
47
+ export function getClientHeaders() {
48
+ const h = { [API_VERSION_HEADER]: apiVersionSent, [SDK_HEADER]: `js/${SDK_VERSION}` };
49
+ // The app is whichever app the SDK is running for (initializeApi({ appId }) / setAppContext).
50
+ if (appContextId)
51
+ h[APP_HEADER] = `${String(appContextId).slice(0, 80)}${clientAppVersion ? `@${clientAppVersion}` : ""}`;
52
+ return h;
53
+ }
54
+ /** The API version this client asks for (the SDK's own, unless `initializeApi({ apiVersion })` set another). */
55
+ export function getApiVersion() {
56
+ return apiVersionSent;
57
+ }
58
+ function addClientHeaders(headers) {
59
+ const lower = new Set(Object.keys(headers).map((k) => k.toLowerCase()));
60
+ for (const [k, v] of Object.entries(getClientHeaders()))
61
+ if (!lower.has(k.toLowerCase()))
62
+ headers[k] = v;
63
+ }
40
64
  /**
41
65
  * Client platform opt-in. When set to 'native', every request carries the
42
66
  * `X-Client-Platform: native` header, which tells AuthKit login endpoints to
@@ -421,6 +445,35 @@ function normalizeErrorResponse(responseBody, statusCode) {
421
445
  message,
422
446
  };
423
447
  }
448
+ // The one error shape (API version 2027-01): { error: { code, message, details?, requestId? } }. Also
449
+ // covers OpenAI-style { error: { message, type, code } } from the AI routes, which used to come out
450
+ // as "[object Object]".
451
+ if (responseBody.error && typeof responseBody.error === 'object' && !Array.isArray(responseBody.error)) {
452
+ const e = responseBody.error;
453
+ const d = Object.assign({}, (e.details && typeof e.details === 'object' ? e.details : {}));
454
+ if (e.requestId)
455
+ d.requestId = e.requestId;
456
+ if (e.type)
457
+ d.type = e.type;
458
+ return {
459
+ code: statusCode,
460
+ errorCode: typeof e.code === 'string' ? e.code : typeof e.type === 'string' ? e.type : undefined,
461
+ message: e.message ? String(e.message) : `Request failed with status ${statusCode}`,
462
+ details: Object.keys(d).length > 0 ? d : undefined,
463
+ };
464
+ }
465
+ // { ok: false, errors: [{ code, message }] } (app publishing): every message, and the first code.
466
+ if (Array.isArray(responseBody.errors) && responseBody.errors.length && !responseBody.message && !responseBody.errorText) {
467
+ const list = responseBody.errors;
468
+ const messages = list.map((x) => (x && typeof x === 'object' ? x.message : x)).filter(Boolean).map(String);
469
+ const first = list.find((x) => x && typeof x === 'object' && typeof x.code === 'string');
470
+ return {
471
+ code: statusCode,
472
+ errorCode: first ? first.code : undefined,
473
+ message: messages.join(' ') || 'Request failed',
474
+ details: Object.assign({ errors: list }, (responseBody.ok === false ? { ok: false } : {})),
475
+ };
476
+ }
424
477
  // Extract all possible fields from the response
425
478
  const { code, errorCode, error, message, errorText, ok } = responseBody, rest = __rest(responseBody
426
479
  // Determine the error code (prefer numeric code, fall back to errorCode or error string)
@@ -555,6 +608,8 @@ export function initializeApi(options) {
555
608
  ? !!options.ngrokSkipBrowserWarning
556
609
  : inferredNgrok;
557
610
  extraHeadersGlobal = options.extraHeaders ? Object.assign({}, options.extraHeaders) : {};
611
+ apiVersionSent = options.apiVersion && /^\d{4}-(0[1-9]|1[0-2])$/.test(options.apiVersion) ? options.apiVersion : API_VERSION;
612
+ clientAppVersion = options.appVersion ? String(options.appVersion).slice(0, 30) : null;
558
613
  // Platform opt-in (native refresh tokens). Preserve an earlier value when a
559
614
  // re-init call omits it, so long-lived native sessions aren't downgraded by a
560
615
  // later bootstrap that forgot to pass platform.
@@ -1103,7 +1158,9 @@ async function proxyRequest(method, path, body, headers, options) {
1103
1158
  method,
1104
1159
  path,
1105
1160
  body: payloadBody,
1106
- headers,
1161
+ // The app's own API version and identity: the host forwards these, so the answer is shaped for the
1162
+ // app's SDK, not the host's.
1163
+ headers: Object.assign(Object.assign({}, getClientHeaders()), (headers || {})),
1107
1164
  options: sanitizeProxyRequestOptions(options),
1108
1165
  };
1109
1166
  logDebug('[smartlinks] proxy:postMessage', { id, method, path, headers: headers ? redactHeaders(headers) : undefined, hasBody: !!body });
@@ -1346,8 +1403,6 @@ export async function request(path) {
1346
1403
  headers["X-Client-Platform"] = clientPlatform;
1347
1404
  if (grantToken)
1348
1405
  headers["X-Grant-Token"] = grantToken;
1349
- if (grantToken)
1350
- headers["X-Grant-Token"] = grantToken;
1351
1406
  if (ngrokSkipBrowserWarning)
1352
1407
  headers["ngrok-skip-browser-warning"] = "true";
1353
1408
  const _getDomain = getSourceDomain();
@@ -1355,6 +1410,7 @@ export async function request(path) {
1355
1410
  headers["X-Source-Domain"] = _getDomain;
1356
1411
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1357
1412
  headers[k] = v;
1413
+ addClientHeaders(headers);
1358
1414
  logDebug('[smartlinks] GET fetch', { url, headers: redactHeaders(headers) });
1359
1415
  const response = await fetch(url, { method: "GET", headers });
1360
1416
  logDebug('[smartlinks] GET response', { url, status: response.status, ok: response.ok });
@@ -1434,6 +1490,7 @@ export async function post(path, body, extraHeaders) {
1434
1490
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1435
1491
  if (!(k in headers))
1436
1492
  headers[k] = v;
1493
+ addClientHeaders(headers);
1437
1494
  // Only set Content-Type for non-FormData bodies
1438
1495
  if (!(body instanceof FormData)) {
1439
1496
  headers["Content-Type"] = "application/json";
@@ -1496,6 +1553,7 @@ export async function put(path, body, extraHeaders) {
1496
1553
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1497
1554
  if (!(k in headers))
1498
1555
  headers[k] = v;
1556
+ addClientHeaders(headers);
1499
1557
  // Only set Content-Type for non-FormData bodies
1500
1558
  if (!(body instanceof FormData)) {
1501
1559
  headers["Content-Type"] = "application/json";
@@ -1558,6 +1616,7 @@ export async function patch(path, body, extraHeaders) {
1558
1616
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1559
1617
  if (!(k in headers))
1560
1618
  headers[k] = v;
1619
+ addClientHeaders(headers);
1561
1620
  // Only set Content-Type for non-FormData bodies
1562
1621
  if (!(body instanceof FormData)) {
1563
1622
  headers["Content-Type"] = "application/json";
@@ -1659,6 +1718,7 @@ export async function requestWithOptions(path, options) {
1659
1718
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1660
1719
  if (!(k in headers))
1661
1720
  headers[k] = v;
1721
+ addClientHeaders(headers);
1662
1722
  logDebug('[smartlinks] requestWithOptions fetch', { url, method: options.method || 'GET', headers: redactHeaders(headers), body: safeBodyPreview(options.body) });
1663
1723
  const response = await fetch(url, Object.assign(Object.assign({}, options), { headers }));
1664
1724
  logDebug('[smartlinks] requestWithOptions response', { url, status: response.status, ok: response.ok });
@@ -1711,6 +1771,7 @@ export async function requestStream(path, options) {
1711
1771
  const body = options === null || options === void 0 ? void 0 : options.body;
1712
1772
  const extraHeaders = (options === null || options === void 0 ? void 0 : options.headers) || {};
1713
1773
  const headers = Object.assign(Object.assign(Object.assign({}, extraHeaders), getApiHeaders()), { Accept: 'text/event-stream' });
1774
+ addClientHeaders(headers);
1714
1775
  if (!(typeof FormData !== 'undefined' && body instanceof FormData) && body !== undefined && !Object.keys(headers).some(k => k.toLowerCase() === 'content-type')) {
1715
1776
  headers['Content-Type'] = 'application/json';
1716
1777
  }
@@ -1771,6 +1832,7 @@ export async function del(path, extraHeaders) {
1771
1832
  for (const [k, v] of Object.entries(extraHeadersGlobal))
1772
1833
  if (!(k in headers))
1773
1834
  headers[k] = v;
1835
+ addClientHeaders(headers);
1774
1836
  logDebug('[smartlinks] DELETE fetch', { url, headers: redactHeaders(headers) });
1775
1837
  const response = await fetch(url, {
1776
1838
  method: "DELETE",