@sinch/functions-runtime 0.4.19 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3790 +1,102 @@
1
- // ../runtime-shared/dist/ai/connect-agent.js
2
- var AgentProvider;
3
- (function(AgentProvider2) {
4
- AgentProvider2["Sinch"] = "sinch";
5
- AgentProvider2["ElevenLabs"] = "elevenlabs";
6
- })(AgentProvider || (AgentProvider = {}));
7
- var AgentSipHelper = class {
8
- /**
9
- * Build a SIP URI for connecting to an ElevenLabs agent
10
- */
11
- static buildElevenLabsSipUri(agentId, options) {
12
- const baseUri = `sip:${agentId}@sip.elevenlabs.io`;
13
- if (options?.customHeaders && Object.keys(options.customHeaders).length > 0) {
14
- const headers = Object.entries(options.customHeaders).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
15
- return `${baseUri};${headers}`;
16
- }
17
- return baseUri;
18
- }
19
- /**
20
- * Build a SIP URI for the given provider and agent
21
- */
22
- static buildSipUri(provider, agentId, options) {
23
- switch (provider) {
24
- case AgentProvider.ElevenLabs:
25
- return this.buildElevenLabsSipUri(agentId, options);
26
- default:
27
- throw new Error(`Unsupported agent provider: ${provider}`);
28
- }
29
- }
30
- };
31
- function createConnectAgentAction(provider, agentId, options) {
32
- if (provider === AgentProvider.Sinch) {
33
- throw new Error("AgentProvider.Sinch uses connectStream, not connectSip. Use connectAgent() from @sinch/agents instead.");
34
- }
35
- const sipUri = AgentSipHelper.buildSipUri(provider, agentId, options);
36
- return {
37
- name: "connectSip",
38
- destination: { endpoint: sipUri },
39
- ...options?.cli && { cli: options.cli },
40
- ...options?.maxDuration !== void 0 && { maxDuration: options.maxDuration },
41
- ...options?.suppressCallbacks !== void 0 && { suppressCallbacks: options.suppressCallbacks }
42
- };
43
- }
44
-
45
- // ../runtime-shared/dist/builders/svaml.js
46
- var BaseSvamlBuilder = class {
47
- instructions = [];
48
- action = null;
49
- /**
50
- * Add a text-to-speech instruction
51
- *
52
- * @param text - Text to speak
53
- * @param locale - Voice locale (e.g., 'en-US')
54
- */
55
- say(text, locale = "en-US") {
56
- const instruction = { name: "say", text, locale };
57
- this.instructions.push(instruction);
58
- return this;
59
- }
60
- /**
61
- * Play an audio file
62
- *
63
- * @param url - URL of the audio file to play
64
- */
65
- play(url) {
66
- const instruction = { name: "play", url };
67
- this.instructions.push(instruction);
68
- return this;
69
- }
70
- /**
71
- * Play multiple audio files
72
- *
73
- * @param urls - Array of audio file URLs
74
- * @param locale - Locale for any TTS prompts
75
- */
76
- playFiles(urls, locale = "en-US") {
77
- const instruction = { name: "playFiles", ids: urls, locale };
78
- this.instructions.push(instruction);
79
- return this;
80
- }
81
- /**
82
- * Start recording the call
83
- *
84
- * @param options - Recording options
85
- */
86
- startRecording(options) {
87
- const instruction = {
88
- name: "startRecording",
89
- options
90
- };
91
- this.instructions.push(instruction);
92
- return this;
93
- }
94
- /**
95
- * Stop recording the call
96
- */
97
- stopRecording() {
98
- const instruction = { name: "stopRecording" };
99
- this.instructions.push(instruction);
100
- return this;
101
- }
102
- /**
103
- * Set a cookie (persists data across callbacks)
104
- *
105
- * @param key - Cookie key
106
- * @param value - Cookie value
107
- */
108
- setCookie(key, value) {
109
- const instruction = { name: "setCookie", key, value };
110
- this.instructions.push(instruction);
111
- return this;
112
- }
113
- /**
114
- * Send DTMF tones
115
- *
116
- * @param digits - DTMF digits to send
117
- */
118
- sendDtmf(digits) {
119
- const instruction = { name: "sendDtmf", value: digits };
120
- this.instructions.push(instruction);
121
- return this;
122
- }
123
- /**
124
- * Hang up the call
125
- */
126
- hangup() {
127
- this.action = { name: "hangup" };
128
- return this;
129
- }
130
- /**
131
- * Continue to next callback
132
- */
133
- continue() {
134
- this.action = { name: "continue" };
135
- return this;
136
- }
137
- /**
138
- * Build the final SVAML response
139
- *
140
- * @throws Error if no action has been set
141
- */
142
- build() {
143
- if (!this.action) {
144
- throw new Error("SVAML response requires an action. Call hangup(), continue(), connectPstn(), etc.");
145
- }
146
- return {
147
- instructions: this.instructions.length > 0 ? this.instructions : void 0,
148
- action: this.action
149
- };
150
- }
151
- };
152
- var IceSvamlBuilder = class extends BaseSvamlBuilder {
153
- /**
154
- * Answer the call explicitly
155
- */
156
- answer() {
157
- const instruction = { name: "answer" };
158
- this.instructions.push(instruction);
159
- return this;
160
- }
161
- /**
162
- * Connect to a PSTN phone number
163
- *
164
- * @param number - E.164 formatted phone number (e.g., '+15551234567')
165
- * @param options - Connection options
166
- *
167
- * @example
168
- * ```typescript
169
- * // Simple connect
170
- * new IceSvamlBuilder().connectPstn('+15551234567').build();
171
- *
172
- * // With options: caller ID, timeout, and AMD
173
- * new IceSvamlBuilder()
174
- * .connectPstn('+15551234567', {
175
- * cli: '+15559876543',
176
- * timeout: 30,
177
- * amd: { enabled: true },
178
- * })
179
- * .build();
180
- * ```
181
- */
182
- connectPstn(number, options) {
183
- this.action = {
184
- name: "connectPstn",
185
- number,
186
- ...options
187
- };
188
- return this;
189
- }
190
- /**
191
- * Connect to a SIP endpoint
192
- *
193
- * @param destination - SIP URI
194
- * @param options - Connection options
195
- */
196
- connectSip(destination, options) {
197
- this.action = {
198
- name: "connectSip",
199
- destination,
200
- ...options
201
- };
202
- return this;
203
- }
204
- /**
205
- * Connect to an MXP (Sinch SDK) user
206
- *
207
- * @param destination - MXP user identifier
208
- * @param options - Connection options
209
- */
210
- connectMxp(destination, options) {
211
- this.action = {
212
- name: "connectMxp",
213
- destination,
214
- ...options
215
- };
216
- return this;
217
- }
218
- /**
219
- * Join a conference
220
- *
221
- * @param conferenceId - Conference ID to join
222
- * @param options - Conference options
223
- */
224
- connectConf(conferenceId, options) {
225
- this.action = {
226
- name: "connectConf",
227
- conferenceId,
228
- ...options
229
- };
230
- return this;
231
- }
232
- /**
233
- * Run an IVR menu
234
- *
235
- * @param menus - Array of menu definitions or MenuStructure from createMenu().build()
236
- * @param options - Menu options
237
- *
238
- * @example
239
- * ```typescript
240
- * // Using MenuTemplates
241
- * new IceSvamlBuilder()
242
- * .runMenu(MenuTemplates.business('Acme Corp'))
243
- * .build();
244
- *
245
- * // Using createMenu builder
246
- * const menu = createMenu()
247
- * .prompt('Press 1 for sales, 2 for support.')
248
- * .option('1', 'return(sales)')
249
- * .option('2', 'return(support)')
250
- * .build();
251
- * new IceSvamlBuilder().runMenu(menu).build();
252
- * ```
253
- */
254
- runMenu(menus, options) {
255
- const menuArray = Array.isArray(menus) ? menus : menus.menus;
256
- const barge = Array.isArray(menus) ? options?.barge : menus.barge;
257
- this.action = {
258
- name: "runMenu",
259
- menus: menuArray,
260
- barge,
261
- ...options
262
- };
263
- return this;
264
- }
265
- /**
266
- * Park the call (put on hold)
267
- *
268
- * @param holdPrompt - Prompt to play while on hold
269
- * @param options - Park options
270
- *
271
- * @example
272
- * ```typescript
273
- * // Park with hold music prompt
274
- * new IceSvamlBuilder()
275
- * .park('Please hold while we connect you.', { maxDuration: 120 })
276
- * .build();
277
- * ```
278
- */
279
- park(holdPrompt, options) {
280
- this.action = {
281
- name: "park",
282
- holdPrompt,
283
- ...options
284
- };
285
- return this;
286
- }
287
- /**
288
- * Connect to an AI voice agent
289
- *
290
- * @param provider - The AI agent provider (e.g., AgentProvider.ElevenLabs)
291
- * @param agentId - The agent ID to connect to
292
- * @param options - Connection options
293
- *
294
- * @example
295
- * ```typescript
296
- * return new IceSvamlBuilder()
297
- * .say('Connecting you to our AI assistant.')
298
- * .connectAgent(AgentProvider.ElevenLabs, 'agent_123')
299
- * .build();
300
- * ```
301
- */
302
- connectAgent(provider, agentId, options) {
303
- this.action = createConnectAgentAction(provider, agentId, options);
304
- return this;
305
- }
306
- };
307
- var AceSvamlBuilder = class extends BaseSvamlBuilder {
308
- };
309
- var PieSvamlBuilder = class extends BaseSvamlBuilder {
310
- /**
311
- * Connect to a PSTN phone number
312
- *
313
- * @param number - E.164 formatted phone number
314
- * @param options - Connection options
315
- */
316
- connectPstn(number, options) {
317
- this.action = {
318
- name: "connectPstn",
319
- number,
320
- ...options
321
- };
322
- return this;
323
- }
324
- /**
325
- * Run an IVR menu
326
- *
327
- * @param menus - Array of menu definitions or MenuStructure from createMenu().build()
328
- * @param options - Menu options
329
- */
330
- runMenu(menus, options) {
331
- const menuArray = Array.isArray(menus) ? menus : menus.menus;
332
- const barge = Array.isArray(menus) ? options?.barge : menus.barge;
333
- this.action = {
334
- name: "runMenu",
335
- menus: menuArray,
336
- barge,
337
- ...options
338
- };
339
- return this;
340
- }
341
- /**
342
- * Park the call (put on hold)
343
- *
344
- * @param holdPrompt - Prompt to play while on hold
345
- * @param options - Park options
346
- */
347
- park(holdPrompt, options) {
348
- this.action = {
349
- name: "park",
350
- holdPrompt,
351
- ...options
352
- };
353
- return this;
354
- }
355
- /**
356
- * Connect to an AI voice agent
357
- *
358
- * @param provider - The AI agent provider (e.g., AgentProvider.ElevenLabs)
359
- * @param agentId - The agent ID to connect to
360
- * @param options - Connection options
361
- *
362
- * @example
363
- * ```typescript
364
- * // Transfer to AI agent based on menu selection
365
- * if (event.menuResult?.value === 'ai') {
366
- * return new PieSvamlBuilder()
367
- * .say('Connecting you to our AI assistant.')
368
- * .connectAgent(AgentProvider.ElevenLabs, 'agent_123')
369
- * .build();
370
- * }
371
- * ```
372
- */
373
- connectAgent(provider, agentId, options) {
374
- this.action = createConnectAgentAction(provider, agentId, options);
375
- return this;
376
- }
377
- };
378
- function createIceBuilder() {
379
- return new IceSvamlBuilder();
380
- }
381
- function createAceBuilder() {
382
- return new AceSvamlBuilder();
383
- }
384
- function createPieBuilder() {
385
- return new PieSvamlBuilder();
386
- }
387
-
388
- // ../runtime-shared/dist/builders/menu.js
389
- var VALID_DTMF_KEYS = [
390
- "0",
391
- "1",
392
- "2",
393
- "3",
394
- "4",
395
- "5",
396
- "6",
397
- "7",
398
- "8",
399
- "9",
400
- "*",
401
- "#"
402
- ];
403
- var MenuBuilder = class {
404
- menuStructure;
405
- currentMenu;
406
- /**
407
- * Create a new MenuBuilder
408
- *
409
- * @param id - Menu ID (must be 'main' for root menu)
410
- * @throws Error if id is not 'main' for root menu
411
- */
412
- constructor(id = "main") {
413
- if (id !== "main") {
414
- throw new Error("Menu structure must start with 'main' menu as id");
415
- }
416
- this.menuStructure = {
417
- barge: true,
418
- menus: []
419
- };
420
- this.currentMenu = {
421
- id,
422
- mainPrompt: "",
423
- options: [],
424
- repeats: 2,
425
- maxDigits: 1,
426
- timeoutMills: 8e3
427
- };
428
- }
429
- /**
430
- * Set the main prompt for the menu
431
- *
432
- * @param text - The prompt text (will be wrapped in TTS tags)
433
- * @param locale - Voice locale (default: 'en-US')
434
- */
435
- prompt(text, locale = "en-US") {
436
- this.currentMenu.mainPrompt = `#tts[${text}]`;
437
- this.currentMenu.locale = locale;
438
- return this;
439
- }
440
- /**
441
- * Set the repeat prompt (played when user doesn't respond)
442
- *
443
- * @param text - The repeat prompt text
444
- */
445
- repeatPrompt(text) {
446
- this.currentMenu.repeatPrompt = `#tts[${text}]`;
447
- return this;
448
- }
449
- /**
450
- * Add a menu option
451
- *
452
- * @param dtmf - The DTMF key (0-9, *, #)
453
- * @param action - Action: 'return', 'return(value)', or 'menu(menuid)'
454
- * @throws Error if DTMF key or action is invalid
455
- */
456
- option(dtmf, action = "return") {
457
- if (!this.isValidDtmf(dtmf)) {
458
- throw new Error(`Invalid DTMF key: ${dtmf}. Must be 0-9, *, or #`);
459
- }
460
- if (!this.isValidAction(action)) {
461
- throw new Error(`Invalid action: ${action}. Must be 'return', 'return(value)', or 'menu(menuid)'`);
462
- }
463
- const menuOption = {
464
- dtmf: dtmf.toString(),
465
- action
466
- };
467
- this.currentMenu.options.push(menuOption);
468
- return this;
469
- }
470
- /**
471
- * Set maximum number of digits to collect
472
- *
473
- * @param digits - Maximum digits (1-20)
474
- * @throws Error if digits is out of range
475
- */
476
- maxDigits(digits) {
477
- if (digits < 1 || digits > 20) {
478
- throw new Error("maxDigits must be between 1 and 20");
479
- }
480
- this.currentMenu.maxDigits = digits;
481
- return this;
482
- }
483
- /**
484
- * Set timeout in milliseconds
485
- *
486
- * @param ms - Timeout in milliseconds (1000-30000)
487
- * @throws Error if timeout is out of range
488
- */
489
- timeout(ms) {
490
- if (ms < 1e3 || ms > 3e4) {
491
- throw new Error("Timeout must be between 1000ms and 30000ms");
492
- }
493
- this.currentMenu.timeoutMills = ms;
494
- return this;
495
- }
496
- /**
497
- * Set number of times to repeat the menu
498
- *
499
- * @param count - Number of repeats (0-5)
500
- * @throws Error if count is out of range
501
- */
502
- repeats(count) {
503
- if (count < 0 || count > 5) {
504
- throw new Error("Repeats must be between 0 and 5");
505
- }
506
- this.currentMenu.repeats = count;
507
- return this;
508
- }
509
- /**
510
- * Enable/disable barge-in (allow interrupting prompts with input)
511
- *
512
- * @param enabled - Whether to allow barge-in (default: true)
513
- */
514
- barge(enabled = true) {
515
- this.menuStructure.barge = enabled;
516
- return this;
517
- }
518
- /**
519
- * Add the current menu and start a new submenu
520
- *
521
- * @param id - Menu ID for the submenu
522
- * @throws Error if submenu ID is invalid
523
- */
524
- addSubmenu(id) {
525
- if (!id || typeof id !== "string") {
526
- throw new Error("Submenu ID must be a non-empty string");
527
- }
528
- this.menuStructure.menus.push({ ...this.currentMenu });
529
- this.currentMenu = {
530
- id,
531
- mainPrompt: "",
532
- options: [],
533
- repeats: 2,
534
- maxDigits: 1,
535
- timeoutMills: 8e3
536
- };
537
- return this;
538
- }
539
- /**
540
- * Build and return the complete menu structure
541
- *
542
- * @throws Error if menu structure is invalid
543
- */
544
- build() {
545
- if (this.currentMenu.options.length > 0) {
546
- this.menuStructure.menus.push({ ...this.currentMenu });
547
- }
548
- if (this.menuStructure.menus.length === 0) {
549
- throw new Error("Menu must have at least one menu with options");
550
- }
551
- if (this.menuStructure.menus[0].id !== "main") {
552
- throw new Error("First menu must have id 'main'");
553
- }
554
- return this.menuStructure;
555
- }
556
- /**
557
- * Get just the menus array (for use with runMenu action)
558
- */
559
- buildMenus() {
560
- return this.build().menus;
561
- }
562
- /**
563
- * Validate DTMF key format
564
- */
565
- isValidDtmf(dtmf) {
566
- return VALID_DTMF_KEYS.includes(dtmf.toString());
567
- }
568
- /**
569
- * Validate action format
570
- */
571
- isValidAction(action) {
572
- if (action === "return")
573
- return true;
574
- if (action.startsWith("return(") && action.endsWith(")"))
575
- return true;
576
- if (action.startsWith("menu(") && action.endsWith(")"))
577
- return true;
578
- return false;
579
- }
580
- };
581
- function createMenu(id = "main") {
582
- return new MenuBuilder(id);
583
- }
584
- function createSimpleMenu(prompt, options = []) {
585
- const builder = createMenu().prompt(prompt);
586
- for (const { dtmf, action } of options) {
587
- builder.option(dtmf, action);
588
- }
589
- return builder.build();
590
- }
591
- var MenuTemplates = {
592
- /**
593
- * Standard business menu (Sales, Support, Operator)
594
- *
595
- * @param companyName - Company name for greeting
596
- */
597
- business(companyName = "Our Company") {
598
- return createMenu().prompt(`Thank you for calling ${companyName}! Press 1 for sales, 2 for support, or 0 for an operator.`).repeatPrompt("Press 1 for sales, 2 for support, or 0 for operator.").option("1", "return(sales)").option("2", "return(support)").option("0", "return(operator)").build();
599
- },
600
- /**
601
- * Yes/No confirmation menu
602
- *
603
- * @param question - Question to ask
604
- */
605
- yesNo(question = "Please make your selection") {
606
- return createMenu().prompt(`${question} Press 1 for Yes, or 2 for No.`).repeatPrompt("Press 1 for Yes, or 2 for No.").option("1", "return(yes)").option("2", "return(no)").build();
607
- },
608
- /**
609
- * Language selection menu
610
- *
611
- * @param languages - Language options
612
- */
613
- language(languages = [
614
- { dtmf: "1", name: "English", value: "en-US" },
615
- { dtmf: "2", name: "Spanish", value: "es-ES" }
616
- ]) {
617
- const promptText = languages.map((lang) => `Press ${lang.dtmf} for ${lang.name}`).join(", ") + ".";
618
- const builder = createMenu().prompt(promptText).repeatPrompt(promptText);
619
- for (const lang of languages) {
620
- builder.option(lang.dtmf, `return(${lang.value})`);
621
- }
622
- return builder.build();
623
- },
624
- /**
625
- * After hours menu
626
- *
627
- * @param companyName - Company name
628
- * @param businessHours - Business hours text
629
- */
630
- afterHours(companyName = "Our Company", businessHours = "9 AM to 5 PM, Monday through Friday") {
631
- return createMenu().prompt(`Thank you for calling ${companyName}. Our office hours are ${businessHours}. Press 1 to leave a voicemail, 2 for our website, or 9 for emergency support.`).repeatPrompt("Press 1 for voicemail, 2 for website, or 9 for emergency support.").option("1", "return(voicemail)").option("2", "return(website)").option("9", "return(emergency)").timeout(1e4).build();
632
- },
633
- /**
634
- * Recording consent menu
635
- */
636
- recordingConsent() {
637
- return createMenu().prompt("For quality and training purposes, this call may be recorded. Press 1 to continue with recording, or press 2 to opt out.").repeatPrompt("Press 1 to allow recording, or press 2 to opt out.").option("1", "return(consent)").option("2", "return(no_consent)").timeout(1e4).build();
638
- },
639
- /**
640
- * Numeric input menu (for collecting multi-digit input like account numbers)
641
- *
642
- * @param prompt - Instructions for user
643
- * @param digits - Number of digits to collect (default: 4)
644
- */
645
- numericInput(prompt, digits = 4) {
646
- return createMenu().prompt(`${prompt} Then press pound.`).repeatPrompt(`Please enter your ${digits} digit number, then press pound.`).maxDigits(digits).option("#", "return").timeout(15e3).build();
647
- }
648
- };
649
-
650
- // ../runtime-shared/dist/config/universal.js
651
- var UniversalConfig = class {
652
- context;
653
- env;
654
- /**
655
- * Create a new UniversalConfig instance
656
- *
657
- * @param context - Function execution context
658
- */
659
- constructor(context) {
660
- this.context = context;
661
- this.env = context.env || process.env;
662
- }
663
- /**
664
- * Get a secret value (e.g., API keys, passwords, tokens)
665
- *
666
- * @param name - Secret name (e.g., 'PROJECT_ID_API_SECRET')
667
- * @param defaultValue - Optional default value if secret not found
668
- */
669
- getSecret(name, defaultValue = null) {
670
- return this.env[name] ?? defaultValue;
671
- }
672
- /**
673
- * Get an environment variable (non-secret configuration)
674
- *
675
- * @param name - Variable name (e.g., 'COMPANY_NAME', 'API_URL')
676
- * @param defaultValue - Optional default value
677
- */
678
- getVariable(name, defaultValue = null) {
679
- return this.env[name] ?? defaultValue;
680
- }
681
- /**
682
- * Check if a secret exists (has a value)
683
- *
684
- * @param name - Secret name
685
- */
686
- hasSecret(name) {
687
- return !!this.env[name];
688
- }
689
- /**
690
- * Check if a variable exists (has a value)
691
- *
692
- * @param name - Variable name
693
- */
694
- hasVariable(name) {
695
- return !!this.env[name];
696
- }
697
- /**
698
- * Get required secret (throws error if not found)
699
- *
700
- * @param name - Secret name
701
- * @throws Error if secret is not found
702
- */
703
- requireSecret(name) {
704
- const value = this.getSecret(name);
705
- if (!value) {
706
- throw new Error(`Required secret '${name}' not found in environment`);
707
- }
708
- return value;
709
- }
710
- /**
711
- * Get required variable (throws error if not found)
712
- *
713
- * @param name - Variable name
714
- * @throws Error if variable is not found
715
- */
716
- requireVariable(name) {
717
- const value = this.getVariable(name);
718
- if (!value) {
719
- throw new Error(`Required variable '${name}' not found in environment`);
720
- }
721
- return value;
722
- }
723
- /**
724
- * Get Sinch application credentials
725
- */
726
- getApplicationCredentials() {
727
- const key = this.env.VOICE_APPLICATION_KEY;
728
- const secret = this.env.VOICE_APPLICATION_SECRET;
729
- if (key && secret) {
730
- return { applicationKey: key, applicationSecret: secret };
731
- }
732
- return null;
733
- }
734
- /**
735
- * Check if running in development mode
736
- */
737
- isDevelopment() {
738
- return this.env.NODE_ENV !== "production";
739
- }
740
- /**
741
- * Check if running in production mode
742
- */
743
- isProduction() {
744
- return this.env.NODE_ENV === "production";
745
- }
746
- /**
747
- * Get cache client instance
748
- */
749
- getCache() {
750
- return this.context.cache;
751
- }
752
- /**
753
- * Get comprehensive configuration summary (useful for debugging)
754
- * Excludes actual secret values for security
755
- */
756
- getConfigSummary() {
757
- const secretKeys = [
758
- "PROJECT_ID_API_SECRET",
759
- "VOICE_APPLICATION_SECRET",
760
- "DATABASE_PASSWORD",
761
- "API_KEY"
762
- ];
763
- const summary = {
764
- environment: this.isProduction() ? "production" : "development",
765
- variables: {},
766
- secrets: {},
767
- hasApplicationCredentials: !!this.getApplicationCredentials()
768
- };
769
- for (const [key, value] of Object.entries(this.env)) {
770
- if (secretKeys.some((secretKey) => key.includes(secretKey))) {
771
- summary.secrets[key] = value ? "[REDACTED]" : "[NOT SET]";
772
- } else if (["NODE_ENV", "PORT", "SINCH_REGION"].includes(key)) {
773
- summary.variables[key] = value;
774
- }
775
- }
776
- return summary;
777
- }
778
- };
779
- function createConfig(context) {
780
- return new UniversalConfig(context);
781
- }
782
- var createUniversalConfig = createConfig;
783
-
784
- // ../runtime-shared/dist/host/middleware.js
785
- import { createRequire } from "module";
786
- var requireCjs = createRequire(import.meta.url);
787
- var defaultOptions = {
788
- limit: "10mb",
789
- allowJson5: true,
790
- camelCase: {
791
- deep: true,
792
- stopPaths: ["custom", "applicationkey"],
793
- exclude: []
794
- }
795
- };
796
- var SPECIAL_CASES = {
797
- callid: "callId",
798
- applicationkey: "applicationKey",
799
- callbackurl: "callbackUrl",
800
- clinumber: "cliNumber",
801
- menuResult: "menuResult",
802
- userid: "userId",
803
- username: "userName",
804
- callleg: "callLeg",
805
- conferenceid: "conferenceId",
806
- participantid: "participantId"
807
- };
808
- function toCamelCase(str) {
809
- if (!str)
810
- return str;
811
- if (str.includes("_") || str.includes("-")) {
812
- return str.replace(/[-_]([a-z])/g, (_, char) => char.toUpperCase());
813
- }
814
- if (/[a-z][A-Z]/.test(str)) {
815
- return str;
816
- }
817
- const lower = str.toLowerCase();
818
- if (SPECIAL_CASES[lower]) {
819
- return SPECIAL_CASES[lower];
820
- }
821
- return str;
822
- }
823
- function transformKeys(obj, options = {}) {
824
- const { stopPaths = [], exclude = [], deep = true } = options;
825
- if (obj === null || obj === void 0) {
826
- return obj;
827
- }
828
- if (Array.isArray(obj)) {
829
- return deep ? obj.map((item) => transformKeys(item, options)) : obj;
830
- }
831
- if (typeof obj !== "object") {
832
- return obj;
833
- }
834
- const result = {};
835
- const DANGEROUS_KEYS = ["__proto__", "constructor", "prototype"];
836
- for (const [key, value] of Object.entries(obj)) {
837
- if (DANGEROUS_KEYS.includes(key)) {
838
- continue;
839
- }
840
- let newKey = key;
841
- let shouldTransformValue = deep;
842
- const isExcluded = exclude.some((pattern) => {
843
- if (pattern instanceof RegExp) {
844
- return pattern.test(key);
845
- }
846
- return pattern === key;
847
- });
848
- if (!isExcluded) {
849
- newKey = toCamelCase(key);
850
- }
851
- if (DANGEROUS_KEYS.includes(newKey)) {
852
- continue;
853
- }
854
- if (stopPaths.includes(newKey)) {
855
- shouldTransformValue = false;
856
- }
857
- result[newKey] = shouldTransformValue ? transformKeys(value, options) : value;
858
- }
859
- return result;
860
- }
861
- function parseJson(text, allowJson5 = true) {
862
- if (!text || typeof text !== "string") {
863
- return {};
864
- }
865
- const trimmed = text.trim();
866
- if (!trimmed) {
867
- return {};
868
- }
869
- try {
870
- return JSON.parse(trimmed);
871
- } catch (e) {
872
- if (!allowJson5) {
873
- throw new Error(`Invalid JSON: ${e.message}`);
874
- }
875
- try {
876
- const cleaned = trimmed.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "").replace(/,(\s*[}\]])/g, "$1");
877
- return JSON.parse(cleaned);
878
- } catch (e2) {
879
- throw new Error(`Invalid JSON/JSON5: ${e.message}`);
880
- }
881
- }
882
- }
883
- function createLenientJsonParser(options = {}) {
884
- const opts = { ...defaultOptions, ...options };
885
- return function lenientJsonParser(req, res, next) {
886
- if (req.body && typeof req.body === "object" && !Buffer.isBuffer(req.body)) {
887
- if (!req._keysTransformed) {
888
- const VOICE_EVENTS = ["ice", "ace", "pie", "dice", "notify"];
889
- const isVoice = req.body.event && VOICE_EVENTS.includes(req.body.event);
890
- if (isVoice) {
891
- req.body = transformKeys(req.body, opts.camelCase);
892
- }
893
- req._keysTransformed = true;
894
- }
895
- return next();
896
- }
897
- let raw = "";
898
- if (typeof req.body === "string") {
899
- raw = req.body;
900
- req.rawBody = raw;
901
- } else if (Buffer.isBuffer(req.body)) {
902
- raw = req.body.toString("utf8");
903
- req.rawBody = raw;
904
- } else {
905
- req.body = {};
906
- return next();
907
- }
908
- try {
909
- let parsed = parseJson(raw, opts.allowJson5);
910
- const VOICE_EVENTS = ["ice", "ace", "pie", "dice", "notify"];
911
- const evt = parsed && typeof parsed === "object" && "event" in parsed ? parsed.event : null;
912
- const isVoice = typeof evt === "string" && VOICE_EVENTS.includes(evt);
913
- if (isVoice) {
914
- parsed = transformKeys(parsed, opts.camelCase);
915
- }
916
- req._keysTransformed = true;
917
- req.body = parsed;
918
- next();
919
- } catch (error) {
920
- res.status(400).json({
921
- error: "Invalid JSON in request body",
922
- message: error.message,
923
- hint: opts.allowJson5 ? "This endpoint accepts JSON and JSON5 (comments and trailing commas allowed)" : "This endpoint requires strict JSON format"
924
- });
925
- }
926
- };
927
- }
928
- function setupJsonParsing(app, options = {}) {
929
- const express = requireCjs("express");
930
- app.use(express.text({
931
- type: ["application/json", "application/*+json", "text/json"],
932
- limit: options.limit || "10mb"
933
- }));
934
- app.use(createLenientJsonParser(options));
935
- return app;
936
- }
937
-
938
- // ../runtime-shared/dist/auth/basic-auth.js
939
- import { timingSafeEqual } from "crypto";
940
- function validateBasicAuth(authHeader, expectedKey, expectedSecret) {
941
- if (!authHeader) {
942
- return false;
943
- }
944
- if (!authHeader.toLowerCase().startsWith("basic ")) {
945
- return false;
946
- }
947
- const decoded = Buffer.from(authHeader.slice(6), "base64").toString("utf-8");
948
- const colonIndex = decoded.indexOf(":");
949
- if (colonIndex === -1) {
950
- return false;
951
- }
952
- const providedKey = decoded.slice(0, colonIndex);
953
- const providedSecret = decoded.slice(colonIndex + 1);
954
- const expectedKeyBuf = Buffer.from(expectedKey);
955
- const providedKeyBuf = Buffer.from(providedKey);
956
- const expectedSecretBuf = Buffer.from(expectedSecret);
957
- const providedSecretBuf = Buffer.from(providedSecret);
958
- const keyMatch = expectedKeyBuf.length === providedKeyBuf.length && timingSafeEqual(expectedKeyBuf, providedKeyBuf);
959
- const secretMatch = expectedSecretBuf.length === providedSecretBuf.length && timingSafeEqual(expectedSecretBuf, providedSecretBuf);
960
- return keyMatch && secretMatch;
961
- }
962
-
963
- // ../runtime-shared/dist/security/index.js
964
- var defaultSecurityOptions = {
965
- webhookProtection: "deploy"
966
- };
967
- function shouldValidateWebhook(mode, isDevelopment) {
968
- const normalizedMode = (mode || "deploy").toLowerCase();
969
- switch (normalizedMode) {
970
- case "never":
971
- return false;
972
- case "always":
973
- return true;
974
- case "deploy":
975
- default:
976
- return !isDevelopment;
977
- }
978
- }
979
- var VALID_MODES = ["never", "deploy", "always"];
980
- function getProtectionMode(config) {
981
- const envValue = process.env.WEBHOOK_PROTECTION ?? process.env.PROTECT_VOICE_CALLBACKS;
982
- if (envValue) {
983
- const normalized = envValue.toLowerCase();
984
- if (VALID_MODES.includes(normalized)) {
985
- return normalized;
986
- }
987
- console.warn(`[SECURITY] Unknown WEBHOOK_PROTECTION value "${envValue}", defaulting to "deploy"`);
988
- return "deploy";
989
- }
990
- const configValue = config?.WebhookProtection ?? config?.webhookProtection ?? config?.ProtectVoiceCallbacks ?? config?.protectVoiceCallbacks;
991
- if (typeof configValue === "string") {
992
- const normalized = configValue.toLowerCase();
993
- if (VALID_MODES.includes(normalized)) {
994
- return normalized;
995
- }
996
- console.warn(`[SECURITY] Unknown webhook protection value "${configValue}", defaulting to "deploy"`);
997
- return "deploy";
998
- }
999
- return "deploy";
1000
- }
1001
- function createSecurityOptions(config) {
1002
- return {
1003
- webhookProtection: getProtectionMode(config)
1004
- };
1005
- }
1006
-
1007
- // ../runtime-shared/dist/sinch/index.js
1008
- import { SinchClient, validateAuthenticationHeader, ConversationCallbackWebhooks } from "@sinch/sdk-core";
1009
- function createSinchClients() {
1010
- const clients = {};
1011
- const hasCredentials = process.env.PROJECT_ID && process.env.PROJECT_ID_API_KEY && process.env.PROJECT_ID_API_SECRET;
1012
- if (process.env.CONVERSATION_WEBHOOK_SECRET) {
1013
- const callbackProcessor = new ConversationCallbackWebhooks(process.env.CONVERSATION_WEBHOOK_SECRET);
1014
- clients.validateConversationWebhook = (headers, body) => {
1015
- try {
1016
- const result = callbackProcessor.validateAuthenticationHeader(headers, body);
1017
- console.log("[SINCH] Conversation webhook validation:", result ? "VALID" : "INVALID");
1018
- return result;
1019
- } catch (error) {
1020
- console.error("[SINCH] Conversation validation error:", error instanceof Error ? error.message : error);
1021
- return false;
1022
- }
1023
- };
1024
- }
1025
- if (!hasCredentials) {
1026
- return clients;
1027
- }
1028
- try {
1029
- const sinchClient = new SinchClient({
1030
- projectId: process.env.PROJECT_ID,
1031
- keyId: process.env.PROJECT_ID_API_KEY,
1032
- keySecret: process.env.PROJECT_ID_API_SECRET
1033
- });
1034
- if (process.env.CONVERSATION_APP_ID) {
1035
- clients.conversation = sinchClient.conversation;
1036
- console.log("[SINCH] Conversation API initialized");
1037
- }
1038
- if (process.env.VOICE_APPLICATION_KEY && process.env.VOICE_APPLICATION_SECRET) {
1039
- const voiceClient = new SinchClient({
1040
- projectId: process.env.PROJECT_ID,
1041
- keyId: process.env.PROJECT_ID_API_KEY,
1042
- keySecret: process.env.PROJECT_ID_API_SECRET,
1043
- applicationKey: process.env.VOICE_APPLICATION_KEY,
1044
- applicationSecret: process.env.VOICE_APPLICATION_SECRET
1045
- });
1046
- clients.voice = voiceClient.voice;
1047
- console.log("[SINCH] Voice API initialized with application credentials");
1048
- }
1049
- if (process.env.SMS_SERVICE_PLAN_ID) {
1050
- clients.sms = sinchClient.sms;
1051
- console.log("[SINCH] SMS API initialized");
1052
- }
1053
- if (process.env.ENABLE_NUMBERS_API === "true") {
1054
- clients.numbers = sinchClient.numbers;
1055
- console.log("[SINCH] Numbers API initialized");
1056
- }
1057
- } catch (error) {
1058
- console.error("[SINCH] Failed to initialize Sinch clients:", error.message);
1059
- return {};
1060
- }
1061
- if (process.env.VOICE_APPLICATION_KEY && process.env.VOICE_APPLICATION_SECRET) {
1062
- clients.validateWebhookSignature = (requestData) => {
1063
- console.log("[SINCH] Validating Voice webhook signature");
1064
- try {
1065
- const result = validateAuthenticationHeader(process.env.VOICE_APPLICATION_KEY, process.env.VOICE_APPLICATION_SECRET, requestData.headers, requestData.body, requestData.path, requestData.method);
1066
- console.log("[SINCH] Validation result:", result ? "VALID" : "INVALID");
1067
- return result;
1068
- } catch (error) {
1069
- console.error("[SINCH] Validation error:", error.message);
1070
- return false;
1071
- }
1072
- };
1073
- }
1074
- return clients;
1075
- }
1076
- var cachedClients = null;
1077
- function getSinchClients() {
1078
- if (!cachedClients) {
1079
- cachedClients = createSinchClients();
1080
- }
1081
- return cachedClients;
1082
- }
1083
- function resetSinchClients() {
1084
- cachedClients = null;
1085
- }
1086
-
1087
- // ../runtime-shared/dist/host/app.js
1088
- import { createRequire as createRequire2 } from "module";
1089
- import { pathToFileURL } from "url";
1090
- import * as nodePath from "path";
1091
- import * as nodeFs from "fs";
1092
- var requireCjs2 = createRequire2(import.meta.url);
1093
- var LANDING_PAGE_HTML = `<!DOCTYPE html>
1094
- <html lang="en">
1095
- <head>
1096
- <meta charset="UTF-8">
1097
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1098
- <title>Sinch Function</title>
1099
- <link rel="icon" type="image/svg+xml" href="/favicon.ico">
1100
- <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap" rel="stylesheet">
1101
- <style>
1102
- * { margin: 0; padding: 0; box-sizing: border-box; }
1103
- body { font-family: "DM Sans", Arial, sans-serif; min-height: 100vh; overflow: hidden; background: #ffffff; }
1104
- #gradient-canvas { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; }
1105
- .content { position: relative; z-index: 10; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 2rem; mix-blend-mode: difference; }
1106
- .icon-wrapper { width: 120px; height: 120px; margin-bottom: 2rem; animation: float 6s ease-in-out infinite; }
1107
- @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-12px); } }
1108
- .icon-wrapper svg { width: 100%; height: 100%; fill: white; }
1109
- .title { font-size: clamp(32px, 6vw, 56px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; color: white; text-align: center; max-width: 600px; margin-bottom: 1.5rem; }
1110
- .status { display: inline-flex; align-items: center; gap: 0.75rem; font-size: 18px; font-weight: 500; color: white; opacity: 0.9; }
1111
- .status-dot { width: 10px; height: 10px; background: white; border-radius: 50%; position: relative; }
1112
- .status-dot::before { content: ''; position: absolute; inset: -4px; border-radius: 50%; border: 2px solid white; animation: ripple 2s ease-out infinite; }
1113
- @keyframes ripple { 0% { transform: scale(1); opacity: 0.6; } 100% { transform: scale(2); opacity: 0; } }
1114
- footer { position: fixed; bottom: 0; left: 0; right: 0; padding: 1.5rem 2rem; text-align: center; z-index: 10; mix-blend-mode: difference; }
1115
- .footer-content { display: flex; align-items: center; justify-content: center; gap: 0.5rem; font-size: 13px; color: white; opacity: 0.7; }
1116
- .footer-content svg { height: 16px; width: auto; fill: white; }
1117
- @media (prefers-reduced-motion: reduce) { .icon-wrapper { animation: none; } .status-dot::before { animation: none; display: none; } }
1118
- </style>
1119
- </head>
1120
- <body>
1121
- <canvas id="gradient-canvas"></canvas>
1122
- <div class="content">
1123
- <div class="icon-wrapper">
1124
- <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
1125
- <path d="M0 0 C20.93144435 -0.58142901 39.09496106 1.50604372 55.875 15.5625 C66.82790249 26.17665293 72.53226475 40.66646351 74.60546875 55.56640625 C74.87588186 58.00035983 74.87588186 58.00035983 76 60 C76.96454894 67.72509952 77.18355452 75.52548686 77.39453125 83.30078125 C77.46339082 85.43557289 77.53307981 87.57033791 77.60351562 89.70507812 C77.70976411 92.99051459 77.81152568 96.27576582 77.89868164 99.56176758 C78.52393733 129.23731142 78.52393733 129.23731142 88 157 C88.35578125 157.67804688 88.7115625 158.35609375 89.078125 159.0546875 C94.76089061 168.37922543 104.94901494 170.48725373 115 173 C115 182.57 115 192.14 115 202 C112.69 202.37125 110.38 202.7425 108 203.125 C99.905737 204.67003153 95.0680161 206.8924082 90.109375 213.53125 C83.71376381 223.52775152 81.23188184 234.44421869 79.9609375 246.09765625 C79.87667007 246.86579147 79.79240265 247.6339267 79.70558167 248.42533875 C78.67925596 258.36255872 78.32712705 268.3341428 77.9375 278.3125 C76.56010435 312.28921394 76.56010435 312.28921394 74.25 321.5 C74.0744458 322.21430176 73.8988916 322.92860352 73.71801758 323.66455078 C69.36621237 340.7251508 62.22279512 355.52722574 46.7734375 364.97265625 C31.08266768 373.31391199 17.46036093 374.45648002 0 374 C0 362.78 0 351.56 0 340 C4.95 339.67 9.9 339.34 15 339 C21.41425661 337.54221441 27.40557289 335.94604143 32 331 C41.96653782 315.14896379 41.37732492 296.30175799 42 278.25 C44.29042973 212.3198731 44.29042973 212.3198731 64.91015625 190 C66.29780265 187.98880883 66.29780265 187.98880883 65.37890625 185.48046875 C64.05564488 183.10009772 62.69232678 181.32846483 60.875 179.3125 C43.91950219 157.82609672 43.67363702 127.5168667 42.25390625 101.43359375 C42.19595886 100.36962875 42.13801147 99.30566376 42.07830811 98.2094574 C41.84407978 93.84466467 41.61402719 89.47975805 41.39819336 85.11401367 C40.99015593 64.27717646 40.99015593 64.27717646 32.98828125 45.5234375 C32 44 32 44 32 42 C31.42121094 41.71253906 30.84242188 41.42507813 30.24609375 41.12890625 C28.83602338 40.42019262 27.43139326 39.70043581 26.03515625 38.96484375 C25.38417969 38.62582031 24.73320313 38.28679687 24.0625 37.9375 C23.41410156 37.59589844 22.76570312 37.25429688 22.09765625 36.90234375 C15.27203813 33.966184 7.11372705 34.47424847 0 34 C0 22.78 0 11.56 0 0 Z" transform="translate(654,325)"/>
1126
- <path d="M0 0 C3.444375 0.04125 6.88875 0.0825 10.4375 0.125 C10.4375 11.345 10.4375 22.565 10.4375 34.125 C7.83875 34.2075 5.24 34.29 2.5625 34.375 C-7.18272292 34.85729903 -15.63749007 36.71684985 -22.5625 44.125 C-31.49595906 57.5251886 -31.12984766 74.21365918 -31.625 89.6875 C-34.18432686 164.24320576 -34.18432686 164.24320576 -54.375 183.4765625 C-55.74969183 185.03433577 -55.74969183 185.03433577 -55.515625 186.95703125 C-54.17099734 190.0155081 -52.28807488 192.49561568 -50.3125 195.1875 C-32.54496946 220.15391355 -32.63824135 251.51444506 -31.51293945 280.92919922 C-31.08045868 292.11365858 -30.51897291 303.08447592 -28.5625 314.125 C-28.43262695 314.88192139 -28.30275391 315.63884277 -28.16894531 316.41870117 C-26.61388783 323.91215705 -23.50529382 330.13896804 -17.1875 334.5625 C-8.59143743 340.04835084 0.27828442 339.49004903 10.4375 340.125 C10.4375 351.345 10.4375 362.565 10.4375 374.125 C-11.03507606 374.69006779 -28.20349315 372.92712593 -45.375 358.5625 C-68.63112564 336.25560398 -67.21470802 299.23895394 -68.0625 269.5625 C-68.59361144 237.84268541 -68.59361144 237.84268541 -82.5625 210.125 C-89.22872268 204.50037462 -95.95018781 203.27807805 -104.5625 201.125 C-104.5625 191.885 -104.5625 182.645 -104.5625 173.125 C-102.0875 172.444375 -99.6125 171.76375 -97.0625 171.0625 C-88.61410179 168.53529591 -83.39407037 165.21504609 -78.3125 157.875 C-77.69451944 156.64176126 -77.11369297 155.38950152 -76.5625 154.125 C-76.05783203 152.97451172 -76.05783203 152.97451172 -75.54296875 151.80078125 C-70.10324087 138.17090127 -68.58488302 123.17691663 -68.1328125 108.6171875 C-68.0590342 106.55597377 -67.98479985 104.49477633 -67.91015625 102.43359375 C-67.79799647 99.2401961 -67.68897443 96.04681123 -67.58837891 92.85302734 C-67.22538737 81.52946225 -66.65494051 70.32073083 -65.13671875 59.0859375 C-64.95793686 57.75983963 -64.95793686 57.75983963 -64.77554321 56.4069519 C-62.24372342 39.06207822 -55.12155189 23.04594995 -40.9609375 12.1171875 C-28.07509054 3.53900119 -15.33988115 -0.26186367 0 0 Z" transform="translate(359.5625,324.875)"/>
1127
- <path d="M0 0 C9.89334431 8.68950817 14.30034619 23.01452361 15.24373245 35.79419899 C15.49099471 41.77148785 15.42334062 47.74978768 15.37109375 53.73046875 C15.36548489 55.63859724 15.36122091 57.54673011 15.35823059 59.4548645 C15.34688325 64.42950786 15.31750548 69.40388024 15.28411865 74.37841797 C15.25319735 79.47359555 15.23967854 84.56881775 15.22460938 89.6640625 C15.19262409 99.62643911 15.13994121 109.58854505 15.078125 119.55078125 C3.528125 119.55078125 -8.021875 119.55078125 -19.921875 119.55078125 C-19.97085938 114.4203125 -20.01984375 109.28984375 -20.0703125 104.00390625 C-20.10574492 100.73175245 -20.14173112 97.45962313 -20.1796875 94.1875 C-20.23973228 89.00671097 -20.29785091 83.82595572 -20.34375 78.64501953 C-20.38093086 74.46275871 -20.42737419 70.28068941 -20.47993851 66.09859467 C-20.49830992 64.51204578 -20.51347972 62.92545612 -20.52521896 61.3388443 C-20.22141003 42.05064114 -20.22141003 42.05064114 -28.921875 25.55078125 C-33.2097739 21.98892101 -37.29807009 19.87523153 -42.921875 19.55078125 C-43.79714844 19.48890625 -44.67242188 19.42703125 -45.57421875 19.36328125 C-54.66067243 18.98906437 -62.9621186 20.4280254 -69.859375 26.73828125 C-76.14726535 33.73487866 -78.0525657 41.92333342 -78.12719727 51.07324219 C-78.13709686 51.82485123 -78.14699646 52.57646027 -78.15719604 53.35084534 C-78.18871966 55.82891721 -78.21353223 58.30700823 -78.23828125 60.78515625 C-78.25885867 62.50580334 -78.27985536 64.22644545 -78.30125427 65.94708252 C-78.35639351 70.47125217 -78.40583867 74.99546682 -78.45410156 79.51971436 C-78.51321858 84.95049451 -78.57940167 90.38119259 -78.64440155 95.81190491 C-78.74230855 104.0581468 -78.83123469 112.30444185 -78.921875 120.55078125 C-90.801875 120.55078125 -102.681875 120.55078125 -114.921875 120.55078125 C-114.921875 77.65078125 -114.921875 34.75078125 -114.921875 -9.44921875 C-103.701875 -9.44921875 -92.481875 -9.44921875 -80.921875 -9.44921875 C-79.96000569 -5.60174152 -79.61528473 -2.14754023 -79.359375 1.80078125 C-79.27558594 3.0640625 -79.19179688 4.32734375 -79.10546875 5.62890625 C-79.04488281 6.593125 -78.98429688 7.55734375 -78.921875 8.55078125 C-78.48875 7.72578125 -78.055625 6.90078125 -77.609375 6.05078125 C-71.50314599 -3.01214812 -59.57220635 -8.76116827 -49.16015625 -11.05859375 C-31.06340614 -13.24155516 -14.8555768 -11.20207112 0 0 Z" transform="translate(613.921875,481.44921875)"/>
1128
- <path d="M0 0 C1.53906801 1.53906801 1.16955456 2.91263628 1.1875 5.0625 C1.1451715 9.92322255 0.65815533 14.68227908 0.0625 19.5 C-0.02427002 20.20648682 -0.11104004 20.91297363 -0.20043945 21.64086914 C-0.86920125 26.7384025 -0.86920125 26.7384025 -2 29 C-2.96808594 28.84144531 -3.93617188 28.68289063 -4.93359375 28.51953125 C-9.31081865 27.89956204 -13.64601408 27.74275212 -18.0625 27.6875 C-18.83916016 27.65849609 -19.61582031 27.62949219 -20.41601562 27.59960938 C-25.75566236 27.54083257 -28.83098013 28.36372264 -33 32 C-37.31404494 38.3211768 -37.31404494 38.3211768 -37 53 C-25.78 53 -14.56 53 -3 53 C-3 62.57 -3 72.14 -3 82 C-14.55 82 -26.1 82 -38 82 C-38 115 -38 148 -38 182 C-49.55 182 -61.1 182 -73 182 C-73 149 -73 116 -73 82 C-79.93 82 -86.86 82 -94 82 C-94 72.43 -94 62.86 -94 53 C-87.07 53 -80.14 53 -73 53 C-73.04125 50.6075 -73.0825 48.215 -73.125 45.75 C-73.17827085 31.60875021 -70.96095372 19.48048613 -61.0078125 8.81640625 C-54.5981324 3.0177657 -47.30019677 0.02408307 -39 -2 C-38.37625488 -2.17200928 -37.75250977 -2.34401855 -37.10986328 -2.52124023 C-25.33848182 -5.19234404 -11.53065338 -2.96722147 0 0 Z" transform="translate(486,419)"/>
1129
- </svg>
1130
- </div>
1131
- <h1 class="title">Your function is ready for traffic</h1>
1132
- <div class="status"><span class="status-dot"></span>Running</div>
1133
- </div>
1134
- <footer>
1135
- <div class="footer-content">
1136
- Powered by
1137
- <svg viewBox="0 0 93 48" xmlns="http://www.w3.org/2000/svg">
1138
- <path d="M92.298 25.271a17.167 17.167 0 0 1-.814 5.312c-1.51 4.734-5.27 8.678-10.06 10.549-5.64 2.202-12.252 1.416-18.624-2.21l-4.649-2.67a16.424 16.424 0 0 1-3.563 3.064l-14.817 8.679-.027.015v-7.501l.027-.014 22.29-13.057a16.017 16.017 0 0 1-.713 3.206l4.656 2.65c5.95 3.386 10.388 2.85 13.065 1.806 2.991-1.167 5.323-3.59 6.245-6.483.692-2.15.679-4.467-.04-6.609-.955-2.88-3.319-5.275-6.324-6.41-2.688-1.014-7.132-1.494-13.04 1.962L29.7 38.747l-.043.028c-4.017 2.35-8.14 3.556-12.065 3.58a18.162 18.162 0 0 1-6.53-1.145C6.247 39.396 2.44 35.498.874 30.783A17.116 17.116 0 0 1 .81 20.166c1.51-4.733 5.272-8.676 10.063-10.548 5.64-2.202 12.252-1.416 18.623 2.212l4.649 2.67a16.377 16.377 0 0 1 3.563-3.067l.281-.163 1.726-1.011-7.37-4.197A3.238 3.238 0 0 1 35.551.437l10.591 6.06L56.52.457a3.238 3.238 0 0 1 3.27 5.588l-29.528 17.05c.132-1.017.36-2.019.683-2.992l-4.656-2.65c-5.946-3.383-10.384-2.847-13.061-1.803-2.991 1.167-5.325 3.59-6.247 6.481a10.623 10.623 0 0 0 .039 6.608c.956 2.882 3.321 5.277 6.324 6.41 2.689 1.012 7.136 1.495 13.042-1.966l36.256-21.208c4.017-2.349 8.14-3.555 12.067-3.579a18.112 18.112 0 0 1 6.53 1.145c4.812 1.813 8.62 5.712 10.187 10.426a17.23 17.23 0 0 1 .872 5.304Z"/>
1139
- </svg>
1140
- </div>
1141
- </footer>
1142
- <script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js"}}</script>
1143
- <script type="module">
1144
- import * as THREE from 'three';
1145
- const COLORS={yellow:new THREE.Color(0xFFBE3C),green:new THREE.Color(0x059688),blue:new THREE.Color(0x3AA7EA),red:new THREE.Color(0xEF5858)};
1146
- const vertexShader=\`varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}\`;
1147
- const fragmentShader=\`uniform float uTime;uniform vec2 uResolution;uniform vec3 uColor1;uniform vec3 uColor2;uniform vec3 uColor3;uniform vec3 uColor4;varying vec2 vUv;vec3 mod289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}vec4 permute(vec4 x){return mod289(((x*34.0)+1.0)*x);}vec4 taylorInvSqrt(vec4 r){return 1.79284291400159-0.85373472095314*r;}float snoise(vec3 v){const vec2 C=vec2(1.0/6.0,1.0/3.0);const vec4 D=vec4(0.0,0.5,1.0,2.0);vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.0-g;vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;i=mod289(i);vec4 p=permute(permute(permute(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));float n_=0.142857142857;vec3 ns=n_*D.wyz-D.xzx;vec4 j=p-49.0*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.0*x_);vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.0-abs(x)-abs(y);vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);vec4 s0=floor(b0)*2.0+1.0;vec4 s1=floor(b1)*2.0+1.0;vec4 sh=-step(h,vec4(0.0));vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);vec4 norm=taylorInvSqrt(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);m=m*m;return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}float metaball(vec2 p,vec2 center,float radius){float d=length(p-center);return radius/(d*d+0.0001);}void main(){vec2 uv=vUv;vec2 aspect=vec2(uResolution.x/uResolution.y,1.0);vec2 p=(uv-0.5)*aspect;float time=uTime*0.15;vec2 blob1=vec2(0.6*sin(time*0.7+snoise(vec3(time*0.2,0.0,0.0))),0.5*cos(time*0.5+snoise(vec3(0.0,time*0.2,0.0))));vec2 blob2=vec2(0.55*cos(time*0.6+1.5+snoise(vec3(time*0.15,1.0,0.0))),0.6*sin(time*0.8+2.0+snoise(vec3(1.0,time*0.15,0.0))));vec2 blob3=vec2(0.7*sin(time*0.5+3.0+snoise(vec3(time*0.1,2.0,0.0))),0.5*cos(time*0.7+1.0+snoise(vec3(2.0,time*0.1,0.0))));vec2 blob4=vec2(0.55*cos(time*0.8+4.5+snoise(vec3(time*0.12,3.0,0.0))),0.65*sin(time*0.6+0.5+snoise(vec3(3.0,time*0.12,0.0))));float size1=0.16+0.04*sin(time*1.2);float size2=0.14+0.03*cos(time*1.5);float size3=0.18+0.05*sin(time*0.9);float size4=0.12+0.04*cos(time*1.1);float m1=metaball(p,blob1,size1);float m2=metaball(p,blob2,size2);float m3=metaball(p,blob3,size3);float m4=metaball(p,blob4,size4);float field=m1+m2+m3+m4;float noise=snoise(vec3(p*3.0,time*0.3))*0.15;field+=noise;vec3 color=vec3(0.0);float total=m1+m2+m3+m4+0.0001;color+=uColor1*(m1/total);color+=uColor2*(m2/total);color+=uColor3*(m3/total);color+=uColor4*(m4/total);float gradientNoise=snoise(vec3(uv*2.0,time*0.1));color+=gradientNoise*0.05;float threshold=0.8;float edge=smoothstep(threshold-0.3,threshold+0.5,field);vec3 bg1=mix(uColor1,uColor3,uv.y)*0.6+0.4;vec3 bg2=mix(uColor2,uColor4,uv.x)*0.6+0.4;vec3 background=mix(bg1,bg2,0.5+0.5*sin(time*0.2));vec3 finalColor=mix(background,color,edge);float vignette=1.0-length(uv-0.5)*0.5;finalColor*=vignette;finalColor=pow(finalColor,vec3(0.95));gl_FragColor=vec4(finalColor,1.0);}\`;
1148
- class GradientAnimation{constructor(){this.canvas=document.getElementById('gradient-canvas');this.scene=new THREE.Scene();this.camera=new THREE.OrthographicCamera(-1,1,1,-1,0,1);this.renderer=new THREE.WebGLRenderer({canvas:this.canvas,antialias:true,alpha:false});this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2));this.renderer.setSize(window.innerWidth,window.innerHeight);this.uniforms={uTime:{value:0},uResolution:{value:new THREE.Vector2(window.innerWidth,window.innerHeight)},uColor1:{value:COLORS.yellow},uColor2:{value:COLORS.green},uColor3:{value:COLORS.blue},uColor4:{value:COLORS.red}};const geometry=new THREE.PlaneGeometry(2,2);const material=new THREE.ShaderMaterial({vertexShader,fragmentShader,uniforms:this.uniforms});this.mesh=new THREE.Mesh(geometry,material);this.scene.add(this.mesh);window.addEventListener('resize',this.onResize.bind(this));this.animate();}onResize(){this.renderer.setSize(window.innerWidth,window.innerHeight);this.uniforms.uResolution.value.set(window.innerWidth,window.innerHeight);}animate(){this.uniforms.uTime.value+=0.016;this.renderer.render(this.scene,this.camera);requestAnimationFrame(this.animate.bind(this));}}
1149
- new GradientAnimation();
1150
- </script>
1151
- </body>
1152
- </html>`;
1153
- function getLandingPageHtml() {
1154
- return LANDING_PAGE_HTML;
1155
- }
1156
- var FAVICON_SVG = `<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
1157
- <rect width="1024" height="1024" fill="#3AA7EA"/>
1158
- <path fill="white" d="M0 0 C20.93144435 -0.58142901 39.09496106 1.50604372 55.875 15.5625 C66.82790249 26.17665293 72.53226475 40.66646351 74.60546875 55.56640625 C74.87588186 58.00035983 74.87588186 58.00035983 76 60 C76.96454894 67.72509952 77.18355452 75.52548686 77.39453125 83.30078125 C77.46339082 85.43557289 77.53307981 87.57033791 77.60351562 89.70507812 C77.70976411 92.99051459 77.81152568 96.27576582 77.89868164 99.56176758 C78.52393733 129.23731142 78.52393733 129.23731142 88 157 C88.35578125 157.67804688 88.7115625 158.35609375 89.078125 159.0546875 C94.76089061 168.37922543 104.94901494 170.48725373 115 173 C115 182.57 115 192.14 115 202 C112.69 202.37125 110.38 202.7425 108 203.125 C99.905737 204.67003153 95.0680161 206.8924082 90.109375 213.53125 C83.71376381 223.52775152 81.23188184 234.44421869 79.9609375 246.09765625 C79.87667007 246.86579147 79.79240265 247.6339267 79.70558167 248.42533875 C78.67925596 258.36255872 78.32712705 268.3341428 77.9375 278.3125 C76.56010435 312.28921394 76.56010435 312.28921394 74.25 321.5 C74.0744458 322.21430176 73.8988916 322.92860352 73.71801758 323.66455078 C69.36621237 340.7251508 62.22279512 355.52722574 46.7734375 364.97265625 C31.08266768 373.31391199 17.46036093 374.45648002 0 374 C0 362.78 0 351.56 0 340 C4.95 339.67 9.9 339.34 15 339 C21.41425661 337.54221441 27.40557289 335.94604143 32 331 C41.96653782 315.14896379 41.37732492 296.30175799 42 278.25 C44.29042973 212.3198731 44.29042973 212.3198731 64.91015625 190 C66.29780265 187.98880883 66.29780265 187.98880883 65.37890625 185.48046875 C64.05564488 183.10009772 62.69232678 181.32846483 60.875 179.3125 C43.91950219 157.82609672 43.67363702 127.5168667 42.25390625 101.43359375 C42.19595886 100.36962875 42.13801147 99.30566376 42.07830811 98.2094574 C41.84407978 93.84466467 41.61402719 89.47975805 41.39819336 85.11401367 C40.99015593 64.27717646 40.99015593 64.27717646 32.98828125 45.5234375 C32 44 32 44 32 42 C31.42121094 41.71253906 30.84242188 41.42507813 30.24609375 41.12890625 C28.83602338 40.42019262 27.43139326 39.70043581 26.03515625 38.96484375 C25.38417969 38.62582031 24.73320313 38.28679687 24.0625 37.9375 C23.41410156 37.59589844 22.76570312 37.25429688 22.09765625 36.90234375 C15.27203813 33.966184 7.11372705 34.47424847 0 34 C0 22.78 0 11.56 0 0 Z" transform="translate(654,325)"/>
1159
- <path fill="white" d="M0 0 C3.444375 0.04125 6.88875 0.0825 10.4375 0.125 C10.4375 11.345 10.4375 22.565 10.4375 34.125 C7.83875 34.2075 5.24 34.29 2.5625 34.375 C-7.18272292 34.85729903 -15.63749007 36.71684985 -22.5625 44.125 C-31.49595906 57.5251886 -31.12984766 74.21365918 -31.625 89.6875 C-34.18432686 164.24320576 -34.18432686 164.24320576 -54.375 183.4765625 C-55.74969183 185.03433577 -55.74969183 185.03433577 -55.515625 186.95703125 C-54.17099734 190.0155081 -52.28807488 192.49561568 -50.3125 195.1875 C-32.54496946 220.15391355 -32.63824135 251.51444506 -31.51293945 280.92919922 C-31.08045868 292.11365858 -30.51897291 303.08447592 -28.5625 314.125 C-28.43262695 314.88192139 -28.30275391 315.63884277 -28.16894531 316.41870117 C-26.61388783 323.91215705 -23.50529382 330.13896804 -17.1875 334.5625 C-8.59143743 340.04835084 0.27828442 339.49004903 10.4375 340.125 C10.4375 351.345 10.4375 362.565 10.4375 374.125 C-11.03507606 374.69006779 -28.20349315 372.92712593 -45.375 358.5625 C-68.63112564 336.25560398 -67.21470802 299.23895394 -68.0625 269.5625 C-68.59361144 237.84268541 -68.59361144 237.84268541 -82.5625 210.125 C-89.22872268 204.50037462 -95.95018781 203.27807805 -104.5625 201.125 C-104.5625 191.885 -104.5625 182.645 -104.5625 173.125 C-102.0875 172.444375 -99.6125 171.76375 -97.0625 171.0625 C-88.61410179 168.53529591 -83.39407037 165.21504609 -78.3125 157.875 C-77.69451944 156.64176126 -77.11369297 155.38950152 -76.5625 154.125 C-76.05783203 152.97451172 -76.05783203 152.97451172 -75.54296875 151.80078125 C-70.10324087 138.17090127 -68.58488302 123.17691663 -68.1328125 108.6171875 C-68.0590342 106.55597377 -67.98479985 104.49477633 -67.91015625 102.43359375 C-67.79799647 99.2401961 -67.68897443 96.04681123 -67.58837891 92.85302734 C-67.22538737 81.52946225 -66.65494051 70.32073083 -65.13671875 59.0859375 C-64.95793686 57.75983963 -64.95793686 57.75983963 -64.77554321 56.4069519 C-62.24372342 39.06207822 -55.12155189 23.04594995 -40.9609375 12.1171875 C-28.07509054 3.53900119 -15.33988115 -0.26186367 0 0 Z" transform="translate(359.5625,324.875)"/>
1160
- <path fill="white" d="M0 0 C9.89334431 8.68950817 14.30034619 23.01452361 15.24373245 35.79419899 C15.49099471 41.77148785 15.42334062 47.74978768 15.37109375 53.73046875 C15.36548489 55.63859724 15.36122091 57.54673011 15.35823059 59.4548645 C15.34688325 64.42950786 15.31750548 69.40388024 15.28411865 74.37841797 C15.25319735 79.47359555 15.23967854 84.56881775 15.22460938 89.6640625 C15.19262409 99.62643911 15.13994121 109.58854505 15.078125 119.55078125 C3.528125 119.55078125 -8.021875 119.55078125 -19.921875 119.55078125 C-19.97085938 114.4203125 -20.01984375 109.28984375 -20.0703125 104.00390625 C-20.10574492 100.73175245 -20.14173112 97.45962313 -20.1796875 94.1875 C-20.23973228 89.00671097 -20.29785091 83.82595572 -20.34375 78.64501953 C-20.38093086 74.46275871 -20.42737419 70.28068941 -20.47993851 66.09859467 C-20.49830992 64.51204578 -20.51347972 62.92545612 -20.52521896 61.3388443 C-20.22141003 42.05064114 -20.22141003 42.05064114 -28.921875 25.55078125 C-33.2097739 21.98892101 -37.29807009 19.87523153 -42.921875 19.55078125 C-43.79714844 19.48890625 -44.67242188 19.42703125 -45.57421875 19.36328125 C-54.66067243 18.98906437 -62.9621186 20.4280254 -69.859375 26.73828125 C-76.14726535 33.73487866 -78.0525657 41.92333342 -78.12719727 51.07324219 C-78.13709686 51.82485123 -78.14699646 52.57646027 -78.15719604 53.35084534 C-78.18871966 55.82891721 -78.21353223 58.30700823 -78.23828125 60.78515625 C-78.25885867 62.50580334 -78.27985536 64.22644545 -78.30125427 65.94708252 C-78.35639351 70.47125217 -78.40583867 74.99546682 -78.45410156 79.51971436 C-78.51321858 84.95049451 -78.57940167 90.38119259 -78.64440155 95.81190491 C-78.74230855 104.0581468 -78.83123469 112.30444185 -78.921875 120.55078125 C-90.801875 120.55078125 -102.681875 120.55078125 -114.921875 120.55078125 C-114.921875 77.65078125 -114.921875 34.75078125 -114.921875 -9.44921875 C-103.701875 -9.44921875 -92.481875 -9.44921875 -80.921875 -9.44921875 C-79.96000569 -5.60174152 -79.61528473 -2.14754023 -79.359375 1.80078125 C-79.27558594 3.0640625 -79.19179688 4.32734375 -79.10546875 5.62890625 C-79.04488281 6.593125 -78.98429688 7.55734375 -78.921875 8.55078125 C-78.48875 7.72578125 -78.055625 6.90078125 -77.609375 6.05078125 C-71.50314599 -3.01214812 -59.57220635 -8.76116827 -49.16015625 -11.05859375 C-31.06340614 -13.24155516 -14.8555768 -11.20207112 0 0 Z" transform="translate(613.921875,481.44921875)"/>
1161
- <path fill="white" d="M0 0 C1.53906801 1.53906801 1.16955456 2.91263628 1.1875 5.0625 C1.1451715 9.92322255 0.65815533 14.68227908 0.0625 19.5 C-0.02427002 20.20648682 -0.11104004 20.91297363 -0.20043945 21.64086914 C-0.86920125 26.7384025 -0.86920125 26.7384025 -2 29 C-2.96808594 28.84144531 -3.93617188 28.68289063 -4.93359375 28.51953125 C-9.31081865 27.89956204 -13.64601408 27.74275212 -18.0625 27.6875 C-18.83916016 27.65849609 -19.61582031 27.62949219 -20.41601562 27.59960938 C-25.75566236 27.54083257 -28.83098013 28.36372264 -33 32 C-37.31404494 38.3211768 -37.31404494 38.3211768 -37 53 C-25.78 53 -14.56 53 -3 53 C-3 62.57 -3 72.14 -3 82 C-14.55 82 -26.1 82 -38 82 C-38 115 -38 148 -38 182 C-49.55 182 -61.1 182 -73 182 C-73 149 -73 116 -73 82 C-79.93 82 -86.86 82 -94 82 C-94 72.43 -94 62.86 -94 53 C-87.07 53 -80.14 53 -73 53 C-73.04125 50.6075 -73.0825 48.215 -73.125 45.75 C-73.17827085 31.60875021 -70.96095372 19.48048613 -61.0078125 8.81640625 C-54.5981324 3.0177657 -47.30019677 0.02408307 -39 -2 C-38.37625488 -2.17200928 -37.75250977 -2.34401855 -37.10986328 -2.52124023 C-25.33848182 -5.19234404 -11.53065338 -2.96722147 0 0 Z" transform="translate(486,419)"/>
1162
- </svg>`;
1163
- function getFaviconSvg() {
1164
- return FAVICON_SVG;
1165
- }
1166
- var VOICE_CALLBACKS = ["ice", "ace", "pie", "dice", "notify"];
1167
- var NOTIFICATION_EVENTS = ["dice", "notify"];
1168
- function isVoiceCallback(functionName) {
1169
- return VOICE_CALLBACKS.includes(functionName);
1170
- }
1171
- function isNotificationEvent(functionName) {
1172
- return NOTIFICATION_EVENTS.includes(functionName);
1173
- }
1174
- function extractFunctionName(path6, body) {
1175
- if (body?.event && isVoiceCallback(body.event)) {
1176
- return body.event;
1177
- }
1178
- const pathname = path6.split("?")[0];
1179
- const segments = pathname.split("/").filter((s) => s && s !== "*");
1180
- if (segments.length === 1 && isVoiceCallback(segments[0])) {
1181
- return segments[0];
1182
- }
1183
- if (segments.length >= 2 && segments[0] === "webhook") {
1184
- return `${segments[1]}Webhook`;
1185
- }
1186
- if (segments.length === 1 && segments[0] === "webhook") {
1187
- return "webhook";
1188
- }
1189
- return segments[segments.length - 1] || "default";
1190
- }
1191
- function generateRequestId() {
1192
- return `req_${Date.now()}_${Math.random().toString(36).substring(7)}`;
1193
- }
1194
- function findFunctionPath() {
1195
- const fs5 = requireCjs2("fs");
1196
- const distPath = nodePath.join(process.cwd(), "dist", "function.js");
1197
- const rootPath = nodePath.join(process.cwd(), "function.js");
1198
- if (fs5.existsSync(distPath)) {
1199
- return distPath;
1200
- }
1201
- return rootPath;
1202
- }
1203
- function formatSvamlResponse(result, functionName) {
1204
- if (!result || typeof result !== "object") {
1205
- throw new Error(`Voice callback ${functionName} must return a valid SVAML object`);
1206
- }
1207
- const svaml = result;
1208
- if (!svaml.action && !svaml.instructions) {
1209
- throw new Error(`Voice callback ${functionName} must return SVAML with an action or instructions`);
1210
- }
1211
- if (!svaml.instructions) {
1212
- svaml.instructions = [];
1213
- }
1214
- return {
1215
- statusCode: 200,
1216
- headers: { "Content-Type": "application/json" },
1217
- body: svaml
1218
- };
1219
- }
1220
- function formatCustomResponse(result) {
1221
- if (!result || typeof result !== "object") {
1222
- return {
1223
- statusCode: 200,
1224
- headers: { "Content-Type": "application/json" },
1225
- body: result
1226
- };
1227
- }
1228
- const response = result;
1229
- if (!response.statusCode) {
1230
- return {
1231
- statusCode: 200,
1232
- headers: { "Content-Type": "application/json" },
1233
- body: result
1234
- };
1235
- }
1236
- return {
1237
- statusCode: response.statusCode,
1238
- headers: response.headers,
1239
- body: response.body
1240
- };
1241
- }
1242
- function validateVoiceRequest(body) {
1243
- if (!body || typeof body !== "object") {
1244
- return {
1245
- valid: false,
1246
- error: "Missing request body",
1247
- expectedEvents: [...VOICE_CALLBACKS]
1248
- };
1249
- }
1250
- const data = body;
1251
- if (!data.event) {
1252
- return {
1253
- valid: false,
1254
- error: "Missing event type in request body",
1255
- expectedEvents: [...VOICE_CALLBACKS]
1256
- };
1257
- }
1258
- if (!data.callId) {
1259
- return {
1260
- valid: false,
1261
- error: "Missing callId in request body"
1262
- };
1263
- }
1264
- return { valid: true };
1265
- }
1266
- var noOpCache = {
1267
- set: async () => {
1268
- },
1269
- get: async () => null,
1270
- has: async () => false,
1271
- delete: async () => false,
1272
- extend: async () => false,
1273
- keys: async () => [],
1274
- getMany: async () => ({})
1275
- };
1276
- var noOpStorage = {
1277
- write: async () => {
1278
- },
1279
- read: async () => Buffer.alloc(0),
1280
- list: async () => [],
1281
- exists: async () => false,
1282
- delete: async () => {
1283
- }
1284
- };
1285
- function buildBaseContext(req, config = {}) {
1286
- return {
1287
- requestId: req?.headers?.["x-request-id"] || generateRequestId(),
1288
- host: req?.headers?.["host"],
1289
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1290
- env: process.env,
1291
- config: {
1292
- projectId: config.projectId || "unknown",
1293
- functionName: config.functionName || "unknown",
1294
- environment: config.environment || "development",
1295
- variables: config.variables
1296
- },
1297
- cache: noOpCache,
1298
- storage: noOpStorage,
1299
- database: "",
1300
- assets: (filename) => {
1301
- const filePath = nodePath.join(process.cwd(), "assets", filename);
1302
- return nodeFs.promises.readFile(filePath, "utf-8");
1303
- }
1304
- };
1305
- }
1306
- async function handleVoiceCallback(functionName, userFunction, context, callbackData, logger) {
1307
- const handler = userFunction[functionName];
1308
- if (!handler || typeof handler !== "function") {
1309
- if (functionName === "ice") {
1310
- throw new Error(`Voice callback 'ice' not found \u2014 export an ice() function in function.ts`);
1311
- }
1312
- if (logger) {
1313
- logger(`${functionName.toUpperCase()} callback not implemented \u2014 returning 200`);
1314
- }
1315
- return { statusCode: 200, body: {}, headers: {} };
1316
- }
1317
- let result;
1318
- switch (functionName) {
1319
- case "ice":
1320
- result = await handler?.(context, callbackData);
1321
- break;
1322
- case "ace":
1323
- result = await handler?.(context, callbackData);
1324
- break;
1325
- case "pie":
1326
- result = await handler?.(context, callbackData);
1327
- break;
1328
- case "dice":
1329
- result = await handler?.(context, callbackData);
1330
- break;
1331
- case "notify":
1332
- result = await handler?.(context, callbackData);
1333
- break;
1334
- default:
1335
- throw new Error(`Unknown voice callback: ${functionName}`);
1336
- }
1337
- if (logger) {
1338
- logger("Function result:", result);
1339
- }
1340
- if (isNotificationEvent(functionName)) {
1341
- if (logger) {
1342
- logger(`${functionName.toUpperCase()} callback completed`);
1343
- }
1344
- return {
1345
- statusCode: 200,
1346
- headers: { "Content-Type": "application/json" },
1347
- body: {}
1348
- };
1349
- }
1350
- return formatSvamlResponse(result, functionName);
1351
- }
1352
- async function handleCustomEndpoint(functionName, userFunction, context, request, logger) {
1353
- let handler = userFunction[functionName];
1354
- if ((!handler || typeof handler !== "function") && functionName === "default") {
1355
- handler = userFunction["home"];
1356
- }
1357
- if (!handler || typeof handler !== "function") {
1358
- const available = Object.keys(userFunction).filter((k) => typeof userFunction[k] === "function");
1359
- const pathHint = functionName.endsWith("Webhook") ? `/webhook/${functionName.replace("Webhook", "")}` : `/${functionName}`;
1360
- throw new Error(`No export '${functionName}' found for path ${pathHint}. Available exports: [${available.join(", ")}]. Custom endpoints require a named export matching the last path segment.`);
1361
- }
1362
- const result = await handler(context, request);
1363
- if (logger) {
1364
- logger("Function result:", result);
1365
- }
1366
- return formatCustomResponse(result);
1367
- }
1368
- function createApp(options = {}) {
1369
- const express = requireCjs2("express");
1370
- const app = express();
1371
- const staticDir = options.staticDir ?? (nodeFs.existsSync("./public") ? "./public" : void 0);
1372
- if (staticDir) {
1373
- app.use(express.static(staticDir, {
1374
- index: false,
1375
- // Don't serve index.html for /, we handle that below
1376
- dotfiles: "ignore"
1377
- }));
1378
- }
1379
- const jsonOptions = options.jsonParsingOptions || {
1380
- limit: "10mb",
1381
- allowJson5: true,
1382
- camelCase: {
1383
- deep: true,
1384
- stopPaths: ["custom"],
1385
- exclude: []
1386
- }
1387
- };
1388
- setupJsonParsing(app, jsonOptions);
1389
- app.use(express.urlencoded({ extended: true, limit: "10mb" }));
1390
- return app;
1391
- }
1392
- function createSinchRuntime() {
1393
- const result = {
1394
- startupHandlers: [],
1395
- wsHandlers: /* @__PURE__ */ new Map()
1396
- };
1397
- const runtime = {
1398
- onStartup(handler) {
1399
- result.startupHandlers.push(handler);
1400
- },
1401
- onWebSocket(path6, handler) {
1402
- const normalizedPath = path6.startsWith("/") ? path6 : `/${path6}`;
1403
- result.wsHandlers.set(normalizedPath, handler);
1404
- }
1405
- };
1406
- return { runtime, result };
1407
- }
1408
- function installWebSocketHandlers(server, wsHandlers, logger = console.log) {
1409
- if (wsHandlers.size === 0)
1410
- return;
1411
- const { WebSocketServer } = requireCjs2("ws");
1412
- const wss = new WebSocketServer({ noServer: true });
1413
- server.on("upgrade", (req, socket, head) => {
1414
- const pathname = new URL(req.url || "/", `http://${req.headers.host}`).pathname;
1415
- const handler = wsHandlers.get(pathname);
1416
- if (handler) {
1417
- logger(`[WS] Upgrade request for ${pathname}`);
1418
- wss.handleUpgrade(req, socket, head, (ws) => {
1419
- handler(ws, req);
1420
- });
1421
- } else {
1422
- logger(`[WS] No handler for ${pathname} \u2014 rejecting upgrade`);
1423
- socket.destroy();
1424
- }
1425
- });
1426
- logger(`[WS] WebSocket endpoints registered: ${[...wsHandlers.keys()].join(", ")}`);
1427
- }
1428
- function setupRequestHandler(app, options = {}) {
1429
- const { loadUserFunction = async () => {
1430
- const functionPath = findFunctionPath();
1431
- const functionUrl = pathToFileURL(functionPath).href;
1432
- const module = await import(functionUrl);
1433
- return module.default || module;
1434
- }, buildContext = buildBaseContext, logger = console.log, landingPageEnabled = true, authConfig, authKey, authSecret, onRequestStart = () => {
1435
- }, onRequestEnd = () => {
1436
- } } = options;
1437
- app.use("/{*splat}", async (req, res) => {
1438
- const startTime = Date.now();
1439
- if ((req.method === "GET" || req.method === "HEAD") && req.originalUrl === "/favicon.ico") {
1440
- const svg = getFaviconSvg();
1441
- res.type("image/svg+xml").send(svg);
1442
- return;
1443
- }
1444
- if (req.method === "GET" && req.originalUrl === "/" && landingPageEnabled) {
1445
- const acceptHeader = req.headers.accept || "";
1446
- if (acceptHeader.includes("text/html")) {
1447
- const html = getLandingPageHtml();
1448
- res.type("html").send(html);
1449
- return;
1450
- }
1451
- }
1452
- if (req.method === "GET" && req.originalUrl === "/" && !landingPageEnabled) {
1453
- const indexPath = nodePath.join(process.cwd(), "public", "index.html");
1454
- if (nodeFs.existsSync(indexPath)) {
1455
- res.type("html").sendFile(indexPath);
1456
- return;
1457
- }
1458
- }
1459
- try {
1460
- const functionName = extractFunctionName(req.originalUrl, req.body);
1461
- logger(`[${(/* @__PURE__ */ new Date()).toISOString()}] ${req.method} ${req.path} -> ${functionName}`);
1462
- if (authConfig && authKey && authSecret) {
1463
- const needsAuth = authConfig === "*" || Array.isArray(authConfig) && authConfig.includes(functionName);
1464
- if (needsAuth) {
1465
- const isValid = validateBasicAuth(req.headers.authorization, authKey, authSecret);
1466
- if (!isValid) {
1467
- logger(`[AUTH] Rejected unauthorized request to ${functionName}`);
1468
- res.status(401).set("WWW-Authenticate", 'Basic realm="sinch-function"').json({ error: "Unauthorized" });
1469
- return;
1470
- }
1471
- }
1472
- }
1473
- const protectionMode = getProtectionMode();
1474
- const isDev = process.env.NODE_ENV !== "production" && process.env.ASPNETCORE_ENVIRONMENT !== "Production";
1475
- if (shouldValidateWebhook(protectionMode, isDev)) {
1476
- const sinchClients = getSinchClients();
1477
- if (isVoiceCallback(functionName) && sinchClients.validateWebhookSignature) {
1478
- const rawBody = req.rawBody ?? JSON.stringify(req.body);
1479
- const isValid = sinchClients.validateWebhookSignature({
1480
- method: req.method,
1481
- path: req.path,
1482
- headers: req.headers,
1483
- body: rawBody
1484
- });
1485
- if (!isValid) {
1486
- logger("[SECURITY] Voice webhook signature validation failed");
1487
- res.status(401).json({ error: "Invalid webhook signature" });
1488
- return;
1489
- }
1490
- }
1491
- if (functionName === "conversationWebhook" && sinchClients.validateConversationWebhook) {
1492
- const isValid = sinchClients.validateConversationWebhook(req.headers, req.body);
1493
- if (!isValid) {
1494
- logger("[SECURITY] Conversation webhook signature validation failed");
1495
- res.status(401).json({ error: "Invalid webhook signature" });
1496
- return;
1497
- }
1498
- }
1499
- }
1500
- onRequestStart({ functionName, req });
1501
- const context = buildContext(req);
1502
- const userFunction = await Promise.resolve(loadUserFunction());
1503
- let response;
1504
- if (isVoiceCallback(functionName)) {
1505
- const validation = validateVoiceRequest(req.body);
1506
- if (!validation.valid) {
1507
- res.status(400).json({
1508
- error: validation.error,
1509
- ...validation.expectedEvents && { expectedEvents: validation.expectedEvents }
1510
- });
1511
- return;
1512
- }
1513
- response = await handleVoiceCallback(functionName, userFunction, context, req.body, logger);
1514
- } else {
1515
- const request = {
1516
- method: req.method,
1517
- path: req.path,
1518
- query: req.query,
1519
- headers: req.headers,
1520
- body: req.body,
1521
- params: req.params
1522
- };
1523
- response = await handleCustomEndpoint(functionName, userFunction, context, request, logger);
1524
- }
1525
- res.status(response.statusCode);
1526
- if (response.headers) {
1527
- for (const [key, value] of Object.entries(response.headers)) {
1528
- res.setHeader(key, value);
1529
- }
1530
- }
1531
- const contentType = response.headers?.["Content-Type"];
1532
- const isJsonContent = contentType?.includes("application/json");
1533
- const isHtmlContent = contentType?.includes("text/html");
1534
- if (response.body === void 0) {
1535
- res.end();
1536
- } else if (isJsonContent) {
1537
- res.json(response.body);
1538
- } else if (isHtmlContent) {
1539
- res.send(String(response.body));
1540
- } else {
1541
- res.send(response.body);
1542
- }
1543
- const duration = Date.now() - startTime;
1544
- logger(`[${(/* @__PURE__ */ new Date()).toISOString()}] Response sent: ${response.statusCode} (${duration}ms)`);
1545
- onRequestEnd({
1546
- functionName,
1547
- req,
1548
- response,
1549
- duration,
1550
- statusCode: response.statusCode
1551
- });
1552
- } catch (error) {
1553
- const duration = Date.now() - startTime;
1554
- logger("Function execution error:", {
1555
- error: error.message,
1556
- stack: error.stack,
1557
- function: extractFunctionName(req.originalUrl, req.body)
1558
- });
1559
- res.status(500).json({
1560
- error: "Internal server error",
1561
- message: error.message,
1562
- ...process.env.NODE_ENV === "development" && { stack: error.stack }
1563
- });
1564
- onRequestEnd({
1565
- functionName: extractFunctionName(req.originalUrl, req.body),
1566
- req,
1567
- error,
1568
- duration,
1569
- statusCode: 500
1570
- });
1571
- }
1572
- });
1573
- }
1574
-
1575
- // ../runtime-shared/dist/ai/elevenlabs/state.js
1576
- var ElevenLabsStateManager = class {
1577
- state = {
1578
- isConfigured: false
1579
- };
1580
- /**
1581
- * Get the current state
1582
- */
1583
- getState() {
1584
- return { ...this.state };
1585
- }
1586
- /**
1587
- * Check if ElevenLabs is configured
1588
- */
1589
- isConfigured() {
1590
- return this.state.isConfigured;
1591
- }
1592
- /**
1593
- * Update state with auto-configuration results
1594
- */
1595
- setConfigured(data) {
1596
- this.state = {
1597
- ...data,
1598
- isConfigured: true,
1599
- configuredAt: /* @__PURE__ */ new Date()
1600
- };
1601
- }
1602
- /**
1603
- * Clear the configuration state
1604
- */
1605
- clear() {
1606
- this.state = {
1607
- isConfigured: false
1608
- };
1609
- }
1610
- /**
1611
- * Get the phone number ID for making calls
1612
- */
1613
- getPhoneNumberId() {
1614
- return this.state.phoneNumberId;
1615
- }
1616
- /**
1617
- * Get the SIP address for connecting to the agent
1618
- */
1619
- getSipAddress() {
1620
- return this.state.sipAddress;
1621
- }
1622
- /**
1623
- * Get the configured agent ID
1624
- */
1625
- getAgentId() {
1626
- return this.state.agentId;
1627
- }
1628
- };
1629
- var ElevenLabsState = new ElevenLabsStateManager();
1630
-
1631
- // ../runtime-shared/dist/ai/elevenlabs/client.js
1632
- var ELEVENLABS_API_BASE = "https://api.elevenlabs.io/v1";
1633
- var FETCH_TIMEOUT_MS = 1e4;
1634
- var ElevenLabsClient = class {
1635
- apiKey;
1636
- constructor(apiKey) {
1637
- this.apiKey = apiKey || process.env.ELEVENLABS_API_KEY || "";
1638
- if (!this.apiKey) {
1639
- console.warn("[ElevenLabs] No API key provided. Set ELEVENLABS_API_KEY environment variable.");
1640
- }
1641
- }
1642
- get authHeaders() {
1643
- return { "xi-api-key": this.apiKey, "Content-Type": "application/json" };
1644
- }
1645
- /**
1646
- * Initiate an outbound call to a phone number using an ElevenLabs agent
1647
- */
1648
- async makeCall(options) {
1649
- const phoneNumberId = ElevenLabsState.getPhoneNumberId();
1650
- const request = {
1651
- agent_id: options.agentId,
1652
- customer_phone_number: options.toNumber,
1653
- agent_phone_number_id: phoneNumberId
1654
- };
1655
- if (options.dynamicVariables && Object.keys(options.dynamicVariables).length > 0) {
1656
- request.custom_llm_extra_body = {
1657
- dynamic_variables: options.dynamicVariables
1658
- };
1659
- }
1660
- const response = await fetch(`${ELEVENLABS_API_BASE}/convai/conversation/create_call`, {
1661
- method: "POST",
1662
- headers: this.authHeaders,
1663
- body: JSON.stringify(request),
1664
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1665
- });
1666
- if (!response.ok) {
1667
- const error = await response.text();
1668
- throw new Error(`ElevenLabs API error: ${response.status} - ${error}`);
1669
- }
1670
- return response.json();
1671
- }
1672
- /**
1673
- * Get conversation details including transcript and analysis
1674
- */
1675
- async getConversationDetails(conversationId) {
1676
- const response = await fetch(`${ELEVENLABS_API_BASE}/convai/conversations/${encodeURIComponent(conversationId)}`, {
1677
- headers: { "xi-api-key": this.apiKey },
1678
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1679
- });
1680
- if (!response.ok) {
1681
- const error = await response.text();
1682
- throw new Error(`ElevenLabs API error: ${response.status} - ${error}`);
1683
- }
1684
- const data = await response.json();
1685
- return this.mapConversationResponse(data);
1686
- }
1687
- /**
1688
- * Auto-configure ElevenLabs with Sinch SIP trunk.
1689
- *
1690
- * Step 1: Get or import phone number with SIP trunk config
1691
- * Step 2: Configure agent conversation-init webhook
1692
- *
1693
- * Called by tryAutoConfigureAsync (the orchestrator that reads env vars).
1694
- */
1695
- async autoConfigureAsync(options) {
1696
- console.log(`[ElevenLabs] Starting auto-configuration for agent ${options.agentId}`);
1697
- const phoneResult = await this.getOrImportPhoneNumber(options);
1698
- if (options.webhookBaseUrl) {
1699
- await this.configureAgentWebhooks(options.agentId, options.webhookBaseUrl);
1700
- }
1701
- console.log(`[ElevenLabs] Auto-configuration completed: PhoneNumberId=${phoneResult.phoneNumberId}`);
1702
- return {
1703
- success: true,
1704
- phoneNumberId: phoneResult.phoneNumberId,
1705
- phoneNumber: options.phoneNumber,
1706
- sipAddress: options.sipAddress
1707
- };
1708
- }
1709
- /**
1710
- * Check if phone number already exists in ElevenLabs; create or update it.
1711
- * Matches C# GetOrImportPhoneNumberAsync.
1712
- */
1713
- async getOrImportPhoneNumber(config) {
1714
- const listResponse = await fetch(`${ELEVENLABS_API_BASE}/convai/phone-numbers`, {
1715
- headers: this.authHeaders,
1716
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1717
- });
1718
- if (!listResponse.ok) {
1719
- throw new Error(`Failed to list phone numbers: ${listResponse.status}`);
1720
- }
1721
- const phoneNumbers = await listResponse.json();
1722
- const sipConfig = {
1723
- address: config.sipAddress,
1724
- transport: "tcp",
1725
- media_encryption: "disabled",
1726
- credentials: { username: config.sipUsername, password: config.sipPassword }
1727
- };
1728
- const existing = phoneNumbers.find((p) => p.phone_number === config.phoneNumber);
1729
- if (existing) {
1730
- console.log(`[ElevenLabs] Phone number already exists (${existing.phone_number_id}), updating config`);
1731
- await this.updatePhoneNumberConfig(existing.phone_number_id, config.agentId, sipConfig);
1732
- return { phoneNumberId: existing.phone_number_id };
1733
- }
1734
- const label = `Sinch Functions - ${config.functionName || "Sinch Function"}`;
1735
- console.log("[ElevenLabs] Creating SIP trunk phone number");
1736
- const createResponse2 = await fetch(`${ELEVENLABS_API_BASE}/convai/phone-numbers`, {
1737
- method: "POST",
1738
- headers: this.authHeaders,
1739
- body: JSON.stringify({
1740
- phone_number: config.phoneNumber,
1741
- label,
1742
- provider: "sip_trunk",
1743
- supports_inbound: true,
1744
- supports_outbound: true,
1745
- inbound_trunk_config: { media_encryption: "disabled" },
1746
- outbound_trunk_config: sipConfig
1747
- }),
1748
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1749
- });
1750
- if (!createResponse2.ok) {
1751
- const err = await createResponse2.text();
1752
- throw new Error(`Failed to create phone number: ${createResponse2.status} - ${err}`);
1753
- }
1754
- const created = await createResponse2.json();
1755
- console.log("[ElevenLabs] Phone number created successfully");
1756
- await this.updatePhoneNumberConfig(created.phone_number_id, config.agentId, sipConfig);
1757
- return { phoneNumberId: created.phone_number_id };
1758
- }
1759
- /**
1760
- * Update phone number with agent association and SIP trunk config.
1761
- * Matches C# UpdatePhoneNumberConfigAsync.
1762
- */
1763
- async updatePhoneNumberConfig(phoneNumberId, agentId, sipConfig) {
1764
- const response = await fetch(`${ELEVENLABS_API_BASE}/convai/phone-numbers/${encodeURIComponent(phoneNumberId)}`, {
1765
- method: "PATCH",
1766
- headers: this.authHeaders,
1767
- body: JSON.stringify({
1768
- agent_id: agentId,
1769
- outbound_trunk_config: sipConfig
1770
- }),
1771
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1772
- });
1773
- if (!response.ok) {
1774
- await response.text();
1775
- console.warn(`[ElevenLabs] Failed to update phone number config: ${response.status}`);
1776
- } else {
1777
- console.log("[ElevenLabs] Phone number configuration updated");
1778
- }
1779
- }
1780
- /**
1781
- * Configure agent webhook for conversation-init events.
1782
- * Matches C# ConfigureAgentWebhooksAsync.
1783
- */
1784
- async configureAgentWebhooks(agentId, webhookBaseUrl) {
1785
- const webhookUrl = `${webhookBaseUrl}/webhook/elevenlabs/conversation-init`;
1786
- console.log(`[ElevenLabs] Configuring agent webhook`);
1787
- const response = await fetch(`${ELEVENLABS_API_BASE}/convai/agents/${encodeURIComponent(agentId)}`, {
1788
- method: "PATCH",
1789
- headers: this.authHeaders,
1790
- body: JSON.stringify({
1791
- platform_settings: {
1792
- workspace_overrides: {
1793
- conversation_initiation_client_data_webhook: {
1794
- url: webhookUrl,
1795
- request_headers: {}
1796
- }
1797
- },
1798
- overrides: {
1799
- enable_conversation_initiation_client_data_from_webhook: true
1800
- }
1801
- }
1802
- }),
1803
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1804
- });
1805
- if (!response.ok) {
1806
- await response.text();
1807
- console.error(`[ElevenLabs] Failed to configure agent webhooks: ${response.status}`);
1808
- } else {
1809
- console.log("[ElevenLabs] Agent webhooks configured successfully");
1810
- }
1811
- }
1812
- /**
1813
- * Map API response to our interface
1814
- */
1815
- mapConversationResponse(data) {
1816
- return {
1817
- conversationId: data.conversation_id,
1818
- agentId: data.agent_id,
1819
- status: data.status,
1820
- metadata: data.metadata ? {
1821
- callDurationSeconds: data.metadata.call_duration_secs,
1822
- startTime: data.metadata.start_time_unix_secs ? new Date(data.metadata.start_time_unix_secs * 1e3) : void 0,
1823
- endTime: data.metadata.end_time_unix_secs ? new Date(data.metadata.end_time_unix_secs * 1e3) : void 0
1824
- } : void 0,
1825
- transcript: data.transcript?.map((t) => ({
1826
- role: t.role,
1827
- message: t.message,
1828
- timeInCallSeconds: t.time_in_call_secs
1829
- })),
1830
- analysis: data.analysis ? {
1831
- summary: data.analysis.transcript_summary,
1832
- customData: data.analysis.custom_data
1833
- } : void 0
1834
- };
1835
- }
1836
- };
1837
- function createElevenLabsClient(apiKey) {
1838
- return new ElevenLabsClient(apiKey);
1839
- }
1840
-
1841
- // ../runtime-shared/dist/ai/elevenlabs/controller.js
1842
- var ElevenLabsController = class {
1843
- /**
1844
- * Handle conversation initialization webhook
1845
- * Called when an inbound call is received - allows customizing the conversation
1846
- *
1847
- * @param request - The conversation init request with caller info
1848
- * @returns Response with dynamic variables and/or config overrides
1849
- */
1850
- async handleConversationInit(request) {
1851
- return {};
1852
- }
1853
- /**
1854
- * Handle post-call webhook with transcript and analysis
1855
- *
1856
- * @param webhook - The post-call webhook payload
1857
- */
1858
- async handlePostCall(webhook) {
1859
- console.log("[ElevenLabs] Post-call webhook received:", {
1860
- conversationId: webhook.data.conversation_id,
1861
- agentId: webhook.data.agent_id,
1862
- status: webhook.data.status,
1863
- duration: webhook.data.metadata.call_duration_secs
1864
- });
1865
- }
1866
- /**
1867
- * Handle post-call audio webhook with recording
1868
- *
1869
- * @param webhook - The audio webhook with base64-encoded MP3
1870
- */
1871
- async handlePostCallAudio(webhook) {
1872
- console.log("[ElevenLabs] Post-call audio received:", {
1873
- conversationId: webhook.data.conversation_id,
1874
- agentId: webhook.data.agent_id
1875
- });
1876
- }
1877
- /**
1878
- * Handle call initiation failure webhook
1879
- *
1880
- * @param webhook - The failure webhook with error details
1881
- */
1882
- async handleCallInitiationFailure(webhook) {
1883
- console.error("[ElevenLabs] Call initiation failed:", {
1884
- agentId: webhook.data.agent_id,
1885
- customerNumber: webhook.data.customer_phone_number,
1886
- reason: webhook.data.failure_reason
1887
- });
1888
- }
1889
- /**
1890
- * Express route handler for conversation init endpoint
1891
- * Mount at: POST /elevenlabs/conversation-init
1892
- */
1893
- getConversationInitHandler() {
1894
- return async (req, res) => {
1895
- try {
1896
- const request = req.body;
1897
- const response = await this.handleConversationInit(request);
1898
- res.json(response);
1899
- } catch (error) {
1900
- console.error("[ElevenLabs] Error in conversation init:", error);
1901
- res.status(500).json({ error: "Internal server error" });
1902
- }
1903
- };
1904
- }
1905
- /**
1906
- * Express route handler for webhook endpoint
1907
- * Mount at: POST /elevenlabs/webhook
1908
- * Handles all webhook types based on the 'type' field
1909
- */
1910
- getWebhookHandler() {
1911
- return async (req, res) => {
1912
- try {
1913
- const webhook = req.body;
1914
- switch (webhook.type) {
1915
- case "post_call_transcription":
1916
- await this.handlePostCall(webhook);
1917
- break;
1918
- case "post_call_audio":
1919
- await this.handlePostCallAudio(webhook);
1920
- break;
1921
- case "call_initiation_failure":
1922
- await this.handleCallInitiationFailure(webhook);
1923
- break;
1924
- default:
1925
- console.warn("[ElevenLabs] Unknown webhook type:", webhook.type);
1926
- }
1927
- res.status(200).send("OK");
1928
- } catch (error) {
1929
- console.error("[ElevenLabs] Error processing webhook:", error);
1930
- res.status(500).json({ error: "Internal server error" });
1931
- }
1932
- };
1933
- }
1934
- };
1935
-
1936
- // ../runtime-shared/dist/ai/elevenlabs/autoconfigurator.js
1937
- var FETCH_TIMEOUT_MS2 = 1e4;
1938
- function maskPhone(phone) {
1939
- if (phone.length <= 6)
1940
- return "***";
1941
- return phone.slice(0, 4) + "***" + phone.slice(-4);
1942
- }
1943
- async function tryAutoConfigureAsync(webhookUrl, functionName, sinchPhoneNumber) {
1944
- const autoConfig = process.env.ELEVENLABS_AUTO_CONFIGURE;
1945
- if (!autoConfig || autoConfig.toLowerCase() !== "true") {
1946
- return null;
1947
- }
1948
- console.log("[ElevenLabs] Auto-configuration is enabled");
1949
- const agentId = process.env.ELEVENLABS_AGENT_ID;
1950
- const apiKey = process.env.ELEVENLABS_API_KEY;
1951
- if (!agentId) {
1952
- console.warn("[ElevenLabs] Auto-configuration skipped: ELEVENLABS_AGENT_ID not set. Please configure your agent ID in environment variables.");
1953
- return null;
1954
- }
1955
- if (!apiKey) {
1956
- console.warn("[ElevenLabs] Auto-configuration skipped: ELEVENLABS_API_KEY not set. Please store your API key using: sinch secrets add ELEVENLABS_API_KEY sk_...");
1957
- return null;
1958
- }
1959
- let phoneNumber = sinchPhoneNumber ?? process.env.SINCH_PHONE_NUMBER;
1960
- if (!phoneNumber) {
1961
- console.log("[ElevenLabs] SINCH_PHONE_NUMBER not configured, attempting auto-discovery from Voice API...");
1962
- phoneNumber = await autoDiscoverPhoneNumber();
1963
- }
1964
- if (!phoneNumber) {
1965
- console.warn("[ElevenLabs] Auto-configuration skipped: Sinch phone number not provided and auto-discovery failed. Please set SINCH_PHONE_NUMBER or ensure Voice API credentials are configured.");
1966
- return null;
1967
- }
1968
- if (!webhookUrl) {
1969
- console.warn("[ElevenLabs] Auto-configuration skipped: Webhook URL not provided.");
1970
- return null;
1971
- }
1972
- try {
1973
- new URL(webhookUrl);
1974
- } catch {
1975
- console.warn("[ElevenLabs] Auto-configuration skipped: Webhook URL is not a valid URL.");
1976
- return null;
1977
- }
1978
- const voiceAppKey = process.env.VOICE_APPLICATION_KEY || "";
1979
- const voiceAppSecret = process.env.VOICE_APPLICATION_SECRET || "";
1980
- const safeName = functionName ? functionName.slice(0, 100) : "Sinch Function";
1981
- try {
1982
- console.log(`[ElevenLabs] Starting auto-configuration: Agent=${agentId}, Number=${maskPhone(phoneNumber)}`);
1983
- const client = new ElevenLabsClient(apiKey);
1984
- const result = await client.autoConfigureAsync({
1985
- agentId,
1986
- phoneNumber,
1987
- sipAddress: "use1.vp.sip.sinch.com",
1988
- sipUsername: voiceAppKey,
1989
- sipPassword: voiceAppSecret,
1990
- webhookBaseUrl: webhookUrl,
1991
- functionName: safeName
1992
- });
1993
- if (result.success) {
1994
- ElevenLabsState.setConfigured({
1995
- phoneNumberId: result.phoneNumberId,
1996
- phoneNumber: result.phoneNumber,
1997
- agentId,
1998
- sipAddress: result.sipAddress
1999
- });
2000
- console.log(`[ElevenLabs] Auto-configuration completed! Phone: ${maskPhone(result.phoneNumber ?? "")}, SIP: ${result.sipAddress}`);
2001
- }
2002
- return result;
2003
- } catch (error) {
2004
- const message = error instanceof Error ? error.message : "Unknown error";
2005
- console.error(`[ElevenLabs] Auto-configuration failed: ${message}. The function will start but ElevenLabs integration may not work.`);
2006
- return null;
2007
- }
2008
- }
2009
- async function autoDiscoverPhoneNumber() {
2010
- const appKey = process.env.VOICE_APPLICATION_KEY || "";
2011
- const appSecret = process.env.VOICE_APPLICATION_SECRET || "";
2012
- if (!appKey || !appSecret) {
2013
- console.warn("[ElevenLabs] Voice client not available for phone number auto-discovery. Ensure VOICE_APPLICATION_KEY and VOICE_APPLICATION_SECRET are configured.");
2014
- return void 0;
2015
- }
2016
- try {
2017
- const auth = Buffer.from(`${appKey}:${appSecret}`).toString("base64");
2018
- const configResponse = await fetch(`https://callingapi.sinch.com/v1/configuration/numbers/`, {
2019
- headers: { Authorization: `Basic ${auth}` },
2020
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS2)
2021
- });
2022
- if (!configResponse.ok) {
2023
- console.warn(`[ElevenLabs] Failed to query Voice API for phone numbers: ${configResponse.status}`);
2024
- return void 0;
2025
- }
2026
- const data = await configResponse.json();
2027
- const numbers = (data.numbers || []).filter((n) => n.applicationkey === appKey).map((n) => n.number).filter(Boolean);
2028
- if (numbers.length > 0) {
2029
- console.log(`[ElevenLabs] Auto-discovered ${numbers.length} phone number(s), using first`);
2030
- return numbers[0];
2031
- }
2032
- console.warn("[ElevenLabs] No phone numbers found for the configured Voice application");
2033
- return void 0;
2034
- } catch (error) {
2035
- const message = error instanceof Error ? error.message : "Unknown error";
2036
- console.error(`[ElevenLabs] Failed to auto-discover phone number: ${message}`);
2037
- return void 0;
2038
- }
2039
- }
2040
- var ElevenLabsAutoConfigurator = class {
2041
- static tryAutoConfigureAsync = tryAutoConfigureAsync;
2042
- };
2043
-
2044
- // ../runtime-shared/dist/conversation/message-builder.js
2045
- var ConversationMessageBuilder = class {
2046
- config;
2047
- appId;
2048
- channel;
2049
- identity;
2050
- conversationId;
2051
- messageText;
2052
- /**
2053
- * Create a new builder with configuration
2054
- */
2055
- constructor(config = {}) {
2056
- this.config = config;
2057
- }
2058
- /**
2059
- * Pre-fill builder from an inbound message (for replies)
2060
- */
2061
- fromInbound(inbound) {
2062
- this.appId = inbound.app_id;
2063
- this.channel = inbound.message?.channel_identity?.channel;
2064
- this.identity = inbound.message?.channel_identity?.identity;
2065
- this.conversationId = inbound.message?.conversation_id;
2066
- return this;
2067
- }
2068
- /**
2069
- * Set the app ID (defaults to CONVERSATION_APP_ID from config)
2070
- */
2071
- setAppId(appId) {
2072
- this.appId = appId;
2073
- return this;
2074
- }
2075
- /**
2076
- * Set the recipient channel and identity
2077
- *
2078
- * @param channel - Channel name (SMS, WHATSAPP, MESSENGER, etc.)
2079
- * @param identity - Channel-specific identity (phone number, PSID, etc.)
2080
- */
2081
- to(channel, identity) {
2082
- this.channel = channel;
2083
- this.identity = identity;
2084
- return this;
2085
- }
2086
- /**
2087
- * Set the conversation ID (for non-DISPATCH mode apps)
2088
- */
2089
- setConversationId(conversationId) {
2090
- this.conversationId = conversationId;
2091
- return this;
2092
- }
2093
- /**
2094
- * Set a text message
2095
- */
2096
- text(text) {
2097
- this.messageText = text;
2098
- return this;
2099
- }
2100
- /**
2101
- * Build the SendMessageRequest.
2102
- * Automatically sets SMS_SENDER from config if sending to SMS channel.
2103
- *
2104
- * @returns A SendMessageRequest ready to send via context.conversation.messages.send()
2105
- */
2106
- build() {
2107
- const appId = this.appId || this.config.CONVERSATION_APP_ID;
2108
- if (!appId) {
2109
- throw new Error("AppId required - use setAppId() or set CONVERSATION_APP_ID in config");
2110
- }
2111
- if (!this.channel || !this.identity) {
2112
- throw new Error("Recipient required - use to() or fromInbound()");
2113
- }
2114
- if (!this.messageText) {
2115
- throw new Error("Message required - use text()");
2116
- }
2117
- const request = {
2118
- app_id: appId,
2119
- message: {
2120
- text_message: {
2121
- text: this.messageText
2122
- }
2123
- },
2124
- recipient: {
2125
- identified_by: {
2126
- channel_identities: [
2127
- {
2128
- channel: this.channel,
2129
- identity: this.identity
2130
- }
2131
- ]
2132
- }
2133
- }
2134
- };
2135
- if (this.channel.toUpperCase() === "SMS") {
2136
- const smsSender = this.config.FROM_NUMBER;
2137
- if (smsSender) {
2138
- request.channel_properties = {
2139
- SMS_SENDER: smsSender
2140
- };
2141
- }
2142
- }
2143
- return request;
2144
- }
2145
- };
2146
- function createMessageBuilder(config = {}) {
2147
- return new ConversationMessageBuilder(config);
2148
- }
2149
-
2150
- // ../runtime-shared/dist/conversation/message-helpers.js
2151
- function textReply(inbound, text, smsSender) {
2152
- const channelIdentity = inbound.message?.channel_identity;
2153
- if (!channelIdentity) {
2154
- throw new Error("Inbound message has no channel identity");
2155
- }
2156
- const channel = channelIdentity.channel;
2157
- const identity = channelIdentity.identity;
2158
- if (!channel || !identity) {
2159
- throw new Error("Inbound message has no channel or identity");
2160
- }
2161
- return createChannelMessage(inbound.app_id, channel, identity, text, smsSender);
2162
- }
2163
- function createSms(appId, phoneNumber, text, smsSender) {
2164
- return createChannelMessage(appId, "SMS", phoneNumber, text, smsSender);
2165
- }
2166
- function createWhatsApp(appId, phoneNumber, text) {
2167
- return createChannelMessage(appId, "WHATSAPP", phoneNumber, text);
2168
- }
2169
- function createMessenger(appId, psid, text) {
2170
- return createChannelMessage(appId, "MESSENGER", psid, text);
2171
- }
2172
- function createChannelMessage(appId, channel, identity, text, smsSender) {
2173
- if (!appId)
2174
- throw new Error("appId is required");
2175
- if (!channel)
2176
- throw new Error("channel is required");
2177
- if (!identity)
2178
- throw new Error("identity is required");
2179
- if (!text)
2180
- throw new Error("text is required");
2181
- const request = {
2182
- app_id: appId,
2183
- message: {
2184
- text_message: {
2185
- text
2186
- }
2187
- },
2188
- recipient: {
2189
- identified_by: {
2190
- channel_identities: [
2191
- {
2192
- channel,
2193
- identity
2194
- }
2195
- ]
2196
- }
2197
- }
2198
- };
2199
- if (channel.toUpperCase() === "SMS" && smsSender) {
2200
- request.channel_properties = {
2201
- SMS_SENDER: smsSender
2202
- };
2203
- }
2204
- return request;
2205
- }
2206
- var ConversationMessage = {
2207
- textReply,
1
+ #!/usr/bin/env node
2
+ import { createRequire as __sinchCreateRequire } from 'node:module';
3
+ const require = __sinchCreateRequire(import.meta.url);
4
+ import {
5
+ AceSvamlBuilder,
6
+ AgentProvider,
7
+ AgentSipHelper,
8
+ ConversationController,
9
+ ConversationMessage,
10
+ ConversationMessageBuilder,
11
+ DefaultEndpointHandler,
12
+ ElevenLabsAutoConfigurator,
13
+ ElevenLabsClient,
14
+ ElevenLabsController,
15
+ ElevenLabsState,
16
+ IceSvamlBuilder,
17
+ LocalCache,
18
+ LocalStorage,
19
+ MenuBuilder,
20
+ MenuTemplates,
21
+ NOTIFICATION_EVENTS,
22
+ PieSvamlBuilder,
23
+ SecretsLoader,
24
+ TemplateRender,
25
+ TunnelClient,
26
+ UniversalConfig,
27
+ VOICE_CALLBACKS,
28
+ VersionExtractor,
29
+ VoiceErrorHelper,
30
+ buildBaseContext,
31
+ createAceBuilder,
32
+ createApp,
33
+ createCacheClient,
34
+ createChannelMessage,
35
+ createConfig,
36
+ createConnectAgentAction,
37
+ createElevenLabsClient,
38
+ createErrorResponse,
39
+ createIceBuilder,
40
+ createJsonResponse,
41
+ createLenientJsonParser,
42
+ createMenu,
43
+ createMessageBuilder,
44
+ createMessageHelper,
45
+ createMessenger,
46
+ createPieBuilder,
47
+ createResponse,
48
+ createSecurityOptions,
49
+ createSimpleMenu,
50
+ createSinchRuntime,
2208
51
  createSms,
52
+ createStorageClient,
53
+ createUniversalConfig,
2209
54
  createWhatsApp,
2210
- createMessenger,
2211
- createChannelMessage
2212
- };
2213
-
2214
- // ../runtime-shared/dist/conversation/controller.js
2215
- var ConversationController = class {
2216
- conversation;
2217
- config;
2218
- constructor(conversation, config = {}) {
2219
- this.conversation = conversation;
2220
- this.config = config;
2221
- }
2222
- /**
2223
- * MESSAGE_INBOUND - Called when a user sends a message.
2224
- * Override this to handle incoming messages from users.
2225
- */
2226
- async handleMessageInbound(event) {
2227
- }
2228
- /**
2229
- * MESSAGE_DELIVERY - Called when message delivery status updates.
2230
- * Override this to track delivery receipts.
2231
- */
2232
- async handleMessageDelivery(event) {
2233
- }
2234
- /**
2235
- * EVENT_INBOUND - Called for events like composing indicators.
2236
- * Override this to handle typing indicators, read receipts, etc.
2237
- */
2238
- async handleEventInbound(event) {
2239
- }
2240
- /**
2241
- * CONVERSATION_START - Called when a conversation begins.
2242
- * Override this to handle conversation initialization.
2243
- */
2244
- async handleConversationStart(event) {
2245
- }
2246
- /**
2247
- * CONVERSATION_STOP - Called when a conversation ends.
2248
- * Override this to handle conversation cleanup.
2249
- */
2250
- async handleConversationStop(event) {
2251
- }
2252
- /**
2253
- * Gets the sender number from configuration (FROM_NUMBER).
2254
- * Used for setting SMS_SENDER channel property when sending to SMS channel.
2255
- */
2256
- get fromNumber() {
2257
- return this.config.FROM_NUMBER;
2258
- }
2259
- /**
2260
- * Create a text reply to an inbound message.
2261
- * Automatically sets SMS_SENDER from FROM_NUMBER config.
2262
- */
2263
- reply(inbound, text) {
2264
- return textReply(inbound, text, this.fromNumber);
2265
- }
2266
- /**
2267
- * Create a ConversationMessageBuilder for building messages with full control.
2268
- */
2269
- createMessage() {
2270
- return new ConversationMessageBuilder(this.config);
2271
- }
2272
- /**
2273
- * Create a ConversationMessageBuilder pre-filled from an inbound message.
2274
- */
2275
- createReply(inbound) {
2276
- return new ConversationMessageBuilder(this.config).fromInbound(inbound);
2277
- }
2278
- /**
2279
- * Express route handler for the webhook endpoint.
2280
- * Mount at: POST /conversation
2281
- *
2282
- * Routes to appropriate handler based on event type.
2283
- * Uses manual JSON parsing as workaround for SDK issues with extra fields.
2284
- */
2285
- getWebhookHandler() {
2286
- return async (req, res) => {
2287
- try {
2288
- const body = req.body;
2289
- const verbose = this.config.VERBOSE === "true";
2290
- if (!body) {
2291
- res.status(400).json({ error: "Empty request body" });
2292
- return;
2293
- }
2294
- if (!this.conversation) {
2295
- console.error("[Conversation] Client not configured");
2296
- res.status(500).json({ error: "Conversation API not configured" });
2297
- return;
2298
- }
2299
- if (body.message?.direction === "TO_APP" && body.message?.contact_message) {
2300
- if (verbose) {
2301
- console.log("[Conversation] MESSAGE_INBOUND event detected");
2302
- }
2303
- await this.handleMessageInbound(body);
2304
- res.status(200).send("OK");
2305
- return;
2306
- }
2307
- if (body.message_delivery_report) {
2308
- if (verbose) {
2309
- console.log("[Conversation] MESSAGE_DELIVERY event detected");
2310
- }
2311
- await this.handleMessageDelivery(body);
2312
- res.status(200).send("OK");
2313
- return;
2314
- }
2315
- if (body.event?.contact_event) {
2316
- if (verbose) {
2317
- console.log("[Conversation] EVENT_INBOUND event detected");
2318
- }
2319
- await this.handleEventInbound(body);
2320
- res.status(200).send("OK");
2321
- return;
2322
- }
2323
- if (body.conversation_event) {
2324
- const eventType = body.conversation_event.type;
2325
- if (eventType === "CONVERSATION_START") {
2326
- if (verbose) {
2327
- console.log("[Conversation] CONVERSATION_START event detected");
2328
- }
2329
- await this.handleConversationStart(body);
2330
- } else if (eventType === "CONVERSATION_STOP") {
2331
- if (verbose) {
2332
- console.log("[Conversation] CONVERSATION_STOP event detected");
2333
- }
2334
- await this.handleConversationStop(body);
2335
- }
2336
- res.status(200).send("OK");
2337
- return;
2338
- }
2339
- if (verbose) {
2340
- console.log("[Conversation] Unknown event type, ignoring");
2341
- }
2342
- res.status(200).json({ status: "ignored", reason: "unknown_event_type" });
2343
- } catch (error) {
2344
- console.error("[Conversation] Error processing webhook:", error);
2345
- res.status(500).json({ error: "Internal server error" });
2346
- }
2347
- };
2348
- }
2349
- };
2350
-
2351
- // ../runtime-shared/dist/conversation/extensions.js
2352
- function getText(event) {
2353
- return event.message?.contact_message?.text_message?.text;
2354
- }
2355
- function getMedia(event) {
2356
- return event.message?.contact_message?.media_message;
2357
- }
2358
- function getPostbackData(event) {
2359
- return event.message?.contact_message?.choice_response_message?.postback_data;
2360
- }
2361
- function getContactId(event) {
2362
- return event.message?.contact_id;
2363
- }
2364
- function getConversationId(event) {
2365
- return event.message?.conversation_id;
2366
- }
2367
- function getChannel(event) {
2368
- return event.message?.channel_identity?.channel;
2369
- }
2370
- function getIdentity(event) {
2371
- return event.message?.channel_identity?.identity;
2372
- }
2373
- function getTo(event) {
2374
- return event.message?.sender_id;
2375
- }
2376
- function getLocation(event) {
2377
- return event.message?.contact_message?.location_message;
2378
- }
2379
- function isTextMessage(event) {
2380
- return event.message?.contact_message?.text_message !== void 0;
2381
- }
2382
- function isMediaMessage(event) {
2383
- return event.message?.contact_message?.media_message !== void 0;
2384
- }
2385
- function isPostback(event) {
2386
- return event.message?.contact_message?.choice_response_message !== void 0;
2387
- }
2388
- function createMessageHelper(event) {
2389
- return {
2390
- getText: () => getText(event),
2391
- getMedia: () => getMedia(event),
2392
- getPostbackData: () => getPostbackData(event),
2393
- getContactId: () => getContactId(event),
2394
- getConversationId: () => getConversationId(event),
2395
- getChannel: () => getChannel(event),
2396
- getIdentity: () => getIdentity(event),
2397
- getTo: () => getTo(event),
2398
- getLocation: () => getLocation(event),
2399
- isTextMessage: () => isTextMessage(event),
2400
- isMediaMessage: () => isMediaMessage(event),
2401
- isPostback: () => isPostback(event)
2402
- };
2403
- }
2404
-
2405
- // ../runtime-shared/dist/voice/helpers.js
2406
- var COUNTRY_CODES = {
2407
- "+1": { code: "US", format: (n) => `(${n.slice(0, 3)}) ${n.slice(3, 6)}-${n.slice(6)}` },
2408
- "+44": { code: "GB", format: (n) => `0${n.slice(0, 4)} ${n.slice(4)}` },
2409
- "+46": {
2410
- code: "SE",
2411
- format: (n) => `0${n.slice(0, 2)}-${n.slice(2, 5)} ${n.slice(5, 7)} ${n.slice(7)}`
2412
- },
2413
- "+49": { code: "DE", format: (n) => `0${n.slice(0, 3)} ${n.slice(3)}` },
2414
- "+33": {
2415
- code: "FR",
2416
- format: (n) => `0${n.slice(0, 1)} ${n.slice(1, 3)} ${n.slice(3, 5)} ${n.slice(5, 7)} ${n.slice(7)}`
2417
- },
2418
- "+61": { code: "AU", format: (n) => `0${n.slice(0, 1)} ${n.slice(1, 5)} ${n.slice(5)}` }
2419
- };
2420
- function toLocalPhoneNumber(phoneNumber, defaultRegion = "US") {
2421
- if (!phoneNumber || !phoneNumber.startsWith("+")) {
2422
- return phoneNumber;
2423
- }
2424
- const sortedCodes = Object.keys(COUNTRY_CODES).sort((a, b) => b.length - a.length);
2425
- for (const prefix of sortedCodes) {
2426
- if (phoneNumber.startsWith(prefix)) {
2427
- const national = phoneNumber.slice(prefix.length);
2428
- try {
2429
- return COUNTRY_CODES[prefix].format(national);
2430
- } catch {
2431
- return phoneNumber;
2432
- }
2433
- }
2434
- }
2435
- return phoneNumber.slice(1);
2436
- }
2437
- function formatPhoneNumber(phoneNumber) {
2438
- const cleaned = phoneNumber.replace(/[^\d+]/g, "");
2439
- if (cleaned.startsWith("+")) {
2440
- return toLocalPhoneNumber(cleaned);
2441
- }
2442
- if (cleaned.length === 10) {
2443
- return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`;
2444
- }
2445
- return phoneNumber;
2446
- }
2447
- var VoiceErrorHelper = {
2448
- /**
2449
- * Create a standard error response that plays a message and hangs up
2450
- *
2451
- * @param message - Error message to speak
2452
- * @param locale - Language locale (default: "en-US")
2453
- * @returns SVAML response object
2454
- */
2455
- createErrorResponse(message, locale = "en-US") {
2456
- return new IceSvamlBuilder().say(message, locale).hangup().build();
2457
- },
2458
- /**
2459
- * Create a service unavailable response
2460
- *
2461
- * @param locale - Language locale (default: "en-US")
2462
- * @returns SVAML response object
2463
- */
2464
- serviceUnavailable(locale = "en-US") {
2465
- return this.createErrorResponse("We're sorry, our service is temporarily unavailable. Please try again later.", locale);
2466
- },
2467
- /**
2468
- * Create an invalid input response for PIE handlers
2469
- *
2470
- * @param locale - Language locale (default: "en-US")
2471
- * @returns SVAML response object
2472
- */
2473
- invalidInput(locale = "en-US") {
2474
- return new PieSvamlBuilder().say("Invalid selection. Please try again.", locale).continue().build();
2475
- },
2476
- /**
2477
- * Create a timeout response for PIE handlers
2478
- *
2479
- * @param locale - Language locale (default: "en-US")
2480
- * @returns SVAML response object
2481
- */
2482
- timeout(locale = "en-US") {
2483
- return new PieSvamlBuilder().say("We did not receive a response. Please try again.", locale).continue().build();
2484
- },
2485
- /**
2486
- * Create a goodbye response that thanks the caller and hangs up
2487
- *
2488
- * @param locale - Language locale (default: "en-US")
2489
- * @returns SVAML response object
2490
- */
2491
- goodbye(locale = "en-US") {
2492
- return new IceSvamlBuilder().say("Thank you for calling. Goodbye!", locale).hangup().build();
2493
- }
2494
- };
2495
- function formatDuration(seconds) {
2496
- if (seconds < 60) {
2497
- return `${Math.round(seconds)}s`;
2498
- }
2499
- const minutes = Math.floor(seconds / 60);
2500
- const remainingSeconds = Math.round(seconds % 60);
2501
- if (remainingSeconds === 0) {
2502
- return `${minutes}m`;
2503
- }
2504
- return `${minutes}m ${remainingSeconds}s`;
2505
- }
2506
- function extractCallerNumber(cli) {
2507
- if (!cli)
2508
- return void 0;
2509
- return cli.replace(/[^\d+]/g, "");
2510
- }
2511
-
2512
- // ../runtime-shared/dist/utils/templateRender.js
2513
- import fs from "fs";
2514
- import path from "path";
2515
- var TemplateRender = class {
2516
- /**
2517
- * Load and render an HTML template with variables
2518
- * @param templatePath - Path to the HTML template file
2519
- * @param variables - Object containing variables to replace in template
2520
- * @returns Rendered HTML string
2521
- */
2522
- static render(templatePath, variables = {}) {
2523
- try {
2524
- const template = fs.readFileSync(templatePath, "utf8");
2525
- let rendered = template;
2526
- for (const [key, value] of Object.entries(variables)) {
2527
- const placeholder = `{{${key}}}`;
2528
- const regex = new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
2529
- rendered = rendered.replace(regex, String(value));
2530
- }
2531
- return rendered;
2532
- } catch (error) {
2533
- console.error("Error rendering template:", error);
2534
- throw new Error(`Failed to render template: ${templatePath}`);
2535
- }
2536
- }
2537
- /**
2538
- * Get the absolute path to a template file relative to the current directory
2539
- * @param templateName - Name of the template file (e.g., 'index.html')
2540
- * @param baseDir - Base directory to search from (defaults to cwd)
2541
- * @returns Absolute path to the template file
2542
- */
2543
- static getTemplatePath(templateName, baseDir) {
2544
- const searchDir = baseDir || process.cwd();
2545
- const pagesPath = path.join(searchDir, "utils", "pages", templateName);
2546
- if (fs.existsSync(pagesPath)) {
2547
- return pagesPath;
2548
- }
2549
- const directPath = path.join(searchDir, "pages", templateName);
2550
- if (fs.existsSync(directPath)) {
2551
- return directPath;
2552
- }
2553
- return path.join(searchDir, "utils", "pages", templateName);
2554
- }
2555
- };
2556
-
2557
- // ../runtime-shared/dist/utils/versionExtractor.js
2558
- import fs2 from "fs";
2559
- import path2 from "path";
2560
- var VersionExtractor = class {
2561
- /**
2562
- * Extract version from README.md file in the template directory
2563
- * Looks for "Template Version: X.X.X" pattern in the last few lines
2564
- * @param templateDir - Path to the template directory containing README.md
2565
- * @returns Version string or default fallback
2566
- */
2567
- static getTemplateVersion(templateDir = process.cwd()) {
2568
- try {
2569
- const readmePath = path2.join(templateDir, "README.md");
2570
- if (!fs2.existsSync(readmePath)) {
2571
- console.warn("README.md not found, using default version");
2572
- return "v1.0.0";
2573
- }
2574
- const readmeContent = fs2.readFileSync(readmePath, "utf8");
2575
- const lines = readmeContent.split("\n");
2576
- const versionPattern = /Template Version:\s*([\d.]+)/i;
2577
- for (let i = lines.length - 1; i >= Math.max(0, lines.length - 10); i--) {
2578
- const match = lines[i].match(versionPattern);
2579
- if (match) {
2580
- return `v${match[1]}`;
2581
- }
2582
- }
2583
- console.warn("Version pattern not found in README.md, using default");
2584
- return "v1.0.0";
2585
- } catch (error) {
2586
- console.error("Error reading template version:", error.message);
2587
- return "v1.0.0";
2588
- }
2589
- }
2590
- };
2591
-
2592
- // ../runtime-shared/dist/utils/defaultEndpointHandler.js
2593
- var DefaultEndpointHandler = class {
2594
- /**
2595
- * Handle the default endpoint with content negotiation
2596
- * @param context - Function context with config and cache
2597
- * @param request - HTTP request object with method, path, query, headers, body, params
2598
- * @param options - Configuration options for the response
2599
- * @returns HTTP response object with statusCode, headers, and body
2600
- */
2601
- static async handle(context, request, options = {}) {
2602
- const { serviceName = "Sinch Function", companyName = "Your Company", templateVersion = "v1.0.0", availableEndpoints = {} } = options;
2603
- console.info("Default endpoint called");
2604
- console.info(`Request: ${request.method} ${request.path}`);
2605
- const acceptHeader = request.headers?.accept || request.headers?.Accept || "";
2606
- const wantsHtml = acceptHeader.includes("text/html") || !acceptHeader.includes("application/json") && !acceptHeader.includes("application/*") && !acceptHeader.includes("*/*");
2607
- if (wantsHtml) {
2608
- try {
2609
- const templatePath = TemplateRender.getTemplatePath("index.html");
2610
- const html = TemplateRender.render(templatePath, {
2611
- companyName: serviceName,
2612
- requestId: context.requestId,
2613
- method: request.method,
2614
- path: request.path,
2615
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2616
- templateVersion,
2617
- runtime: "Node.js"
2618
- });
2619
- return {
2620
- statusCode: 200,
2621
- headers: {
2622
- "Content-Type": "text/html; charset=utf-8"
2623
- },
2624
- body: html
2625
- };
2626
- } catch (error) {
2627
- console.warn("HTML template not found, returning JSON");
2628
- }
2629
- }
2630
- return {
2631
- statusCode: 200,
2632
- headers: {
2633
- "Content-Type": "application/json"
2634
- },
2635
- body: {
2636
- message: `Welcome to ${serviceName}`,
2637
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2638
- requestId: context.requestId,
2639
- method: request.method,
2640
- path: request.path,
2641
- availableEndpoints,
2642
- usage: {
2643
- html: "Set Accept: text/html header or visit in browser",
2644
- json: "Set Accept: application/json header or use API client"
2645
- }
2646
- }
2647
- };
2648
- }
2649
- };
2650
-
2651
- // ../runtime-shared/dist/utils/functionLoader.js
2652
- import path3 from "path";
2653
- function findFunctionPath2() {
2654
- return path3.join(process.cwd(), "dist", "function.js");
2655
- }
2656
-
2657
- // ../runtime-shared/dist/types/api.js
2658
- function createResponse(statusCode, body, headers) {
2659
- return { statusCode, body, headers };
2660
- }
2661
- function createJsonResponse(body, statusCode = 200) {
2662
- return {
2663
- statusCode,
2664
- headers: { "Content-Type": "application/json" },
2665
- body
2666
- };
2667
- }
2668
- function createErrorResponse(message, statusCode = 400) {
2669
- return {
2670
- statusCode,
2671
- headers: { "Content-Type": "application/json" },
2672
- body: { error: message }
2673
- };
2674
- }
2675
-
2676
- // src/cache/local.ts
2677
- var globalCache = /* @__PURE__ */ new Map();
2678
- var LocalCache = class {
2679
- cache;
2680
- constructor() {
2681
- this.cache = globalCache;
2682
- }
2683
- async set(key, value, ttlSeconds = 3600) {
2684
- this.cache.set(key, {
2685
- value,
2686
- expiresAt: Date.now() + ttlSeconds * 1e3
2687
- });
2688
- }
2689
- async get(key) {
2690
- const item = this.cache.get(key);
2691
- if (!item || Date.now() > item.expiresAt) {
2692
- this.cache.delete(key);
2693
- return null;
2694
- }
2695
- return item.value;
2696
- }
2697
- async has(key) {
2698
- const value = await this.get(key);
2699
- return value !== null;
2700
- }
2701
- async delete(key) {
2702
- return this.cache.delete(key);
2703
- }
2704
- async extend(key, additionalSeconds) {
2705
- const item = this.cache.get(key);
2706
- if (!item || Date.now() > item.expiresAt) {
2707
- return false;
2708
- }
2709
- item.expiresAt += additionalSeconds * 1e3;
2710
- return true;
2711
- }
2712
- async keys(pattern = "*") {
2713
- const allKeys = Array.from(this.cache.keys());
2714
- const now = Date.now();
2715
- for (const key of allKeys) {
2716
- const item = this.cache.get(key);
2717
- if (item && now > item.expiresAt) {
2718
- this.cache.delete(key);
2719
- }
2720
- }
2721
- const validKeys = Array.from(this.cache.keys());
2722
- if (pattern === "*") {
2723
- return validKeys;
2724
- }
2725
- const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
2726
- return validKeys.filter((key) => regex.test(key));
2727
- }
2728
- async getMany(keys) {
2729
- const results = {};
2730
- for (const key of keys) {
2731
- results[key] = await this.get(key);
2732
- }
2733
- return results;
2734
- }
2735
- /**
2736
- * Clear all entries from the cache
2737
- * (Utility method for testing)
2738
- */
2739
- async clear() {
2740
- this.cache.clear();
2741
- }
2742
- /**
2743
- * Get the number of entries in the cache
2744
- * (Utility method for debugging)
2745
- */
2746
- get size() {
2747
- return this.cache.size;
2748
- }
2749
- };
2750
- function createCacheClient(_projectId, _functionName) {
2751
- return new LocalCache();
2752
- }
2753
-
2754
- // src/storage/local.ts
2755
- import * as fs3 from "fs/promises";
2756
- import * as path4 from "path";
2757
- var LocalStorage = class {
2758
- baseDir;
2759
- constructor(baseDir) {
2760
- this.baseDir = baseDir ?? path4.join(process.cwd(), ".sinch", "storage");
2761
- }
2762
- resolvePath(key) {
2763
- const sanitized = key.replace(/^\/+/, "").replace(/\.\./g, "_");
2764
- return path4.join(this.baseDir, sanitized);
2765
- }
2766
- async write(key, data) {
2767
- const filePath = this.resolvePath(key);
2768
- await fs3.mkdir(path4.dirname(filePath), { recursive: true });
2769
- await fs3.writeFile(filePath, data);
2770
- }
2771
- async read(key) {
2772
- const filePath = this.resolvePath(key);
2773
- return fs3.readFile(filePath);
2774
- }
2775
- async list(prefix) {
2776
- const results = [];
2777
- await this.walkDir(this.baseDir, "", results);
2778
- if (prefix) {
2779
- return results.filter((f) => f.startsWith(prefix));
2780
- }
2781
- return results;
2782
- }
2783
- async exists(key) {
2784
- const filePath = this.resolvePath(key);
2785
- try {
2786
- await fs3.access(filePath);
2787
- return true;
2788
- } catch {
2789
- return false;
2790
- }
2791
- }
2792
- async delete(key) {
2793
- const filePath = this.resolvePath(key);
2794
- await fs3.rm(filePath, { force: true });
2795
- }
2796
- async walkDir(dir, relative, results) {
2797
- let entries;
2798
- try {
2799
- entries = await fs3.readdir(dir, { withFileTypes: true });
2800
- } catch {
2801
- return;
2802
- }
2803
- for (const entry of entries) {
2804
- const rel = relative ? `${relative}/${entry.name}` : entry.name;
2805
- if (entry.isDirectory()) {
2806
- await this.walkDir(path4.join(dir, entry.name), rel, results);
2807
- } else {
2808
- results.push(rel);
2809
- }
2810
- }
2811
- }
2812
- };
2813
- function createStorageClient(baseDir) {
2814
- return new LocalStorage(baseDir);
2815
- }
2816
-
2817
- // src/tunnel/index.ts
2818
- import WebSocket from "ws";
2819
- import axios from "axios";
2820
-
2821
- // src/tunnel/webhook-config.ts
2822
- import { SinchClient as SinchClient2 } from "@sinch/sdk-core";
2823
- import { randomBytes } from "crypto";
2824
- var SINCH_FN_URL_PATTERN = /\.fn(-\w+)?\.sinch\.com/;
2825
- function isOurWebhook(target) {
2826
- return !!target && SINCH_FN_URL_PATTERN.test(target);
2827
- }
2828
- function isTunnelUrl(target) {
2829
- return !!target && target.includes("tunnel.fn");
2830
- }
2831
- async function configureConversationWebhooks(webhookUrl, config) {
2832
- try {
2833
- const conversationAppId = process.env.CONVERSATION_APP_ID;
2834
- const projectId = process.env.PROJECT_ID;
2835
- const keyId = process.env.PROJECT_ID_API_KEY;
2836
- const keySecret = process.env.PROJECT_ID_API_SECRET;
2837
- if (!conversationAppId || !projectId || !keyId || !keySecret) {
2838
- console.log("\u{1F4A1} Conversation API not fully configured - skipping webhook setup");
2839
- return;
2840
- }
2841
- console.log(`\u{1F4AC} Conversation webhook URL: ${webhookUrl}`);
2842
- const sinchClient = new SinchClient2({
2843
- projectId,
2844
- keyId,
2845
- keySecret
2846
- });
2847
- const webhooksResult = await sinchClient.conversation.webhooks.list({
2848
- app_id: conversationAppId
2849
- });
2850
- const existingWebhooks = webhooksResult.webhooks || [];
2851
- const deployedWebhook = existingWebhooks.find(
2852
- (w) => isOurWebhook(w.target)
2853
- );
2854
- if (!deployedWebhook || !deployedWebhook.id) {
2855
- console.log("\u26A0\uFE0F No deployed webhook found \u2014 deploy first");
2856
- return;
2857
- }
2858
- config.conversationWebhookId = deployedWebhook.id;
2859
- config.originalTarget = deployedWebhook.target;
2860
- const hmacSecret = randomBytes(32).toString("hex");
2861
- process.env.CONVERSATION_WEBHOOK_SECRET = hmacSecret;
2862
- resetSinchClients();
2863
- await sinchClient.conversation.webhooks.update({
2864
- webhook_id: deployedWebhook.id,
2865
- webhookUpdateRequestBody: {
2866
- target: webhookUrl,
2867
- secret: hmacSecret
2868
- },
2869
- update_mask: ["target", "secret"]
2870
- });
2871
- console.log(`\u2705 Updated Conversation webhook to tunnel: ${webhookUrl}`);
2872
- console.log("\u{1F512} HMAC secret configured for webhook signature validation");
2873
- console.log("\u{1F4AC} Send a message to your Conversation app to test!");
2874
- } catch (error) {
2875
- console.log("\u26A0\uFE0F Could not configure Conversation webhooks:", error instanceof Error ? error.message : error);
2876
- }
2877
- }
2878
- async function cleanupConversationWebhook(config) {
2879
- if (!config.conversationWebhookId) return;
2880
- try {
2881
- const conversationAppId = process.env.CONVERSATION_APP_ID;
2882
- const projectId = process.env.PROJECT_ID;
2883
- const keyId = process.env.PROJECT_ID_API_KEY;
2884
- const keySecret = process.env.PROJECT_ID_API_SECRET;
2885
- if (!conversationAppId || !projectId || !keyId || !keySecret) return;
2886
- const sinchClient = new SinchClient2({
2887
- projectId,
2888
- keyId,
2889
- keySecret
2890
- });
2891
- let restoreTarget = config.originalTarget;
2892
- if (!restoreTarget || isTunnelUrl(restoreTarget)) {
2893
- const functionName = process.env.FUNCTION_NAME || process.env.FUNCTION_ID;
2894
- if (functionName) {
2895
- restoreTarget = `https://${functionName}.fn-dev.sinch.com/webhook/conversation`;
2896
- console.log(`\u{1F527} Derived restore target from env: ${restoreTarget}`);
2897
- } else {
2898
- console.log("\u26A0\uFE0F Cannot restore webhook \u2014 no FUNCTION_NAME or FUNCTION_ID available");
2899
- return;
2900
- }
2901
- }
2902
- await sinchClient.conversation.webhooks.update({
2903
- webhook_id: config.conversationWebhookId,
2904
- webhookUpdateRequestBody: {
2905
- target: restoreTarget
2906
- },
2907
- update_mask: ["target"]
2908
- });
2909
- console.log(`\u{1F504} Restored webhook target to: ${restoreTarget}`);
2910
- config.conversationWebhookId = void 0;
2911
- config.originalTarget = void 0;
2912
- delete process.env.CONVERSATION_WEBHOOK_SECRET;
2913
- resetSinchClients();
2914
- } catch (error) {
2915
- console.log("\u26A0\uFE0F Could not restore Conversation webhook:", error instanceof Error ? error.message : error);
2916
- }
2917
- }
2918
- async function configureElevenLabs() {
2919
- try {
2920
- const agentId = process.env.ELEVENLABS_AGENT_ID;
2921
- const apiKey = process.env.ELEVENLABS_API_KEY;
2922
- if (!agentId || !apiKey) {
2923
- console.log("\u{1F4A1} ElevenLabs not fully configured - skipping auto-configuration");
2924
- return;
2925
- }
2926
- void apiKey;
2927
- console.log("\u{1F916} ElevenLabs auto-configuration enabled");
2928
- console.log(` Agent ID: ${agentId}`);
2929
- } catch (error) {
2930
- console.log("\u26A0\uFE0F Could not configure ElevenLabs:", error instanceof Error ? error.message : error);
2931
- }
2932
- }
2933
-
2934
- // src/tunnel/index.ts
2935
- var TUNNEL_GATEWAY_DEFAULT = "https://tunnel.fn.sinch.com";
2936
- var TunnelClient = class {
2937
- ws = null;
2938
- tunnelUrl = null;
2939
- tunnelId = null;
2940
- isConnected = false;
2941
- reconnectAttempts = 0;
2942
- maxReconnectAttempts = 10;
2943
- reconnectDelay = 5e3;
2944
- heartbeatInterval = null;
2945
- localPort;
2946
- webhookConfig = {};
2947
- welcomeResolver = null;
2948
- constructor(localPort = 3e3) {
2949
- this.localPort = localPort;
2950
- }
2951
- getTunnelGatewayUrl() {
2952
- const explicitUrl = process.env.TUNNEL_GATEWAY_URL;
2953
- if (explicitUrl) {
2954
- return explicitUrl;
2955
- }
2956
- return TUNNEL_GATEWAY_DEFAULT;
2957
- }
2958
- generateTunnelId() {
2959
- const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2960
- const timestamp = Date.now();
2961
- let timestampPart = "";
2962
- let t = timestamp;
2963
- for (let i = 0; i < 10; i++) {
2964
- timestampPart = ENCODING[t % 32] + timestampPart;
2965
- t = Math.floor(t / 32);
2966
- }
2967
- const randomBytes2 = new Uint8Array(10);
2968
- crypto.getRandomValues(randomBytes2);
2969
- let randomPart = "";
2970
- for (let i = 0; i < 10; i++) {
2971
- const byte = randomBytes2[i];
2972
- randomPart += ENCODING[byte >> 3];
2973
- if (randomPart.length < 16) {
2974
- randomPart += ENCODING[(byte & 7) << 2 | (i + 1 < 10 ? randomBytes2[i + 1] >> 6 : 0)];
2975
- }
2976
- }
2977
- randomPart = randomPart.substring(0, 16);
2978
- return timestampPart + randomPart;
2979
- }
2980
- async connect() {
2981
- if (process.env.SINCH_TUNNEL !== "true") {
2982
- console.log("Tunnel is disabled (set SINCH_TUNNEL=true to enable)");
2983
- return;
2984
- }
2985
- const gatewayUrl = this.getTunnelGatewayUrl();
2986
- this.tunnelId = this.generateTunnelId();
2987
- const gatewayUri = new URL(gatewayUrl);
2988
- const wsUrl = new URL(gatewayUrl);
2989
- wsUrl.protocol = gatewayUri.protocol === "https:" ? "wss:" : "ws:";
2990
- wsUrl.pathname = "/ws";
2991
- wsUrl.searchParams.set("tunnel", this.tunnelId);
2992
- const tunnelEndpoint = wsUrl.toString();
2993
- console.log(`Connecting to tunnel gateway at ${tunnelEndpoint}...`);
2994
- try {
2995
- this.ws = new WebSocket(tunnelEndpoint);
2996
- const welcomePromise = new Promise((resolve, reject) => {
2997
- this.welcomeResolver = resolve;
2998
- setTimeout(() => reject(new Error("Timed out waiting for welcome message")), 1e4);
2999
- });
3000
- this.ws.on("open", () => {
3001
- this.isConnected = true;
3002
- this.reconnectAttempts = 0;
3003
- console.log("WebSocket connected, waiting for welcome message...");
3004
- });
3005
- this.ws.on("message", async (data) => {
3006
- try {
3007
- const message = JSON.parse(data.toString());
3008
- await this.handleMessage(message);
3009
- } catch (error) {
3010
- console.error("Error processing tunnel message:", error);
3011
- }
3012
- });
3013
- this.ws.on("close", async () => {
3014
- this.isConnected = false;
3015
- console.log("Tunnel connection closed");
3016
- this.stopHeartbeat();
3017
- this.scheduleReconnect();
3018
- });
3019
- this.ws.on("error", (error) => {
3020
- console.error("Tunnel connection error:", error.message);
3021
- });
3022
- await welcomePromise;
3023
- if (!this.tunnelUrl) {
3024
- throw new Error("Did not receive tunnel URL from gateway");
3025
- }
3026
- console.log("Tunnel connected successfully!");
3027
- this.startHeartbeat();
3028
- await this.configureWebhooks();
3029
- } catch (error) {
3030
- console.error("Failed to establish tunnel connection:", error.message);
3031
- this.scheduleReconnect();
3032
- }
3033
- }
3034
- async handleMessage(message) {
3035
- switch (message.type) {
3036
- case "welcome":
3037
- this.handleWelcomeMessage(message);
3038
- break;
3039
- case "request":
3040
- await this.handleRequest(message);
3041
- break;
3042
- case "ping":
3043
- this.sendPong();
3044
- break;
3045
- }
3046
- }
3047
- /**
3048
- * Build a full tunnel URL with optional sub-path and tunnel query param.
3049
- * e.g. buildTunnelUrl('/webhook/conversation') →
3050
- * https://tunnel.fn.sinch.com/ingress/webhook/conversation?tunnel=01KKT...
3051
- */
3052
- buildTunnelUrl(path6) {
3053
- const base = this.tunnelUrl.replace(/\/$/, "");
3054
- return `${base}${path6 || ""}?tunnel=${this.tunnelId}`;
3055
- }
3056
- handleWelcomeMessage(message) {
3057
- this.tunnelId = message.tunnelId || null;
3058
- this.tunnelUrl = message.publicUrl || null;
3059
- console.log(`Received welcome: tunnelId=${this.tunnelId}`);
3060
- if (this.welcomeResolver) {
3061
- this.welcomeResolver(true);
3062
- this.welcomeResolver = null;
3063
- }
3064
- }
3065
- async handleRequest(message) {
3066
- const verbose = process.env.VERBOSE === "true";
3067
- console.log(`Forwarding ${message.method} request to ${message.path}`);
3068
- if (verbose && message.body) {
3069
- console.log(` \u2190 Request body: ${message.body.substring(0, 2e3)}`);
3070
- }
3071
- try {
3072
- const localUrl = `http://localhost:${this.localPort}${message.path}${message.query || ""}`;
3073
- const axiosConfig = {
3074
- method: message.method,
3075
- url: localUrl,
3076
- headers: {}
3077
- };
3078
- if (message.headers) {
3079
- axiosConfig.headers = { ...message.headers };
3080
- }
3081
- if (message.body) {
3082
- axiosConfig.data = message.body;
3083
- }
3084
- const response = await axios(axiosConfig);
3085
- const headers = {};
3086
- for (const [key, value] of Object.entries(response.headers)) {
3087
- if (value) {
3088
- const normalizedKey = key.toLowerCase() === "content-type" ? "Content-Type" : key.toLowerCase() === "content-length" ? "Content-Length" : key;
3089
- headers[normalizedKey] = String(value);
3090
- }
3091
- }
3092
- if (!headers["Content-Type"] && response.data) {
3093
- headers["Content-Type"] = "application/json";
3094
- }
3095
- const body = typeof response.data === "string" ? response.data : JSON.stringify(response.data);
3096
- const responseMessage = {
3097
- type: "response",
3098
- id: message.id,
3099
- statusCode: response.status,
3100
- headers,
3101
- body
3102
- };
3103
- if (verbose) {
3104
- console.log(` \u2192 Response ${response.status}: ${body.substring(0, 2e3)}`);
3105
- }
3106
- this.ws?.send(JSON.stringify(responseMessage));
3107
- } catch (error) {
3108
- console.error(`Error forwarding request: ${error.message} (${error.response?.status || "no response"})`);
3109
- if (verbose && error.response?.data) {
3110
- console.error(` \u2192 Error body: ${typeof error.response.data === "string" ? error.response.data : JSON.stringify(error.response.data)}`.substring(0, 2e3));
3111
- }
3112
- const errorResponse = {
3113
- type: "response",
3114
- id: message.id,
3115
- statusCode: error.response?.status || 502,
3116
- headers: { "Content-Type": "text/plain" },
3117
- body: "Error forwarding request to local server"
3118
- };
3119
- this.ws?.send(JSON.stringify(errorResponse));
3120
- }
3121
- }
3122
- sendPong() {
3123
- const pongMessage = { type: "pong" };
3124
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
3125
- this.ws.send(JSON.stringify(pongMessage));
3126
- }
3127
- }
3128
- startHeartbeat() {
3129
- this.heartbeatInterval = setInterval(() => {
3130
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
3131
- const pingMessage = { type: "ping" };
3132
- this.ws.send(JSON.stringify(pingMessage));
3133
- }
3134
- }, 3e4);
3135
- }
3136
- stopHeartbeat() {
3137
- if (this.heartbeatInterval) {
3138
- clearInterval(this.heartbeatInterval);
3139
- this.heartbeatInterval = null;
3140
- }
3141
- }
3142
- /**
3143
- * Configure all webhooks (Voice, Conversation, ElevenLabs)
3144
- */
3145
- async configureWebhooks() {
3146
- const hasNewFormat = "AUTO_CONFIGURE" in process.env;
3147
- const autoEnabled = process.env.AUTO_CONFIGURE === "true";
3148
- const sinchServices = (process.env.SINCH_SERVICES ?? "").split(",").map((s) => s.trim());
3149
- const autoConfigVoice = hasNewFormat ? autoEnabled && sinchServices.includes("voice") : process.env.AUTO_CONFIGURE_VOICE !== "false" && !!process.env.VOICE_APPLICATION_KEY;
3150
- const autoConfigConversation = hasNewFormat ? autoEnabled && sinchServices.includes("conversation") : process.env.AUTO_CONFIGURE_CONVERSATION !== "false" && !!process.env.CONVERSATION_APP_ID;
3151
- if (autoConfigVoice && process.env.VOICE_APPLICATION_KEY) {
3152
- await this.configureVoiceWebhooks();
3153
- }
3154
- if (autoConfigConversation && process.env.CONVERSATION_APP_ID) {
3155
- await configureConversationWebhooks(this.buildTunnelUrl("/webhook/conversation"), this.webhookConfig);
3156
- }
3157
- if (process.env.ELEVENLABS_AUTO_CONFIGURE === "true") {
3158
- await configureElevenLabs();
3159
- }
3160
- }
3161
- /**
3162
- * Cleanup webhooks on disconnect
3163
- */
3164
- async cleanupWebhooks() {
3165
- await cleanupConversationWebhook(this.webhookConfig);
3166
- }
3167
- async configureVoiceWebhooks() {
3168
- try {
3169
- const appKey = process.env.VOICE_APPLICATION_KEY;
3170
- const appSecret = process.env.VOICE_APPLICATION_SECRET;
3171
- if (!appKey || !appSecret) {
3172
- console.log("\u{1F4A1} Voice API not configured - skipping phone number display");
3173
- return;
3174
- }
3175
- try {
3176
- const updateUrl = `https://callingapi.sinch.com/v1/configuration/callbacks/applications/${appKey}/`;
3177
- const auth = Buffer.from(`${appKey}:${appSecret}`).toString("base64");
3178
- await axios.post(
3179
- updateUrl,
3180
- {
3181
- url: {
3182
- primary: this.buildTunnelUrl(),
3183
- fallback: null
3184
- }
3185
- },
3186
- {
3187
- headers: {
3188
- Authorization: `Basic ${auth}`,
3189
- "Content-Type": "application/json"
3190
- }
3191
- }
3192
- );
3193
- console.log("\u2705 Updated voice webhook URL");
3194
- } catch (error) {
3195
- console.log("\u26A0\uFE0F Could not update webhook URL:", error.message);
3196
- }
3197
- try {
3198
- const listUrl = `https://callingapi.sinch.com/v1/configuration/numbers/`;
3199
- const auth = Buffer.from(`${appKey}:${appSecret}`).toString("base64");
3200
- const response = await axios.get(listUrl, {
3201
- headers: {
3202
- Authorization: `Basic ${auth}`
3203
- }
3204
- });
3205
- const numbers = response.data?.numbers || [];
3206
- const appNumbers = numbers.filter((n) => n.applicationkey === appKey);
3207
- if (appNumbers.length > 0) {
3208
- console.log("\u{1F4F1} Test Phone Numbers:");
3209
- appNumbers.forEach((num) => {
3210
- console.log(` \u260E\uFE0F ${num.number}`);
3211
- });
3212
- console.log("\u{1F4A1} Call any of these numbers to test your voice function!");
3213
- } else {
3214
- console.log("\u26A0\uFE0F No phone numbers assigned to this application yet");
3215
- console.log("\u{1F4A1} Add numbers at https://dashboard.sinch.com/voice/apps");
3216
- }
3217
- } catch (error) {
3218
- console.log("\u{1F4A1} Could not fetch phone numbers:", error.message);
3219
- }
3220
- } catch (error) {
3221
- console.log("\u{1F4A1} Could not fetch phone numbers (Voice API may not be configured)");
3222
- }
3223
- }
3224
- scheduleReconnect() {
3225
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
3226
- console.error("Max reconnection attempts reached. Giving up.");
3227
- return;
3228
- }
3229
- this.reconnectAttempts++;
3230
- const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), 3e4);
3231
- console.log(`Attempting to reconnect in ${delay / 1e3} seconds...`);
3232
- setTimeout(() => this.connect(), delay);
3233
- }
3234
- async disconnect() {
3235
- this.stopHeartbeat();
3236
- await this.cleanupWebhooks();
3237
- if (this.ws) {
3238
- this.ws.close();
3239
- this.ws = null;
3240
- }
3241
- this.isConnected = false;
3242
- }
3243
- getTunnelUrl() {
3244
- if (!this.tunnelUrl || !this.tunnelId) return null;
3245
- return this.buildTunnelUrl();
3246
- }
3247
- getIsConnected() {
3248
- return this.isConnected;
3249
- }
3250
- };
3251
- var tunnelInstance = null;
3252
- function getTunnelClient(localPort = 3e3) {
3253
- if (!tunnelInstance) {
3254
- tunnelInstance = new TunnelClient(localPort);
3255
- }
3256
- return tunnelInstance;
3257
- }
3258
-
3259
- // src/secrets/index.ts
3260
- import fs4 from "fs";
3261
- import path5 from "path";
3262
- import os from "os";
3263
- import crypto2 from "crypto";
3264
-
3265
- // src/secrets/keychain.ts
3266
- import { execFile, spawn } from "child_process";
3267
- import { promisify } from "util";
3268
- var execFileAsync = promisify(execFile);
3269
- function b64(value) {
3270
- return Buffer.from(value, "utf8").toString("base64");
3271
- }
3272
- function psParam(name, value) {
3273
- return `$${name} = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(value)}'));`;
3274
- }
3275
- var WIN32_CRED_READ_SCRIPT = `
3276
- Add-Type -TypeDefinition @'
3277
- using System;
3278
- using System.Runtime.InteropServices;
3279
- public class CredManager {
3280
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
3281
- private struct CREDENTIAL {
3282
- public int Flags;
3283
- public int Type;
3284
- public IntPtr TargetName;
3285
- public IntPtr Comment;
3286
- public long LastWritten;
3287
- public int CredentialBlobSize;
3288
- public IntPtr CredentialBlob;
3289
- public int Persist;
3290
- public int AttributeCount;
3291
- public IntPtr Attributes;
3292
- public IntPtr TargetAlias;
3293
- public IntPtr UserName;
3294
- }
3295
- [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
3296
- private static extern bool CredReadW(string target, int type, int flags, out IntPtr cred);
3297
- [DllImport("advapi32.dll")]
3298
- private static extern void CredFree(IntPtr cred);
3299
- public static string Read(string target) {
3300
- IntPtr credPtr;
3301
- if (!CredReadW(target, 1, 0, out credPtr)) return null;
3302
- try {
3303
- CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
3304
- if (c.CredentialBlobSize > 0 && c.CredentialBlob != IntPtr.Zero)
3305
- return Marshal.PtrToStringUni(c.CredentialBlob, c.CredentialBlobSize / 2);
3306
- return "";
3307
- } finally { CredFree(credPtr); }
3308
- }
3309
- }
3310
- '@
3311
- $r = [CredManager]::Read($target)
3312
- if ($r -ne $null) { [Console]::Write($r) }
3313
- else { exit 1 }
3314
- `;
3315
- var WIN32_CRED_WRITE_SCRIPT = `
3316
- Add-Type -TypeDefinition @'
3317
- using System;
3318
- using System.Runtime.InteropServices;
3319
- using System.Text;
3320
- public class CredWriter {
3321
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
3322
- private struct CREDENTIAL {
3323
- public int Flags;
3324
- public int Type;
3325
- public string TargetName;
3326
- public string Comment;
3327
- public long LastWritten;
3328
- public int CredentialBlobSize;
3329
- public IntPtr CredentialBlob;
3330
- public int Persist;
3331
- public int AttributeCount;
3332
- public IntPtr Attributes;
3333
- public string TargetAlias;
3334
- public string UserName;
3335
- }
3336
- [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
3337
- private static extern bool CredWriteW(ref CREDENTIAL cred, int flags);
3338
- public static bool Write(string target, string password) {
3339
- byte[] blob = Encoding.Unicode.GetBytes(password);
3340
- CREDENTIAL c = new CREDENTIAL();
3341
- c.Type = 1;
3342
- c.TargetName = target;
3343
- c.CredentialBlobSize = blob.Length;
3344
- c.CredentialBlob = Marshal.AllocHGlobal(blob.Length);
3345
- Marshal.Copy(blob, 0, c.CredentialBlob, blob.Length);
3346
- c.Persist = 2;
3347
- try { return CredWriteW(ref c, 0); }
3348
- finally { Marshal.FreeHGlobal(c.CredentialBlob); }
3349
- }
3350
- }
3351
- '@
3352
- if (-not [CredWriter]::Write($target, $password)) { exit 1 }
3353
- `;
3354
- var WIN32_CRED_DELETE_SCRIPT = `
3355
- Add-Type -TypeDefinition @'
3356
- using System;
3357
- using System.Runtime.InteropServices;
3358
- public class CredDeleter {
3359
- [DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
3360
- private static extern bool CredDeleteW(string target, int type, int flags);
3361
- public static bool Delete(string target) { return CredDeleteW(target, 1, 0); }
3362
- }
3363
- '@
3364
- if (-not [CredDeleter]::Delete($target)) { exit 1 }
3365
- `;
3366
- function winTarget(service, account) {
3367
- return `${service}/${account}`;
3368
- }
3369
- var windowsKeychain = {
3370
- async getPassword(service, account) {
3371
- try {
3372
- const params = psParam("target", winTarget(service, account));
3373
- const { stdout } = await execFileAsync(
3374
- "powershell.exe",
3375
- ["-NoProfile", "-NonInteractive", "-Command", params + WIN32_CRED_READ_SCRIPT],
3376
- { timeout: 15e3, windowsHide: true }
3377
- );
3378
- return stdout;
3379
- } catch {
3380
- return null;
3381
- }
3382
- },
3383
- async setPassword(service, account, password) {
3384
- const params = psParam("target", winTarget(service, account)) + psParam("password", password);
3385
- await execFileAsync(
3386
- "powershell.exe",
3387
- ["-NoProfile", "-NonInteractive", "-Command", params + WIN32_CRED_WRITE_SCRIPT],
3388
- { timeout: 15e3, windowsHide: true }
3389
- );
3390
- },
3391
- async deletePassword(service, account) {
3392
- try {
3393
- const params = psParam("target", winTarget(service, account));
3394
- await execFileAsync(
3395
- "powershell.exe",
3396
- ["-NoProfile", "-NonInteractive", "-Command", params + WIN32_CRED_DELETE_SCRIPT],
3397
- { timeout: 15e3, windowsHide: true }
3398
- );
3399
- return true;
3400
- } catch {
3401
- return false;
3402
- }
3403
- }
3404
- };
3405
- var macKeychain = {
3406
- async getPassword(service, account) {
3407
- try {
3408
- const { stdout } = await execFileAsync(
3409
- "security",
3410
- ["find-generic-password", "-s", service, "-a", account, "-w"],
3411
- { timeout: 15e3 }
3412
- );
3413
- return stdout.trimEnd();
3414
- } catch {
3415
- return null;
3416
- }
3417
- },
3418
- async setPassword(service, account, password) {
3419
- await execFileAsync(
3420
- "security",
3421
- ["add-generic-password", "-U", "-s", service, "-a", account, "-w", password],
3422
- { timeout: 15e3 }
3423
- );
3424
- },
3425
- async deletePassword(service, account) {
3426
- try {
3427
- await execFileAsync(
3428
- "security",
3429
- ["delete-generic-password", "-s", service, "-a", account],
3430
- { timeout: 15e3 }
3431
- );
3432
- return true;
3433
- } catch {
3434
- return false;
3435
- }
3436
- }
3437
- };
3438
- function debugKeychain(op, err) {
3439
- if (!process.env.DEBUG?.includes("sinch:keychain")) return;
3440
- const e = err;
3441
- const stderr = e.stderr?.toString() ?? "";
3442
- const code = e.code ?? e.exitCode ?? "?";
3443
- const message = e.message ?? String(err);
3444
- console.debug(`[keychain] secret-tool ${op} failed (code=${code}): ${stderr || message}`);
3445
- }
3446
- var linuxKeychain = {
3447
- async getPassword(service, account) {
3448
- try {
3449
- const { stdout } = await execFileAsync(
3450
- "secret-tool",
3451
- ["lookup", "service", service, "account", account],
3452
- { timeout: 15e3 }
3453
- );
3454
- return stdout.trimEnd();
3455
- } catch (err) {
3456
- debugKeychain("lookup", err);
3457
- return null;
3458
- }
3459
- },
3460
- // secret-tool reads password from stdin (avoids exposing it in process args)
3461
- async setPassword(service, account, password) {
3462
- const child = spawn(
3463
- "secret-tool",
3464
- ["store", "--label", `${service}/${account}`, "service", service, "account", account],
3465
- { stdio: ["pipe", "pipe", "pipe"] }
3466
- );
3467
- let stderr = "";
3468
- child.stderr?.on("data", (chunk) => {
3469
- stderr += chunk.toString();
3470
- });
3471
- child.stdin.write(password);
3472
- child.stdin.end();
3473
- await new Promise((resolve, reject) => {
3474
- child.on("close", (code) => {
3475
- if (code === 0) {
3476
- resolve();
3477
- } else {
3478
- const err = Object.assign(
3479
- new Error(
3480
- `secret-tool store failed (exit ${code})${stderr ? ": " + stderr.trim() : ""}`
3481
- ),
3482
- { stderr, exitCode: code }
3483
- );
3484
- debugKeychain("store", err);
3485
- reject(err);
3486
- }
3487
- });
3488
- child.on("error", (err) => {
3489
- debugKeychain("store", err);
3490
- reject(err);
3491
- });
3492
- });
3493
- },
3494
- async deletePassword(service, account) {
3495
- try {
3496
- await execFileAsync(
3497
- "secret-tool",
3498
- ["clear", "service", service, "account", account],
3499
- { timeout: 15e3 }
3500
- );
3501
- return true;
3502
- } catch (err) {
3503
- debugKeychain("clear", err);
3504
- return false;
3505
- }
3506
- }
3507
- };
3508
- function getBackend() {
3509
- switch (process.platform) {
3510
- case "win32":
3511
- return windowsKeychain;
3512
- case "darwin":
3513
- return macKeychain;
3514
- default:
3515
- return linuxKeychain;
3516
- }
3517
- }
3518
- var backend = getBackend();
3519
- async function getPassword(service, account) {
3520
- return backend.getPassword(service, account);
3521
- }
3522
- async function setPassword(service, account, password) {
3523
- return backend.setPassword(service, account, password);
3524
- }
3525
- async function deletePassword(service, account) {
3526
- return backend.deletePassword(service, account);
3527
- }
3528
-
3529
- // src/secrets/index.ts
3530
- var SecretsLoader = class {
3531
- SERVICE_NAME = "sinch-cli";
3532
- username = os.userInfo().username;
3533
- /**
3534
- * Load secrets from OS keychain for variables declared in .env
3535
- * Only loads secrets that have empty values in .env (security best practice)
3536
- */
3537
- async loadFromKeychain() {
3538
- if (process.env.NODE_ENV === "production") {
3539
- return false;
3540
- }
3541
- try {
3542
- const envPath = path5.join(process.cwd(), ".env");
3543
- if (!fs4.existsSync(envPath)) {
3544
- console.debug("[Secrets] No .env file found, skipping keychain load");
3545
- return false;
3546
- }
3547
- const envContent = fs4.readFileSync(envPath, "utf8");
3548
- const envLines = envContent.replace(/\r\n/g, "\n").split("\n");
3549
- const secretsToLoad = [];
3550
- envLines.forEach((line) => {
3551
- const trimmedLine = line.replace(/\r$/, "").trim();
3552
- if (trimmedLine && !trimmedLine.startsWith("#")) {
3553
- const equalIndex = trimmedLine.indexOf("=");
3554
- if (equalIndex !== -1) {
3555
- const envKey = trimmedLine.substring(0, equalIndex).trim();
3556
- const envValue = trimmedLine.substring(equalIndex + 1).trim();
3557
- if (envKey && envValue === "" && !process.env[envKey]) {
3558
- secretsToLoad.push(envKey);
3559
- }
3560
- }
3561
- }
3562
- });
3563
- if (secretsToLoad.length === 0) {
3564
- console.debug("[Secrets] No empty variables found in .env");
3565
- return false;
3566
- }
3567
- let secretsLoaded = 0;
3568
- if (secretsToLoad.includes("PROJECT_ID_API_SECRET")) {
3569
- let apiSecret = await getPassword(this.SERVICE_NAME, `${this.username}-keySecret`);
3570
- let fromPlaintext = false;
3571
- if (!apiSecret) {
3572
- apiSecret = this.readProfilePlaintext("keySecretPlaintext");
3573
- fromPlaintext = !!apiSecret;
3574
- }
3575
- if (apiSecret) {
3576
- process.env.PROJECT_ID_API_SECRET = apiSecret;
3577
- if (fromPlaintext) {
3578
- this.warnPlaintext("PROJECT_ID_API_SECRET");
3579
- } else {
3580
- console.log("\u2705 Loaded PROJECT_ID_API_SECRET from secure storage");
3581
- }
3582
- secretsLoaded++;
3583
- }
3584
- }
3585
- if (secretsToLoad.includes("VOICE_APPLICATION_SECRET")) {
3586
- const applicationKey = process.env.VOICE_APPLICATION_KEY || this.getApplicationKeyFromConfig();
3587
- let appSecret = null;
3588
- let fromPlaintext = false;
3589
- if (applicationKey) {
3590
- appSecret = await getPassword(this.SERVICE_NAME, applicationKey);
3591
- }
3592
- if (!appSecret) {
3593
- appSecret = this.readProfilePlaintext("applicationSecretPlaintext");
3594
- fromPlaintext = !!appSecret;
3595
- }
3596
- if (appSecret) {
3597
- process.env.VOICE_APPLICATION_SECRET = appSecret;
3598
- if (fromPlaintext) {
3599
- this.warnPlaintext("VOICE_APPLICATION_SECRET");
3600
- } else {
3601
- console.log("\u2705 Loaded VOICE_APPLICATION_SECRET from secure storage");
3602
- }
3603
- secretsLoaded++;
3604
- }
3605
- }
3606
- const functionName = this.getFunctionNameFromConfig();
3607
- for (const secretName of secretsToLoad) {
3608
- if (secretName === "PROJECT_ID_API_SECRET" || secretName === "VOICE_APPLICATION_SECRET") {
3609
- continue;
3610
- }
3611
- if (functionName) {
3612
- const value = await getPassword(
3613
- this.SERVICE_NAME,
3614
- `${functionName}-${secretName}`
3615
- );
3616
- if (value) {
3617
- process.env[secretName] = value;
3618
- console.log(`\u2705 Loaded ${secretName} from secure storage`);
3619
- secretsLoaded++;
3620
- }
3621
- }
3622
- }
3623
- if (secretsLoaded === 0) {
3624
- const probe = await this.probeKeychain();
3625
- if (!probe.ok) {
3626
- console.warn(`\u26A0\uFE0F Keychain unreachable: ${probe.reason}`);
3627
- if (probe.hint) console.warn(` ${probe.hint}`);
3628
- console.warn(" Sinch CLI may have stored credentials in plaintext config instead.");
3629
- console.warn(" Run `sinch auth status` to verify, or re-run `sinch auth login`.");
3630
- } else {
3631
- console.log("\u2139\uFE0F No secrets found in secure storage for declared variables");
3632
- console.log("\u{1F4A1} To configure Sinch auth: sinch auth login");
3633
- console.log("\u{1F4A1} To add custom secrets: sinch secrets add <KEY> <VALUE>");
3634
- }
3635
- }
3636
- return secretsLoaded > 0;
3637
- } catch (error) {
3638
- console.error("[Secrets] Unexpected error:", error.message);
3639
- console.log("\u{1F4A1} To manage secrets manually, use: sinch secrets");
3640
- return false;
3641
- }
3642
- }
3643
- /**
3644
- * Helper to get application key from sinch.json
3645
- */
3646
- getApplicationKeyFromConfig() {
3647
- try {
3648
- const sinchJsonPath = path5.join(process.cwd(), "sinch.json");
3649
- if (fs4.existsSync(sinchJsonPath)) {
3650
- const sinchConfig = JSON.parse(fs4.readFileSync(sinchJsonPath, "utf8"));
3651
- return sinchConfig.voiceAppId || sinchConfig.applicationKey || null;
3652
- }
3653
- } catch (error) {
3654
- console.debug("[Secrets] Could not read sinch.json:", error.message);
3655
- }
3656
- return null;
3657
- }
3658
- /**
3659
- * Helper to get function name from sinch.json
3660
- */
3661
- getFunctionNameFromConfig() {
3662
- try {
3663
- const sinchJsonPath = path5.join(process.cwd(), "sinch.json");
3664
- if (fs4.existsSync(sinchJsonPath)) {
3665
- const sinchConfig = JSON.parse(fs4.readFileSync(sinchJsonPath, "utf8"));
3666
- return sinchConfig.name || null;
3667
- }
3668
- } catch (error) {
3669
- console.debug("[Secrets] Could not read sinch.json:", error.message);
3670
- }
3671
- return null;
3672
- }
3673
- /**
3674
- * Read a plaintext credential field from the active CLI profile.
3675
- * Scoped to the canonical pair (keySecretPlaintext, applicationSecretPlaintext)
3676
- * that sinch-cli writes when the OS keychain is unreachable. See
3677
- * sinch-cli/src/lib/credentials.ts store() for the writer side.
3678
- */
3679
- readProfilePlaintext(field) {
3680
- try {
3681
- const home = os.homedir();
3682
- const metaPath = path5.join(home, ".sinch", "config.json");
3683
- let activeProfile = "default";
3684
- if (fs4.existsSync(metaPath)) {
3685
- const meta = JSON.parse(fs4.readFileSync(metaPath, "utf8"));
3686
- if (typeof meta.activeProfile === "string" && meta.activeProfile) {
3687
- activeProfile = meta.activeProfile;
3688
- }
3689
- }
3690
- if (/[\\/]/.test(activeProfile) || activeProfile.includes("..")) {
3691
- return null;
3692
- }
3693
- const profilePath = path5.join(home, ".sinch", "profiles", `${activeProfile}.json`);
3694
- if (!fs4.existsSync(profilePath)) return null;
3695
- const profile = JSON.parse(fs4.readFileSync(profilePath, "utf8"));
3696
- const value = profile[field];
3697
- return typeof value === "string" && value.length > 0 ? value : null;
3698
- } catch (err) {
3699
- console.debug("[Secrets] Could not read plaintext profile fallback:", String(err));
3700
- return null;
3701
- }
3702
- }
3703
- /**
3704
- * Active write/read/delete round-trip to verify the OS keychain is reachable.
3705
- * Used to distinguish "keychain works but no entries stored" from "keychain
3706
- * unreachable" so error messages can be specific. Cost: 3 secret-tool /
3707
- * security / PowerShell invocations, only when no secrets were loaded.
3708
- */
3709
- async probeKeychain() {
3710
- const sentinelAccount = `__sinch_probe_${crypto2.randomUUID()}`;
3711
- const sentinelValue = crypto2.randomUUID();
3712
- try {
3713
- await setPassword(this.SERVICE_NAME, sentinelAccount, sentinelValue);
3714
- } catch (err) {
3715
- return {
3716
- ok: false,
3717
- reason: `write failed (${err instanceof Error ? err.message : String(err)})`,
3718
- hint: this.platformHint()
3719
- };
3720
- }
3721
- let readBack = null;
3722
- try {
3723
- readBack = await getPassword(this.SERVICE_NAME, sentinelAccount);
3724
- } catch {
3725
- }
3726
- try {
3727
- await deletePassword(this.SERVICE_NAME, sentinelAccount);
3728
- } catch {
3729
- }
3730
- if (readBack !== sentinelValue) {
3731
- return {
3732
- ok: false,
3733
- reason: "write reported success but value cannot be read back",
3734
- hint: this.platformHint()
3735
- };
3736
- }
3737
- return { ok: true };
3738
- }
3739
- platformHint() {
3740
- if (process.platform === "linux") {
3741
- return 'On Linux/WSL: sudo apt install libsecret-tools gnome-keyring dbus-x11 && eval "$(gnome-keyring-daemon --start --components=secrets)"';
3742
- }
3743
- if (process.platform === "darwin") {
3744
- return "On macOS: unlock the login keychain (Keychain Access app) and retry";
3745
- }
3746
- return "On Windows: ensure Credential Manager is accessible from this user session";
3747
- }
3748
- warnPlaintext(envVar) {
3749
- console.warn(
3750
- `\u26A0\uFE0F Loaded ${envVar} from plaintext config (~/.sinch/profiles/<active>.json) \u2014 keychain unavailable.`
3751
- );
3752
- console.warn(` ${this.platformHint()}`);
3753
- }
3754
- /**
3755
- * Load custom secrets added via 'sinch functions secrets' command
3756
- */
3757
- async loadCustomSecrets(secretNames = []) {
3758
- const secrets = {};
3759
- try {
3760
- const functionName = this.getFunctionNameFromConfig();
3761
- if (!functionName) {
3762
- console.debug("[Secrets] Could not determine function name for custom secrets");
3763
- return secrets;
3764
- }
3765
- for (const secretName of secretNames) {
3766
- const value = await getPassword(this.SERVICE_NAME, `${functionName}-${secretName}`);
3767
- if (value) {
3768
- secrets[secretName] = value;
3769
- process.env[secretName] = value;
3770
- }
3771
- }
3772
- } catch (error) {
3773
- console.debug("[Secrets] Could not load custom secrets:", error.message);
3774
- }
3775
- return secrets;
3776
- }
3777
- /**
3778
- * Check if the native keychain is available.
3779
- * Always true — no native npm deps required. The underlying OS tool
3780
- * (secret-tool, security, CredManager) may still be absent, in which
3781
- * case getPassword() silently returns null per credential.
3782
- */
3783
- async isAvailable() {
3784
- return true;
3785
- }
3786
- };
3787
- var secretsLoader = new SecretsLoader();
55
+ defaultSecurityOptions,
56
+ extractCallerNumber,
57
+ extractFunctionName,
58
+ findFunctionPath,
59
+ formatCustomResponse,
60
+ formatDuration,
61
+ formatPhoneNumber,
62
+ formatSvamlResponse,
63
+ generateRequestId,
64
+ getChannel,
65
+ getContactId,
66
+ getConversationId,
67
+ getFaviconSvg,
68
+ getIdentity,
69
+ getLandingPageHtml,
70
+ getLocation,
71
+ getMedia,
72
+ getPostbackData,
73
+ getProtectionMode,
74
+ getSinchClients,
75
+ getText,
76
+ getTo,
77
+ getTunnelClient,
78
+ handleCustomEndpoint,
79
+ handleVoiceCallback,
80
+ installWebSocketHandlers,
81
+ isMediaMessage,
82
+ isNotificationEvent,
83
+ isPostback,
84
+ isTextMessage,
85
+ isVoiceCallback,
86
+ parseJson,
87
+ resetSinchClients,
88
+ secretsLoader,
89
+ setupJsonParsing,
90
+ setupRequestHandler,
91
+ shouldValidateWebhook,
92
+ textReply,
93
+ toCamelCase,
94
+ toLocalPhoneNumber,
95
+ transformKeys,
96
+ tryAutoConfigureAsync,
97
+ validateBasicAuth,
98
+ validateVoiceRequest
99
+ } from "./chunk-KKZKLUQ5.js";
3788
100
  export {
3789
101
  AceSvamlBuilder,
3790
102
  AgentProvider,
@@ -3841,7 +153,7 @@ export {
3841
153
  defaultSecurityOptions,
3842
154
  extractCallerNumber,
3843
155
  extractFunctionName,
3844
- findFunctionPath2 as findFunctionPath,
156
+ findFunctionPath,
3845
157
  formatCustomResponse,
3846
158
  formatDuration,
3847
159
  formatPhoneNumber,