@proveanything/smartlinks 2.1.37 → 2.1.39
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.
- package/README.md +1 -0
- package/dist/adminViews.d.ts +6 -1
- package/dist/adminViews.js +17 -0
- package/dist/api/asset.js +2 -0
- package/dist/api/files.d.ts +69 -0
- package/dist/api/files.js +81 -0
- package/dist/api/index.d.ts +1 -0
- package/dist/api/index.js +1 -0
- package/dist/docs/API_SUMMARY.md +123 -1
- package/dist/docs/admin-views.md +14 -0
- package/dist/docs/assets.md +4 -0
- package/dist/docs/files.md +69 -0
- package/dist/docs/overview.md +482 -481
- package/dist/docs/server-functions.md +1219 -1197
- package/dist/openapi.yaml +166 -0
- package/dist/types/asset.d.ts +17 -0
- package/dist/types/files.d.ts +78 -0
- package/dist/types/files.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +1 -0
- package/docs/API_SUMMARY.md +123 -1
- package/docs/admin-views.md +14 -0
- package/docs/assets.md +4 -0
- package/docs/files.md +69 -0
- package/docs/overview.md +482 -481
- package/docs/server-functions.md +1219 -1197
- package/openapi.yaml +166 -0
- package/package.json +1 -1
|
@@ -1,1197 +1,1219 @@
|
|
|
1
|
-
# Server functions ("edge functions")
|
|
2
|
-
|
|
3
|
-
> **SmartLinks SDK 2.x** (current `latest`). Part of the installable-app platform
|
|
4
|
-
> (author → register → install → run → test). Install `@proveanything/smartlinks@^2`.
|
|
5
|
-
|
|
6
|
-
A **server function** is arbitrary server-side JavaScript your app deploys directly into
|
|
7
|
-
SmartLinks. It runs on the SmartLinks servers — with access to the full SDK, to your app's
|
|
8
|
-
secrets, and to outbound network — so you can do things a browser app can't: validate and
|
|
9
|
-
write on the server, call third-party systems with credentials the client never sees, react
|
|
10
|
-
to events, and run scheduled work.
|
|
11
|
-
|
|
12
|
-
Every server function has the **same shape**, no matter how it's triggered or where it runs:
|
|
13
|
-
|
|
14
|
-
```ts
|
|
15
|
-
export async function myFunction(ctx, event) {
|
|
16
|
-
// ctx — a SmartLinks SDK pre-scoped to your declared authority, plus secrets, caller, fetch, log
|
|
17
|
-
// event — the trigger payload (the HTTP body, the event, or the cron tick)
|
|
18
|
-
return { ok: true } // returned to the caller (http) or recorded as the run result (event/cron)
|
|
19
|
-
}
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
You never receive a raw API key or a superuser client. The platform builds `ctx` fresh for
|
|
23
|
-
each invocation and **pre-scopes every handle to exactly what your function declared** — this
|
|
24
|
-
is how a function stays safe even when it runs with elevated authority.
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
## Declaring a function
|
|
29
|
-
|
|
30
|
-
Functions are declared in your `app.manifest.json` under `functions`, and the handlers ship
|
|
31
|
-
in a bundle alongside your widgets/containers:
|
|
32
|
-
|
|
33
|
-
```jsonc
|
|
34
|
-
{
|
|
35
|
-
"functions": {
|
|
36
|
-
"files": { "js": { "umd": "functions.umd.js" } },
|
|
37
|
-
"definitions": [
|
|
38
|
-
{
|
|
39
|
-
"name": "submitCompetitionEntry",
|
|
40
|
-
"description": "Validate a competition entry and record it server-side.",
|
|
41
|
-
"trigger": { "type": "http", "methods": ["POST"] },
|
|
42
|
-
"visibility": "public", // WHO may call it
|
|
43
|
-
"authority": "collection", // WHOSE authority it runs as
|
|
44
|
-
"elevated": true, // required ack for public + collection
|
|
45
|
-
"capabilities": ["sl:records:write", "network:api.recaptcha.net"],
|
|
46
|
-
"apiVersion": "2026-09"
|
|
47
|
-
},
|
|
48
|
-
{
|
|
49
|
-
"name": "onProofCreated",
|
|
50
|
-
"trigger": { "type": "event", "eventTypes": ["proof.created"] },
|
|
51
|
-
"capabilities": ["sl:records:write", "secrets:crm-key", "network"]
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
"name": "nightlyReconcile",
|
|
55
|
-
"trigger": { "type": "cron", "schedule": "0 2 * * *" },
|
|
56
|
-
"capabilities": ["sl:products:read", "sl:records:write"]
|
|
57
|
-
}
|
|
58
|
-
]
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
Each definition maps to an exported handler of the same `name` (override with `handler`).
|
|
64
|
-
|
|
65
|
-
## Building the functions bundle
|
|
66
|
-
|
|
67
|
-
The handlers ship as a **self-contained UMD** — one file, all dependencies compiled in, no
|
|
68
|
-
`require`/`import` of platform or Node modules (see [Runtime](#runtime--what-your-function-can-use)).
|
|
69
|
-
Your functions entry just **named-exports** each handler:
|
|
70
|
-
|
|
71
|
-
```js
|
|
72
|
-
// src/functions/index.js — the functions entry
|
|
73
|
-
export async function submitCompetitionEntry(ctx, event) { /* … */ }
|
|
74
|
-
export async function onProofCreated(ctx, event) { /* … */ }
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
Build it to `dist/functions.umd.js` with a Vite lib build — **UMD format, nothing externalised**
|
|
78
|
-
(so it's self-contained), and don't wipe the widgets you built into the same `dist/`:
|
|
79
|
-
|
|
80
|
-
```ts
|
|
81
|
-
// vite.functions.config.ts
|
|
82
|
-
import { defineConfig } from 'vite'
|
|
83
|
-
export default defineConfig({
|
|
84
|
-
build: {
|
|
85
|
-
lib: { entry: 'src/functions/index.js', formats: ['umd'], name: 'functions',
|
|
86
|
-
fileName: () => 'functions.umd.js' },
|
|
87
|
-
outDir: 'dist',
|
|
88
|
-
emptyOutDir: false, // co-exist with the widgets/containers build
|
|
89
|
-
rollupOptions: { external: [] } // bundle everything — no Node/platform externals
|
|
90
|
-
},
|
|
91
|
-
})
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
```jsonc
|
|
95
|
-
// package.json — build widgets/containers as usual, then the functions bundle
|
|
96
|
-
"scripts": {
|
|
97
|
-
"build": "vite build && vite build --config vite.functions.config.ts"
|
|
98
|
-
}
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
That emits `dist/functions.umd.js`, whose named exports the platform pairs with your manifest
|
|
102
|
-
`definitions`. In the manifest, `functions.files.js.umd` is **`functions.umd.js`** — relative to the
|
|
103
|
-
published build (the contents of `dist/`), like the widget and container files; not
|
|
104
|
-
`dist/functions.umd.js`. Publishing refuses a release whose functions bundle isn't there.
|
|
105
|
-
|
|
106
|
-
Then **deploy** it — for dev, `smartlinks-publish` uploads `dist/` and registers in one step (see
|
|
107
|
-
[Deploying & registering](deploying-apps.md)).
|
|
108
|
-
|
|
109
|
-
---
|
|
110
|
-
|
|
111
|
-
## The two security questions every function answers
|
|
112
|
-
|
|
113
|
-
Server-side code needs two questions answered up front. SmartLinks makes both **explicit and
|
|
114
|
-
declarative** — you state them in the manifest, and the platform enforces them. This is the
|
|
115
|
-
same split every extensible platform lands on (Salesforce `with/without sharing`, Shopify
|
|
116
|
-
online/offline tokens, Lambda's invoke-policy vs execution-role).
|
|
117
|
-
|
|
118
|
-
### 1. `visibility` — who is allowed to call it? *(http only)*
|
|
119
|
-
|
|
120
|
-
| Value | Meaning |
|
|
121
|
-
|---|---|
|
|
122
|
-
| `admin` *(default)* | Callable only from an authenticated admin surface. |
|
|
123
|
-
| `public` | Publicly callable — no authenticated user required. |
|
|
124
|
-
|
|
125
|
-
### 2. `authority` — whose authority does it run as?
|
|
126
|
-
|
|
127
|
-
This decides what `ctx.sl` can do.
|
|
128
|
-
|
|
129
|
-
| Value | `ctx.sl` is scoped to | Use when |
|
|
130
|
-
|---|---|---|
|
|
131
|
-
| `caller` *(default)* | The **invoking user** (their session/JWT). Can only do what that user could. | Admin actions that should respect the user's own permissions and be attributed to them. |
|
|
132
|
-
| `collection` | A **collection-admin principal for _this_ collection only** — never a global superuser. | A privileged server-side action a public/anonymous caller can't be trusted to do directly. |
|
|
133
|
-
|
|
134
|
-
`authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
|
|
135
|
-
functions have no external caller, so they always run as `collection`.
|
|
136
|
-
|
|
137
|
-
### Limiting it to some people: `userGroups`
|
|
138
|
-
|
|
139
|
-
An `http` function can name the [user groups](user-groups.md) allowed to call it:
|
|
140
|
-
|
|
141
|
-
```jsonc
|
|
142
|
-
"userGroups": ["qc-controller", "manager"] // the caller must be in at least one
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
The platform checks this before your code runs. A signed-in caller in none of them gets
|
|
146
|
-
`403 NOT_IN_USER_GROUP`; an anonymous one gets `401 SIGN_IN_REQUIRED`; a collection admin always
|
|
147
|
-
passes. Inside any function, `ctx.caller.userGroups` lists the caller's own keys for finer rules.
|
|
148
|
-
`userGroups` doesn't replace `elevated: true` on a `public` + `collection` function.
|
|
149
|
-
|
|
150
|
-
### The combinations
|
|
151
|
-
|
|
152
|
-
- **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
|
|
153
|
-
- **`http` + `public` + `caller`** — runs as the anonymous/public user (limited). The safe public default.
|
|
154
|
-
- **`http` + `public` + `collection`** — publicly callable, runs with collection authority.
|
|
155
|
-
The powerful one (e.g. "submit competition entry" needs to validate then write a record no
|
|
156
|
-
anonymous user may write directly). **Your responsibility:** validate the input and prevent
|
|
157
|
-
abuse — see below.
|
|
158
|
-
- **`event` / `cron`** — background work; runs as `collection`.
|
|
159
|
-
|
|
160
|
-
> ### ⚠️ Public + collection authority is the sharp edge
|
|
161
|
-
> A `public` + `collection` function is reachable by anyone and runs with elevated authority.
|
|
162
|
-
> The platform shrinks the blast radius for you — the authority is capped to **this one
|
|
163
|
-
> collection**, and further capped by your declared **capabilities** (a competition-entry
|
|
164
|
-
> function that declares only `sl:records:write` cannot delete products or read other
|
|
165
|
-
> secrets, even though it's "elevated"). But **validating the request is still your job**:
|
|
166
|
-
> check the payload, rate-limit using `ctx.caller`, guard against replay. Treat the function
|
|
167
|
-
> body as a trust boundary.
|
|
168
|
-
>
|
|
169
|
-
> Because it's the sharp edge, a `public` + `collection` function must **explicitly opt in**
|
|
170
|
-
> with `elevated: true` in its declaration — a conscious acknowledgment that you're exposing
|
|
171
|
-
> collection authority to public callers. Without it, install/validation fails.
|
|
172
|
-
|
|
173
|
-
---
|
|
174
|
-
|
|
175
|
-
## Capabilities — least privilege, declared and capped
|
|
176
|
-
|
|
177
|
-
`capabilities` is the allow-list of what your function may reach. It is surfaced at install
|
|
178
|
-
time for consent and **enforced at runtime** — including for `collection`-authority functions.
|
|
179
|
-
Declare the minimum you need.
|
|
180
|
-
|
|
181
|
-
| Capability | Grants |
|
|
182
|
-
|---|---|
|
|
183
|
-
| `sl:<resource>:read` / `sl:<resource>:write` | SDK access to that resource, e.g. `sl:products:read`, `sl:records:write`, `sl:attestations:write`, `sl:contacts:write`, `sl:bookings:write`. |
|
|
184
|
-
| `network` | `ctx.fetch` to any host. |
|
|
185
|
-
| `network:<host>` | `ctx.fetch` to that host only (repeat for several). Prefer this over blanket `network`. |
|
|
186
|
-
| `network:*.<domain>` | `ctx.fetch` to any subdomain of `<domain>` (not `<domain>` itself), for a customer's own endpoint at a provider, e.g. `network:*.servicebus.windows.net`. `<domain>` needs at least two labels (`*.com` is not honoured). |
|
|
187
|
-
| `secrets:<name>` | `ctx.secrets.get('<name>')` for that one secret (see [Secrets](#secrets--api-keys-per-collection)). |
|
|
188
|
-
| `tools:<name>` / `tools:<family>.*` | `ctx.sl.tools.run('<name>', args)` for a platform tool, e.g. `tools:pdf.create`, or `tools:pdf.*` for every PDF tool (see [Platform tools](#platform-tools--pdfs-labels-barcodes)). |
|
|
189
|
-
|
|
190
|
-
If you don't declare `network`, `ctx.fetch` is absent. Reading a secret you didn't declare with
|
|
191
|
-
`secrets:<name>` throws.
|
|
192
|
-
|
|
193
|
-
---
|
|
194
|
-
|
|
195
|
-
## The `ctx` object
|
|
196
|
-
|
|
197
|
-
```ts
|
|
198
|
-
interface ServerFunctionContext {
|
|
199
|
-
collectionId: string
|
|
200
|
-
appId: string
|
|
201
|
-
|
|
202
|
-
/** SmartLinks SDK, pre-scoped to your declared `authority`. Capabilities cap what it may do.
|
|
203
|
-
* Key resources: `sl.appRecords` (per-app records, incl. race-safe `claim`), `sl.appData`
|
|
204
|
-
* (general/app-wide config + data — URLs, flags, arrays), `sl.counters` (atomic numbering),
|
|
205
|
-
* `sl.tags`, `sl.contacts`, `sl.interactions`, `sl.products`, `sl.attestations`. */
|
|
206
|
-
sl: SmartLinks
|
|
207
|
-
|
|
208
|
-
/** Capability-gated secrets (need `secrets:<name>`). `get(name)` reads this app's own secret on the
|
|
209
|
-
* collection first, then the app-level one; `app(name)` reads the app-level secret only. */
|
|
210
|
-
secrets: { get(ref: string): Promise<string | null>; app(ref: string): Promise<string | null> }
|
|
211
|
-
|
|
212
|
-
/** Who invoked this function. */
|
|
213
|
-
caller: {
|
|
214
|
-
userId: string | null // null for anonymous/public/system calls
|
|
215
|
-
anonymous: boolean
|
|
216
|
-
origin?: string | null // http
|
|
217
|
-
ip?: string | null // http
|
|
218
|
-
via: 'http' | 'event' | 'cron'
|
|
219
|
-
userGroups: readonly string[] // keys of the user groups the caller is in ([] when anonymous)
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
|
|
223
|
-
fetch: typeof fetch
|
|
224
|
-
|
|
225
|
-
/** Structured logging — returned inline on the admin surface and recorded as an
|
|
226
|
-
* execution activity event (owner Errors & Activity console). See "Seeing your
|
|
227
|
-
* function's runs and logs" below. */
|
|
228
|
-
log: (message: string, data?: Record<string, any>) => void
|
|
229
|
-
}
|
|
230
|
-
```
|
|
231
|
-
|
|
232
|
-
**Use `ctx.sl` for anything SmartLinks** — it is the same SDK surface you use client-side,
|
|
233
|
-
already authenticated as your declared authority and scoped to the collection. Do **not** try
|
|
234
|
-
to construct your own SDK client or carry your own key; that's what `ctx.sl` is for, and it's
|
|
235
|
-
the only way authority stays correct.
|
|
236
|
-
|
|
237
|
-
### Calling a function from your app (client side)
|
|
238
|
-
|
|
239
|
-
From a page/UI, invoke an `http`-trigger function with the SDK — no manual fetch, no URL building:
|
|
240
|
-
|
|
241
|
-
```ts
|
|
242
|
-
// public function (runs on the caller's authority — signed-in owner, else public):
|
|
243
|
-
const res = await SL.functions.call(collectionId, 'increment', { /* becomes event.body */ })
|
|
244
|
-
// admin surface (needs an admin session):
|
|
245
|
-
const res = await SL.functions.callAdmin(collectionId, 'recomputeTotals', { … })
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
`res` is whatever your handler returns. See the `edge-function-test` example for a full page +
|
|
249
|
-
function + manifest.
|
|
250
|
-
|
|
251
|
-
#### Functions are ALWAYS app-scoped
|
|
252
|
-
|
|
253
|
-
A function belongs to an app, so the canonical route carries the appId:
|
|
254
|
-
`POST /collection/:collectionId/app/:appId/functions/:name`. Two different installed apps can each
|
|
255
|
-
ship a function of the same name without clashing.
|
|
256
|
-
|
|
257
|
-
The SDK fills the appId in for you. Initialize with your app's id once, then call by bare name —
|
|
258
|
-
the SDK routes it app-scoped:
|
|
259
|
-
|
|
260
|
-
```ts
|
|
261
|
-
SL.initializeApi({ baseURL, appId: 'my-counter-app' }) // usually done by the host/bootstrap
|
|
262
|
-
await SL.functions.call(collectionId, 'pressCounter') // → /collection/:c/app/my-counter-app/functions/pressCounter
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
To call a *different* app's function, pass the appId explicitly:
|
|
266
|
-
|
|
267
|
-
```ts
|
|
268
|
-
await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'some-other-app' })
|
|
269
|
-
```
|
|
270
|
-
|
|
271
|
-
**Where it runs.** A function runs on a collection when the app is **installed** there (enabled in
|
|
272
|
-
the collection's apps); or the app is **restricted** to a list of collections (what publishing from
|
|
273
|
-
Forge sets for every developer) and this collection is on it, e.g. your own sandbox; or the app is
|
|
274
|
-
**public**, meaning a registered app with no restriction list, which only platform admins can
|
|
275
|
-
publish. Anything else gets `404 APP_NOT_INSTALLED`: a function can run with the collection's own
|
|
276
|
-
authority and secrets, so a developer's app can't reach a collection that hasn't taken it on.
|
|
277
|
-
|
|
278
|
-
**Who may run server code at all.** Until functions move to an isolated runner, only TRUSTED apps
|
|
279
|
-
execute: public (unrestricted) apps, or apps a platform admin has marked `functionsTrusted: true`.
|
|
280
|
-
Developer apps — restricted to their own collections, which includes every app published from
|
|
281
|
-
self-serve Forge — get `403 FUNCTIONS_NOT_ENABLED` until they're trusted. A platform admin can also
|
|
282
|
-
switch any app's functions off with `functionsTrusted: false`.
|
|
283
|
-
|
|
284
|
-
**Which release.** With no channel, the server runs the release the collection has **installed** (stable for a
|
|
285
|
-
public app that isn't installed) — what production wants, so app code just calls `SL.functions.call(collectionId, name)`. To run
|
|
286
|
-
another release, the channel goes **in the path**: `/app/:appId/<dev|alpha|beta|stable>/functions/:name`.
|
|
287
|
-
The SDK adds it for you when the host tells the app which channel it's running as — Forge's preview
|
|
288
|
-
of a Test build passes `appChannel=dev` in the app's context, so the same code calls the dev build
|
|
289
|
-
there and the installed build in production. You can also set it yourself:
|
|
290
|
-
|
|
291
|
-
```ts
|
|
292
|
-
SL.initializeApi({ baseURL, appId: 'my-counter-app', appChannel: 'dev' }) // whole app
|
|
293
|
-
await SL.functions.call(collectionId, 'pressCounter', {}, { channel: 'beta' }) // one call
|
|
294
|
-
await SL.functions.call(collectionId, 'pressCounter', {}, { channel: null }) // force the installed release
|
|
295
|
-
```
|
|
296
|
-
|
|
297
|
-
**Public address on the collection's own site (webhooks, integrations).** Every collection has a
|
|
298
|
-
site host — `<name>.smartlinks.host` once a name is claimed, else `c-<collectionId>.smartlinks.host` —
|
|
299
|
-
returned as `collection.siteHost`. App functions are reachable there:
|
|
300
|
-
|
|
301
|
-
```
|
|
302
|
-
https://<siteHost>/_fn/<appId>[/<channel>]/<function>[/<sub-path…>]
|
|
303
|
-
```
|
|
304
|
-
|
|
305
|
-
```ts
|
|
306
|
-
const col = await SL.collection.get(collectionId)
|
|
307
|
-
const webhookUrl = SL.functions.siteUrl(col, 'stripeWebhook', { appId: 'my-shop' })
|
|
308
|
-
// → https://acme.smartlinks.host/_fn/my-shop/stripeWebhook (give this to Stripe)
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
Built for integrations: **every HTTP method** the function declares in `trigger.methods` (default
|
|
312
|
-
POST only), **any content type** with the exact bytes in `event.rawBody` (verify signatures with
|
|
313
|
-
`crypto.subtle`), **sub-paths** after the name when the function declares `trigger.path` (`"/*"`, or a
|
|
314
|
-
pattern like `"/orders/:id"` → `event.params.id`), and the function's own `Response` — status, headers,
|
|
315
|
-
CORS — goes back unchanged (the platform adds no CORS headers there; declare `OPTIONS` and answer
|
|
316
|
-
preflights yourself if browsers call you cross-origin). Bodies up to 6 MB.
|
|
317
|
-
|
|
318
|
-
```js
|
|
319
|
-
// manifest: { name: 'orders', trigger: { type: 'http', methods: ['GET', 'PUT'], path: '/orders/:id' }, visibility: 'public' }
|
|
320
|
-
export async function orders(ctx, event) {
|
|
321
|
-
if (event.method === 'GET') return ctx.sl.appRecords.get(event.params.id)
|
|
322
|
-
// PUT: verify the sender first — e.g. an HMAC over event.rawBody with a secret
|
|
323
|
-
}
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
Security: the platform never hands a caller's SmartLinks credential to function code (if it signed
|
|
327
|
-
the caller in from `Authorization`, that header is removed and you get `ctx.caller`); your OWN
|
|
328
|
-
`Authorization` scheme for webhooks passes through. `siteUrl` only includes a channel you ask for —
|
|
329
|
-
point production webhooks at the bare address and test ones at `/dev/`.
|
|
330
|
-
|
|
331
|
-
The channel is never a query parameter: the function owns its query string (`?channel=sms` reaches
|
|
332
|
-
your handler untouched), and a configured URL — a webhook, a third-party callback — can only ever
|
|
333
|
-
hit the channel it names. Point production webhooks at the bare path and test ones at `/dev/`.
|
|
334
|
-
|
|
335
|
-
If no appId is available (not set on init, none passed), the call falls back to the **deprecated
|
|
336
|
-
flat path** `/collection/:c/functions/:name`, which searches only the collection's **enabled** apps,
|
|
337
|
-
resolves by bare name, and **rejects with `409 AMBIGUOUS_FUNCTION`** when more than one defines that
|
|
338
|
-
name (a first-party builtin still wins). Always prefer an appId.
|
|
339
|
-
|
|
340
|
-
> There is no such thing as an app-less function. First-party builtins (e.g. the `functions.ping`
|
|
341
|
-
> diagnostic) belong to the reserved `smartlinks` app. A "global" function is just an app enabled on
|
|
342
|
-
> the `global` collection and called at `/collection/global/app/:appId/functions/:name` — same two
|
|
343
|
-
> facets (collection + app), with `global` as the sentinel collection.
|
|
344
|
-
|
|
345
|
-
---
|
|
346
|
-
|
|
347
|
-
## Inputs — data handed to your function
|
|
348
|
-
|
|
349
|
-
Declare what your function needs and the platform fetches it **before** the run: read it from `ctx.inputs` instead of calling `ctx.sl` first. One less round trip — and for functions running in the isolated runner, one less network hop.
|
|
350
|
-
|
|
351
|
-
```jsonc
|
|
352
|
-
// app.manifest.json → functions.definitions[]
|
|
353
|
-
{
|
|
354
|
-
"name": "onProductChanged",
|
|
355
|
-
"trigger": { "type": "event", "eventTypes": ["product.updated"] },
|
|
356
|
-
"capabilities": ["sl:products:read", "sl:data:read"],
|
|
357
|
-
"inputs": { "appConfig": true } // entity is on by default for event triggers
|
|
358
|
-
}
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
```js
|
|
362
|
-
export async function onProductChanged(ctx, event) {
|
|
363
|
-
const product = ctx.inputs.entity // the product that changed
|
|
364
|
-
const { interactionIds } = ctx.inputs.appConfig || {} // this app's config for the collection
|
|
365
|
-
}
|
|
366
|
-
```
|
|
367
|
-
|
|
368
|
-
| Input | What you get | Needs | Triggers |
|
|
369
|
-
|---|---|---|---|
|
|
370
|
-
| `entity` | The record the event is about: the product, your app's record, or the interaction event. **On by default**; `"entity": false` opts out. | read on that resource (`sl:products:read`, `sl:records:read`) | event |
|
|
371
|
-
| `collection` | The collection's public record | — | all |
|
|
372
|
-
| `appConfig` | Your app's config for this collection (where setup like `interactionIds` lives) | `sl:data:read` | all |
|
|
373
|
-
| `product` | A product named by the request: `{ "from": "body.productId" }`, `"query.<field>"` or `"path"` | `sl:products:read` | http |
|
|
374
|
-
|
|
375
|
-
- **Same rules as `ctx.sl`.** Inputs are fetched with your function's authority and capabilities, scoped to the collection it runs in — a product from another collection is never fetched.
|
|
376
|
-
- **Never an error.** Not found, not allowed or larger than 256 KB → that input is `null`. Check before you use it.
|
|
377
|
-
- **Current state.** Event inputs are fetched when your function runs, so you see the record as it is now; `event` still carries the ids.
|
|
378
|
-
- **Checked at publish.** An unknown input, a bad `from`, or a missing capability fails validation.
|
|
379
|
-
- **Testing:** pass `inputs` to the test context — `createFunctionTestContext({ def, inputs: { entity: { id: 'p1', name: 'Kettle' } } })`.
|
|
380
|
-
|
|
381
|
-
## Exposing a function to the AI agent
|
|
382
|
-
|
|
383
|
-
An `http` function can be offered to the AI agent as a **callable tool**, alongside the built-in
|
|
384
|
-
tools. The model calls it, the server runs it, and the result is fed back into the loop. Opt in from
|
|
385
|
-
the manifest with an `agent` block (full reference: [agent-tools.md](agent-tools.md)):
|
|
386
|
-
|
|
387
|
-
```jsonc
|
|
388
|
-
{
|
|
389
|
-
"name": "getLoyaltyBalance",
|
|
390
|
-
"trigger": { "type": "http" },
|
|
391
|
-
"visibility": "admin",
|
|
392
|
-
"authority": "caller",
|
|
393
|
-
"capabilities": ["sl:records:read"],
|
|
394
|
-
"agent": {
|
|
395
|
-
"tool": true,
|
|
396
|
-
"title": "Loyalty balance",
|
|
397
|
-
"description": "Look up a member's current loyalty points balance.",
|
|
398
|
-
"input": {
|
|
399
|
-
"type": "object",
|
|
400
|
-
"properties": { "memberId": { "type": "string" } },
|
|
401
|
-
"required": ["memberId"]
|
|
402
|
-
},
|
|
403
|
-
"approval": "auto" // 'require' = human confirms before each call
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
```
|
|
407
|
-
|
|
408
|
-
The agent becomes **just another caller surface** — your function's `visibility`, `authority`, and
|
|
409
|
-
`capabilities` are enforced exactly as on the http route. Nothing new is granted. The agent's tool
|
|
410
|
-
arguments arrive as the function's request `body`, and whatever you return becomes the tool result the
|
|
411
|
-
model sees. `approval: "require"` tools are held back from the autonomous server-side loop until the
|
|
412
|
-
human-approval UX ships.
|
|
413
|
-
|
|
414
|
-
Include your app's functions in an agent run:
|
|
415
|
-
|
|
416
|
-
```ts
|
|
417
|
-
// Agentic Responses:
|
|
418
|
-
await SL.ai.chat.responses.create(collectionId, {
|
|
419
|
-
model: 'balanced', input: 'What is member 42's balance?',
|
|
420
|
-
server_tools: true, // built-in tools
|
|
421
|
-
app_functions: { appId: 'my-loyalty-app' }, // + this app's ai.tool functions
|
|
422
|
-
})
|
|
423
|
-
|
|
424
|
-
// Or the one-shot agent loop:
|
|
425
|
-
await SL.ai.agent.run(collectionId, {
|
|
426
|
-
input: '…', appFunctions: { appId: 'my-loyalty-app' },
|
|
427
|
-
})
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
On the **consumer surface**, a `visibility: "public"` function reaches a public assistant via the
|
|
431
|
-
public agent loop — the caller runs as the signed-in consumer (`'owner'`, send the authKit bearer) or
|
|
432
|
-
anonymous (`'public'`):
|
|
433
|
-
|
|
434
|
-
```ts
|
|
435
|
-
await SL.ai.publicClient.agentRun(collectionId, {
|
|
436
|
-
input: '…',
|
|
437
|
-
appFunctions: { appId: 'my-app' }, // this app's public agent tools
|
|
438
|
-
server_tools: ['web.search'], // built-ins are an explicit allowlist on the public surface
|
|
439
|
-
})
|
|
440
|
-
```
|
|
441
|
-
|
|
442
|
-
`channel` (default `'stable'`, pass `'dev'` to test a dev build) and `only: string[]` narrow which
|
|
443
|
-
functions are exposed. Only `http` functions with `agent.tool: true` are eligible; `event`/`cron`
|
|
444
|
-
functions never are. A built-in tool of the same name wins the clash.
|
|
445
|
-
|
|
446
|
-
### One unified toolbelt
|
|
447
|
-
|
|
448
|
-
Rather than juggling `server_tools` + `app_functions`, declare everything in one `toolbelt` — built-in
|
|
449
|
-
tools, one **or several** apps' functions, and (reserved, staged) front-end client tools:
|
|
450
|
-
|
|
451
|
-
```ts
|
|
452
|
-
await SL.ai.chat.responses.create(collectionId, {
|
|
453
|
-
input: '…',
|
|
454
|
-
toolbelt: {
|
|
455
|
-
builtins: ['web.search', 'document.read'], // true = all, [names] = subset, omit = none
|
|
456
|
-
appFunctions: [{ appId: 'loyalty' }, { appId: 'catalog' }], // several apps at once
|
|
457
|
-
// clientTools: [ … ] // reserved — the client-tool bridge is staged
|
|
458
|
-
},
|
|
459
|
-
})
|
|
460
|
-
```
|
|
461
|
-
|
|
462
|
-
The same `toolbelt` works on `ai.agent.run` and `ai.publicClient.agentRun` (on the public surface
|
|
463
|
-
`builtins` is an explicit allowlist — `true` is treated as none). Precedence on a name clash: a
|
|
464
|
-
built-in wins, then earlier `appFunctions` sources win over later ones.
|
|
465
|
-
|
|
466
|
-
> Directly (no model): every function is also callable deterministically — `SL.functions.call` /
|
|
467
|
-
> `callAdmin` (above), the same way the built-in tools are callable via `SL.ai.tools.run`.
|
|
468
|
-
|
|
469
|
-
---
|
|
470
|
-
|
|
471
|
-
## Runtime — what your function can use
|
|
472
|
-
|
|
473
|
-
Your function runs in a **web-standard sandbox** (think Cloudflare Workers / Deno), **not
|
|
474
|
-
Node**. Concretely it targets the **WinterTC Minimum Common Web Platform API** (WinterTC is the
|
|
475
|
-
Ecma International technical committee for this, formerly WinterCG) — the same surface those
|
|
476
|
-
runtimes guarantee — so what you can rely on is portable, and the future isolated runner will
|
|
477
|
-
host the same bundle unchanged.
|
|
478
|
-
|
|
479
|
-
**Available globals** (no import needed):
|
|
480
|
-
- **Data / encoding:** `JSON`, `URL`, `URLSearchParams`, `TextEncoder` / `TextDecoder`,
|
|
481
|
-
`atob` / `btoa`, `Buffer`, `structuredClone`.
|
|
482
|
-
- **Crypto:** `crypto` (Web Crypto) — `crypto.subtle` for hashing / HMAC / encrypt / sign /
|
|
483
|
-
verify, `crypto.getRandomValues`, `crypto.randomUUID`.
|
|
484
|
-
- **HTTP:** `fetch`, `Headers`, `Request`, `Response`, `FormData`, `Blob`, `File`,
|
|
485
|
-
`AbortController` / `AbortSignal` (use one for **request timeouts**).
|
|
486
|
-
- **Streams & timing:** `ReadableStream` / `WritableStream` / `TransformStream`,
|
|
487
|
-
`CompressionStream` / `DecompressionStream` (gzip/deflate for third-party payloads), the timer
|
|
488
|
-
functions, `queueMicrotask`, `performance`, `console`.
|
|
489
|
-
- **Runtime identity:** `navigator.userAgent` reports the runtime key (currently
|
|
490
|
-
`"SmartLinks-Functions"`) — use it if a portable dependency needs to feature-detect the host.
|
|
491
|
-
It stays stable when functions move to the isolated runner.
|
|
492
|
-
|
|
493
|
-
**Not available:** `require` / `import` of platform or Node modules, `process`, `fs`, and the
|
|
494
|
-
Node built-ins (`node:crypto`, `node:http`, …). There is no ambient database, key, or network
|
|
495
|
-
handle — everything the platform gives you comes through **`ctx`**.
|
|
496
|
-
|
|
497
|
-
**Dependencies:** bundle them. Your build must produce a **self-contained** UMD (deps compiled
|
|
498
|
-
in), and those deps must be **edge-compatible** — pure JS / Web APIs. A library that reaches for
|
|
499
|
-
Node built-ins (e.g. `axios`'s Node adapter, anything using `node:crypto`) will fail to load.
|
|
500
|
-
Prefer the platform primitives above over a dependency; when you do need one, pick edge-safe:
|
|
501
|
-
|
|
502
|
-
| Need | Native? | Recommended (bundle, edge-safe) |
|
|
503
|
-
|---|---|---|
|
|
504
|
-
| JSON | **native** — `JSON.parse/stringify` | — |
|
|
505
|
-
| XML parse / build | no | `fast-xml-parser` |
|
|
506
|
-
| CSV | no | `papaparse` |
|
|
507
|
-
| Schema validation of inputs | no | `zod` |
|
|
508
|
-
| JWT (sign/verify for a third-party API) | Web Crypto can, verbosely | `jose` |
|
|
509
|
-
| Hash / HMAC / encrypt | **native** — `crypto.subtle` | — |
|
|
510
|
-
| PDF **text** extraction (cheap first-pass, no AI) | no | `unpdf` — a serverless/WASM pdf.js build with no Node deps; `import { extractText } from 'unpdf'`. Text only. |
|
|
511
|
-
|
|
512
|
-
> **PDFs in a server function:** for a cheap text-layer check use `unpdf` (edge-safe, WASM). For
|
|
513
|
-
> anything heavier — rendering pages, vision extraction, **barcode/QR decode**, or prepress/spot-colour
|
|
514
|
-
> inspection, **OCR of small print** — call the platform tools `pdf.render` / `pdf.extract` /
|
|
515
|
-
> `pdf.decodeBarcodes` / `pdf.inspectGraphics` / `image.ocr` via `ai.tools.run`; those run in the full
|
|
516
|
-
> platform runtime, not the sandbox.
|
|
517
|
-
|
|
518
|
-
**The common actions, and how to do each:**
|
|
519
|
-
|
|
520
|
-
| You want to… | Use | Requires |
|
|
521
|
-
|---|---|---|
|
|
522
|
-
| Call a third-party API (GET/POST) | `ctx.fetch(url, init)` — the standard Fetch API | capability `network` or `network:<host>` |
|
|
523
|
-
| Read a secret (API key, signing key) | `await ctx.secrets.get('<ref>')` | capability `secrets:<ref>` |
|
|
524
|
-
| Hash / HMAC-sign / verify / encrypt | `crypto.subtle` (Web Crypto) | — |
|
|
525
|
-
| Random id / bytes | `crypto.randomUUID()` / `crypto.getRandomValues()` | — |
|
|
526
|
-
| Read or write SmartLinks data | `ctx.sl.*` (records, products, attestations, …) | the matching `sl:<res>:<read\|write>` |
|
|
527
|
-
| Read/write your app's own data (config, URLs, counters, arrays) | `ctx.sl.appData.get()` / `ctx.sl.appData.set({…})` — collection-scoped by default; `ctx.sl.appData.global.*` (or `{ scope:'global' }`, or declare `dataScope:'global'`) for the app-wide bucket. It's your OWN namespace, so **any** authority may read/write it | `sl:data:read` / `sl:data:write` |
|
|
528
|
-
| Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
|
|
529
|
-
| Guarantee a UNIQUE claim (one entry per tag, one-per-user, idempotency key, a number nobody else holds) | `ctx.sl.appRecords.claim({ …, singletonPer, customId })` → `{ record, created, conflict? }` — see below | `sl:records:write` |
|
|
530
|
-
| Hand out the next number (tickets, order numbers) | `ctx.sl.counters.next('tickets')` — atomic, distinct per caller | `sl:data:write` |
|
|
531
|
-
| Track a job through its stages (a production job, a repair, a fulfilment) | `ctx.sl.workOrders` — the shared work order; stages, holds, progress → `operations.md` | `sl:workorders:write` |
|
|
532
|
-
| Know how much of something there is and where; move, allocate, hold or count it | `ctx.sl.stock` — quantities in containers, changed by movements, never below zero → `operations.md` | `sl:stock:write` |
|
|
533
|
-
| Ask whether you will run short, and when | `ctx.sl.stock.position({ productId, horizonDays })` — on hand, on order, being made, needed, first short day | `sl:stock:read` |
|
|
534
|
-
| Say what a product is made of, or what a batch really used | `ctx.sl.boms`, `ctx.sl.madeFrom` → `operations.md` | `sl:boms:write`, `sl:madefrom:write` |
|
|
535
|
-
| Change numbers in a record (stock, counts, balances) without losing updates | `ctx.sl.appRecords.adjust(id, { qty: -5 }, { atLeast: { qty: 0 } })` — in place, conditions checked after the change | `sl:records:write` |
|
|
536
|
-
| Several record writes that land together or not at all (a stock move) | `ctx.sl.transaction([ops], { idempotencyKey })` — see below | `sl:records:write` |
|
|
537
|
-
| Totals: stock per location, forecast per SKU | `ctx.sl.appRecords.aggregate({ groupBy: ['data.location'], metrics: ['sum:qty'] })` | `sl:records:read` |
|
|
538
|
-
| Keep a history of what happened (stock moves, counts) without growing your records | `ctx.sl.history.log('stock.moved', {…})`, or a `log` op in a transaction; read with `ctx.sl.history.query({…})` | `sl:history:write` / `sl:history:read` |
|
|
539
|
-
| Check a tapped tag is real | `ctx.sl.tags.resolve(proofId)` → `{ id, claimSetId, code }` or `null` | `sl:tags:read` |
|
|
540
|
-
| Put a visitor's details on a contact | `ctx.sl.contacts.upsert({ email, firstName, … })` → `{ contactId, created }` (fills empty fields only) | `sl:contacts:write` |
|
|
541
|
-
| Record "they did X" | `ctx.sl.interactions.record({ interactionId, contactId, outcome, metadata })` | `sl:interactions:write` |
|
|
542
|
-
| Message one person: a confirmation, a reminder, a cancellation, an update | `ctx.sl.messages.send({ to: 'caller' \| contactId, templateId \| message: { subject, body }, about: { type, id, view?, params? } })` → `{ ok, channel }` or `{ ok: false, reason }` — their preferred channel, their opt-outs respected, logged with your app and what it's about; see [comms.md](comms.md#messaging-one-person-from-an-app) | `sl:messages:write` |
|
|
543
|
-
| Land a loyalty / CRM provider's view of a person (member id, tier, points, tags, external ids) | `ctx.sl.members.apply({ identity, contact?, loyalty?, tags?, externalIds? }, { provider })` → `{ contactId, op }` — matches by id, external id, email or phone; profile fields fill-empty only; see [connectors.md](connectors.md#loyalty-and-crm-connectors) | `sl:members:write` |
|
|
544
|
-
| Invoke a connector's action — redeem, enrol, issue a coupon, raise a ticket — with the connector's credentials | `ctx.sl.connectors.call('acme-loyalty', 'redeem', { rewardId })` → the action's result; `ctx.sl.connectors.actions(appId)` lists them; see [connectors.md](connectors.md#actions-provider-operations-on-demand) | `sl:connectors:write` |
|
|
545
|
-
| Ask "is this person gold or above?" without holding their member record | `ctx.sl.entitlements.check('tier>=gold')` → `{ allowed, basis, asOf, attributes }` for the signed-in caller (or `{ identity, token, fallback }`); see [entitlements.md](entitlements.md) | `sl:entitlements:read` |
|
|
546
|
-
| Take a booking with your own checks (hours, queue token, payment) | `ctx.sl.bookings.create({ slotId \| resource + time, contactId, status, idempotencyKey })` — never oversold, never double-booked; also `confirm` / `cancel` / `move` / `mine` / `freebusy` / `message` (everyone booked, hydrated) / `slots.*` / `blocks.*` (see [bookings.md](bookings.md)) | `sl:bookings:write` (`sl:bookings:read` to read) |
|
|
547
|
-
|
|
548
|
-
Notes:
|
|
549
|
-
- **Talking to the SmartLinks core is `ctx.sl`, not HTTP.** The common pattern — *validate /
|
|
550
|
-
process, then act on the core* — is: check the input, then call `ctx.sl.appRecords.create(…)`,
|
|
551
|
-
`ctx.sl.products.update(…)`, etc. `ctx.sl` is already authenticated as your declared authority
|
|
552
|
-
and capped by your capabilities, so you never construct a SmartLinks API URL or carry a key.
|
|
553
|
-
Use `fetch`/`ctx.fetch` for *third-party* servers; use `ctx.sl` for SmartLinks itself.
|
|
554
|
-
- **There is one `fetch`, and it is capability-gated.** Whether you call the global `fetch` or
|
|
555
|
-
`ctx.fetch`, the behaviour is identical: the call **throws** unless your declared `network`
|
|
556
|
-
(or `network:<host>`) capability covers the target host — the same way Deno's `fetch` throws
|
|
557
|
-
without `--allow-net`. There is no ungated escape hatch. Declare the hosts you need.
|
|
558
|
-
- **Secrets are read-only at runtime.** You fetch a secret you declared; you do **not** set or
|
|
559
|
-
rotate secrets from a function — that's an admin/deploy-time operation on the platform.
|
|
560
|
-
- **Signing a webhook / verifying a signature** is `crypto.subtle` with an HMAC key imported
|
|
561
|
-
from a secret — no Node `crypto` needed.
|
|
562
|
-
|
|
563
|
-
---
|
|
564
|
-
|
|
565
|
-
## Uniqueness, numbering and people — the race-safe primitives
|
|
566
|
-
|
|
567
|
-
A public function is called by many people at once. These primitives make the outcome right no matter
|
|
568
|
-
how the calls interleave — the **database** decides, never a read-then-write in your code.
|
|
569
|
-
|
|
570
|
-
### `appRecords.claim(fields)` — a unique create
|
|
571
|
-
|
|
572
|
-
Like `create`, but the record names a **unique key**, and it's inserted only if that key is free.
|
|
573
|
-
Otherwise you get the record already holding it back, **unchanged** (never updated):
|
|
574
|
-
|
|
575
|
-
```ts
|
|
576
|
-
const { record, created, conflict } = await ctx.sl.appRecords.claim({
|
|
577
|
-
recordType: 'entry',
|
|
578
|
-
singletonPer: 'proof', proofId: tag.id, // key 1: one live entry per tag
|
|
579
|
-
customId: String(number), // key 2: one record per number, ever
|
|
580
|
-
data: { number },
|
|
581
|
-
})
|
|
582
|
-
// created: true → you got it
|
|
583
|
-
// created: false → conflict 'singleton' (this tag already has an entry: `record` is it)
|
|
584
|
-
// or 'customId' (that number is held by someone else: take another)
|
|
585
|
-
```
|
|
586
|
-
|
|
587
|
-
- **`singletonPer`** — `'collection' | 'product' | 'variant' | 'batch' | 'proof'`, with its anchor id
|
|
588
|
-
(`productId`, `proofId`, …). One **live** record per key; deleting it frees the key.
|
|
589
|
-
- **`customId`** — unique per `(recordType, scopeType, scopeId, sourceSystem)`, case-insensitive, and
|
|
590
|
-
**never reused** (deleted records keep theirs). Right for numbers that must never be handed out twice.
|
|
591
|
-
- Give at least one; with both, the record is created only if both are free.
|
|
592
|
-
- Of any number of concurrent claims on one key, **exactly one** gets `created: true`.
|
|
593
|
-
|
|
594
|
-
### `counters.next(name, { start?, by? })` — the next number
|
|
595
|
-
|
|
596
|
-
An atomic counter for your app in this collection: every caller gets a distinct value, even under a
|
|
597
|
-
burst (one row, incremented in one statement). The first call returns `start` (default 1). Counters only
|
|
598
|
-
move forward and live apart from your config, so no config save can rewind one. `counters.get(name)`
|
|
599
|
-
reads the last value handed out (`null` before the first). Name a new counter to start again from `start`.
|
|
600
|
-
|
|
601
|
-
**Counter + claim = a number nobody else can ever hold.** Take `next()`, then `claim` with
|
|
602
|
-
`customId: String(n)`. If the claim says `conflict: 'customId'`, take `next()` again. A failed or raced
|
|
603
|
-
attempt only leaves a gap — never a duplicate.
|
|
604
|
-
|
|
605
|
-
### `appRecords.adjust(id, by, { atLeast?, atMost? })` — numbers that never lose an update
|
|
606
|
-
|
|
607
|
-
Adds to numbers in a record's `data` in ONE statement, so twenty scanners taking from the same bin at
|
|
608
|
-
once each land: no read-then-write, no lost counts. A missing value counts as 0. `atLeast` / `atMost` are
|
|
609
|
-
checked on the values **after** the change, inside the same statement:
|
|
610
|
-
|
|
611
|
-
```ts
|
|
612
|
-
// Take 5 from bin A — refused (nothing changes) if it would go below zero.
|
|
613
|
-
await ctx.sl.appRecords.adjust(binA, { qty: -5 }, { atLeast: { qty: 0 } })
|
|
614
|
-
```
|
|
615
|
-
|
|
616
|
-
Refusals carry `code`: `NOT_FOUND` (not this app's record in this collection, or deleted), `NOT_A_NUMBER`
|
|
617
|
-
(the key holds something else), `CONDITION_FAILED` (409, with the `current` values). Only top-level data
|
|
618
|
-
keys; a key named only in a condition is checked as it stands.
|
|
619
|
-
|
|
620
|
-
### `transaction(ops, { idempotencyKey? })` — all or nothing
|
|
621
|
-
|
|
622
|
-
Several writes as ONE transaction: every op lands, or none does. The classic: take stock out of bin A,
|
|
623
|
-
put it on order line B, and log the move.
|
|
624
|
-
|
|
625
|
-
```ts
|
|
626
|
-
const { results, replayed } = await ctx.sl.transaction([
|
|
627
|
-
{ op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
|
|
628
|
-
{ op: 'adjust', recordId: orderLineB, by: { picked: 5 } },
|
|
629
|
-
{ op: 'create', record: { recordType: 'movement', data: { from: binA, to: orderLineB, qty: 5 } } },
|
|
630
|
-
], { idempotencyKey: scanId })
|
|
631
|
-
```
|
|
632
|
-
|
|
633
|
-
- Ops: `create` (`record`), `update` (`recordId`, `fields`), `adjust` (`recordId`, `by`, `atLeast?`,
|
|
634
|
-
`atMost?`), `delete` (`recordId`), `log` (`type`, `data`, `entityId?`: a history event, see below).
|
|
635
|
-
Up to 50, run in order. This app's records in this collection only.
|
|
636
|
-
- A failing op rolls everything back. The error says which op (`opIndex`) and why (its `code`).
|
|
637
|
-
- Change events and realtime updates go out only after the transaction commits, never for a rollback.
|
|
638
|
-
- **`idempotencyKey`** ("this was already done"): recorded in the same commit, with what was written
|
|
639
|
-
(ids only). The same key again within 7 days doesn't write; it returns those records as they are now,
|
|
640
|
-
with `replayed: true`. So a handheld that retries after a dropped signal never moves stock twice. Two
|
|
641
|
-
calls with one key at the same moment: one commits, the other replays it. A transaction that failed
|
|
642
|
-
leaves its key free, so a retry can still succeed.
|
|
643
|
-
- Use the scan's or the request's own id as the key (one key = one intended change).
|
|
644
|
-
- Browser code never writes stock directly: a warehouse screen calls your function.
|
|
645
|
-
|
|
646
|
-
### `history` — what happened, kept without growing your records
|
|
647
|
-
|
|
648
|
-
Keep **current state** in records (a bin's quantity, an order's status) and **what happened** in the app's
|
|
649
|
-
history: append-only events in SmartLinks' analytics store, kept for good, cheap however many there
|
|
650
|
-
are. Picking every order line for years would bloat records; as history it costs nothing operational.
|
|
651
|
-
|
|
652
|
-
```ts
|
|
653
|
-
// In a transaction: commits with the stock change, or not at all.
|
|
654
|
-
await ctx.sl.transaction([
|
|
655
|
-
{ op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
|
|
656
|
-
{ op: 'log', type: 'stock.moved', entityId: binA, data: { sku: 'EDP-50', from: 'A1', to: orderId, qty: 5 } },
|
|
657
|
-
], { idempotencyKey: scanId })
|
|
658
|
-
|
|
659
|
-
// On its own:
|
|
660
|
-
await ctx.sl.history.log('count.taken', { bin: 'A1', counted: 40, expected: 42 }, { entityId: binA })
|
|
661
|
-
|
|
662
|
-
// Reading back: this app's events in this collection, newest first (default last 30 days, max 400).
|
|
663
|
-
const moves = await ctx.sl.history.query({ types: 'stock.moved', entityId: binA, limit: 20 })
|
|
664
|
-
// → [{ id, at, type, entityId, data, actorType, actorId }]
|
|
665
|
-
```
|
|
666
|
-
|
|
667
|
-
- `type`: lowercase letters, digits and `. _ -` (`stock.moved`). `data`: up to 32 KB, so **log a summary**:
|
|
668
|
-
one line for "5 of EDP-50", not five; one line for an RFID count, not one per tag.
|
|
669
|
-
- Delivery takes seconds and is retried until it lands; a logged event is never lost. A query reads the
|
|
670
|
-
analytics store, so expect about a second: right for a history panel, not for a hot path.
|
|
671
|
-
- The person who called your function is recorded as the actor.
|
|
672
|
-
|
|
673
|
-
### `appRecords.aggregate(params)` — totals
|
|
674
|
-
|
|
675
|
-
Counts and sums over your app's records, worked out in the database:
|
|
676
|
-
|
|
677
|
-
```ts
|
|
678
|
-
await ctx.sl.appRecords.aggregate({
|
|
679
|
-
groupBy: ['data.location', 'data.sku'], // columns, or top-level data keys
|
|
680
|
-
metrics: ['count', 'sum:qty'], // sum: / avg: / min: / max: over data numbers
|
|
681
|
-
filters: { record_type: 'bin', data: { warehouse: 'north' }, dataRange: { qty: { gt: 0 } } },
|
|
682
|
-
})
|
|
683
|
-
// → { groups: [{ 'data.location': 'A1', 'data.sku': 'EDP-50', count: 3, sum_qty: 42 }, …] }
|
|
684
|
-
```
|
|
685
|
-
|
|
686
|
-
Non-numbers are ignored by `sum`/`avg`/`min`/`max`. The same request works from the browser through
|
|
687
|
-
`app.records.aggregate` (admin) — see [app-objects.md](app-objects.md).
|
|
688
|
-
|
|
689
|
-
### `tags.resolve(id)` — is this tap real?
|
|
690
|
-
|
|
691
|
-
A tap hands your app the virtual-proof id `<claimSetId>-<code>`. `resolve` returns
|
|
692
|
-
`{ id, claimSetId, code }` when that code exists in a claim set of **this** collection, else `null`.
|
|
693
|
-
Key records to the returned canonical `id`, and refuse `null` — otherwise anyone can invent ids.
|
|
694
|
-
|
|
695
|
-
### `contacts.upsert(details)` / `contacts.forCaller()`
|
|
696
|
-
|
|
697
|
-
`upsert` finds the contact by `email` or `phone` (one is required) or creates it, and only **fills
|
|
698
|
-
empty fields** — it never overwrites a name or field the contact already has, because a visitor's typed
|
|
699
|
-
details are unverified. It's race-safe: two simultaneous entries with one email end on one contact.
|
|
700
|
-
Returns `{ contactId, created }`. `forCaller()` is the signed-in caller's own contact (`null` when
|
|
701
|
-
anonymous): `{ contactId, email, phone, firstName, lastName, displayName, tags, customFields }`. Use it
|
|
702
|
-
to check what a member is before returning member-only content — a level the staff set
|
|
703
|
-
(`customFields.level`), a tag. It includes staff-only fields, so return only what the caller may see
|
|
704
|
-
(see members.md). **Never return contact ids to public callers** — keep them on your records.
|
|
705
|
-
|
|
706
|
-
This is not consent. A ticked "keep me updated" box is evidence you can record (below); subscribing
|
|
707
|
-
someone to marketing is the double opt-in flow (`comms.signup`, see comms.md).
|
|
708
|
-
|
|
709
|
-
### `interactions.record(event)` — "they did X"
|
|
710
|
-
|
|
711
|
-
Records an event of one of **your app's interaction types**: create the type once in admin with
|
|
712
|
-
`SL.interactions.ensureType(collectionId, { appId, key: 'raffle-entry' })`, keep its id in your app
|
|
713
|
-
config, and pass that id. Unknown ids are refused (`INTERACTION_TYPE_NOT_FOUND`). The event runs the
|
|
714
|
-
type's effects and emits `interaction.submitted`, like any submission.
|
|
715
|
-
|
|
716
|
-
```ts
|
|
717
|
-
await ctx.sl.interactions.record({
|
|
718
|
-
interactionId: config.interactionIds.entered,
|
|
719
|
-
contactId, // optional
|
|
720
|
-
outcome: 'entered',
|
|
721
|
-
metadata: { number, consent: true },
|
|
722
|
-
})
|
|
723
|
-
```
|
|
724
|
-
|
|
725
|
-
### `bookings.*` — places and time that can't be oversold
|
|
726
|
-
|
|
727
|
-
`ctx.sl.bookings` is your app's own bookings, slots and blocks (`sl:bookings:read` / `write`). A
|
|
728
|
-
function books **admin-side**: any status, the admin zone, any contact — your app's public booking
|
|
729
|
-
rules (`publicCreate.bookings`) don't apply, because the function *is* your rules. The platform still
|
|
730
|
-
guarantees no overbooking and no overlapping time, so a clash throws (`code`: `SLOT_FULL`,
|
|
731
|
-
`RESOURCE_TAKEN`, `PER_CONTACT_LIMIT`, `HOLD_EXPIRED`, …; with `status` and `details`). Pass an
|
|
732
|
-
`idempotencyKey` so a retried request returns the first booking (`replayed: true`).
|
|
733
|
-
|
|
734
|
-
```ts
|
|
735
|
-
const me = await ctx.sl.contacts.forCaller()
|
|
736
|
-
if (!me) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
737
|
-
try {
|
|
738
|
-
const booking = await ctx.sl.bookings.create({
|
|
739
|
-
slotId: body.slotId, quantity: body.quantity, contactId: me.contactId,
|
|
740
|
-
status: 'held', holdMinutes: 15, idempotencyKey: body.requestId,
|
|
741
|
-
})
|
|
742
|
-
return Response.json({ id: booking.id, holdExpiresAt: booking.holdExpiresAt })
|
|
743
|
-
} catch (e: any) {
|
|
744
|
-
if (e.code === 'SLOT_FULL') return Response.json({ error: 'sold out', remaining: e.details?.remaining }, { status: 409 })
|
|
745
|
-
throw e
|
|
746
|
-
}
|
|
747
|
-
```
|
|
748
|
-
|
|
749
|
-
`ctx.sl.bookings.message({ templateId, slotId | from, to, resourceType?, resourceId?, channel? })` sends a
|
|
750
|
-
template to everyone booked (each hydrated with their own booking) — the five-line reminder cron:
|
|
751
|
-
|
|
752
|
-
```ts
|
|
753
|
-
// manifest: { name: 'remind', trigger: { type: 'cron', schedule: '0 17 * * *' }, capabilities: ['sl:bookings:write'] }
|
|
754
|
-
export async function remind(ctx) {
|
|
755
|
-
const from = new Date(); from.setDate(from.getDate() + 1); from.setHours(0, 0, 0, 0)
|
|
756
|
-
const to = new Date(from); to.setDate(to.getDate() + 1)
|
|
757
|
-
return ctx.sl.bookings.message({ templateId: 'bp.' + ctx.collectionId + '.reminder', from, to })
|
|
758
|
-
}
|
|
759
|
-
```
|
|
760
|
-
|
|
761
|
-
The local harness runs bookings in memory with the same rules (capacity, per-person limits, no
|
|
762
|
-
overlaps, idempotency, holds): `ctx.memory.bookings`.
|
|
763
|
-
|
|
764
|
-
---
|
|
765
|
-
|
|
766
|
-
## Platform tools — PDFs, labels, barcodes
|
|
767
|
-
|
|
768
|
-
`ctx.sl.tools.run(name, args)` runs one of the platform's deterministic tools from your function: no
|
|
769
|
-
model, no agent loop. Declare each tool as a capability: `tools:pdf.create`, or `tools:pdf.*` for the
|
|
770
|
-
whole family. Open to functions: `pdf.create`, `pdf.merge`, `pdf.fill`, `pdf.inspect`, `pdf.render`,
|
|
771
|
-
`pdf.decodeBarcodes`, `pdf.inspectGraphics`, `pdf.preflight`, `pdf.printReady`, `pdf.edit`,
|
|
772
|
-
`image.transform`, `image.ocr`, and `pdf.extract` (a PDF + a JSON schema → its fields; it calls a model, so it is refused when the collection's AI budget is used up) (arguments as in [ai.md](ai.md)). A site's server code may use them too.
|
|
773
|
-
|
|
774
|
-
- **Identity:** the call runs as the function's collection, whatever the caller. An anonymous caller
|
|
775
|
-
holding only your own key gets the same result; the work is attributed and billed to the collection.
|
|
776
|
-
- **Rate:** per collection (10 calls a second by default); bursts wait rather than fail.
|
|
777
|
-
- **Failure:** throws an `Error` with `code` (`bad_args`, `too_large`, `too_many_pages`,
|
|
778
|
-
`resource_timeout`, `timeout`, `busy`, `TOOL_NOT_AVAILABLE`, or a capability denial).
|
|
779
|
-
|
|
780
|
-
**Labels with `pdf.create`.** Exact page sizes, many pages in one render, and bytes straight back:
|
|
781
|
-
|
|
782
|
-
```ts
|
|
783
|
-
// capabilities: ["tools:pdf.create", "tools:pdf.decodeBarcodes"]
|
|
784
|
-
export async function printLabel(ctx, event) {
|
|
785
|
-
const { gtin, lot, expiry, qty = 1 } = event.body
|
|
786
|
-
const barcode = bwipjs.toSVG({ bcid: 'gs1-128', text: `(01)${gtin}(10)${lot}(17)${expiry}` }) // inline SVG
|
|
787
|
-
const pdf = await ctx.sl.tools.run('pdf.create', {
|
|
788
|
-
width: 100, height: 50, unit: 'mm', // exact; output is 1:1
|
|
789
|
-
head: '<style>.l{position:absolute;font:3mm Arial}</style>',
|
|
790
|
-
pages: Array.from({ length: qty }, () => `<div class="l" style="left:4mm;top:3mm">Lot ${lot}</div>
|
|
791
|
-
<div style="position:absolute;left:4mm;top:10mm;width:92mm">${barcode}</div>`),
|
|
792
|
-
return: 'base64', // or 'signedUrl' + expiresIn
|
|
793
|
-
})
|
|
794
|
-
return { pdf: pdf.base64, pages: pdf.pageCount }
|
|
795
|
-
}
|
|
796
|
-
```
|
|
797
|
-
|
|
798
|
-
- **Page size:** `width` + `height` (+ `unit`: mm, cm, in, pt, px) is exact to the point. Otherwise
|
|
799
|
-
`format` ("A4", "Letter"), or the document's own CSS `@page { size }` when neither is given.
|
|
800
|
-
- **Pages:** `pages: [html, …]` lays one fragment per page; with an exact size and no margin each page
|
|
801
|
-
box is that size (overflow hidden), so a long value can't push onto the next label. Up to 2000 pages
|
|
802
|
-
and 10 MB of HTML per render.
|
|
803
|
-
- **Output:** 1:1 at scale 1 with backgrounds; text stays text and SVG stays vector (render barcodes as
|
|
804
|
-
inline SVG, e.g. bwip-js `toSVG`, never as a canvas bitmap). Colour is RGB; for CMYK pass the result
|
|
805
|
-
through `pdf.printReady`.
|
|
806
|
-
- **What loads:** JavaScript does not run. Images, fonts and stylesheets load only from SmartLinks hosts
|
|
807
|
-
(our CDN), Google Fonts or inline `data:` URIs; anything else is skipped and listed in `warnings`.
|
|
808
|
-
Embed brand fonts as `data:` URIs in `@font-face`, or host them on the SmartLinks CDN.
|
|
809
|
-
- **Delivery:** `return: 'base64'` (nothing stored), `'signedUrl'` (private link that expires after
|
|
810
|
-
`expiresIn` seconds, default 900, max 7 days — use this for anything with lot, expiry or serial
|
|
811
|
-
data), or `'url'` (public and permanent — artwork and documents meant to be shared).
|
|
812
|
-
- **Cache:** the same inputs return the earlier render without rendering again (`cached: true`).
|
|
813
|
-
- **Verify:** `pdf.decodeBarcodes` on a `signedUrl` reads the codes back deterministically, so you can
|
|
814
|
-
confirm the digits before answering.
|
|
815
|
-
|
|
816
|
-
## Files — `ctx.sl.assets`
|
|
817
|
-
|
|
818
|
-
The collection's assets are its lasting files: a record per file, kept as long as the asset is. Server
|
|
819
|
-
code reads them (a PDF to parse, a photo to check) and saves what it makes (a job sheet, a label, a
|
|
820
|
-
report) as assets of its own app. Declare `sl:assets:read` or `sl:assets:write`, with **collection
|
|
821
|
-
authority** (an asset belongs to the collection, not to a visitor).
|
|
822
|
-
|
|
823
|
-
```ts
|
|
824
|
-
// capabilities: ["sl:assets:write", "tools:pdf.create"], authority: "collection"
|
|
825
|
-
const pdf = await ctx.sl.tools.run('pdf.create', { format: 'A4', html, return: 'base64' })
|
|
826
|
-
const sheet = await ctx.sl.assets.create({
|
|
827
|
-
name: `Job ${job.ref}.pdf`, contentType: 'application/pdf', base64: pdf.base64,
|
|
828
|
-
labels: ['job-sheet'], metadata: { workOrderId: job.id },
|
|
829
|
-
})
|
|
830
|
-
// later: the bytes back
|
|
831
|
-
const { base64, contentType } = await ctx.sl.assets.read(sheet.id)
|
|
832
|
-
```
|
|
833
|
-
|
|
834
|
-
- **Reads see every asset** in the collection: `get`, `list({ productId?, proofId?, appId?, labels? })`,
|
|
835
|
-
`read(id)` (base64, or `{ as: 'text' }`).
|
|
836
|
-
- **Writes act on this app's own assets only.** `create` stamps the asset with your app;
|
|
837
|
-
`replace(id, file)` keeps the old file as a version (same id, same `assetUrl`); `update(id, { name,
|
|
838
|
-
labels, metadata })`; `remove(id)`. Changing another app's asset is refused (`NOT_YOURS`).
|
|
839
|
-
- **Size.** `read`, `create` and `replace` carry the file as base64, so up to **7 MB**. Bigger files go
|
|
840
|
-
straight to storage, never through SmartLinks:
|
|
841
|
-
|
|
842
|
-
```ts
|
|
843
|
-
// capabilities add: "network:storage.googleapis.com"
|
|
844
|
-
const { uploadId, sessionUrl } = await ctx.sl.assets.startUpload({ name: 'line-3.mp4', contentType: 'video/mp4' })
|
|
845
|
-
await ctx.fetch(sessionUrl, { method: 'PUT', body: bytes }) // one request, or chunks with Content-Range
|
|
846
|
-
const video = await ctx.sl.assets.finishUpload(uploadId)
|
|
847
|
-
```
|
|
848
|
-
|
|
849
|
-
To read a large file, fetch its `url` (declare the CDN host, `network:cdn.smartlinks.app`).
|
|
850
|
-
- **Who can open the file.** An asset's file is served from the CDN under an unguessable address, as
|
|
851
|
-
every asset is. Keep the address to the people who should have it.
|
|
852
|
-
|
|
853
|
-
##
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
```ts
|
|
860
|
-
// capabilities: ["sl:
|
|
861
|
-
const
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
})
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
-
|
|
872
|
-
-
|
|
873
|
-
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
and
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
```
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
`
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
2.
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1
|
+
# Server functions ("edge functions")
|
|
2
|
+
|
|
3
|
+
> **SmartLinks SDK 2.x** (current `latest`). Part of the installable-app platform
|
|
4
|
+
> (author → register → install → run → test). Install `@proveanything/smartlinks@^2`.
|
|
5
|
+
|
|
6
|
+
A **server function** is arbitrary server-side JavaScript your app deploys directly into
|
|
7
|
+
SmartLinks. It runs on the SmartLinks servers — with access to the full SDK, to your app's
|
|
8
|
+
secrets, and to outbound network — so you can do things a browser app can't: validate and
|
|
9
|
+
write on the server, call third-party systems with credentials the client never sees, react
|
|
10
|
+
to events, and run scheduled work.
|
|
11
|
+
|
|
12
|
+
Every server function has the **same shape**, no matter how it's triggered or where it runs:
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
export async function myFunction(ctx, event) {
|
|
16
|
+
// ctx — a SmartLinks SDK pre-scoped to your declared authority, plus secrets, caller, fetch, log
|
|
17
|
+
// event — the trigger payload (the HTTP body, the event, or the cron tick)
|
|
18
|
+
return { ok: true } // returned to the caller (http) or recorded as the run result (event/cron)
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You never receive a raw API key or a superuser client. The platform builds `ctx` fresh for
|
|
23
|
+
each invocation and **pre-scopes every handle to exactly what your function declared** — this
|
|
24
|
+
is how a function stays safe even when it runs with elevated authority.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## Declaring a function
|
|
29
|
+
|
|
30
|
+
Functions are declared in your `app.manifest.json` under `functions`, and the handlers ship
|
|
31
|
+
in a bundle alongside your widgets/containers:
|
|
32
|
+
|
|
33
|
+
```jsonc
|
|
34
|
+
{
|
|
35
|
+
"functions": {
|
|
36
|
+
"files": { "js": { "umd": "functions.umd.js" } },
|
|
37
|
+
"definitions": [
|
|
38
|
+
{
|
|
39
|
+
"name": "submitCompetitionEntry",
|
|
40
|
+
"description": "Validate a competition entry and record it server-side.",
|
|
41
|
+
"trigger": { "type": "http", "methods": ["POST"] },
|
|
42
|
+
"visibility": "public", // WHO may call it
|
|
43
|
+
"authority": "collection", // WHOSE authority it runs as
|
|
44
|
+
"elevated": true, // required ack for public + collection
|
|
45
|
+
"capabilities": ["sl:records:write", "network:api.recaptcha.net"],
|
|
46
|
+
"apiVersion": "2026-09"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
"name": "onProofCreated",
|
|
50
|
+
"trigger": { "type": "event", "eventTypes": ["proof.created"] },
|
|
51
|
+
"capabilities": ["sl:records:write", "secrets:crm-key", "network"]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"name": "nightlyReconcile",
|
|
55
|
+
"trigger": { "type": "cron", "schedule": "0 2 * * *" },
|
|
56
|
+
"capabilities": ["sl:products:read", "sl:records:write"]
|
|
57
|
+
}
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Each definition maps to an exported handler of the same `name` (override with `handler`).
|
|
64
|
+
|
|
65
|
+
## Building the functions bundle
|
|
66
|
+
|
|
67
|
+
The handlers ship as a **self-contained UMD** — one file, all dependencies compiled in, no
|
|
68
|
+
`require`/`import` of platform or Node modules (see [Runtime](#runtime--what-your-function-can-use)).
|
|
69
|
+
Your functions entry just **named-exports** each handler:
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
// src/functions/index.js — the functions entry
|
|
73
|
+
export async function submitCompetitionEntry(ctx, event) { /* … */ }
|
|
74
|
+
export async function onProofCreated(ctx, event) { /* … */ }
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Build it to `dist/functions.umd.js` with a Vite lib build — **UMD format, nothing externalised**
|
|
78
|
+
(so it's self-contained), and don't wipe the widgets you built into the same `dist/`:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
// vite.functions.config.ts
|
|
82
|
+
import { defineConfig } from 'vite'
|
|
83
|
+
export default defineConfig({
|
|
84
|
+
build: {
|
|
85
|
+
lib: { entry: 'src/functions/index.js', formats: ['umd'], name: 'functions',
|
|
86
|
+
fileName: () => 'functions.umd.js' },
|
|
87
|
+
outDir: 'dist',
|
|
88
|
+
emptyOutDir: false, // co-exist with the widgets/containers build
|
|
89
|
+
rollupOptions: { external: [] } // bundle everything — no Node/platform externals
|
|
90
|
+
},
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
```jsonc
|
|
95
|
+
// package.json — build widgets/containers as usual, then the functions bundle
|
|
96
|
+
"scripts": {
|
|
97
|
+
"build": "vite build && vite build --config vite.functions.config.ts"
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
That emits `dist/functions.umd.js`, whose named exports the platform pairs with your manifest
|
|
102
|
+
`definitions`. In the manifest, `functions.files.js.umd` is **`functions.umd.js`** — relative to the
|
|
103
|
+
published build (the contents of `dist/`), like the widget and container files; not
|
|
104
|
+
`dist/functions.umd.js`. Publishing refuses a release whose functions bundle isn't there.
|
|
105
|
+
|
|
106
|
+
Then **deploy** it — for dev, `smartlinks-publish` uploads `dist/` and registers in one step (see
|
|
107
|
+
[Deploying & registering](deploying-apps.md)).
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## The two security questions every function answers
|
|
112
|
+
|
|
113
|
+
Server-side code needs two questions answered up front. SmartLinks makes both **explicit and
|
|
114
|
+
declarative** — you state them in the manifest, and the platform enforces them. This is the
|
|
115
|
+
same split every extensible platform lands on (Salesforce `with/without sharing`, Shopify
|
|
116
|
+
online/offline tokens, Lambda's invoke-policy vs execution-role).
|
|
117
|
+
|
|
118
|
+
### 1. `visibility` — who is allowed to call it? *(http only)*
|
|
119
|
+
|
|
120
|
+
| Value | Meaning |
|
|
121
|
+
|---|---|
|
|
122
|
+
| `admin` *(default)* | Callable only from an authenticated admin surface. |
|
|
123
|
+
| `public` | Publicly callable — no authenticated user required. |
|
|
124
|
+
|
|
125
|
+
### 2. `authority` — whose authority does it run as?
|
|
126
|
+
|
|
127
|
+
This decides what `ctx.sl` can do.
|
|
128
|
+
|
|
129
|
+
| Value | `ctx.sl` is scoped to | Use when |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `caller` *(default)* | The **invoking user** (their session/JWT). Can only do what that user could. | Admin actions that should respect the user's own permissions and be attributed to them. |
|
|
132
|
+
| `collection` | A **collection-admin principal for _this_ collection only** — never a global superuser. | A privileged server-side action a public/anonymous caller can't be trusted to do directly. |
|
|
133
|
+
|
|
134
|
+
`authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
|
|
135
|
+
functions have no external caller, so they always run as `collection`.
|
|
136
|
+
|
|
137
|
+
### Limiting it to some people: `userGroups`
|
|
138
|
+
|
|
139
|
+
An `http` function can name the [user groups](user-groups.md) allowed to call it:
|
|
140
|
+
|
|
141
|
+
```jsonc
|
|
142
|
+
"userGroups": ["qc-controller", "manager"] // the caller must be in at least one
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The platform checks this before your code runs. A signed-in caller in none of them gets
|
|
146
|
+
`403 NOT_IN_USER_GROUP`; an anonymous one gets `401 SIGN_IN_REQUIRED`; a collection admin always
|
|
147
|
+
passes. Inside any function, `ctx.caller.userGroups` lists the caller's own keys for finer rules.
|
|
148
|
+
`userGroups` doesn't replace `elevated: true` on a `public` + `collection` function.
|
|
149
|
+
|
|
150
|
+
### The combinations
|
|
151
|
+
|
|
152
|
+
- **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
|
|
153
|
+
- **`http` + `public` + `caller`** — runs as the anonymous/public user (limited). The safe public default.
|
|
154
|
+
- **`http` + `public` + `collection`** — publicly callable, runs with collection authority.
|
|
155
|
+
The powerful one (e.g. "submit competition entry" needs to validate then write a record no
|
|
156
|
+
anonymous user may write directly). **Your responsibility:** validate the input and prevent
|
|
157
|
+
abuse — see below.
|
|
158
|
+
- **`event` / `cron`** — background work; runs as `collection`.
|
|
159
|
+
|
|
160
|
+
> ### ⚠️ Public + collection authority is the sharp edge
|
|
161
|
+
> A `public` + `collection` function is reachable by anyone and runs with elevated authority.
|
|
162
|
+
> The platform shrinks the blast radius for you — the authority is capped to **this one
|
|
163
|
+
> collection**, and further capped by your declared **capabilities** (a competition-entry
|
|
164
|
+
> function that declares only `sl:records:write` cannot delete products or read other
|
|
165
|
+
> secrets, even though it's "elevated"). But **validating the request is still your job**:
|
|
166
|
+
> check the payload, rate-limit using `ctx.caller`, guard against replay. Treat the function
|
|
167
|
+
> body as a trust boundary.
|
|
168
|
+
>
|
|
169
|
+
> Because it's the sharp edge, a `public` + `collection` function must **explicitly opt in**
|
|
170
|
+
> with `elevated: true` in its declaration — a conscious acknowledgment that you're exposing
|
|
171
|
+
> collection authority to public callers. Without it, install/validation fails.
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## Capabilities — least privilege, declared and capped
|
|
176
|
+
|
|
177
|
+
`capabilities` is the allow-list of what your function may reach. It is surfaced at install
|
|
178
|
+
time for consent and **enforced at runtime** — including for `collection`-authority functions.
|
|
179
|
+
Declare the minimum you need.
|
|
180
|
+
|
|
181
|
+
| Capability | Grants |
|
|
182
|
+
|---|---|
|
|
183
|
+
| `sl:<resource>:read` / `sl:<resource>:write` | SDK access to that resource, e.g. `sl:products:read`, `sl:records:write`, `sl:attestations:write`, `sl:contacts:write`, `sl:bookings:write`. |
|
|
184
|
+
| `network` | `ctx.fetch` to any host. |
|
|
185
|
+
| `network:<host>` | `ctx.fetch` to that host only (repeat for several). Prefer this over blanket `network`. |
|
|
186
|
+
| `network:*.<domain>` | `ctx.fetch` to any subdomain of `<domain>` (not `<domain>` itself), for a customer's own endpoint at a provider, e.g. `network:*.servicebus.windows.net`. `<domain>` needs at least two labels (`*.com` is not honoured). |
|
|
187
|
+
| `secrets:<name>` | `ctx.secrets.get('<name>')` for that one secret (see [Secrets](#secrets--api-keys-per-collection)). |
|
|
188
|
+
| `tools:<name>` / `tools:<family>.*` | `ctx.sl.tools.run('<name>', args)` for a platform tool, e.g. `tools:pdf.create`, or `tools:pdf.*` for every PDF tool (see [Platform tools](#platform-tools--pdfs-labels-barcodes)). |
|
|
189
|
+
|
|
190
|
+
If you don't declare `network`, `ctx.fetch` is absent. Reading a secret you didn't declare with
|
|
191
|
+
`secrets:<name>` throws.
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## The `ctx` object
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
interface ServerFunctionContext {
|
|
199
|
+
collectionId: string
|
|
200
|
+
appId: string
|
|
201
|
+
|
|
202
|
+
/** SmartLinks SDK, pre-scoped to your declared `authority`. Capabilities cap what it may do.
|
|
203
|
+
* Key resources: `sl.appRecords` (per-app records, incl. race-safe `claim`), `sl.appData`
|
|
204
|
+
* (general/app-wide config + data — URLs, flags, arrays), `sl.counters` (atomic numbering),
|
|
205
|
+
* `sl.tags`, `sl.contacts`, `sl.interactions`, `sl.products`, `sl.attestations`. */
|
|
206
|
+
sl: SmartLinks
|
|
207
|
+
|
|
208
|
+
/** Capability-gated secrets (need `secrets:<name>`). `get(name)` reads this app's own secret on the
|
|
209
|
+
* collection first, then the app-level one; `app(name)` reads the app-level secret only. */
|
|
210
|
+
secrets: { get(ref: string): Promise<string | null>; app(ref: string): Promise<string | null> }
|
|
211
|
+
|
|
212
|
+
/** Who invoked this function. */
|
|
213
|
+
caller: {
|
|
214
|
+
userId: string | null // null for anonymous/public/system calls
|
|
215
|
+
anonymous: boolean
|
|
216
|
+
origin?: string | null // http
|
|
217
|
+
ip?: string | null // http
|
|
218
|
+
via: 'http' | 'event' | 'cron'
|
|
219
|
+
userGroups: readonly string[] // keys of the user groups the caller is in ([] when anonymous)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
|
|
223
|
+
fetch: typeof fetch
|
|
224
|
+
|
|
225
|
+
/** Structured logging — returned inline on the admin surface and recorded as an
|
|
226
|
+
* execution activity event (owner Errors & Activity console). See "Seeing your
|
|
227
|
+
* function's runs and logs" below. */
|
|
228
|
+
log: (message: string, data?: Record<string, any>) => void
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
**Use `ctx.sl` for anything SmartLinks** — it is the same SDK surface you use client-side,
|
|
233
|
+
already authenticated as your declared authority and scoped to the collection. Do **not** try
|
|
234
|
+
to construct your own SDK client or carry your own key; that's what `ctx.sl` is for, and it's
|
|
235
|
+
the only way authority stays correct.
|
|
236
|
+
|
|
237
|
+
### Calling a function from your app (client side)
|
|
238
|
+
|
|
239
|
+
From a page/UI, invoke an `http`-trigger function with the SDK — no manual fetch, no URL building:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
// public function (runs on the caller's authority — signed-in owner, else public):
|
|
243
|
+
const res = await SL.functions.call(collectionId, 'increment', { /* becomes event.body */ })
|
|
244
|
+
// admin surface (needs an admin session):
|
|
245
|
+
const res = await SL.functions.callAdmin(collectionId, 'recomputeTotals', { … })
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
`res` is whatever your handler returns. See the `edge-function-test` example for a full page +
|
|
249
|
+
function + manifest.
|
|
250
|
+
|
|
251
|
+
#### Functions are ALWAYS app-scoped
|
|
252
|
+
|
|
253
|
+
A function belongs to an app, so the canonical route carries the appId:
|
|
254
|
+
`POST /collection/:collectionId/app/:appId/functions/:name`. Two different installed apps can each
|
|
255
|
+
ship a function of the same name without clashing.
|
|
256
|
+
|
|
257
|
+
The SDK fills the appId in for you. Initialize with your app's id once, then call by bare name —
|
|
258
|
+
the SDK routes it app-scoped:
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
SL.initializeApi({ baseURL, appId: 'my-counter-app' }) // usually done by the host/bootstrap
|
|
262
|
+
await SL.functions.call(collectionId, 'pressCounter') // → /collection/:c/app/my-counter-app/functions/pressCounter
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
To call a *different* app's function, pass the appId explicitly:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
await SL.functions.call(collectionId, 'pressCounter', {}, { appId: 'some-other-app' })
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
**Where it runs.** A function runs on a collection when the app is **installed** there (enabled in
|
|
272
|
+
the collection's apps); or the app is **restricted** to a list of collections (what publishing from
|
|
273
|
+
Forge sets for every developer) and this collection is on it, e.g. your own sandbox; or the app is
|
|
274
|
+
**public**, meaning a registered app with no restriction list, which only platform admins can
|
|
275
|
+
publish. Anything else gets `404 APP_NOT_INSTALLED`: a function can run with the collection's own
|
|
276
|
+
authority and secrets, so a developer's app can't reach a collection that hasn't taken it on.
|
|
277
|
+
|
|
278
|
+
**Who may run server code at all.** Until functions move to an isolated runner, only TRUSTED apps
|
|
279
|
+
execute: public (unrestricted) apps, or apps a platform admin has marked `functionsTrusted: true`.
|
|
280
|
+
Developer apps — restricted to their own collections, which includes every app published from
|
|
281
|
+
self-serve Forge — get `403 FUNCTIONS_NOT_ENABLED` until they're trusted. A platform admin can also
|
|
282
|
+
switch any app's functions off with `functionsTrusted: false`.
|
|
283
|
+
|
|
284
|
+
**Which release.** With no channel, the server runs the release the collection has **installed** (stable for a
|
|
285
|
+
public app that isn't installed) — what production wants, so app code just calls `SL.functions.call(collectionId, name)`. To run
|
|
286
|
+
another release, the channel goes **in the path**: `/app/:appId/<dev|alpha|beta|stable>/functions/:name`.
|
|
287
|
+
The SDK adds it for you when the host tells the app which channel it's running as — Forge's preview
|
|
288
|
+
of a Test build passes `appChannel=dev` in the app's context, so the same code calls the dev build
|
|
289
|
+
there and the installed build in production. You can also set it yourself:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
SL.initializeApi({ baseURL, appId: 'my-counter-app', appChannel: 'dev' }) // whole app
|
|
293
|
+
await SL.functions.call(collectionId, 'pressCounter', {}, { channel: 'beta' }) // one call
|
|
294
|
+
await SL.functions.call(collectionId, 'pressCounter', {}, { channel: null }) // force the installed release
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
**Public address on the collection's own site (webhooks, integrations).** Every collection has a
|
|
298
|
+
site host — `<name>.smartlinks.host` once a name is claimed, else `c-<collectionId>.smartlinks.host` —
|
|
299
|
+
returned as `collection.siteHost`. App functions are reachable there:
|
|
300
|
+
|
|
301
|
+
```
|
|
302
|
+
https://<siteHost>/_fn/<appId>[/<channel>]/<function>[/<sub-path…>]
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
```ts
|
|
306
|
+
const col = await SL.collection.get(collectionId)
|
|
307
|
+
const webhookUrl = SL.functions.siteUrl(col, 'stripeWebhook', { appId: 'my-shop' })
|
|
308
|
+
// → https://acme.smartlinks.host/_fn/my-shop/stripeWebhook (give this to Stripe)
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Built for integrations: **every HTTP method** the function declares in `trigger.methods` (default
|
|
312
|
+
POST only), **any content type** with the exact bytes in `event.rawBody` (verify signatures with
|
|
313
|
+
`crypto.subtle`), **sub-paths** after the name when the function declares `trigger.path` (`"/*"`, or a
|
|
314
|
+
pattern like `"/orders/:id"` → `event.params.id`), and the function's own `Response` — status, headers,
|
|
315
|
+
CORS — goes back unchanged (the platform adds no CORS headers there; declare `OPTIONS` and answer
|
|
316
|
+
preflights yourself if browsers call you cross-origin). Bodies up to 6 MB.
|
|
317
|
+
|
|
318
|
+
```js
|
|
319
|
+
// manifest: { name: 'orders', trigger: { type: 'http', methods: ['GET', 'PUT'], path: '/orders/:id' }, visibility: 'public' }
|
|
320
|
+
export async function orders(ctx, event) {
|
|
321
|
+
if (event.method === 'GET') return ctx.sl.appRecords.get(event.params.id)
|
|
322
|
+
// PUT: verify the sender first — e.g. an HMAC over event.rawBody with a secret
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
Security: the platform never hands a caller's SmartLinks credential to function code (if it signed
|
|
327
|
+
the caller in from `Authorization`, that header is removed and you get `ctx.caller`); your OWN
|
|
328
|
+
`Authorization` scheme for webhooks passes through. `siteUrl` only includes a channel you ask for —
|
|
329
|
+
point production webhooks at the bare address and test ones at `/dev/`.
|
|
330
|
+
|
|
331
|
+
The channel is never a query parameter: the function owns its query string (`?channel=sms` reaches
|
|
332
|
+
your handler untouched), and a configured URL — a webhook, a third-party callback — can only ever
|
|
333
|
+
hit the channel it names. Point production webhooks at the bare path and test ones at `/dev/`.
|
|
334
|
+
|
|
335
|
+
If no appId is available (not set on init, none passed), the call falls back to the **deprecated
|
|
336
|
+
flat path** `/collection/:c/functions/:name`, which searches only the collection's **enabled** apps,
|
|
337
|
+
resolves by bare name, and **rejects with `409 AMBIGUOUS_FUNCTION`** when more than one defines that
|
|
338
|
+
name (a first-party builtin still wins). Always prefer an appId.
|
|
339
|
+
|
|
340
|
+
> There is no such thing as an app-less function. First-party builtins (e.g. the `functions.ping`
|
|
341
|
+
> diagnostic) belong to the reserved `smartlinks` app. A "global" function is just an app enabled on
|
|
342
|
+
> the `global` collection and called at `/collection/global/app/:appId/functions/:name` — same two
|
|
343
|
+
> facets (collection + app), with `global` as the sentinel collection.
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
## Inputs — data handed to your function
|
|
348
|
+
|
|
349
|
+
Declare what your function needs and the platform fetches it **before** the run: read it from `ctx.inputs` instead of calling `ctx.sl` first. One less round trip — and for functions running in the isolated runner, one less network hop.
|
|
350
|
+
|
|
351
|
+
```jsonc
|
|
352
|
+
// app.manifest.json → functions.definitions[]
|
|
353
|
+
{
|
|
354
|
+
"name": "onProductChanged",
|
|
355
|
+
"trigger": { "type": "event", "eventTypes": ["product.updated"] },
|
|
356
|
+
"capabilities": ["sl:products:read", "sl:data:read"],
|
|
357
|
+
"inputs": { "appConfig": true } // entity is on by default for event triggers
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
```js
|
|
362
|
+
export async function onProductChanged(ctx, event) {
|
|
363
|
+
const product = ctx.inputs.entity // the product that changed
|
|
364
|
+
const { interactionIds } = ctx.inputs.appConfig || {} // this app's config for the collection
|
|
365
|
+
}
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
| Input | What you get | Needs | Triggers |
|
|
369
|
+
|---|---|---|---|
|
|
370
|
+
| `entity` | The record the event is about: the product, your app's record, or the interaction event. **On by default**; `"entity": false` opts out. | read on that resource (`sl:products:read`, `sl:records:read`) | event |
|
|
371
|
+
| `collection` | The collection's public record | — | all |
|
|
372
|
+
| `appConfig` | Your app's config for this collection (where setup like `interactionIds` lives) | `sl:data:read` | all |
|
|
373
|
+
| `product` | A product named by the request: `{ "from": "body.productId" }`, `"query.<field>"` or `"path"` | `sl:products:read` | http |
|
|
374
|
+
|
|
375
|
+
- **Same rules as `ctx.sl`.** Inputs are fetched with your function's authority and capabilities, scoped to the collection it runs in — a product from another collection is never fetched.
|
|
376
|
+
- **Never an error.** Not found, not allowed or larger than 256 KB → that input is `null`. Check before you use it.
|
|
377
|
+
- **Current state.** Event inputs are fetched when your function runs, so you see the record as it is now; `event` still carries the ids.
|
|
378
|
+
- **Checked at publish.** An unknown input, a bad `from`, or a missing capability fails validation.
|
|
379
|
+
- **Testing:** pass `inputs` to the test context — `createFunctionTestContext({ def, inputs: { entity: { id: 'p1', name: 'Kettle' } } })`.
|
|
380
|
+
|
|
381
|
+
## Exposing a function to the AI agent
|
|
382
|
+
|
|
383
|
+
An `http` function can be offered to the AI agent as a **callable tool**, alongside the built-in
|
|
384
|
+
tools. The model calls it, the server runs it, and the result is fed back into the loop. Opt in from
|
|
385
|
+
the manifest with an `agent` block (full reference: [agent-tools.md](agent-tools.md)):
|
|
386
|
+
|
|
387
|
+
```jsonc
|
|
388
|
+
{
|
|
389
|
+
"name": "getLoyaltyBalance",
|
|
390
|
+
"trigger": { "type": "http" },
|
|
391
|
+
"visibility": "admin",
|
|
392
|
+
"authority": "caller",
|
|
393
|
+
"capabilities": ["sl:records:read"],
|
|
394
|
+
"agent": {
|
|
395
|
+
"tool": true,
|
|
396
|
+
"title": "Loyalty balance",
|
|
397
|
+
"description": "Look up a member's current loyalty points balance.",
|
|
398
|
+
"input": {
|
|
399
|
+
"type": "object",
|
|
400
|
+
"properties": { "memberId": { "type": "string" } },
|
|
401
|
+
"required": ["memberId"]
|
|
402
|
+
},
|
|
403
|
+
"approval": "auto" // 'require' = human confirms before each call
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
The agent becomes **just another caller surface** — your function's `visibility`, `authority`, and
|
|
409
|
+
`capabilities` are enforced exactly as on the http route. Nothing new is granted. The agent's tool
|
|
410
|
+
arguments arrive as the function's request `body`, and whatever you return becomes the tool result the
|
|
411
|
+
model sees. `approval: "require"` tools are held back from the autonomous server-side loop until the
|
|
412
|
+
human-approval UX ships.
|
|
413
|
+
|
|
414
|
+
Include your app's functions in an agent run:
|
|
415
|
+
|
|
416
|
+
```ts
|
|
417
|
+
// Agentic Responses:
|
|
418
|
+
await SL.ai.chat.responses.create(collectionId, {
|
|
419
|
+
model: 'balanced', input: 'What is member 42's balance?',
|
|
420
|
+
server_tools: true, // built-in tools
|
|
421
|
+
app_functions: { appId: 'my-loyalty-app' }, // + this app's ai.tool functions
|
|
422
|
+
})
|
|
423
|
+
|
|
424
|
+
// Or the one-shot agent loop:
|
|
425
|
+
await SL.ai.agent.run(collectionId, {
|
|
426
|
+
input: '…', appFunctions: { appId: 'my-loyalty-app' },
|
|
427
|
+
})
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
On the **consumer surface**, a `visibility: "public"` function reaches a public assistant via the
|
|
431
|
+
public agent loop — the caller runs as the signed-in consumer (`'owner'`, send the authKit bearer) or
|
|
432
|
+
anonymous (`'public'`):
|
|
433
|
+
|
|
434
|
+
```ts
|
|
435
|
+
await SL.ai.publicClient.agentRun(collectionId, {
|
|
436
|
+
input: '…',
|
|
437
|
+
appFunctions: { appId: 'my-app' }, // this app's public agent tools
|
|
438
|
+
server_tools: ['web.search'], // built-ins are an explicit allowlist on the public surface
|
|
439
|
+
})
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
`channel` (default `'stable'`, pass `'dev'` to test a dev build) and `only: string[]` narrow which
|
|
443
|
+
functions are exposed. Only `http` functions with `agent.tool: true` are eligible; `event`/`cron`
|
|
444
|
+
functions never are. A built-in tool of the same name wins the clash.
|
|
445
|
+
|
|
446
|
+
### One unified toolbelt
|
|
447
|
+
|
|
448
|
+
Rather than juggling `server_tools` + `app_functions`, declare everything in one `toolbelt` — built-in
|
|
449
|
+
tools, one **or several** apps' functions, and (reserved, staged) front-end client tools:
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
await SL.ai.chat.responses.create(collectionId, {
|
|
453
|
+
input: '…',
|
|
454
|
+
toolbelt: {
|
|
455
|
+
builtins: ['web.search', 'document.read'], // true = all, [names] = subset, omit = none
|
|
456
|
+
appFunctions: [{ appId: 'loyalty' }, { appId: 'catalog' }], // several apps at once
|
|
457
|
+
// clientTools: [ … ] // reserved — the client-tool bridge is staged
|
|
458
|
+
},
|
|
459
|
+
})
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
The same `toolbelt` works on `ai.agent.run` and `ai.publicClient.agentRun` (on the public surface
|
|
463
|
+
`builtins` is an explicit allowlist — `true` is treated as none). Precedence on a name clash: a
|
|
464
|
+
built-in wins, then earlier `appFunctions` sources win over later ones.
|
|
465
|
+
|
|
466
|
+
> Directly (no model): every function is also callable deterministically — `SL.functions.call` /
|
|
467
|
+
> `callAdmin` (above), the same way the built-in tools are callable via `SL.ai.tools.run`.
|
|
468
|
+
|
|
469
|
+
---
|
|
470
|
+
|
|
471
|
+
## Runtime — what your function can use
|
|
472
|
+
|
|
473
|
+
Your function runs in a **web-standard sandbox** (think Cloudflare Workers / Deno), **not
|
|
474
|
+
Node**. Concretely it targets the **WinterTC Minimum Common Web Platform API** (WinterTC is the
|
|
475
|
+
Ecma International technical committee for this, formerly WinterCG) — the same surface those
|
|
476
|
+
runtimes guarantee — so what you can rely on is portable, and the future isolated runner will
|
|
477
|
+
host the same bundle unchanged.
|
|
478
|
+
|
|
479
|
+
**Available globals** (no import needed):
|
|
480
|
+
- **Data / encoding:** `JSON`, `URL`, `URLSearchParams`, `TextEncoder` / `TextDecoder`,
|
|
481
|
+
`atob` / `btoa`, `Buffer`, `structuredClone`.
|
|
482
|
+
- **Crypto:** `crypto` (Web Crypto) — `crypto.subtle` for hashing / HMAC / encrypt / sign /
|
|
483
|
+
verify, `crypto.getRandomValues`, `crypto.randomUUID`.
|
|
484
|
+
- **HTTP:** `fetch`, `Headers`, `Request`, `Response`, `FormData`, `Blob`, `File`,
|
|
485
|
+
`AbortController` / `AbortSignal` (use one for **request timeouts**).
|
|
486
|
+
- **Streams & timing:** `ReadableStream` / `WritableStream` / `TransformStream`,
|
|
487
|
+
`CompressionStream` / `DecompressionStream` (gzip/deflate for third-party payloads), the timer
|
|
488
|
+
functions, `queueMicrotask`, `performance`, `console`.
|
|
489
|
+
- **Runtime identity:** `navigator.userAgent` reports the runtime key (currently
|
|
490
|
+
`"SmartLinks-Functions"`) — use it if a portable dependency needs to feature-detect the host.
|
|
491
|
+
It stays stable when functions move to the isolated runner.
|
|
492
|
+
|
|
493
|
+
**Not available:** `require` / `import` of platform or Node modules, `process`, `fs`, and the
|
|
494
|
+
Node built-ins (`node:crypto`, `node:http`, …). There is no ambient database, key, or network
|
|
495
|
+
handle — everything the platform gives you comes through **`ctx`**.
|
|
496
|
+
|
|
497
|
+
**Dependencies:** bundle them. Your build must produce a **self-contained** UMD (deps compiled
|
|
498
|
+
in), and those deps must be **edge-compatible** — pure JS / Web APIs. A library that reaches for
|
|
499
|
+
Node built-ins (e.g. `axios`'s Node adapter, anything using `node:crypto`) will fail to load.
|
|
500
|
+
Prefer the platform primitives above over a dependency; when you do need one, pick edge-safe:
|
|
501
|
+
|
|
502
|
+
| Need | Native? | Recommended (bundle, edge-safe) |
|
|
503
|
+
|---|---|---|
|
|
504
|
+
| JSON | **native** — `JSON.parse/stringify` | — |
|
|
505
|
+
| XML parse / build | no | `fast-xml-parser` |
|
|
506
|
+
| CSV | no | `papaparse` |
|
|
507
|
+
| Schema validation of inputs | no | `zod` |
|
|
508
|
+
| JWT (sign/verify for a third-party API) | Web Crypto can, verbosely | `jose` |
|
|
509
|
+
| Hash / HMAC / encrypt | **native** — `crypto.subtle` | — |
|
|
510
|
+
| PDF **text** extraction (cheap first-pass, no AI) | no | `unpdf` — a serverless/WASM pdf.js build with no Node deps; `import { extractText } from 'unpdf'`. Text only. |
|
|
511
|
+
|
|
512
|
+
> **PDFs in a server function:** for a cheap text-layer check use `unpdf` (edge-safe, WASM). For
|
|
513
|
+
> anything heavier — rendering pages, vision extraction, **barcode/QR decode**, or prepress/spot-colour
|
|
514
|
+
> inspection, **OCR of small print** — call the platform tools `pdf.render` / `pdf.extract` /
|
|
515
|
+
> `pdf.decodeBarcodes` / `pdf.inspectGraphics` / `image.ocr` via `ai.tools.run`; those run in the full
|
|
516
|
+
> platform runtime, not the sandbox.
|
|
517
|
+
|
|
518
|
+
**The common actions, and how to do each:**
|
|
519
|
+
|
|
520
|
+
| You want to… | Use | Requires |
|
|
521
|
+
|---|---|---|
|
|
522
|
+
| Call a third-party API (GET/POST) | `ctx.fetch(url, init)` — the standard Fetch API | capability `network` or `network:<host>` |
|
|
523
|
+
| Read a secret (API key, signing key) | `await ctx.secrets.get('<ref>')` | capability `secrets:<ref>` |
|
|
524
|
+
| Hash / HMAC-sign / verify / encrypt | `crypto.subtle` (Web Crypto) | — |
|
|
525
|
+
| Random id / bytes | `crypto.randomUUID()` / `crypto.getRandomValues()` | — |
|
|
526
|
+
| Read or write SmartLinks data | `ctx.sl.*` (records, products, attestations, …) | the matching `sl:<res>:<read\|write>` |
|
|
527
|
+
| Read/write your app's own data (config, URLs, counters, arrays) | `ctx.sl.appData.get()` / `ctx.sl.appData.set({…})` — collection-scoped by default; `ctx.sl.appData.global.*` (or `{ scope:'global' }`, or declare `dataScope:'global'`) for the app-wide bucket. It's your OWN namespace, so **any** authority may read/write it | `sl:data:read` / `sl:data:write` |
|
|
528
|
+
| Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
|
|
529
|
+
| Guarantee a UNIQUE claim (one entry per tag, one-per-user, idempotency key, a number nobody else holds) | `ctx.sl.appRecords.claim({ …, singletonPer, customId })` → `{ record, created, conflict? }` — see below | `sl:records:write` |
|
|
530
|
+
| Hand out the next number (tickets, order numbers) | `ctx.sl.counters.next('tickets')` — atomic, distinct per caller | `sl:data:write` |
|
|
531
|
+
| Track a job through its stages (a production job, a repair, a fulfilment) | `ctx.sl.workOrders` — the shared work order; stages, holds, progress → `operations.md` | `sl:workorders:write` |
|
|
532
|
+
| Know how much of something there is and where; move, allocate, hold or count it | `ctx.sl.stock` — quantities in containers, changed by movements, never below zero → `operations.md` | `sl:stock:write` |
|
|
533
|
+
| Ask whether you will run short, and when | `ctx.sl.stock.position({ productId, horizonDays })` — on hand, on order, being made, needed, first short day | `sl:stock:read` |
|
|
534
|
+
| Say what a product is made of, or what a batch really used | `ctx.sl.boms`, `ctx.sl.madeFrom` → `operations.md` | `sl:boms:write`, `sl:madefrom:write` |
|
|
535
|
+
| Change numbers in a record (stock, counts, balances) without losing updates | `ctx.sl.appRecords.adjust(id, { qty: -5 }, { atLeast: { qty: 0 } })` — in place, conditions checked after the change | `sl:records:write` |
|
|
536
|
+
| Several record writes that land together or not at all (a stock move) | `ctx.sl.transaction([ops], { idempotencyKey })` — see below | `sl:records:write` |
|
|
537
|
+
| Totals: stock per location, forecast per SKU | `ctx.sl.appRecords.aggregate({ groupBy: ['data.location'], metrics: ['sum:qty'] })` | `sl:records:read` |
|
|
538
|
+
| Keep a history of what happened (stock moves, counts) without growing your records | `ctx.sl.history.log('stock.moved', {…})`, or a `log` op in a transaction; read with `ctx.sl.history.query({…})` | `sl:history:write` / `sl:history:read` |
|
|
539
|
+
| Check a tapped tag is real | `ctx.sl.tags.resolve(proofId)` → `{ id, claimSetId, code }` or `null` | `sl:tags:read` |
|
|
540
|
+
| Put a visitor's details on a contact | `ctx.sl.contacts.upsert({ email, firstName, … })` → `{ contactId, created }` (fills empty fields only) | `sl:contacts:write` |
|
|
541
|
+
| Record "they did X" | `ctx.sl.interactions.record({ interactionId, contactId, outcome, metadata })` | `sl:interactions:write` |
|
|
542
|
+
| Message one person: a confirmation, a reminder, a cancellation, an update | `ctx.sl.messages.send({ to: 'caller' \| contactId, templateId \| message: { subject, body }, about: { type, id, view?, params? } })` → `{ ok, channel }` or `{ ok: false, reason }` — their preferred channel, their opt-outs respected, logged with your app and what it's about; see [comms.md](comms.md#messaging-one-person-from-an-app) | `sl:messages:write` |
|
|
543
|
+
| Land a loyalty / CRM provider's view of a person (member id, tier, points, tags, external ids) | `ctx.sl.members.apply({ identity, contact?, loyalty?, tags?, externalIds? }, { provider })` → `{ contactId, op }` — matches by id, external id, email or phone; profile fields fill-empty only; see [connectors.md](connectors.md#loyalty-and-crm-connectors) | `sl:members:write` |
|
|
544
|
+
| Invoke a connector's action — redeem, enrol, issue a coupon, raise a ticket — with the connector's credentials | `ctx.sl.connectors.call('acme-loyalty', 'redeem', { rewardId })` → the action's result; `ctx.sl.connectors.actions(appId)` lists them; see [connectors.md](connectors.md#actions-provider-operations-on-demand) | `sl:connectors:write` |
|
|
545
|
+
| Ask "is this person gold or above?" without holding their member record | `ctx.sl.entitlements.check('tier>=gold')` → `{ allowed, basis, asOf, attributes }` for the signed-in caller (or `{ identity, token, fallback }`); see [entitlements.md](entitlements.md) | `sl:entitlements:read` |
|
|
546
|
+
| Take a booking with your own checks (hours, queue token, payment) | `ctx.sl.bookings.create({ slotId \| resource + time, contactId, status, idempotencyKey })` — never oversold, never double-booked; also `confirm` / `cancel` / `move` / `mine` / `freebusy` / `message` (everyone booked, hydrated) / `slots.*` / `blocks.*` (see [bookings.md](bookings.md)) | `sl:bookings:write` (`sl:bookings:read` to read) |
|
|
547
|
+
|
|
548
|
+
Notes:
|
|
549
|
+
- **Talking to the SmartLinks core is `ctx.sl`, not HTTP.** The common pattern — *validate /
|
|
550
|
+
process, then act on the core* — is: check the input, then call `ctx.sl.appRecords.create(…)`,
|
|
551
|
+
`ctx.sl.products.update(…)`, etc. `ctx.sl` is already authenticated as your declared authority
|
|
552
|
+
and capped by your capabilities, so you never construct a SmartLinks API URL or carry a key.
|
|
553
|
+
Use `fetch`/`ctx.fetch` for *third-party* servers; use `ctx.sl` for SmartLinks itself.
|
|
554
|
+
- **There is one `fetch`, and it is capability-gated.** Whether you call the global `fetch` or
|
|
555
|
+
`ctx.fetch`, the behaviour is identical: the call **throws** unless your declared `network`
|
|
556
|
+
(or `network:<host>`) capability covers the target host — the same way Deno's `fetch` throws
|
|
557
|
+
without `--allow-net`. There is no ungated escape hatch. Declare the hosts you need.
|
|
558
|
+
- **Secrets are read-only at runtime.** You fetch a secret you declared; you do **not** set or
|
|
559
|
+
rotate secrets from a function — that's an admin/deploy-time operation on the platform.
|
|
560
|
+
- **Signing a webhook / verifying a signature** is `crypto.subtle` with an HMAC key imported
|
|
561
|
+
from a secret — no Node `crypto` needed.
|
|
562
|
+
|
|
563
|
+
---
|
|
564
|
+
|
|
565
|
+
## Uniqueness, numbering and people — the race-safe primitives
|
|
566
|
+
|
|
567
|
+
A public function is called by many people at once. These primitives make the outcome right no matter
|
|
568
|
+
how the calls interleave — the **database** decides, never a read-then-write in your code.
|
|
569
|
+
|
|
570
|
+
### `appRecords.claim(fields)` — a unique create
|
|
571
|
+
|
|
572
|
+
Like `create`, but the record names a **unique key**, and it's inserted only if that key is free.
|
|
573
|
+
Otherwise you get the record already holding it back, **unchanged** (never updated):
|
|
574
|
+
|
|
575
|
+
```ts
|
|
576
|
+
const { record, created, conflict } = await ctx.sl.appRecords.claim({
|
|
577
|
+
recordType: 'entry',
|
|
578
|
+
singletonPer: 'proof', proofId: tag.id, // key 1: one live entry per tag
|
|
579
|
+
customId: String(number), // key 2: one record per number, ever
|
|
580
|
+
data: { number },
|
|
581
|
+
})
|
|
582
|
+
// created: true → you got it
|
|
583
|
+
// created: false → conflict 'singleton' (this tag already has an entry: `record` is it)
|
|
584
|
+
// or 'customId' (that number is held by someone else: take another)
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
- **`singletonPer`** — `'collection' | 'product' | 'variant' | 'batch' | 'proof'`, with its anchor id
|
|
588
|
+
(`productId`, `proofId`, …). One **live** record per key; deleting it frees the key.
|
|
589
|
+
- **`customId`** — unique per `(recordType, scopeType, scopeId, sourceSystem)`, case-insensitive, and
|
|
590
|
+
**never reused** (deleted records keep theirs). Right for numbers that must never be handed out twice.
|
|
591
|
+
- Give at least one; with both, the record is created only if both are free.
|
|
592
|
+
- Of any number of concurrent claims on one key, **exactly one** gets `created: true`.
|
|
593
|
+
|
|
594
|
+
### `counters.next(name, { start?, by? })` — the next number
|
|
595
|
+
|
|
596
|
+
An atomic counter for your app in this collection: every caller gets a distinct value, even under a
|
|
597
|
+
burst (one row, incremented in one statement). The first call returns `start` (default 1). Counters only
|
|
598
|
+
move forward and live apart from your config, so no config save can rewind one. `counters.get(name)`
|
|
599
|
+
reads the last value handed out (`null` before the first). Name a new counter to start again from `start`.
|
|
600
|
+
|
|
601
|
+
**Counter + claim = a number nobody else can ever hold.** Take `next()`, then `claim` with
|
|
602
|
+
`customId: String(n)`. If the claim says `conflict: 'customId'`, take `next()` again. A failed or raced
|
|
603
|
+
attempt only leaves a gap — never a duplicate.
|
|
604
|
+
|
|
605
|
+
### `appRecords.adjust(id, by, { atLeast?, atMost? })` — numbers that never lose an update
|
|
606
|
+
|
|
607
|
+
Adds to numbers in a record's `data` in ONE statement, so twenty scanners taking from the same bin at
|
|
608
|
+
once each land: no read-then-write, no lost counts. A missing value counts as 0. `atLeast` / `atMost` are
|
|
609
|
+
checked on the values **after** the change, inside the same statement:
|
|
610
|
+
|
|
611
|
+
```ts
|
|
612
|
+
// Take 5 from bin A — refused (nothing changes) if it would go below zero.
|
|
613
|
+
await ctx.sl.appRecords.adjust(binA, { qty: -5 }, { atLeast: { qty: 0 } })
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
Refusals carry `code`: `NOT_FOUND` (not this app's record in this collection, or deleted), `NOT_A_NUMBER`
|
|
617
|
+
(the key holds something else), `CONDITION_FAILED` (409, with the `current` values). Only top-level data
|
|
618
|
+
keys; a key named only in a condition is checked as it stands.
|
|
619
|
+
|
|
620
|
+
### `transaction(ops, { idempotencyKey? })` — all or nothing
|
|
621
|
+
|
|
622
|
+
Several writes as ONE transaction: every op lands, or none does. The classic: take stock out of bin A,
|
|
623
|
+
put it on order line B, and log the move.
|
|
624
|
+
|
|
625
|
+
```ts
|
|
626
|
+
const { results, replayed } = await ctx.sl.transaction([
|
|
627
|
+
{ op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
|
|
628
|
+
{ op: 'adjust', recordId: orderLineB, by: { picked: 5 } },
|
|
629
|
+
{ op: 'create', record: { recordType: 'movement', data: { from: binA, to: orderLineB, qty: 5 } } },
|
|
630
|
+
], { idempotencyKey: scanId })
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
- Ops: `create` (`record`), `update` (`recordId`, `fields`), `adjust` (`recordId`, `by`, `atLeast?`,
|
|
634
|
+
`atMost?`), `delete` (`recordId`), `log` (`type`, `data`, `entityId?`: a history event, see below).
|
|
635
|
+
Up to 50, run in order. This app's records in this collection only.
|
|
636
|
+
- A failing op rolls everything back. The error says which op (`opIndex`) and why (its `code`).
|
|
637
|
+
- Change events and realtime updates go out only after the transaction commits, never for a rollback.
|
|
638
|
+
- **`idempotencyKey`** ("this was already done"): recorded in the same commit, with what was written
|
|
639
|
+
(ids only). The same key again within 7 days doesn't write; it returns those records as they are now,
|
|
640
|
+
with `replayed: true`. So a handheld that retries after a dropped signal never moves stock twice. Two
|
|
641
|
+
calls with one key at the same moment: one commits, the other replays it. A transaction that failed
|
|
642
|
+
leaves its key free, so a retry can still succeed.
|
|
643
|
+
- Use the scan's or the request's own id as the key (one key = one intended change).
|
|
644
|
+
- Browser code never writes stock directly: a warehouse screen calls your function.
|
|
645
|
+
|
|
646
|
+
### `history` — what happened, kept without growing your records
|
|
647
|
+
|
|
648
|
+
Keep **current state** in records (a bin's quantity, an order's status) and **what happened** in the app's
|
|
649
|
+
history: append-only events in SmartLinks' analytics store, kept for good, cheap however many there
|
|
650
|
+
are. Picking every order line for years would bloat records; as history it costs nothing operational.
|
|
651
|
+
|
|
652
|
+
```ts
|
|
653
|
+
// In a transaction: commits with the stock change, or not at all.
|
|
654
|
+
await ctx.sl.transaction([
|
|
655
|
+
{ op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
|
|
656
|
+
{ op: 'log', type: 'stock.moved', entityId: binA, data: { sku: 'EDP-50', from: 'A1', to: orderId, qty: 5 } },
|
|
657
|
+
], { idempotencyKey: scanId })
|
|
658
|
+
|
|
659
|
+
// On its own:
|
|
660
|
+
await ctx.sl.history.log('count.taken', { bin: 'A1', counted: 40, expected: 42 }, { entityId: binA })
|
|
661
|
+
|
|
662
|
+
// Reading back: this app's events in this collection, newest first (default last 30 days, max 400).
|
|
663
|
+
const moves = await ctx.sl.history.query({ types: 'stock.moved', entityId: binA, limit: 20 })
|
|
664
|
+
// → [{ id, at, type, entityId, data, actorType, actorId }]
|
|
665
|
+
```
|
|
666
|
+
|
|
667
|
+
- `type`: lowercase letters, digits and `. _ -` (`stock.moved`). `data`: up to 32 KB, so **log a summary**:
|
|
668
|
+
one line for "5 of EDP-50", not five; one line for an RFID count, not one per tag.
|
|
669
|
+
- Delivery takes seconds and is retried until it lands; a logged event is never lost. A query reads the
|
|
670
|
+
analytics store, so expect about a second: right for a history panel, not for a hot path.
|
|
671
|
+
- The person who called your function is recorded as the actor.
|
|
672
|
+
|
|
673
|
+
### `appRecords.aggregate(params)` — totals
|
|
674
|
+
|
|
675
|
+
Counts and sums over your app's records, worked out in the database:
|
|
676
|
+
|
|
677
|
+
```ts
|
|
678
|
+
await ctx.sl.appRecords.aggregate({
|
|
679
|
+
groupBy: ['data.location', 'data.sku'], // columns, or top-level data keys
|
|
680
|
+
metrics: ['count', 'sum:qty'], // sum: / avg: / min: / max: over data numbers
|
|
681
|
+
filters: { record_type: 'bin', data: { warehouse: 'north' }, dataRange: { qty: { gt: 0 } } },
|
|
682
|
+
})
|
|
683
|
+
// → { groups: [{ 'data.location': 'A1', 'data.sku': 'EDP-50', count: 3, sum_qty: 42 }, …] }
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
Non-numbers are ignored by `sum`/`avg`/`min`/`max`. The same request works from the browser through
|
|
687
|
+
`app.records.aggregate` (admin) — see [app-objects.md](app-objects.md).
|
|
688
|
+
|
|
689
|
+
### `tags.resolve(id)` — is this tap real?
|
|
690
|
+
|
|
691
|
+
A tap hands your app the virtual-proof id `<claimSetId>-<code>`. `resolve` returns
|
|
692
|
+
`{ id, claimSetId, code }` when that code exists in a claim set of **this** collection, else `null`.
|
|
693
|
+
Key records to the returned canonical `id`, and refuse `null` — otherwise anyone can invent ids.
|
|
694
|
+
|
|
695
|
+
### `contacts.upsert(details)` / `contacts.forCaller()`
|
|
696
|
+
|
|
697
|
+
`upsert` finds the contact by `email` or `phone` (one is required) or creates it, and only **fills
|
|
698
|
+
empty fields** — it never overwrites a name or field the contact already has, because a visitor's typed
|
|
699
|
+
details are unverified. It's race-safe: two simultaneous entries with one email end on one contact.
|
|
700
|
+
Returns `{ contactId, created }`. `forCaller()` is the signed-in caller's own contact (`null` when
|
|
701
|
+
anonymous): `{ contactId, email, phone, firstName, lastName, displayName, tags, customFields }`. Use it
|
|
702
|
+
to check what a member is before returning member-only content — a level the staff set
|
|
703
|
+
(`customFields.level`), a tag. It includes staff-only fields, so return only what the caller may see
|
|
704
|
+
(see members.md). **Never return contact ids to public callers** — keep them on your records.
|
|
705
|
+
|
|
706
|
+
This is not consent. A ticked "keep me updated" box is evidence you can record (below); subscribing
|
|
707
|
+
someone to marketing is the double opt-in flow (`comms.signup`, see comms.md).
|
|
708
|
+
|
|
709
|
+
### `interactions.record(event)` — "they did X"
|
|
710
|
+
|
|
711
|
+
Records an event of one of **your app's interaction types**: create the type once in admin with
|
|
712
|
+
`SL.interactions.ensureType(collectionId, { appId, key: 'raffle-entry' })`, keep its id in your app
|
|
713
|
+
config, and pass that id. Unknown ids are refused (`INTERACTION_TYPE_NOT_FOUND`). The event runs the
|
|
714
|
+
type's effects and emits `interaction.submitted`, like any submission.
|
|
715
|
+
|
|
716
|
+
```ts
|
|
717
|
+
await ctx.sl.interactions.record({
|
|
718
|
+
interactionId: config.interactionIds.entered,
|
|
719
|
+
contactId, // optional
|
|
720
|
+
outcome: 'entered',
|
|
721
|
+
metadata: { number, consent: true },
|
|
722
|
+
})
|
|
723
|
+
```
|
|
724
|
+
|
|
725
|
+
### `bookings.*` — places and time that can't be oversold
|
|
726
|
+
|
|
727
|
+
`ctx.sl.bookings` is your app's own bookings, slots and blocks (`sl:bookings:read` / `write`). A
|
|
728
|
+
function books **admin-side**: any status, the admin zone, any contact — your app's public booking
|
|
729
|
+
rules (`publicCreate.bookings`) don't apply, because the function *is* your rules. The platform still
|
|
730
|
+
guarantees no overbooking and no overlapping time, so a clash throws (`code`: `SLOT_FULL`,
|
|
731
|
+
`RESOURCE_TAKEN`, `PER_CONTACT_LIMIT`, `HOLD_EXPIRED`, …; with `status` and `details`). Pass an
|
|
732
|
+
`idempotencyKey` so a retried request returns the first booking (`replayed: true`).
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
const me = await ctx.sl.contacts.forCaller()
|
|
736
|
+
if (!me) return Response.json({ error: 'sign in' }, { status: 401 })
|
|
737
|
+
try {
|
|
738
|
+
const booking = await ctx.sl.bookings.create({
|
|
739
|
+
slotId: body.slotId, quantity: body.quantity, contactId: me.contactId,
|
|
740
|
+
status: 'held', holdMinutes: 15, idempotencyKey: body.requestId,
|
|
741
|
+
})
|
|
742
|
+
return Response.json({ id: booking.id, holdExpiresAt: booking.holdExpiresAt })
|
|
743
|
+
} catch (e: any) {
|
|
744
|
+
if (e.code === 'SLOT_FULL') return Response.json({ error: 'sold out', remaining: e.details?.remaining }, { status: 409 })
|
|
745
|
+
throw e
|
|
746
|
+
}
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
`ctx.sl.bookings.message({ templateId, slotId | from, to, resourceType?, resourceId?, channel? })` sends a
|
|
750
|
+
template to everyone booked (each hydrated with their own booking) — the five-line reminder cron:
|
|
751
|
+
|
|
752
|
+
```ts
|
|
753
|
+
// manifest: { name: 'remind', trigger: { type: 'cron', schedule: '0 17 * * *' }, capabilities: ['sl:bookings:write'] }
|
|
754
|
+
export async function remind(ctx) {
|
|
755
|
+
const from = new Date(); from.setDate(from.getDate() + 1); from.setHours(0, 0, 0, 0)
|
|
756
|
+
const to = new Date(from); to.setDate(to.getDate() + 1)
|
|
757
|
+
return ctx.sl.bookings.message({ templateId: 'bp.' + ctx.collectionId + '.reminder', from, to })
|
|
758
|
+
}
|
|
759
|
+
```
|
|
760
|
+
|
|
761
|
+
The local harness runs bookings in memory with the same rules (capacity, per-person limits, no
|
|
762
|
+
overlaps, idempotency, holds): `ctx.memory.bookings`.
|
|
763
|
+
|
|
764
|
+
---
|
|
765
|
+
|
|
766
|
+
## Platform tools — PDFs, labels, barcodes
|
|
767
|
+
|
|
768
|
+
`ctx.sl.tools.run(name, args)` runs one of the platform's deterministic tools from your function: no
|
|
769
|
+
model, no agent loop. Declare each tool as a capability: `tools:pdf.create`, or `tools:pdf.*` for the
|
|
770
|
+
whole family. Open to functions: `pdf.create`, `pdf.merge`, `pdf.fill`, `pdf.inspect`, `pdf.render`,
|
|
771
|
+
`pdf.decodeBarcodes`, `pdf.inspectGraphics`, `pdf.preflight`, `pdf.printReady`, `pdf.edit`,
|
|
772
|
+
`image.transform`, `image.ocr`, and `pdf.extract` (a PDF + a JSON schema → its fields; it calls a model, so it is refused when the collection's AI budget is used up) (arguments as in [ai.md](ai.md)). A site's server code may use them too.
|
|
773
|
+
|
|
774
|
+
- **Identity:** the call runs as the function's collection, whatever the caller. An anonymous caller
|
|
775
|
+
holding only your own key gets the same result; the work is attributed and billed to the collection.
|
|
776
|
+
- **Rate:** per collection (10 calls a second by default); bursts wait rather than fail.
|
|
777
|
+
- **Failure:** throws an `Error` with `code` (`bad_args`, `too_large`, `too_many_pages`,
|
|
778
|
+
`resource_timeout`, `timeout`, `busy`, `TOOL_NOT_AVAILABLE`, or a capability denial).
|
|
779
|
+
|
|
780
|
+
**Labels with `pdf.create`.** Exact page sizes, many pages in one render, and bytes straight back:
|
|
781
|
+
|
|
782
|
+
```ts
|
|
783
|
+
// capabilities: ["tools:pdf.create", "tools:pdf.decodeBarcodes"]
|
|
784
|
+
export async function printLabel(ctx, event) {
|
|
785
|
+
const { gtin, lot, expiry, qty = 1 } = event.body
|
|
786
|
+
const barcode = bwipjs.toSVG({ bcid: 'gs1-128', text: `(01)${gtin}(10)${lot}(17)${expiry}` }) // inline SVG
|
|
787
|
+
const pdf = await ctx.sl.tools.run('pdf.create', {
|
|
788
|
+
width: 100, height: 50, unit: 'mm', // exact; output is 1:1
|
|
789
|
+
head: '<style>.l{position:absolute;font:3mm Arial}</style>',
|
|
790
|
+
pages: Array.from({ length: qty }, () => `<div class="l" style="left:4mm;top:3mm">Lot ${lot}</div>
|
|
791
|
+
<div style="position:absolute;left:4mm;top:10mm;width:92mm">${barcode}</div>`),
|
|
792
|
+
return: 'base64', // or 'signedUrl' + expiresIn
|
|
793
|
+
})
|
|
794
|
+
return { pdf: pdf.base64, pages: pdf.pageCount }
|
|
795
|
+
}
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
- **Page size:** `width` + `height` (+ `unit`: mm, cm, in, pt, px) is exact to the point. Otherwise
|
|
799
|
+
`format` ("A4", "Letter"), or the document's own CSS `@page { size }` when neither is given.
|
|
800
|
+
- **Pages:** `pages: [html, …]` lays one fragment per page; with an exact size and no margin each page
|
|
801
|
+
box is that size (overflow hidden), so a long value can't push onto the next label. Up to 2000 pages
|
|
802
|
+
and 10 MB of HTML per render.
|
|
803
|
+
- **Output:** 1:1 at scale 1 with backgrounds; text stays text and SVG stays vector (render barcodes as
|
|
804
|
+
inline SVG, e.g. bwip-js `toSVG`, never as a canvas bitmap). Colour is RGB; for CMYK pass the result
|
|
805
|
+
through `pdf.printReady`.
|
|
806
|
+
- **What loads:** JavaScript does not run. Images, fonts and stylesheets load only from SmartLinks hosts
|
|
807
|
+
(our CDN), Google Fonts or inline `data:` URIs; anything else is skipped and listed in `warnings`.
|
|
808
|
+
Embed brand fonts as `data:` URIs in `@font-face`, or host them on the SmartLinks CDN.
|
|
809
|
+
- **Delivery:** `return: 'base64'` (nothing stored), `'signedUrl'` (private link that expires after
|
|
810
|
+
`expiresIn` seconds, default 900, max 7 days — use this for anything with lot, expiry or serial
|
|
811
|
+
data), or `'url'` (public and permanent — artwork and documents meant to be shared).
|
|
812
|
+
- **Cache:** the same inputs return the earlier render without rendering again (`cached: true`).
|
|
813
|
+
- **Verify:** `pdf.decodeBarcodes` on a `signedUrl` reads the codes back deterministically, so you can
|
|
814
|
+
confirm the digits before answering.
|
|
815
|
+
|
|
816
|
+
## Files — `ctx.sl.assets`
|
|
817
|
+
|
|
818
|
+
The collection's assets are its lasting files: a record per file, kept as long as the asset is. Server
|
|
819
|
+
code reads them (a PDF to parse, a photo to check) and saves what it makes (a job sheet, a label, a
|
|
820
|
+
report) as assets of its own app. Declare `sl:assets:read` or `sl:assets:write`, with **collection
|
|
821
|
+
authority** (an asset belongs to the collection, not to a visitor).
|
|
822
|
+
|
|
823
|
+
```ts
|
|
824
|
+
// capabilities: ["sl:assets:write", "tools:pdf.create"], authority: "collection"
|
|
825
|
+
const pdf = await ctx.sl.tools.run('pdf.create', { format: 'A4', html, return: 'base64' })
|
|
826
|
+
const sheet = await ctx.sl.assets.create({
|
|
827
|
+
name: `Job ${job.ref}.pdf`, contentType: 'application/pdf', base64: pdf.base64,
|
|
828
|
+
labels: ['job-sheet'], metadata: { workOrderId: job.id },
|
|
829
|
+
})
|
|
830
|
+
// later: the bytes back
|
|
831
|
+
const { base64, contentType } = await ctx.sl.assets.read(sheet.id)
|
|
832
|
+
```
|
|
833
|
+
|
|
834
|
+
- **Reads see every asset** in the collection: `get`, `list({ productId?, proofId?, appId?, labels? })`,
|
|
835
|
+
`read(id)` (base64, or `{ as: 'text' }`).
|
|
836
|
+
- **Writes act on this app's own assets only.** `create` stamps the asset with your app;
|
|
837
|
+
`replace(id, file)` keeps the old file as a version (same id, same `assetUrl`); `update(id, { name,
|
|
838
|
+
labels, metadata })`; `remove(id)`. Changing another app's asset is refused (`NOT_YOURS`).
|
|
839
|
+
- **Size.** `read`, `create` and `replace` carry the file as base64, so up to **7 MB**. Bigger files go
|
|
840
|
+
straight to storage, never through SmartLinks:
|
|
841
|
+
|
|
842
|
+
```ts
|
|
843
|
+
// capabilities add: "network:storage.googleapis.com"
|
|
844
|
+
const { uploadId, sessionUrl } = await ctx.sl.assets.startUpload({ name: 'line-3.mp4', contentType: 'video/mp4' })
|
|
845
|
+
await ctx.fetch(sessionUrl, { method: 'PUT', body: bytes }) // one request, or chunks with Content-Range
|
|
846
|
+
const video = await ctx.sl.assets.finishUpload(uploadId)
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
To read a large file, fetch its `url` (declare the CDN host, `network:cdn.smartlinks.app`).
|
|
850
|
+
- **Who can open the file.** An asset's file is served from the CDN under an unguessable address, as
|
|
851
|
+
every asset is. Keep the address to the people who should have it.
|
|
852
|
+
|
|
853
|
+
## Temporary and fetched files — `ctx.sl.files`
|
|
854
|
+
|
|
855
|
+
For files nobody browses: a page or a PDF fetched to read, what was read from it, a result to pass between steps.
|
|
856
|
+
They're private to your app, temporary unless kept, and never show in asset lists (see [files.md](files.md)).
|
|
857
|
+
Declare `sl:files:read` / `sl:files:write`.
|
|
858
|
+
|
|
859
|
+
```ts
|
|
860
|
+
// capabilities: ["sl:files:write"], authority: "collection"
|
|
861
|
+
const page = await ctx.sl.files.fetch('https://supplier.example/spec.pdf', { ttl: '7d' }) // cached by address
|
|
862
|
+
const { text } = await ctx.sl.files.extract(page.id, 'markdown') // read once, kept beside it
|
|
863
|
+
const { data } = await ctx.sl.files.extract(page.id, 'json', { schema }) // typed fields
|
|
864
|
+
const note = await ctx.sl.files.put({ name: 'step.json', data: { done: 2 }, ttl: '1d' })
|
|
865
|
+
const { url } = await ctx.sl.files.link(note.id, { minutes: 15 }) // a signed link
|
|
866
|
+
await ctx.sl.files.keep(page.id) // permanent + public
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
- `fetch(url, { ttl?, maxAge?, force? })`: the same address gives your app the same file while it's fresh; once
|
|
870
|
+
stale, an unchanged page isn't downloaded again. Public addresses only, up to 50 MB.
|
|
871
|
+
- `extract(id, 'text' | 'markdown' | 'ocr' | 'json', { schema?, prompt? })`: each file is read each way once.
|
|
872
|
+
- `get`, `read(id, { as: 'text' | 'base64' })`, `link`, `keep`, `remove`, `list({ origin?, derivedFromId? })`.
|
|
873
|
+
- `ttl` is `1h` to `30d` (default `1d`); a temporary file is removed when it expires.
|
|
874
|
+
|
|
875
|
+
## AI — `ctx.sl.ai`
|
|
876
|
+
|
|
877
|
+
`ctx.sl.ai.generate({ prompt, system?, files?, schema?, quality? })` asks a model. `files` are PDFs,
|
|
878
|
+
photos or text (`{ assetId }`, `{ base64, contentType }` or `{ text }`); with a `schema` (JSON
|
|
879
|
+
Schema) the answer is parsed into `data`. Declare `sl:ai:write`; any authority may use it.
|
|
880
|
+
|
|
881
|
+
```ts
|
|
882
|
+
// capabilities: ["sl:ai:write", "sl:assets:read"], authority: "collection"
|
|
883
|
+
const { data } = await ctx.sl.ai.generate({
|
|
884
|
+
prompt: 'Read this sales order.',
|
|
885
|
+
files: [{ assetId }],
|
|
886
|
+
schema: { type: 'object', properties: { salesOrderNumber: { type: 'string' }, lines: { type: 'array', items: { type: 'object', properties: { code: { type: 'string' }, qty: { type: 'number' } } } } } },
|
|
887
|
+
})
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
- **Budget, enforced.** Every call is recorded and priced against the collection and your app. When the
|
|
891
|
+
collection's monthly AI budget or credits are used up, the call throws `AI_BUDGET_EXCEEDED` /
|
|
892
|
+
`AI_CREDITS_EXHAUSTED` (402) before anything is spent. Catch it and tell the person plainly.
|
|
893
|
+
- **Quality.** `'fast'` (the default) is quick and cheap; `'best'` thinks harder and costs more.
|
|
894
|
+
- **Limits.** Up to 10 files and 7 MB in all; 5 calls a second per collection (bursts wait).
|
|
895
|
+
- **Failure.** `AI_BAD_JSON` (502) when the answer wasn't JSON of the shape asked for: try again, or ask
|
|
896
|
+
for less at once.
|
|
897
|
+
|
|
898
|
+
### Uploaded files on a site
|
|
899
|
+
|
|
900
|
+
In a site's own functions, a file posted to the function arrives intact: `event.rawBytes` holds the
|
|
901
|
+
exact bytes of any request, and a multipart form's files are in `event.files` as
|
|
902
|
+
`[{ field, filename, contentType, size, base64 }]` (its text fields in `event.body`). `base64` goes
|
|
903
|
+
straight into `ctx.sl.assets.create` or `ctx.sl.ai.generate`.
|
|
904
|
+
|
|
905
|
+
### Making an email attachment
|
|
906
|
+
|
|
907
|
+
A flow step can attach a file your function makes: `"attach": [{ "function": "receiptPdf" }]` in a
|
|
908
|
+
site's `cloud/flows.json` (or an app's blueprint). When the email goes, the platform calls your function
|
|
909
|
+
(your app's, in this collection, as the collection, like a connector step) with:
|
|
910
|
+
|
|
911
|
+
```ts
|
|
912
|
+
event.body = { purpose: 'attachment', eventType, interactionId, outcome, contactId, metadata, booking? } // booking: ready-formatted
|
|
913
|
+
```
|
|
914
|
+
|
|
915
|
+
and attaches what it returns:
|
|
916
|
+
|
|
917
|
+
```ts
|
|
918
|
+
// capabilities: ["tools:pdf.create"]
|
|
919
|
+
export async function receiptPdf(ctx, event) {
|
|
920
|
+
const b = event.body.booking
|
|
921
|
+
const pdf = await ctx.sl.tools.run('pdf.create', { format: 'A4', html: `<h1>Receipt</h1><p>${b.serviceName}, ${b.when.dateTime}</p>`, return: 'signedUrl' })
|
|
922
|
+
return { filename: `receipt-${b.id}.pdf`, file: pdf.url } // a private file you made
|
|
923
|
+
// or { filename, contentType: 'application/pdf', content: '<base64>' }, a list of those, or null for none
|
|
924
|
+
}
|
|
925
|
+
```
|
|
926
|
+
|
|
927
|
+
- Files: PDF, calendar (`.ics`), images, text / CSV and Office documents; at most 5 per email and 10 MB
|
|
928
|
+
in all. A private file must be one this platform made (`return: 'signedUrl'`), never an outside URL.
|
|
929
|
+
- If your function fails or returns something else, the email still goes without it (the reason is in
|
|
930
|
+
your function's runs).
|
|
931
|
+
- Other sources need no code: `"calendar"` (a booking event's calendar invite) and
|
|
932
|
+
`{ "asset": "<assetId>" }` (a file in the collection's assets) — see bookings.md, "Flows on booking events".
|
|
933
|
+
|
|
934
|
+
---
|
|
935
|
+
|
|
936
|
+
## Worked example — a public competition entry
|
|
937
|
+
|
|
938
|
+
```ts
|
|
939
|
+
// dist/functions — handler for the manifest definition above
|
|
940
|
+
export async function submitCompetitionEntry(ctx, event) {
|
|
941
|
+
const { name, email, answer, captchaToken } = event.body || {}
|
|
942
|
+
|
|
943
|
+
// 1. Validate — this is YOUR job on a public function.
|
|
944
|
+
if (!email || !answer) return { ok: false, error: 'missing_fields' }
|
|
945
|
+
|
|
946
|
+
// 2. Use a declared secret + declared host to verify a captcha.
|
|
947
|
+
const secret = await ctx.secrets.get('recaptcha-secret')
|
|
948
|
+
const verify = await ctx.fetch('https://api.recaptcha.net/verify', {
|
|
949
|
+
method: 'POST',
|
|
950
|
+
body: new URLSearchParams({ secret, response: captchaToken }),
|
|
951
|
+
}).then(r => r.json())
|
|
952
|
+
if (!verify.success) return { ok: false, error: 'captcha_failed' }
|
|
953
|
+
|
|
954
|
+
// 3. Write with collection authority — something an anonymous caller can't do directly.
|
|
955
|
+
const entry = await ctx.sl.appRecords.create({
|
|
956
|
+
recordType: 'competition-entry',
|
|
957
|
+
data: { name, email, answer, ip: ctx.caller.ip, submittedAt: new Date().toISOString() },
|
|
958
|
+
})
|
|
959
|
+
|
|
960
|
+
ctx.log('entry recorded', { entryId: entry.id })
|
|
961
|
+
return { ok: true, entryId: entry.id }
|
|
962
|
+
}
|
|
963
|
+
```
|
|
964
|
+
|
|
965
|
+
Declared as `public` + `collection` + `['sl:records:write', 'secrets:recaptcha-secret',
|
|
966
|
+
'network:api.recaptcha.net']`, this function is publicly callable, verifies the request
|
|
967
|
+
itself, and writes a record no anonymous user could write — but it cannot touch products,
|
|
968
|
+
other secrets, or any other collection.
|
|
969
|
+
|
|
970
|
+
---
|
|
971
|
+
|
|
972
|
+
## Secrets — API keys per collection
|
|
973
|
+
|
|
974
|
+
A function that calls another system needs that system's key, and each collection (each customer)
|
|
975
|
+
has its own. Your app's **admin screen** saves it; your **functions** read it by the same name.
|
|
976
|
+
|
|
977
|
+
**1. Declare it** on every function that reads it:
|
|
978
|
+
|
|
979
|
+
```jsonc
|
|
980
|
+
{ "name": "pullOrders", "trigger": { "type": "cron", "schedule": "0,30 * * * *" },
|
|
981
|
+
"capabilities": ["network:api.example-shop.com", "secrets:shop-api-key"] }
|
|
982
|
+
```
|
|
983
|
+
|
|
984
|
+
**2. Save it from your admin screen**, signed in as a collection admin:
|
|
985
|
+
|
|
986
|
+
```ts
|
|
987
|
+
await SL.secrets.put(collectionId, 'shop-api-key', apiKeyFromTheForm) // create or replace
|
|
988
|
+
const { secrets } = await SL.secrets.listOwn(collectionId) // names + masked hints, e.g. "••••1234"
|
|
989
|
+
await SL.secrets.removeOwn(collectionId, 'shop-api-key')
|
|
990
|
+
```
|
|
991
|
+
|
|
992
|
+
The app comes from the SDK's app context (`initializeApi({ appId })`), or pass `{ appId }` as the
|
|
993
|
+
last argument. Secrets are write-only: nothing ever returns the value, so show the hint ("saved,
|
|
994
|
+
ends 1234") and offer "replace", not "edit". Build this into your own settings screen; the platform
|
|
995
|
+
doesn't prompt for it at install.
|
|
996
|
+
|
|
997
|
+
**3. Read it in the function:**
|
|
998
|
+
|
|
999
|
+
```ts
|
|
1000
|
+
const key = await ctx.secrets.get('shop-api-key') // null until an admin has saved it
|
|
1001
|
+
if (!key) { ctx.log('shop not connected yet'); return { skipped: 'not connected' } }
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
**Each app's secrets are its own.** `shop-api-key` saved by your app and `shop-api-key` saved by
|
|
1005
|
+
another app on the same collection are two different secrets; your functions only ever read yours.
|
|
1006
|
+
|
|
1007
|
+
`ctx.secrets.get(name)` looks in this order:
|
|
1008
|
+
1. your app's secret on this collection (saved with `SL.secrets.put`);
|
|
1009
|
+
2. *SmartLinks' own apps only:* a collection-wide secret of that name. Third-party apps never read these;
|
|
1010
|
+
3. your app's shared, app-level secret (the same for every collection), if Forge has one for it.
|
|
1011
|
+
|
|
1012
|
+
Don't use `SL.secrets.set` for this. It creates a collection secret with a **generated** ref
|
|
1013
|
+
(`sec_…`) for integration flows, which a function can't name in its manifest.
|
|
1014
|
+
|
|
1015
|
+
---
|
|
1016
|
+
|
|
1017
|
+
## Scheduled functions (cron)
|
|
1018
|
+
|
|
1019
|
+
A `cron` function runs on a schedule, on **every collection that has the app installed**, with
|
|
1020
|
+
`collection` authority (there's no caller). It's the shape for polling another system ("pull new
|
|
1021
|
+
orders every 15 minutes"), nightly reconciles, digests and clean-ups.
|
|
1022
|
+
|
|
1023
|
+
```jsonc
|
|
1024
|
+
{
|
|
1025
|
+
"name": "pullOrders",
|
|
1026
|
+
"trigger": { "type": "cron", "schedule": "*/15 * * * *" },
|
|
1027
|
+
"capabilities": ["sl:records:write", "network:api.example-shop.com", "secrets:shop-api-key"]
|
|
1028
|
+
},
|
|
1029
|
+
{
|
|
1030
|
+
"name": "morningDigest",
|
|
1031
|
+
"trigger": { "type": "cron", "schedule": "0 9 * * MON-FRI", "timezone": "Europe/London" },
|
|
1032
|
+
"capabilities": ["sl:records:read", "network:hooks.slack.com", "secrets:slack-webhook"]
|
|
1033
|
+
}
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
- **`schedule`** — standard 5-field cron: minute, hour, day-of-month, month, day-of-week. Lists,
|
|
1037
|
+
ranges and steps (`0,30`, `9-17`, `*/15`), month and day names (`JAN`, `MON-FRI`; Sunday is 0 or 7),
|
|
1038
|
+
and `@hourly` / `@daily` / `@weekly` / `@monthly` / `@yearly`. When both day-of-month and
|
|
1039
|
+
day-of-week are restricted, a day matching either fires (as in cron).
|
|
1040
|
+
- **`timezone`** *(optional)* — an IANA zone like `"Europe/London"`; the schedule follows its
|
|
1041
|
+
summer time. Default UTC.
|
|
1042
|
+
- **At most every 5 minutes.** A faster schedule, a bad expression or an unknown zone fails the
|
|
1043
|
+
release (`SCHEDULE_INVALID`), so it never silently doesn't run.
|
|
1044
|
+
|
|
1045
|
+
**What runs:** each installation runs the current release of the channel it's installed on, so a
|
|
1046
|
+
test collection with the app on `dev` runs your dev build on its schedule. Disabled installs and
|
|
1047
|
+
expired dev installs don't run.
|
|
1048
|
+
|
|
1049
|
+
**The event** your handler receives:
|
|
1050
|
+
|
|
1051
|
+
```ts
|
|
1052
|
+
{ type: 'cron', schedule: '*/15 * * * *', timezone: null, scheduledAt: '2026-10-06T10:15:00.000Z' }
|
|
1053
|
+
```
|
|
1054
|
+
|
|
1055
|
+
`scheduledAt` is the minute the run was due, which is not always the moment it starts: runs queue,
|
|
1056
|
+
and a late one still carries its own minute. Use it, not `Date.now()`, as the end of the window
|
|
1057
|
+
you're syncing.
|
|
1058
|
+
|
|
1059
|
+
**Write it to be safe to run twice.** Each (collection, function, minute) is enqueued once, but a
|
|
1060
|
+
run that fails part-way can be retried, and a slow run can still be going when the next one starts.
|
|
1061
|
+
Keep a cursor (last `scheduledAt` or the other system's own cursor) in the app's records or config,
|
|
1062
|
+
and upsert by the other system's ID instead of inserting blindly.
|
|
1063
|
+
|
|
1064
|
+
Each run is logged like any other function run, and a failure shows in the collection's Errors view.
|
|
1065
|
+
|
|
1066
|
+
---
|
|
1067
|
+
|
|
1068
|
+
## Invoking an http function
|
|
1069
|
+
|
|
1070
|
+
An `http` function is called by POSTing to the app-scoped functions endpoint on the
|
|
1071
|
+
surface that matches its `visibility`:
|
|
1072
|
+
|
|
1073
|
+
```
|
|
1074
|
+
POST /admin/collection/:collectionId/app/:appId/functions/:name # visibility: admin (collection-admin auth)
|
|
1075
|
+
POST /public/collection/:collectionId/app/:appId/functions/:name # visibility: public (auth optional)
|
|
1076
|
+
GET /{admin|public}/collection/:collectionId/app/:appId/functions # list this app's functions on the surface
|
|
1077
|
+
POST /{admin|public}/collection/:collectionId/app/:appId/dev/functions/:name # a specific channel's release
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
Add a channel segment to run a specific release: `/app/:appId/dev/functions/:name` (also `alpha`,
|
|
1081
|
+
`beta`, `stable`; anything else is a 404). Without one, the collection's installed release runs.
|
|
1082
|
+
The app must be installed on the collection, on the app's restricted list, or a public app (see
|
|
1083
|
+
"Where it runs"); otherwise `404 APP_NOT_INSTALLED`.
|
|
1084
|
+
|
|
1085
|
+
The bare-name form (`/collection/:c/functions/:name`, no `/app/:appId`) is a **deprecated alias**:
|
|
1086
|
+
it searches only the collection's **enabled** apps, resolves by name, lets a first-party builtin
|
|
1087
|
+
win, and returns `409 AMBIGUOUS_FUNCTION` when two enabled apps define the same name. Prefer the
|
|
1088
|
+
app-scoped route (the SDK emits it automatically once an appId is set — see "Calling a function
|
|
1089
|
+
from your app").
|
|
1090
|
+
|
|
1091
|
+
The handler receives the request as `event`: `event.body` (parsed JSON), `event.query`,
|
|
1092
|
+
`event.headers`, `event.rawBody` (raw bytes, for XML/form/other inputs), and `event.contentType`.
|
|
1093
|
+
A function only runs on its own surface — calling an `admin` function on the public endpoint is a
|
|
1094
|
+
`403`. `GET` on either endpoint lists the functions callable on that surface.
|
|
1095
|
+
|
|
1096
|
+
**Response contract — your return IS the response (no envelope):**
|
|
1097
|
+
- Return a **plain value** → it becomes the JSON body, HTTP `200`. (`SL.functions.call()` gives you
|
|
1098
|
+
that value directly — `res.value`, not `res.result.value`.)
|
|
1099
|
+
- Return a web-standard **`Response`** → passed through verbatim: your status, headers, content-type
|
|
1100
|
+
and body (XML, CSV, text, binary, redirect, custom status). `Response` is a runtime global.
|
|
1101
|
+
```js
|
|
1102
|
+
return new Response(toXml(data), { status: 200, headers: { "content-type": "application/xml" } })
|
|
1103
|
+
```
|
|
1104
|
+
- **Throw** → HTTP `500` `{ error: "FUNCTION_ERROR", message, code }`. For *expected* errors (400/404/
|
|
1105
|
+
409…), return a `Response` with your own status + body.
|
|
1106
|
+
|
|
1107
|
+
One rule: **plain object ⇒ 200; want any other status/headers/content-type ⇒ return a `Response`.**
|
|
1108
|
+
Timing comes back in an `X-SL-Function-Duration-Ms` header (admin surface); your `ctx.log` lines land
|
|
1109
|
+
in the collection's Errors & Activity feed — the body stays purely your output.
|
|
1110
|
+
|
|
1111
|
+
The admin surface is collection-admin gated, so an admin function's `caller` authority runs
|
|
1112
|
+
at admin level, attributed to the signed-in admin. The public surface resolves auth if a
|
|
1113
|
+
token is present (→ `owner`) and treats its absence as anonymous (→ `public`); a
|
|
1114
|
+
`collection`-authority function runs elevated regardless.
|
|
1115
|
+
|
|
1116
|
+
### Before it will resolve
|
|
1117
|
+
|
|
1118
|
+
An http call returns `404 FUNCTION_NOT_FOUND` unless **both** of these are true (this is the
|
|
1119
|
+
most common first-run surprise):
|
|
1120
|
+
|
|
1121
|
+
1. **The app's release is registered on the channel** the collection follows (see
|
|
1122
|
+
[deploying-apps.md](deploying-apps.md)) — that's what publishes the function bundle into
|
|
1123
|
+
the registry the runtime loads from.
|
|
1124
|
+
2. **The app is enabled on the collection** (`appConfig.apps[]`, on that same channel — see
|
|
1125
|
+
[appConfig.md](appConfig.md)).
|
|
1126
|
+
|
|
1127
|
+
So the end-to-end path is: *write → register the release → enable on a collection → call.*
|
|
1128
|
+
|
|
1129
|
+
### Seeing your function's runs and logs
|
|
1130
|
+
|
|
1131
|
+
Every invocation is recorded as an **execution** activity event, carrying your `ctx.log`
|
|
1132
|
+
lines. Where to look, easiest first:
|
|
1133
|
+
|
|
1134
|
+
- **Admin-surface response** — timing comes back in the `X-SL-Function-Duration-Ms` header (logs are in Errors & Activity, not the body).
|
|
1135
|
+
- **Deployed test mode** — see below; real run, isolated logging.
|
|
1136
|
+
- **Owner console** — the collection's **Advanced → Errors & Activity → events** tab,
|
|
1137
|
+
filtered to **source = execution**: each run shows as `function <name> ok` (or an error),
|
|
1138
|
+
and the detail carries your `ctx.log` output. (Telemetry is streamed, so allow a few
|
|
1139
|
+
seconds.)
|
|
1140
|
+
|
|
1141
|
+
## Testing & preview
|
|
1142
|
+
|
|
1143
|
+
You don't have to deploy to find out whether a function works. There are three levels of
|
|
1144
|
+
fidelity — use them in order.
|
|
1145
|
+
|
|
1146
|
+
### 1. Local harness (fast, offline)
|
|
1147
|
+
|
|
1148
|
+
`@proveanything/smartlinks/testing` builds a `ctx` that **enforces the declared capability
|
|
1149
|
+
envelope**, so a function fails locally the same way it would in production — the common
|
|
1150
|
+
"I forgot to declare `sl:records:write`" bug is caught before you deploy, not after.
|
|
1151
|
+
|
|
1152
|
+
```ts
|
|
1153
|
+
import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
|
|
1154
|
+
import manifest from '../public/app.manifest.json'
|
|
1155
|
+
import { submitCompetitionEntry } from '../src/functions'
|
|
1156
|
+
|
|
1157
|
+
const def = manifest.functions.definitions.find(d => d.name === 'submitCompetitionEntry')
|
|
1158
|
+
|
|
1159
|
+
const ctx = createFunctionTestContext({
|
|
1160
|
+
def, // capabilities enforced come from the manifest itself
|
|
1161
|
+
caller: { userId: 'tester' },
|
|
1162
|
+
secrets: { 'recaptcha-secret': 'test-value' }, // fixtures — real secrets are server-only
|
|
1163
|
+
})
|
|
1164
|
+
|
|
1165
|
+
const res = await submitCompetitionEntry(ctx, { method: 'POST', body: { email: 'a@b.com', answer: '42' } })
|
|
1166
|
+
// ctx.sl.appRecords.create(...) throws CapabilityError unless `def` declares sl:records:write
|
|
1167
|
+
// With no `sl` impl, records / counters / contacts / interactions run in memory with the platform's
|
|
1168
|
+
// uniqueness rules — assert on ctx.memory. Share createFunctionTestMemory() between contexts to
|
|
1169
|
+
// simulate concurrent callers; restrict ids with knownTags / knownInteractionTypes.
|
|
1170
|
+
```
|
|
1171
|
+
|
|
1172
|
+
Pass the **`def`** (not a hand-typed capability list) so "tested" can't drift from
|
|
1173
|
+
"declared". By default `ctx.sl` methods return a stub result (pure unit test — no network);
|
|
1174
|
+
inject `sl` to delegate to your live SDK for real reads/writes:
|
|
1175
|
+
|
|
1176
|
+
```ts
|
|
1177
|
+
const ctx = createFunctionTestContext({
|
|
1178
|
+
def,
|
|
1179
|
+
sl: { appRecords: { create: (fields) => mySdk.app.records.create(fields) } },
|
|
1180
|
+
})
|
|
1181
|
+
```
|
|
1182
|
+
|
|
1183
|
+
### 2. Deployed test mode (high fidelity, safe)
|
|
1184
|
+
|
|
1185
|
+
Register to the `dev` channel and invoke on the real server — real secrets, real data —
|
|
1186
|
+
without a live run *(coming next)*: a test invocation is forced to `caller` authority,
|
|
1187
|
+
side-effecting writes are dry-run, and the traffic is logged separately from live metrics.
|
|
1188
|
+
|
|
1189
|
+
### 3. Live
|
|
1190
|
+
|
|
1191
|
+
Point a real collection at the channel and invoke for real.
|
|
1192
|
+
|
|
1193
|
+
### What differs across the three
|
|
1194
|
+
|
|
1195
|
+
| | Capabilities | `ctx.sl` | Secrets | Authority | Writes |
|
|
1196
|
+
|---|---|---|---|---|---|
|
|
1197
|
+
| **Local harness** | Enforced (from `def`) | Stub, or your injected SDK | Fixtures you pass | Informational | Whatever your impl does |
|
|
1198
|
+
| **Deployed test** | Enforced | Real (test-scoped) | Real | Forced to `caller` | Dry-run |
|
|
1199
|
+
| **Live** | Enforced | Real | Real | As declared | Real |
|
|
1200
|
+
|
|
1201
|
+
### Recommended CI pattern
|
|
1202
|
+
|
|
1203
|
+
1. **Unit** — run each handler through `createFunctionTestContext` (no network); assert
|
|
1204
|
+
behaviour *and* that capabilities are sufficient (an under-declared capability throws).
|
|
1205
|
+
2. **Post-deploy smoke** — after registering to `dev`, hit each function once in test mode.
|
|
1206
|
+
|
|
1207
|
+
## Where functions run (and why it doesn't change how you write them)
|
|
1208
|
+
|
|
1209
|
+
SmartLinks runs first-party (trusted) functions **in-process** and untrusted third-party
|
|
1210
|
+
functions in an **isolated runner**. The difference is enforcement, not authoring:
|
|
1211
|
+
|
|
1212
|
+
- **In-process** trusts the author; `ctx` is built directly.
|
|
1213
|
+
- **Isolated runner** enforces the `authority` boundary and `capabilities` at the container
|
|
1214
|
+
edge — `ctx.sl` is a proxy over the declared authority, `ctx.fetch` is filtered to the
|
|
1215
|
+
declared hosts, and there is no ambient filesystem, network, or environment.
|
|
1216
|
+
|
|
1217
|
+
Because the **contract is identical**, a function you write today runs unchanged if it later
|
|
1218
|
+
moves lanes. Write to the `ctx` contract and declare your capabilities honestly, and the
|
|
1219
|
+
platform takes care of the rest.
|