@sinch/functions-runtime 0.5.14 → 0.5.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +178 -124
  2. package/package.json +3 -3
package/README.md CHANGED
@@ -1,189 +1,243 @@
1
1
  # @sinch/functions-runtime
2
2
 
3
- Development runtime for Sinch Functions - build serverless communication workflows with ease.
3
+ The Node.js SDK for [Sinch Functions](https://developers.sinch.com/docs/functions): serverless functions that answer phone calls, reply to messages and serve HTTP endpoints on Sinch infrastructure.
4
4
 
5
- ## Getting Started
5
+ A function is one file, `function.ts`, that exports handlers. The runtime hosts it, gives every handler a `context` with configuration, cache, storage, a SQLite database and pre-configured Sinch API clients, and turns voice handlers' return values into SVAML.
6
6
 
7
- The easiest way to get started is using the Sinch CLI:
7
+ ## Install
8
+
9
+ Functions are created and run with the Sinch CLI, which installs this package for you:
8
10
 
9
11
  ```bash
10
- # Install the CLI
11
12
  npm install -g @sinch/cli
12
-
13
- # Create a new function (interactive)
14
- sinch functions init
13
+ sinch auth login
14
+ sinch functions init # pick a template
15
+ sinch functions dev # local server with hot reload and a tunnel for callbacks
16
+ sinch functions deploy
15
17
  ```
16
18
 
17
- The interactive prompt will guide you through:
18
-
19
- 1. Selecting a runtime (Node.js, C#, etc.)
20
- 2. Choosing a template (simple-voice-ivr recommended for first project)
21
- 3. Setting up your project
22
-
23
- Then start the local development server:
24
-
25
- ```bash
26
- sinch functions dev
19
+ Requires Node.js 24 or later. See the [quickstart](https://developers.sinch.com/docs/functions/functions/quickstart) for the full walk-through.
20
+
21
+ ## A voice function
22
+
23
+ ```ts
24
+ import type { FunctionContext, IceCallback, PieCallback } from '@sinch/functions-runtime';
25
+ import { IceSvamlBuilder, PieSvamlBuilder, createMenu } from '@sinch/functions-runtime';
26
+
27
+ export default {
28
+ async ice(context: FunctionContext, event: IceCallback) {
29
+ const menu = createMenu()
30
+ .prompt('Press 1 for sales, 2 for support.')
31
+ .option('1', 'return(sales)')
32
+ .option('2', 'return(support)')
33
+ .timeout(5000)
34
+ .repeats(2)
35
+ .build();
36
+
37
+ return new IceSvamlBuilder().runMenu(menu).build();
38
+ },
39
+
40
+ async pie(context: FunctionContext, event: PieCallback) {
41
+ if (event.menuResult?.value === 'sales') {
42
+ return new PieSvamlBuilder()
43
+ .say('Connecting you to sales.')
44
+ .connectPstn('+15551234567')
45
+ .build();
46
+ }
47
+ return new PieSvamlBuilder().say('Goodbye.').hangup().build();
48
+ },
49
+ };
27
50
  ```
28
51
 
29
- Your function is now running locally with hot reload!
30
-
31
- ## Deploy to Production
32
-
33
- When you're ready to deploy:
52
+ ### Callbacks
34
53
 
35
- ```bash
36
- sinch functions deploy
37
- ```
54
+ | Handler | Fires when | Returns |
55
+ | -------- | --------------------------------------------------- | ------- |
56
+ | `ice` | An incoming call reaches your number | SVAML |
57
+ | `ace` | An outbound call is answered | SVAML |
58
+ | `pie` | The caller pressed keys or spoke after a menu | SVAML |
59
+ | `dice` | The call ended | nothing |
60
+ | `notify` | A notification event arrives (recording, and so on) | nothing |
38
61
 
39
- Your function will be built and deployed to the Sinch Functions platform.
62
+ Only `ice` is required. The platform may still post the others; the runtime answers `200` for any handler you did not implement.
40
63
 
41
- ## Features
64
+ Handlers receive camelCased payloads typed as `IceCallback`, `AceCallback`, `PieCallback`, `DiceCallback` and `NotifyCallback`. The call identifier arrives as `callId`.
42
65
 
43
- ### SVAML Builders
66
+ ### SVAML builders
44
67
 
45
- Build voice responses with a fluent API:
68
+ Each builder chains instructions (`say`, `play`, `playFiles`, `setCookie`, `sendDtmf`, `startRecording`, `stopRecording`), ends with one action and finishes with `build()`. The actions available depend on the callback:
46
69
 
47
- ```typescript
48
- import { IceSvamlBuilder, AceSvamlBuilder, PieSvamlBuilder } from '@sinch/functions-runtime';
70
+ | Builder | Actions |
71
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
72
+ | `IceSvamlBuilder` | `hangup`, `continue`, `connectPstn`, `connectSip`, `connectMxp`, `connectConf`, `runMenu`, `park`, `connectAgent`; also the `answer` instruction |
73
+ | `AceSvamlBuilder` | `hangup`, `continue` |
74
+ | `PieSvamlBuilder` | `hangup`, `continue`, `connectPstn`, `runMenu`, `park`, `connectAgent` |
49
75
 
50
- // ICE (Incoming Call Event) - handle incoming calls
51
- const iceResponse = new IceSvamlBuilder()
52
- .say('Hello, welcome!')
76
+ ```ts
77
+ new IceSvamlBuilder()
78
+ .say('Please hold.')
53
79
  .connectPstn('+15551234567', {
54
- cli: '+15559999999',
80
+ cli: '+15559876543',
81
+ timeout: 30,
55
82
  enableAce: true,
56
83
  enableDice: true,
57
84
  })
58
85
  .build();
86
+ ```
59
87
 
60
- // ACE (Answered Call Event) - handle answered outbound calls
61
- const aceResponse = new AceSvamlBuilder().say('The call has been answered.').continue().build();
88
+ ### Menus
62
89
 
63
- // PIE (Prompt Input Event) - handle user input
64
- const pieResponse = new PieSvamlBuilder()
65
- .say('You pressed ' + selection)
66
- .hangup()
67
- .build();
68
- ```
90
+ `createMenu()` builds a DTMF menu with prompts, options, timeouts and repeats. `MenuTemplates` has ready-made ones: `business(name)`, `yesNo(question)`, `language()`, `afterHours(name)` and `numericInput(prompt, digits)`.
69
91
 
70
- ### Menu Builder
92
+ ## HTTP handlers
71
93
 
72
- Create IVR menus with validation:
94
+ Any other exported async function is an HTTP endpoint named after the export. `export async function notes(...)` answers requests to `/notes`.
73
95
 
74
- ```typescript
75
- import { MenuBuilder, MenuTemplates } from '@sinch/functions-runtime';
96
+ ```ts
97
+ import type { FunctionContext, FunctionRequest, FunctionResponse } from '@sinch/functions-runtime';
76
98
 
77
- // Use pre-built templates
78
- const businessMenu = MenuTemplates.business('Acme Corp');
79
- const yesNoMenu = MenuTemplates.yesNo('Do you want to continue?');
99
+ export async function notes(
100
+ context: FunctionContext,
101
+ request: FunctionRequest
102
+ ): Promise<FunctionResponse> {
103
+ if (request.method === 'POST') {
104
+ const { key, content } = request.body as { key: string; content: string };
105
+ await context.storage.write(`notes/${key}.txt`, content);
106
+ return { statusCode: 201, body: { key } };
107
+ }
108
+ return { statusCode: 200, body: await context.storage.list('notes/') };
109
+ }
110
+ ```
80
111
 
81
- // Or build custom menus
82
- const customMenu = new MenuBuilder()
83
- .prompt('Press 1 for English, 2 for Spanish')
84
- .option('1', 'menu(english)')
85
- .option('2', 'menu(spanish)')
86
- .addSubmenu('english')
87
- .prompt('Press 1 for sales, 2 for support')
88
- .option('1', 'return(en-sales)')
89
- .option('2', 'return(en-support)')
90
- .build();
112
+ `FunctionRequest` carries `method`, `path`, `query`, `headers`, `body` and `params`. Return `{ statusCode, headers?, body? }`, or use `createJsonResponse`, `createResponse` and `createErrorResponse`.
113
+
114
+ Webhooks from other Sinch products are plain HTTP handlers too. An inbound Conversation API message, for example:
115
+
116
+ ```ts
117
+ export async function conversationWebhook(
118
+ context: FunctionContext,
119
+ request: FunctionRequest
120
+ ): Promise<FunctionResponse> {
121
+ const body = request.body as Record<string, unknown>;
122
+ const contactId = body.contact_id as string | undefined;
123
+ const text = (body.message as any)?.contact_message?.text_message?.text as string | undefined;
124
+ if (!contactId || !text) return { statusCode: 200, body: { ok: true } };
125
+
126
+ await context.conversation!.messages.send({
127
+ sendMessageRequestBody: {
128
+ app_id: context.env!.CONVERSATION_APP_ID!,
129
+ recipient: { contact_id: contactId },
130
+ message: { text_message: { text: 'Thanks for your message.' } },
131
+ },
132
+ });
133
+ return { statusCode: 200, body: { ok: true } };
134
+ }
91
135
  ```
92
136
 
93
- ### Cache
137
+ Helpers such as `getText`, `getChannel`, `getContactId`, `isTextMessage` and `ConversationMessageBuilder` are exported for working with Conversation API payloads.
138
+
139
+ ### Protecting endpoints
140
+
141
+ Export `auth` to require HTTP Basic authentication with your project API key and secret. `'*'` protects every endpoint; an array names the ones to protect.
142
+
143
+ ```ts
144
+ export const auth = ['notes', 'config'];
145
+ ```
94
146
 
95
- Store and retrieve data across function invocations:
147
+ ## Startup and WebSockets
96
148
 
97
- ```typescript
98
- export async function ice(context, event) {
99
- const cache = context.cache;
149
+ Export `setup` to run code once before the server accepts requests, or to accept WebSocket connections (for example a `connectStream` media stream).
100
150
 
101
- // Store data
102
- await cache.set('call-count', 1, 3600); // TTL in seconds
151
+ ```ts
152
+ import type { SinchRuntime } from '@sinch/functions-runtime';
103
153
 
104
- // Retrieve data
105
- const count = await cache.get('call-count');
154
+ export function setup(runtime: SinchRuntime) {
155
+ runtime.onStartup(async (context) => {
156
+ await context.cache.set('ready', true);
157
+ });
158
+ runtime.onWebSocket('/stream', (ws, req) => {
159
+ ws.on('message', (frame) => {
160
+ /* audio */
161
+ });
162
+ });
106
163
  }
107
164
  ```
108
165
 
109
- ### Configuration
166
+ ## The context
110
167
 
111
- Access environment variables and secrets:
168
+ Every handler receives a `FunctionContext`.
112
169
 
113
- ```typescript
114
- import { createConfig } from '@sinch/functions-runtime';
170
+ | Member | What it is |
171
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
172
+ | `context.config` | `projectId`, `functionName`, `environment` and the `variables` you set at init or deploy |
173
+ | `context.env` | Environment variables, including secrets |
174
+ | `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production |
175
+ | `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production |
176
+ | `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver |
177
+ | `context.assets(name)` | Reads a file from the function's `assets/` directory |
178
+ | `context.voice` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set |
179
+ | `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set |
180
+ | `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set |
181
+ | `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true` |
115
182
 
116
- export async function ice(context, event) {
117
- const config = createConfig(context);
183
+ The API clients also need `PROJECT_ID`, `PROJECT_ID_API_KEY` and `PROJECT_ID_API_SECRET`, which `sinch auth login` provides. A client whose variables are missing is `undefined`. Full list: [SDK environment variables](https://developers.sinch.com/docs/functions/reference/sdk-env-vars).
118
184
 
119
- // Get variables
120
- const companyName = config.getVariable('COMPANY_NAME', 'Default');
185
+ ```ts
186
+ import { DatabaseSync } from 'node:sqlite';
121
187
 
122
- // Get secrets (encrypted at rest)
123
- const apiKey = config.getSecret('API_KEY');
124
- }
188
+ const db = new DatabaseSync(context.database);
189
+ db.exec('CREATE TABLE IF NOT EXISTS visits (day TEXT PRIMARY KEY, n INTEGER NOT NULL DEFAULT 0)');
125
190
  ```
126
191
 
127
- ## Voice Callbacks
192
+ `createConfig(context)` wraps the configuration with `getVariable`, `requireVariable`, `getSecret`, `requireSecret`, `isDevelopment` and `getApplicationCredentials`.
128
193
 
129
- | Callback | Description | Returns |
130
- | -------- | ------------------------------------------------------- | ------- |
131
- | `ice` | Incoming Call Event - first callback for incoming calls | SVAML |
132
- | `ace` | Answered Call Event - when outbound call is answered | SVAML |
133
- | `pie` | Prompt Input Event - user input (DTMF/voice) | SVAML |
134
- | `dice` | Disconnected Call Event - call ended | None |
135
- | `notify` | Notification events | None |
194
+ ## Voice API v2
136
195
 
137
- `ace`, `pie`, `dice`, and `notify` are optional — the platform may call them even if your function doesn't implement a handler, and the runtime returns `200` for those unimplemented callbacks (only `ice` is required).
196
+ The v2 call control API, which can attach media streams to calls the function places, is a separate import. It is a preview: the import path stays, but the API may change before it is final.
138
197
 
139
- Type callback data with `IceCallback` / `AceCallback` / `PieCallback` / `DiceCallback` / `NotifyCallback` — these match what your handler receives (the runtime delivers `callId`, not the raw API's `callid`).
198
+ ```ts
199
+ import { createClient, commands } from '@sinch/functions-runtime/voice/v2';
140
200
 
141
- ## TypeScript Support
201
+ const voice = createClient(context);
202
+ ```
142
203
 
143
- Full TypeScript support with comprehensive types:
204
+ ## Local development and production
144
205
 
145
- ```typescript
146
- import type { FunctionContext, IceCallback, SvamletResponse } from '@sinch/functions-runtime';
206
+ This package is the local development runtime and the SDK you import from. `sinch functions dev` runs your function on `http://localhost:3000` (override with `PORT`) with hot reload, an in-memory cache, filesystem storage and a tunnel that forwards live Sinch callbacks to your machine.
147
207
 
148
- export async function ice(
149
- context: FunctionContext,
150
- event: IceCallback
151
- ): Promise<SvamletResponse> {
152
- // Full type safety and IntelliSense!
153
- }
154
- ```
208
+ When you deploy, the platform installs `@sinch/functions-runtime-prod` in the container. It exposes the same API, so nothing in `function.ts` changes between environments. Do not install the prod package yourself.
155
209
 
156
- ## Request Limits
210
+ ## Limits
157
211
 
158
- | Limit | Value |
159
- | -------------------------------------- | ---------------------- |
160
- | Request body | 10 MB (10485760 bytes) |
161
- | Request/response body retained in logs | First 64 KB |
212
+ | Limit | Value |
213
+ | ------------------------------------- | ----------- |
214
+ | Request body | 10 MB |
215
+ | Request or response body kept in logs | First 64 KB |
162
216
 
163
- A body larger than the limit is rejected with `413` and a JSON response naming it:
217
+ The 10 MB cap applies locally and deployed, so a request that works in `sinch functions dev` works in production. A deployed function rejects a larger body with `413` and a JSON body naming the limit; the platform router in front of it enforces the same cap, so a `413` without that JSON body came from the router. Deployed functions keep the first 64 KB of text bodies (JSON, XML, plain text, form data) in their logs and append `…[truncated — N bytes total]` past that. Binary bodies are never logged. See [limits](https://developers.sinch.com/docs/functions/reference/limits).
164
218
 
165
- ```json
166
- {
167
- "error": "Payload too large",
168
- "message": "Request body exceeds the 10mb limit",
169
- "limit": "10mb"
170
- }
171
- ```
219
+ ## TypeScript
172
220
 
173
- A deployed function sits behind the platform router, which enforces the same 10 MB cap, so a body
174
- that is accepted locally is accepted once deployed. If you receive a `413` **without** the JSON
175
- body above, the router rejected the request before it reached your function.
221
+ Everything is typed. Import types alongside the builders:
176
222
 
177
- Logs retain the first 64 KB of a request or response body, appending
178
- `…[truncated — N bytes total]` when the body was longer. Only text formats are retained — JSON,
179
- XML, plain text and form data. Anything else, including uploads, images, audio, video, PDFs and
180
- archives, is not logged at all. Your function still receives every body in full.
223
+ ```ts
224
+ import type {
225
+ FunctionContext,
226
+ IceCallback,
227
+ SvamletResponse,
228
+ VoiceFunction,
229
+ } from '@sinch/functions-runtime';
230
+ ```
181
231
 
182
232
  ## Documentation
183
233
 
184
- - [Sinch Functions Documentation](https://developers.sinch.com/docs/functions)
185
- - [Sinch Voice API](https://developers.sinch.com/docs/voice)
186
- - [SVAML Reference](https://developers.sinch.com/docs/voice/api-reference/svaml)
234
+ - [Sinch Functions](https://developers.sinch.com/docs/functions)
235
+ - [Your first function](https://developers.sinch.com/docs/functions/functions/quickstart)
236
+ - [Local development](https://developers.sinch.com/docs/functions/functions/local-development)
237
+ - [Function context reference](https://developers.sinch.com/docs/functions/reference/function-context)
238
+ - [SVAML cheatsheet](https://developers.sinch.com/docs/functions/reference/svaml-cheatsheet)
239
+ - [Templates](https://developers.sinch.com/docs/functions/functions/templates)
240
+ - [Voice API](https://developers.sinch.com/docs/voice) and [Conversation API](https://developers.sinch.com/docs/conversation)
187
241
 
188
242
  ## License
189
243
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sinch/functions-runtime",
3
- "version": "0.5.14",
4
- "description": "Development runtime for Sinch Functions - serverless voice applications",
3
+ "version": "0.5.16",
4
+ "description": "Node.js SDK and local development runtime for Sinch Functions: voice, messaging and HTTP serverless functions",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
@@ -43,7 +43,7 @@
43
43
  ],
44
44
  "author": "Sinch",
45
45
  "license": "MIT",
46
- "homepage": "https://developers.sinch.com",
46
+ "homepage": "https://developers.sinch.com/docs/functions",
47
47
  "bugs": {
48
48
  "url": "https://sinch.com/support"
49
49
  },