@signalwire/sdk 2.0.4 → 3.5.0
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/CHANGELOG.md +785 -0
- package/LICENSE +21 -0
- package/README.md +163 -68
- package/dist/AGENTS.md +13 -0
- package/dist/AgentBase.d.ts +550 -163
- package/dist/AgentBase.js +1640 -514
- package/dist/AgentBase.js.map +1 -1
- package/dist/AgentServer.d.ts +21 -0
- package/dist/AgentServer.js +154 -47
- package/dist/AgentServer.js.map +1 -1
- package/dist/AuthHandler.d.ts +14 -2
- package/dist/AuthHandler.js +7 -2
- package/dist/AuthHandler.js.map +1 -1
- package/dist/ConfigLoader.d.ts +5 -13
- package/dist/ConfigLoader.js +15 -29
- package/dist/ConfigLoader.js.map +1 -1
- package/dist/ContextBuilder.d.ts +202 -9
- package/dist/ContextBuilder.js +219 -36
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/DataMap.d.ts +158 -45
- package/dist/DataMap.js +167 -52
- package/dist/DataMap.js.map +1 -1
- package/dist/FunctionResult.d.ts +277 -83
- package/dist/FunctionResult.js +444 -116
- package/dist/FunctionResult.js.map +1 -1
- package/dist/Logger.d.ts +30 -5
- package/dist/Logger.js +77 -19
- package/dist/Logger.js.map +1 -1
- package/dist/POM/PromptObjectModel.d.ts +163 -0
- package/dist/POM/PromptObjectModel.js +481 -0
- package/dist/POM/PromptObjectModel.js.map +1 -0
- package/dist/ParameterSchema.d.ts +306 -0
- package/dist/ParameterSchema.js +251 -0
- package/dist/ParameterSchema.js.map +1 -0
- package/dist/PlatformContracts.d.ts +21 -0
- package/dist/PlatformContracts.generated.d.ts +109 -0
- package/dist/PlatformContracts.generated.js +8 -0
- package/dist/PlatformContracts.generated.js.map +1 -0
- package/dist/PlatformContracts.js +2 -0
- package/dist/PlatformContracts.js.map +1 -0
- package/dist/PomBuilder.d.ts +28 -0
- package/dist/PomBuilder.js +81 -3
- package/dist/PomBuilder.js.map +1 -1
- package/dist/PostPrompt.d.ts +110 -0
- package/dist/PostPrompt.js +204 -0
- package/dist/PostPrompt.js.map +1 -0
- package/dist/PromptManager.d.ts +29 -1
- package/dist/PromptManager.js +37 -1
- package/dist/PromptManager.js.map +1 -1
- package/dist/PublicFetch.d.ts +132 -0
- package/dist/PublicFetch.js +311 -0
- package/dist/PublicFetch.js.map +1 -0
- package/dist/RobotsTxt.d.ts +41 -0
- package/dist/RobotsTxt.js +152 -0
- package/dist/RobotsTxt.js.map +1 -0
- package/dist/SWMLHandler.js.map +1 -1
- package/dist/SWMLService.d.ts +265 -66
- package/dist/SWMLService.js +652 -112
- package/dist/SWMLService.js.map +1 -1
- package/dist/SchemaUtils.d.ts +115 -2
- package/dist/SchemaUtils.js +444 -12
- package/dist/SchemaUtils.js.map +1 -1
- package/dist/SecurityUtils.d.ts +55 -8
- package/dist/SecurityUtils.js +162 -49
- package/dist/SecurityUtils.js.map +1 -1
- package/dist/ServerlessAdapter.d.ts +156 -7
- package/dist/ServerlessAdapter.js +399 -42
- package/dist/ServerlessAdapter.js.map +1 -1
- package/dist/SessionManager.d.ts +11 -2
- package/dist/SessionManager.js +50 -18
- package/dist/SessionManager.js.map +1 -1
- package/dist/SslConfig.d.ts +2 -1
- package/dist/SslConfig.js +4 -1
- package/dist/SslConfig.js.map +1 -1
- package/dist/SwaigActions.generated.d.ts +23 -0
- package/dist/SwaigActions.generated.js +8 -0
- package/dist/SwaigActions.generated.js.map +1 -0
- package/dist/SwaigContracts.d.ts +15 -0
- package/dist/SwaigContracts.generated.d.ts +264 -0
- package/dist/SwaigContracts.generated.js +12 -0
- package/dist/SwaigContracts.generated.js.map +1 -0
- package/dist/SwaigContracts.js +2 -0
- package/dist/SwaigContracts.js.map +1 -0
- package/dist/SwaigFunction.d.ts +110 -4
- package/dist/SwaigFunction.js +151 -19
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/SwmlBuilder.d.ts +68 -19
- package/dist/SwmlBuilder.js +74 -38
- package/dist/SwmlBuilder.js.map +1 -1
- package/dist/SwmlVerbMethods.generated.d.ts +41 -4
- package/dist/SwmlVerbMethods.generated.js +1 -1
- package/dist/TypeInference.d.ts +39 -3
- package/dist/TypeInference.js +256 -16
- package/dist/TypeInference.js.map +1 -1
- package/dist/WebService.d.ts +79 -11
- package/dist/WebService.js +320 -109
- package/dist/WebService.js.map +1 -1
- package/dist/WebhookMiddleware.d.ts +119 -0
- package/dist/WebhookMiddleware.js +271 -0
- package/dist/WebhookMiddleware.js.map +1 -0
- package/dist/WebhookValidator.d.ts +92 -0
- package/dist/WebhookValidator.js +409 -0
- package/dist/WebhookValidator.js.map +1 -0
- package/dist/agents/BedrockAgent.d.ts +162 -0
- package/dist/agents/BedrockAgent.js +323 -0
- package/dist/agents/BedrockAgent.js.map +1 -0
- package/dist/ai-chat/AIChatClient.d.ts +316 -0
- package/dist/ai-chat/AIChatClient.js +535 -0
- package/dist/ai-chat/AIChatClient.js.map +1 -0
- package/dist/ai-chat/ChatGateway.d.ts +408 -0
- package/dist/ai-chat/ChatGateway.js +747 -0
- package/dist/ai-chat/ChatGateway.js.map +1 -0
- package/dist/ai-chat/HandoffRouter.d.ts +282 -0
- package/dist/ai-chat/HandoffRouter.js +518 -0
- package/dist/ai-chat/HandoffRouter.js.map +1 -0
- package/dist/ai-chat/index.d.ts +12 -0
- package/dist/ai-chat/index.js +10 -0
- package/dist/ai-chat/index.js.map +1 -0
- package/dist/capabilities.d.ts +64 -0
- package/dist/capabilities.js +95 -0
- package/dist/capabilities.js.map +1 -0
- package/dist/cli/agent-loader.d.ts +32 -6
- package/dist/cli/agent-loader.js +95 -34
- package/dist/cli/agent-loader.js.map +1 -1
- package/dist/cli/datamap-exec.d.ts +175 -0
- package/dist/cli/datamap-exec.js +1284 -0
- package/dist/cli/datamap-exec.js.map +1 -0
- package/dist/cli/function-args.d.ts +40 -0
- package/dist/cli/function-args.js +146 -0
- package/dist/cli/function-args.js.map +1 -0
- package/dist/cli/simulation.d.ts +99 -0
- package/dist/cli/simulation.js +490 -0
- package/dist/cli/simulation.js.map +1 -0
- package/dist/cli/swaig-test.d.ts +12 -25
- package/dist/cli/swaig-test.js +935 -367
- package/dist/cli/swaig-test.js.map +1 -1
- package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
- package/dist/cli/tsdocs/agentsNote.js +92 -0
- package/dist/cli/tsdocs/agentsNote.js.map +1 -0
- package/dist/cli/tsdocs/api-index.json +1 -0
- package/dist/cli/tsdocs/api.d.ts +91 -0
- package/dist/cli/tsdocs/api.js +372 -0
- package/dist/cli/tsdocs/api.js.map +1 -0
- package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
- package/dist/cli/tsdocs/apiTypes.js +7 -0
- package/dist/cli/tsdocs/apiTypes.js.map +1 -0
- package/dist/cli/tsdocs/bin.d.ts +6 -0
- package/dist/cli/tsdocs/bin.js +23 -0
- package/dist/cli/tsdocs/bin.js.map +1 -0
- package/dist/cli/tsdocs/files.d.ts +108 -0
- package/dist/cli/tsdocs/files.js +287 -0
- package/dist/cli/tsdocs/files.js.map +1 -0
- package/dist/cli/tsdocs/index.d.ts +28 -0
- package/dist/cli/tsdocs/index.js +307 -0
- package/dist/cli/tsdocs/index.js.map +1 -0
- package/dist/cli/tsdocs/live.d.ts +41 -0
- package/dist/cli/tsdocs/live.js +202 -0
- package/dist/cli/tsdocs/live.js.map +1 -0
- package/dist/cli/tsdocs/locate.d.ts +51 -0
- package/dist/cli/tsdocs/locate.js +75 -0
- package/dist/cli/tsdocs/locate.js.map +1 -0
- package/dist/cli/tsdocs/render.d.ts +75 -0
- package/dist/cli/tsdocs/render.js +323 -0
- package/dist/cli/tsdocs/render.js.map +1 -0
- package/dist/cli/tsdocs/topics.d.ts +43 -0
- package/dist/cli/tsdocs/topics.js +916 -0
- package/dist/cli/tsdocs/topics.js.map +1 -0
- package/dist/index.d.ts +102 -39
- package/dist/index.js +107 -30
- package/dist/index.js.map +1 -1
- package/dist/livewire/index.d.ts +229 -155
- package/dist/livewire/index.js +298 -195
- package/dist/livewire/index.js.map +1 -1
- package/dist/llms.txt +65 -0
- package/dist/prefabs/CallSessionStore.d.ts +52 -0
- package/dist/prefabs/CallSessionStore.js +72 -0
- package/dist/prefabs/CallSessionStore.js.map +1 -0
- package/dist/prefabs/ConciergeAgent.d.ts +13 -1
- package/dist/prefabs/ConciergeAgent.js +36 -31
- package/dist/prefabs/ConciergeAgent.js.map +1 -1
- package/dist/prefabs/FAQBotAgent.d.ts +9 -1
- package/dist/prefabs/FAQBotAgent.js +113 -47
- package/dist/prefabs/FAQBotAgent.js.map +1 -1
- package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
- package/dist/prefabs/InfoGathererAgent.js +67 -58
- package/dist/prefabs/InfoGathererAgent.js.map +1 -1
- package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
- package/dist/prefabs/ReceptionistAgent.js +39 -31
- package/dist/prefabs/ReceptionistAgent.js.map +1 -1
- package/dist/prefabs/SurveyAgent.d.ts +22 -4
- package/dist/prefabs/SurveyAgent.js +84 -68
- package/dist/prefabs/SurveyAgent.js.map +1 -1
- package/dist/relay/Action.d.ts +44 -21
- package/dist/relay/Action.js +75 -17
- package/dist/relay/Action.js.map +1 -1
- package/dist/relay/Call.d.ts +312 -47
- package/dist/relay/Call.js +369 -18
- package/dist/relay/Call.js.map +1 -1
- package/dist/relay/Deferred.js.map +1 -1
- package/dist/relay/Message.d.ts +26 -5
- package/dist/relay/Message.js +36 -6
- package/dist/relay/Message.js.map +1 -1
- package/dist/relay/RelayClient.d.ts +79 -14
- package/dist/relay/RelayClient.js +268 -61
- package/dist/relay/RelayClient.js.map +1 -1
- package/dist/relay/RelayError.d.ts +14 -0
- package/dist/relay/RelayError.js +15 -0
- package/dist/relay/RelayError.js.map +1 -1
- package/dist/relay/RelayEvent.d.ts +96 -65
- package/dist/relay/RelayEvent.js +85 -56
- package/dist/relay/RelayEvent.js.map +1 -1
- package/dist/relay/closedSets.d.ts +111 -0
- package/dist/relay/closedSets.js +83 -0
- package/dist/relay/closedSets.js.map +1 -0
- package/dist/relay/index.d.ts +3 -1
- package/dist/relay/index.js +1 -0
- package/dist/relay/index.js.map +1 -1
- package/dist/relay/normalize.js.map +1 -1
- package/dist/relay/protocol.types.generated.d.ts +1195 -0
- package/dist/relay/protocol.types.generated.js +8 -0
- package/dist/relay/protocol.types.generated.js.map +1 -0
- package/dist/relay/types.d.ts +81 -39
- package/dist/rest/HttpClient.d.ts +36 -8
- package/dist/rest/HttpClient.js +233 -40
- package/dist/rest/HttpClient.js.map +1 -1
- package/dist/rest/RequestOptions.d.ts +110 -0
- package/dist/rest/RequestOptions.js +113 -0
- package/dist/rest/RequestOptions.js.map +1 -0
- package/dist/rest/RestError.d.ts +52 -6
- package/dist/rest/RestError.js +89 -5
- package/dist/rest/RestError.js.map +1 -1
- package/dist/rest/base/CrudResource.d.ts +16 -26
- package/dist/rest/base/CrudResource.js +19 -33
- package/dist/rest/base/CrudResource.js.map +1 -1
- package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
- package/dist/rest/base/CrudWithAddresses.js +2 -2
- package/dist/rest/base/CrudWithAddresses.js.map +1 -1
- package/dist/rest/base/FabricResource.d.ts +15 -0
- package/dist/rest/base/FabricResource.js +16 -0
- package/dist/rest/base/FabricResource.js.map +1 -0
- package/dist/rest/base/ReadResource.d.ts +62 -0
- package/dist/rest/base/ReadResource.js +69 -0
- package/dist/rest/base/ReadResource.js.map +1 -0
- package/dist/rest/callHandler.d.ts +63 -0
- package/dist/rest/callHandler.js +62 -0
- package/dist/rest/callHandler.js.map +1 -0
- package/dist/rest/index.d.ts +19 -76
- package/dist/rest/index.js +49 -120
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
- package/dist/rest/namespaces/_client_tree_generated.js +171 -0
- package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
- package/dist/rest/namespaces/addresses.d.ts +3 -42
- package/dist/rest/namespaces/addresses.js +3 -50
- package/dist/rest/namespaces/addresses.js.map +1 -1
- package/dist/rest/namespaces/calling.d.ts +6 -378
- package/dist/rest/namespaces/calling.js +6 -473
- package/dist/rest/namespaces/calling.js.map +1 -1
- package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
- package/dist/rest/namespaces/calling.resources.generated.js +477 -0
- package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
- package/dist/rest/namespaces/calling.types.generated.js +8 -0
- package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
- package/dist/rest/namespaces/chat.d.ts +4 -18
- package/dist/rest/namespaces/chat.js +4 -21
- package/dist/rest/namespaces/chat.js.map +1 -1
- package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/chat.resources.generated.js +29 -0
- package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
- package/dist/rest/namespaces/chat.types.generated.js +8 -0
- package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
- package/dist/rest/namespaces/datasphere.d.ts +6 -62
- package/dist/rest/namespaces/datasphere.js +6 -72
- package/dist/rest/namespaces/datasphere.js.map +1 -1
- package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
- package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
- package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
- package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
- package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
- package/dist/rest/namespaces/fabric.d.ts +11 -273
- package/dist/rest/namespaces/fabric.js +14 -363
- package/dist/rest/namespaces/fabric.js.map +1 -1
- package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
- package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
- package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
- package/dist/rest/namespaces/fabric.types.generated.js +8 -0
- package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
- package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
- package/dist/rest/namespaces/fax.resources.generated.js +14 -0
- package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
- package/dist/rest/namespaces/fax.types.generated.js +8 -0
- package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
- package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
- package/dist/rest/namespaces/imported-numbers.js +3 -21
- package/dist/rest/namespaces/imported-numbers.js.map +1 -1
- package/dist/rest/namespaces/logs.d.ts +10 -101
- package/dist/rest/namespaces/logs.js +10 -128
- package/dist/rest/namespaces/logs.js.map +1 -1
- package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
- package/dist/rest/namespaces/logs.resources.generated.js +17 -0
- package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
- package/dist/rest/namespaces/logs.types.generated.js +8 -0
- package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
- package/dist/rest/namespaces/lookup.d.ts +3 -25
- package/dist/rest/namespaces/lookup.js +3 -27
- package/dist/rest/namespaces/lookup.js.map +1 -1
- package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
- package/dist/rest/namespaces/message.resources.generated.js +14 -0
- package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
- package/dist/rest/namespaces/message.types.generated.js +8 -0
- package/dist/rest/namespaces/message.types.generated.js.map +1 -0
- package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
- package/dist/rest/namespaces/messages.resources.generated.js +44 -0
- package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
- package/dist/rest/namespaces/messages.types.generated.js +8 -0
- package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
- package/dist/rest/namespaces/mfa.d.ts +3 -42
- package/dist/rest/namespaces/mfa.js +3 -49
- package/dist/rest/namespaces/mfa.js.map +1 -1
- package/dist/rest/namespaces/number-groups.d.ts +3 -45
- package/dist/rest/namespaces/number-groups.js +3 -53
- package/dist/rest/namespaces/number-groups.js.map +1 -1
- package/dist/rest/namespaces/phone-numbers.d.ts +9 -57
- package/dist/rest/namespaces/phone-numbers.js +9 -63
- package/dist/rest/namespaces/phone-numbers.js.map +1 -1
- package/dist/rest/namespaces/project.d.ts +6 -42
- package/dist/rest/namespaces/project.js +6 -51
- package/dist/rest/namespaces/project.js.map +1 -1
- package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
- package/dist/rest/namespaces/project.resources.generated.js +44 -0
- package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
- package/dist/rest/namespaces/project.types.generated.js +8 -0
- package/dist/rest/namespaces/project.types.generated.js.map +1 -0
- package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/projects.resources.generated.js +25 -0
- package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
- package/dist/rest/namespaces/projects.types.generated.js +8 -0
- package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
- package/dist/rest/namespaces/pubsub.d.ts +4 -18
- package/dist/rest/namespaces/pubsub.js +4 -21
- package/dist/rest/namespaces/pubsub.js.map +1 -1
- package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
- package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
- package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
- package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
- package/dist/rest/namespaces/queues.d.ts +3 -38
- package/dist/rest/namespaces/queues.js +3 -44
- package/dist/rest/namespaces/queues.js.map +1 -1
- package/dist/rest/namespaces/recordings.d.ts +3 -34
- package/dist/rest/namespaces/recordings.js +3 -40
- package/dist/rest/namespaces/recordings.js.map +1 -1
- package/dist/rest/namespaces/registry.d.ts +6 -137
- package/dist/rest/namespaces/registry.js +6 -173
- package/dist/rest/namespaces/registry.js.map +1 -1
- package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
- package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
- package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
- package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
- package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
- package/dist/rest/namespaces/short-codes.d.ts +3 -35
- package/dist/rest/namespaces/short-codes.js +3 -41
- package/dist/rest/namespaces/short-codes.js.map +1 -1
- package/dist/rest/namespaces/sip-profile.d.ts +3 -24
- package/dist/rest/namespaces/sip-profile.js +3 -29
- package/dist/rest/namespaces/sip-profile.js.map +1 -1
- package/dist/rest/namespaces/verified-callers.d.ts +3 -29
- package/dist/rest/namespaces/verified-callers.js +3 -34
- package/dist/rest/namespaces/verified-callers.js.map +1 -1
- package/dist/rest/namespaces/video.d.ts +10 -227
- package/dist/rest/namespaces/video.js +10 -288
- package/dist/rest/namespaces/video.js.map +1 -1
- package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
- package/dist/rest/namespaces/video.resources.generated.js +171 -0
- package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
- package/dist/rest/namespaces/video.types.generated.js +8 -0
- package/dist/rest/namespaces/video.types.generated.js.map +1 -0
- package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
- package/dist/rest/namespaces/voice.resources.generated.js +17 -0
- package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
- package/dist/rest/namespaces/voice.types.generated.js +8 -0
- package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
- package/dist/rest/pagination.d.ts +5 -1
- package/dist/rest/pagination.js +40 -20
- package/dist/rest/pagination.js.map +1 -1
- package/dist/rest/types.d.ts +21 -3
- package/dist/schema.json +299 -98
- package/dist/skills/SkillBase.d.ts +97 -20
- package/dist/skills/SkillBase.js +100 -17
- package/dist/skills/SkillBase.js.map +1 -1
- package/dist/skills/SkillManager.d.ts +66 -13
- package/dist/skills/SkillManager.js +101 -20
- package/dist/skills/SkillManager.js.map +1 -1
- package/dist/skills/SkillName.d.ts +44 -0
- package/dist/skills/SkillName.js +2 -0
- package/dist/skills/SkillName.js.map +1 -0
- package/dist/skills/SkillRegistry.d.ts +47 -7
- package/dist/skills/SkillRegistry.js +85 -13
- package/dist/skills/SkillRegistry.js.map +1 -1
- package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
- package/dist/skills/builtin/api_ninjas_trivia.js +24 -8
- package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
- package/dist/skills/builtin/ask_claude.d.ts +14 -4
- package/dist/skills/builtin/ask_claude.js +36 -14
- package/dist/skills/builtin/ask_claude.js.map +1 -1
- package/dist/skills/builtin/claude_skills.d.ts +3 -1
- package/dist/skills/builtin/claude_skills.js +19 -15
- package/dist/skills/builtin/claude_skills.js.map +1 -1
- package/dist/skills/builtin/custom_skills.d.ts +10 -3
- package/dist/skills/builtin/custom_skills.js +26 -9
- package/dist/skills/builtin/custom_skills.js.map +1 -1
- package/dist/skills/builtin/datasphere.d.ts +5 -3
- package/dist/skills/builtin/datasphere.js +34 -25
- package/dist/skills/builtin/datasphere.js.map +1 -1
- package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
- package/dist/skills/builtin/datasphere_serverless.js +17 -6
- package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
- package/dist/skills/builtin/datetime.d.ts +3 -1
- package/dist/skills/builtin/datetime.js +11 -7
- package/dist/skills/builtin/datetime.js.map +1 -1
- package/dist/skills/builtin/google_maps.d.ts +29 -14
- package/dist/skills/builtin/google_maps.js +89 -269
- package/dist/skills/builtin/google_maps.js.map +1 -1
- package/dist/skills/builtin/index.d.ts +8 -6
- package/dist/skills/builtin/index.js +8 -6
- package/dist/skills/builtin/index.js.map +1 -1
- package/dist/skills/builtin/info_gatherer.d.ts +4 -2
- package/dist/skills/builtin/info_gatherer.js +20 -12
- package/dist/skills/builtin/info_gatherer.js.map +1 -1
- package/dist/skills/builtin/joke.d.ts +16 -6
- package/dist/skills/builtin/joke.js +54 -37
- package/dist/skills/builtin/joke.js.map +1 -1
- package/dist/skills/builtin/math.d.ts +3 -1
- package/dist/skills/builtin/math.js +14 -9
- package/dist/skills/builtin/math.js.map +1 -1
- package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
- package/dist/skills/builtin/mcp_gateway.js +77 -46
- package/dist/skills/builtin/mcp_gateway.js.map +1 -1
- package/dist/skills/builtin/native_vector_search.d.ts +19 -5
- package/dist/skills/builtin/native_vector_search.js +179 -61
- package/dist/skills/builtin/native_vector_search.js.map +1 -1
- package/dist/skills/builtin/play_background_file.d.ts +21 -15
- package/dist/skills/builtin/play_background_file.js +43 -122
- package/dist/skills/builtin/play_background_file.js.map +1 -1
- package/dist/skills/builtin/spider.d.ts +46 -1
- package/dist/skills/builtin/spider.js +317 -101
- package/dist/skills/builtin/spider.js.map +1 -1
- package/dist/skills/builtin/swml_transfer.d.ts +14 -3
- package/dist/skills/builtin/swml_transfer.js +45 -24
- package/dist/skills/builtin/swml_transfer.js.map +1 -1
- package/dist/skills/builtin/weather_api.d.ts +24 -13
- package/dist/skills/builtin/weather_api.js +57 -31
- package/dist/skills/builtin/weather_api.js.map +1 -1
- package/dist/skills/builtin/web_search.d.ts +48 -10
- package/dist/skills/builtin/web_search.js +301 -84
- package/dist/skills/builtin/web_search.js.map +1 -1
- package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
- package/dist/skills/builtin/wikipedia_search.js +32 -14
- package/dist/skills/builtin/wikipedia_search.js.map +1 -1
- package/dist/skills/index.d.ts +3 -2
- package/dist/skills/index.js +1 -1
- package/dist/skills/index.js.map +1 -1
- package/dist/swml_verbs_generated.d.ts +2824 -0
- package/dist/swml_verbs_generated.js +12 -0
- package/dist/swml_verbs_generated.js.map +1 -0
- package/dist/types.d.ts +65 -6
- package/dist/web.d.ts +27 -0
- package/dist/web.js +20 -0
- package/dist/web.js.map +1 -0
- package/docs/agent-guide.md +1034 -0
- package/docs/ai_chat.md +560 -0
- package/docs/api-reference.md +3534 -0
- package/docs/architecture.md +846 -0
- package/docs/bedrock_agent.md +411 -0
- package/docs/cli-guide.md +403 -0
- package/docs/cloud_functions_guide.md +399 -0
- package/docs/configuration.md +548 -0
- package/docs/contexts-guide.md +884 -0
- package/docs/datamap-guide.md +1160 -0
- package/docs/developer_pain_points.md +548 -0
- package/docs/llm_parameters.md +298 -0
- package/docs/mcp_gateway_reference.md +354 -0
- package/docs/mcp_integration.md +162 -0
- package/docs/pgi_agent_guide.md +1820 -0
- package/docs/prefabs-guide.md +815 -0
- package/docs/programmatically_governed_inference.md +301 -0
- package/docs/sdk_features.md +501 -0
- package/docs/security.md +559 -0
- package/docs/serverless-guide.md +520 -0
- package/docs/skills-guide.md +1223 -0
- package/docs/skills-system.md +405 -0
- package/docs/skills_parameter_schema.md +417 -0
- package/docs/swaig-reference.md +1938 -0
- package/docs/swml_service_guide.md +573 -0
- package/docs/third_party_skills.md +410 -0
- package/docs/web_service.md +666 -0
- package/examples/README.md +202 -0
- package/examples/advanced-datamap.ts +108 -0
- package/examples/advanced-dynamic-config.ts +70 -0
- package/examples/auto-vivified.ts +95 -0
- package/examples/call-flow.ts +65 -0
- package/examples/comprehensive-dynamic.ts +125 -0
- package/examples/contexts-steps.ts +65 -0
- package/examples/custom-path.ts +45 -0
- package/examples/datamap-tools.ts +51 -0
- package/examples/datasphere-multi-instance.ts +66 -0
- package/examples/datasphere-serverless-env.ts +87 -0
- package/examples/datasphere-webhook-env.ts +65 -0
- package/examples/datasphere.ts +56 -0
- package/examples/declarative.ts +100 -0
- package/examples/dynamic-config.ts +54 -0
- package/examples/dynamic-info-gatherer.ts +69 -0
- package/examples/dynamic-swml-service.ts +67 -0
- package/examples/gather-info.ts +95 -0
- package/examples/gather-per-question-functions-demo.ts +139 -0
- package/examples/joke-agent.ts +34 -0
- package/examples/kubernetes-agent.ts +45 -0
- package/examples/llm-params.ts +75 -0
- package/examples/mcp-agent.ts +89 -0
- package/examples/mcp-gateway.ts +81 -0
- package/examples/multi-agent.ts +80 -0
- package/examples/multi-endpoint.ts +79 -0
- package/examples/pgi/case-domain.ts +114 -0
- package/examples/pgi/serve.ts +16 -0
- package/examples/pgi/support-agent.ts +265 -0
- package/examples/pom-prompt.ts +70 -0
- package/examples/prefab-concierge.ts +42 -0
- package/examples/prefab-faq.ts +58 -0
- package/examples/prefab-info-gatherer.ts +33 -0
- package/examples/prefab-receptionist.ts +36 -0
- package/examples/prefab-survey.ts +69 -0
- package/examples/quickstart-agent.ts +29 -0
- package/examples/quickstart-relay.ts +25 -0
- package/examples/quickstart-rest.ts +25 -0
- package/examples/record-call.ts +65 -0
- package/examples/relay-demo.ts +33 -0
- package/examples/room-and-sip.ts +93 -0
- package/examples/serverless-lambda.ts +43 -0
- package/examples/session-state.ts +83 -0
- package/examples/simple-agent.ts +36 -0
- package/examples/simple-static.ts +29 -0
- package/examples/skills-demo.ts +41 -0
- package/examples/step-function-inheritance-demo.ts +124 -0
- package/examples/swaig-features.ts +193 -0
- package/examples/swml-service-routing.ts +66 -0
- package/examples/swml-service.ts +38 -0
- package/examples/swmlservice_ai_sidecar.ts +104 -0
- package/examples/swmlservice_swaig_standalone.ts +79 -0
- package/examples/tap.ts +67 -0
- package/examples/typed-tools.ts +68 -0
- package/examples/verb-methods.ts +45 -0
- package/examples/web-search-multi-instance.ts +75 -0
- package/examples/web-search.ts +38 -0
- package/examples/wikipedia.ts +36 -0
- package/livewire/README.md +164 -0
- package/livewire/docs/migration-guide.md +251 -0
- package/livewire/examples/livewire-basic-agent.ts +74 -0
- package/livewire/examples/livewire-handoff.ts +196 -0
- package/livewire/examples/livewire-multi-tool.ts +121 -0
- package/package.json +88 -13
- package/relay/README.md +101 -0
- package/relay/docs/call-methods.md +622 -0
- package/relay/docs/client-reference.md +281 -0
- package/relay/docs/events.md +193 -0
- package/relay/docs/getting-started.md +221 -0
- package/relay/docs/guide.md +386 -0
- package/relay/docs/messaging.md +246 -0
- package/relay/examples/relay-inbound.ts +66 -0
- package/relay/examples/relay-messaging.ts +74 -0
- package/relay/examples/relay-outbound.ts +76 -0
- package/rest/README.md +141 -0
- package/rest/docs/calling.md +313 -0
- package/rest/docs/client-reference.md +149 -0
- package/rest/docs/fabric.md +192 -0
- package/rest/docs/getting-started.md +138 -0
- package/rest/docs/guide.md +421 -0
- package/rest/docs/namespaces.md +367 -0
- package/rest/docs/phone-binding.md +116 -0
- package/rest/examples/rest-10dlc-registration.ts +177 -0
- package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
- package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
- package/rest/examples/rest-calling-play-and-record.ts +98 -0
- package/rest/examples/rest-client.ts +59 -0
- package/rest/examples/rest-datasphere-search.ts +81 -0
- package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
- package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
- package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
- package/rest/examples/rest-manage-resources.ts +64 -0
- package/rest/examples/rest-phone-number-management.ts +200 -0
- package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
- package/rest/examples/rest-video-rooms.ts +186 -0
- package/tutorial/fred/fred.ts +218 -0
- package/tutorial/fred/tutorial/01-introduction.md +141 -0
- package/tutorial/fred/tutorial/02-setup.md +304 -0
- package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
- package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
- package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
- package/tutorial/fred/tutorial/06-running-testing.md +642 -0
- package/tutorial/fred/tutorial/README.md +56 -0
- package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
- package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
- package/tutorial/full-guardrails-agent/handlers.ts +436 -0
- package/tutorial/full-guardrails-agent/penny.ts +305 -0
- package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
- package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
- package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
- package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
- package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
- package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
- package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
- package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
- package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
- package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
- package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
- package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
- package/tutorial/full-guardrails-agent/workflow.ts +219 -0
- package/tutorial/multi_agents/README.md +175 -0
- package/tutorial/multi_agents/advanced_agent.ts +395 -0
- package/tutorial/multi_agents/extending_agents.ts +641 -0
- package/tutorial/multi_agents/knowledge.ts +59 -0
- package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
- package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
- package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
- package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
- package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
- package/tutorial/multi_agents/pc_builder.ts +529 -0
- package/tutorial/multi_agents/sales_agent.ts +88 -0
- package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
- package/tutorial/multi_agents/sales_knowledge.md +139 -0
- package/tutorial/multi_agents/support_knowledge.md +256 -0
- package/dist/cli/mock-data.d.ts +0 -37
- package/dist/cli/mock-data.js +0 -80
- package/dist/cli/mock-data.js.map +0 -1
- package/dist/generateVerbTypes.d.ts +0 -11
- package/dist/generateVerbTypes.js +0 -265
- package/dist/generateVerbTypes.js.map +0 -1
- package/dist/rest/namespaces/compat.d.ts +0 -585
- package/dist/rest/namespaces/compat.js +0 -735
- package/dist/rest/namespaces/compat.js.map +0 -1
|
@@ -0,0 +1,1284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DataMap execution for swaig-test: runs a DataMap function locally the way
|
|
3
|
+
* the platform runs it (mod_openai's actions.c and swaig.c), so
|
|
4
|
+
* `swaig-test --exec` can test one without a call.
|
|
5
|
+
*
|
|
6
|
+
* The pipeline, as the platform processes a data_map:
|
|
7
|
+
*
|
|
8
|
+
* 1. The top-level `expressions`, against the call data. The first one that
|
|
9
|
+
* produces an output ends the function.
|
|
10
|
+
* 2. The first webhook it requests. A webhook in a list is skipped, without a
|
|
11
|
+
* request, when none of its `require_args` is among the arguments, when it
|
|
12
|
+
* has neither `output` nor `expressions`, or when it has no `url`. Once one
|
|
13
|
+
* is requested, no later webhook runs. It fails when the response has
|
|
14
|
+
* `parse_error` or `protocol_error` (a body that is empty or isn't JSON, a
|
|
15
|
+
* request that doesn't complete) or one of its `error_keys`, whatever the
|
|
16
|
+
* key's value. A status outside 200-299 doesn't fail it by itself; the
|
|
17
|
+
* status is then in the response as `http_code`. If it succeeds, its
|
|
18
|
+
* `foreach`, then its `expressions`, then its `output` build the result
|
|
19
|
+
* from the response. A matched webhook expression's result is expanded a
|
|
20
|
+
* second time, against the same data.
|
|
21
|
+
* 3. The data_map's own `output`, when nothing above produced a result.
|
|
22
|
+
* 4. Otherwise the platform's generic error,
|
|
23
|
+
* `{ response: "There was an error processing this request." }`.
|
|
24
|
+
*
|
|
25
|
+
* `expressions` can be one expression object instead of a list. `webhooks`
|
|
26
|
+
* can be one webhook object, which the platform runs without checking its
|
|
27
|
+
* `require_args` or its errors, so its `foreach`, `expressions` and `output`
|
|
28
|
+
* read an error response (`${parse_error}`, `${raw_response}`,
|
|
29
|
+
* `${http_code}`).
|
|
30
|
+
*
|
|
31
|
+
* The request is a POST when the webhook has `params` (its JSON body, with
|
|
32
|
+
* the arguments merged in by `input_args_as_params`) or its method is POST,
|
|
33
|
+
* and a GET otherwise. Header values are sent as written. Credentials in the
|
|
34
|
+
* url become basic authentication. Redirects are followed as the platform's
|
|
35
|
+
* curl follows them, and every request, redirects included, refuses private
|
|
36
|
+
* and internal addresses.
|
|
37
|
+
*
|
|
38
|
+
* Template data, per stage:
|
|
39
|
+
*
|
|
40
|
+
* - The call data: the `callData` option (the platform's call details, such
|
|
41
|
+
* as `global_data` or `caller_id_num`) at the root, `meta_data` (the
|
|
42
|
+
* function's `meta_data` merged key by key over `global_data`, as the
|
|
43
|
+
* platform merges them when it loads the function), the `prompt_vars`
|
|
44
|
+
* merged into the root, `args` (the arguments) and an empty `input`. The
|
|
45
|
+
* top-level expressions, a webhook's `url` and `params`, and the data_map's
|
|
46
|
+
* own `output` read it, so they write an argument as `${args.city}`. The
|
|
47
|
+
* data_map's own `output` also has `prompt_vars`.
|
|
48
|
+
* - A webhook's `foreach`, `expressions` and `output` read its response: a
|
|
49
|
+
* JSON object's fields at the root (`${current.temp_f}`), a JSON array under
|
|
50
|
+
* `array`, with `prompt_vars`, `global_data` and `input` (a copy of the call
|
|
51
|
+
* data) added. The arguments are `${input.args.city}` there.
|
|
52
|
+
*
|
|
53
|
+
* Templates: `${path}` and `%{path}` read a path of dotted names, matched
|
|
54
|
+
* without regard to ASCII case, each with at most one `[n]` index (negative
|
|
55
|
+
* from the end). The helpers `lc:`, `enc:` and `fmt_ph:` come first, in any
|
|
56
|
+
* case, and apply in a fixed order: `fmt_ph`, then `lc`, then `enc`. Any other
|
|
57
|
+
* name before a colon is part of the path. A template nested in the path
|
|
58
|
+
* expands first, one level deep. A value that isn't a string is inserted as
|
|
59
|
+
* cJSON prints it (72.5 as `72.500000`). A path that doesn't resolve expands
|
|
60
|
+
* to an empty string, and the simulator says so on stderr. An output is
|
|
61
|
+
* expanded as JSON text and parsed, as on the platform, so a template that
|
|
62
|
+
* inserts an object into a string breaks it.
|
|
63
|
+
*
|
|
64
|
+
* Where the simulator can't do what the platform does:
|
|
65
|
+
*
|
|
66
|
+
* - Without the optional libphonenumber-js package, `fmt_ph` formats only a
|
|
67
|
+
* North American number, as `(NPA) NXX-XXXX`, and leaves any other value as
|
|
68
|
+
* it is, saying so on stderr. The platform formats any valid number, and
|
|
69
|
+
* writes `INVALID NUMBER` for one that isn't; with libphonenumber-js
|
|
70
|
+
* installed, so does the simulator. Either way, it reads a vanity number's
|
|
71
|
+
* letters as keypad digits, as the platform's libphonenumber does.
|
|
72
|
+
* - `@{...}` functions are left as they are.
|
|
73
|
+
* - An expression's `expr` isn't evaluated: only its `pattern` is tried.
|
|
74
|
+
* - Patterns are JavaScript regular expressions, where the platform uses PCRE.
|
|
75
|
+
* - The platform follows no redirect for a request it signs; the simulator
|
|
76
|
+
* doesn't sign requests.
|
|
77
|
+
*
|
|
78
|
+
* Mirrors signalwire-python's `signalwire.cli.execution.datamap_exec`.
|
|
79
|
+
*/
|
|
80
|
+
import { createRequire } from 'node:module';
|
|
81
|
+
import { join } from 'node:path';
|
|
82
|
+
import { pathToFileURL } from 'node:url';
|
|
83
|
+
import { _publicFetch } from '../PublicFetch.js';
|
|
84
|
+
/** The result the platform returns when nothing produced an output. */
|
|
85
|
+
export const PLATFORM_ERROR_RESPONSE = 'There was an error processing this request.';
|
|
86
|
+
/** The platform's whole-request timeout for a webhook, in seconds (CURLOPT_TIMEOUT). */
|
|
87
|
+
const HTTP_REQUEST_TIMEOUT = 120;
|
|
88
|
+
/** The characters FreeSWITCH's `SWITCH_URL_UNSAFE` lists, which `enc:` encodes. */
|
|
89
|
+
const URL_UNSAFE = '\r\n #%&+:;<=>?@[\\]^`{|}"';
|
|
90
|
+
const HEX = '0123456789ABCDEF';
|
|
91
|
+
/** Template paths longer than this (in bytes), or deeper, don't resolve. */
|
|
92
|
+
const MAX_PATH_LENGTH = 1024;
|
|
93
|
+
const MAX_PATH_DEPTH = 128;
|
|
94
|
+
const INT_MAX = 2 ** 31 - 1;
|
|
95
|
+
/** The stages that read a webhook's response rather than the call data. */
|
|
96
|
+
const RESPONSE_STAGES = new Set(['webhook foreach', 'webhook expressions', 'webhook output']);
|
|
97
|
+
/** Marks a value that isn't there: a path that doesn't resolve, JSON that doesn't parse. */
|
|
98
|
+
const MISSING = Symbol('missing');
|
|
99
|
+
function isPlainObject(value) {
|
|
100
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
101
|
+
}
|
|
102
|
+
/** Lowercase ASCII letters only, as C's tolower() does. */
|
|
103
|
+
function asciiLower(text) {
|
|
104
|
+
return text.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
105
|
+
}
|
|
106
|
+
/** Set a member as data, so a key such as `__proto__` is an ordinary key. */
|
|
107
|
+
function setItem(obj, key, value) {
|
|
108
|
+
Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true });
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A named member of an object, matched without regard to ASCII case, as
|
|
112
|
+
* cJSON_GetObjectItem() finds it: the first match wins, and arrays and
|
|
113
|
+
* scalars have no named members.
|
|
114
|
+
*/
|
|
115
|
+
function objectItem(container, name) {
|
|
116
|
+
if (!isPlainObject(container))
|
|
117
|
+
return MISSING;
|
|
118
|
+
const wanted = asciiLower(name);
|
|
119
|
+
for (const key of Object.keys(container)) {
|
|
120
|
+
if (asciiLower(key) === wanted)
|
|
121
|
+
return container[key];
|
|
122
|
+
}
|
|
123
|
+
return MISSING;
|
|
124
|
+
}
|
|
125
|
+
function hasItem(container, name) {
|
|
126
|
+
return objectItem(container, name) !== MISSING;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Add a member as cJSON_AddItemToObject() does: cJSON appends a second member
|
|
130
|
+
* with the same name, and lookups find the first, so an existing member keeps
|
|
131
|
+
* its value.
|
|
132
|
+
*/
|
|
133
|
+
function addItem(container, name, value) {
|
|
134
|
+
if (!hasItem(container, name))
|
|
135
|
+
setItem(container, name, value);
|
|
136
|
+
}
|
|
137
|
+
/** Delete the first member matching `name` without regard to ASCII case. */
|
|
138
|
+
function deleteItem(container, name) {
|
|
139
|
+
const wanted = asciiLower(name);
|
|
140
|
+
for (const key of Object.keys(container)) {
|
|
141
|
+
if (asciiLower(key) === wanted) {
|
|
142
|
+
delete container[key];
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** Replace a member, as cJSON_Merge() with replace does. */
|
|
148
|
+
function replaceItem(container, name, value) {
|
|
149
|
+
deleteItem(container, name);
|
|
150
|
+
setItem(container, name, value);
|
|
151
|
+
}
|
|
152
|
+
/** A member's value if it is a string, as cJSON_GetObjectCstr() returns it. */
|
|
153
|
+
function stringItem(container, name) {
|
|
154
|
+
const value = objectItem(container, name);
|
|
155
|
+
return typeof value === 'string' ? value : null;
|
|
156
|
+
}
|
|
157
|
+
/** C's atoi(): the leading integer, or 0. */
|
|
158
|
+
function atoi(text) {
|
|
159
|
+
const match = /^[ \t\n\v\f\r]*([+-]?\d+)/.exec(text);
|
|
160
|
+
return match ? Number.parseInt(match[1], 10) : 0;
|
|
161
|
+
}
|
|
162
|
+
/** mod_openai's cJSON_FSTrue(): JSON true, or a string FreeSWITCH's switch_true() accepts. */
|
|
163
|
+
function isTrue(value) {
|
|
164
|
+
if (value === true)
|
|
165
|
+
return true;
|
|
166
|
+
if (typeof value !== 'string')
|
|
167
|
+
return false;
|
|
168
|
+
if (['yes', 'on', 'true', 't', 'enabled', 'active', 'allow'].includes(value.toLowerCase())) {
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
return /^[+-]?\d+(\.\d+)?$/.test(value.trim()) && atoi(value) !== 0;
|
|
172
|
+
}
|
|
173
|
+
const CJSON_ESCAPES = {
|
|
174
|
+
'"': '\\"',
|
|
175
|
+
'\\': '\\\\',
|
|
176
|
+
'\b': '\\b',
|
|
177
|
+
'\f': '\\f',
|
|
178
|
+
'\n': '\\n',
|
|
179
|
+
'\r': '\\r',
|
|
180
|
+
'\t': '\\t',
|
|
181
|
+
};
|
|
182
|
+
/** A string as cJSON prints it. */
|
|
183
|
+
function cjsonString(text) {
|
|
184
|
+
let out = '"';
|
|
185
|
+
for (const ch of text) {
|
|
186
|
+
const code = ch.charCodeAt(0);
|
|
187
|
+
if (CJSON_ESCAPES[ch])
|
|
188
|
+
out += CJSON_ESCAPES[ch];
|
|
189
|
+
else if (code < 32)
|
|
190
|
+
out += `\\u${code.toString(16).padStart(4, '0')}`;
|
|
191
|
+
else
|
|
192
|
+
out += ch;
|
|
193
|
+
}
|
|
194
|
+
return out + '"';
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* A value as FreeSWITCH's cJSON_Print() formats it: a whole number without a
|
|
198
|
+
* decimal point, any other number with six decimal places (72.5 is
|
|
199
|
+
* `72.500000`), and an object over several lines, one tab per level.
|
|
200
|
+
*/
|
|
201
|
+
function cjsonPrint(value, depth = 0) {
|
|
202
|
+
if (value === null || value === undefined)
|
|
203
|
+
return 'null';
|
|
204
|
+
if (value === true)
|
|
205
|
+
return 'true';
|
|
206
|
+
if (value === false)
|
|
207
|
+
return 'false';
|
|
208
|
+
if (typeof value === 'number') {
|
|
209
|
+
if (!Number.isFinite(value))
|
|
210
|
+
return 'null';
|
|
211
|
+
return Number.isInteger(value) ? BigInt(value).toString() : value.toFixed(6);
|
|
212
|
+
}
|
|
213
|
+
if (typeof value === 'string')
|
|
214
|
+
return cjsonString(value);
|
|
215
|
+
if (Array.isArray(value))
|
|
216
|
+
return `[${value.map((v) => cjsonPrint(v, depth + 1)).join(', ')}]`;
|
|
217
|
+
if (isPlainObject(value)) {
|
|
218
|
+
const inner = depth + 1;
|
|
219
|
+
const members = Object.entries(value).map(([k, v]) => `${'\t'.repeat(inner)}${cjsonString(k)}:\t${cjsonPrint(v, inner)}`);
|
|
220
|
+
if (members.length === 0)
|
|
221
|
+
return `{\n${'\t'.repeat(depth)}}`;
|
|
222
|
+
return `{\n${members.join(',\n')}\n${'\t'.repeat(depth)}}`;
|
|
223
|
+
}
|
|
224
|
+
return cjsonString(String(value));
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Parse JSON as cJSON_Parse() does, or return MISSING. cJSON skips a byte
|
|
228
|
+
* order mark and leading whitespace, accepts control characters inside
|
|
229
|
+
* strings, reads the first value and ignores anything after it, and keeps
|
|
230
|
+
* the first of two members with the same name.
|
|
231
|
+
*/
|
|
232
|
+
function cjsonParse(text) {
|
|
233
|
+
let i = 0;
|
|
234
|
+
if (text.charCodeAt(0) === 0xfeff)
|
|
235
|
+
i = 1;
|
|
236
|
+
const skip = () => {
|
|
237
|
+
while (i < text.length && text.charCodeAt(i) <= 32)
|
|
238
|
+
i++;
|
|
239
|
+
};
|
|
240
|
+
const fail = () => {
|
|
241
|
+
throw new SyntaxError('invalid JSON');
|
|
242
|
+
};
|
|
243
|
+
const parseString = () => {
|
|
244
|
+
let out = '';
|
|
245
|
+
i++; // the opening quote
|
|
246
|
+
while (i < text.length && text[i] !== '"') {
|
|
247
|
+
const ch = text[i];
|
|
248
|
+
if (ch !== '\\') {
|
|
249
|
+
out += ch;
|
|
250
|
+
i++;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const esc = text[i + 1];
|
|
254
|
+
const simple = {
|
|
255
|
+
b: '\b',
|
|
256
|
+
f: '\f',
|
|
257
|
+
n: '\n',
|
|
258
|
+
r: '\r',
|
|
259
|
+
t: '\t',
|
|
260
|
+
'"': '"',
|
|
261
|
+
'\\': '\\',
|
|
262
|
+
'/': '/',
|
|
263
|
+
};
|
|
264
|
+
if (esc !== undefined && esc in simple) {
|
|
265
|
+
out += simple[esc];
|
|
266
|
+
i += 2;
|
|
267
|
+
}
|
|
268
|
+
else if (esc === 'u' && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
|
|
269
|
+
out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
|
|
270
|
+
i += 6;
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
fail();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (i >= text.length)
|
|
277
|
+
fail();
|
|
278
|
+
i++; // the closing quote
|
|
279
|
+
return out;
|
|
280
|
+
};
|
|
281
|
+
const parseValue = (depth) => {
|
|
282
|
+
if (depth > 1000)
|
|
283
|
+
fail();
|
|
284
|
+
skip();
|
|
285
|
+
const ch = text[i];
|
|
286
|
+
if (ch === '"')
|
|
287
|
+
return parseString();
|
|
288
|
+
if (ch === '{') {
|
|
289
|
+
i++;
|
|
290
|
+
const obj = {};
|
|
291
|
+
skip();
|
|
292
|
+
if (text[i] === '}') {
|
|
293
|
+
i++;
|
|
294
|
+
return obj;
|
|
295
|
+
}
|
|
296
|
+
for (;;) {
|
|
297
|
+
skip();
|
|
298
|
+
if (text[i] !== '"')
|
|
299
|
+
fail();
|
|
300
|
+
const key = parseString();
|
|
301
|
+
skip();
|
|
302
|
+
if (text[i] !== ':')
|
|
303
|
+
fail();
|
|
304
|
+
i++;
|
|
305
|
+
const value = parseValue(depth + 1);
|
|
306
|
+
if (!Object.hasOwn(obj, key))
|
|
307
|
+
setItem(obj, key, value);
|
|
308
|
+
skip();
|
|
309
|
+
if (text[i] === ',') {
|
|
310
|
+
i++;
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (text[i] === '}') {
|
|
314
|
+
i++;
|
|
315
|
+
return obj;
|
|
316
|
+
}
|
|
317
|
+
fail();
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (ch === '[') {
|
|
321
|
+
i++;
|
|
322
|
+
const arr = [];
|
|
323
|
+
skip();
|
|
324
|
+
if (text[i] === ']') {
|
|
325
|
+
i++;
|
|
326
|
+
return arr;
|
|
327
|
+
}
|
|
328
|
+
for (;;) {
|
|
329
|
+
arr.push(parseValue(depth + 1));
|
|
330
|
+
skip();
|
|
331
|
+
if (text[i] === ',') {
|
|
332
|
+
i++;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (text[i] === ']') {
|
|
336
|
+
i++;
|
|
337
|
+
return arr;
|
|
338
|
+
}
|
|
339
|
+
fail();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
for (const [word, value] of [
|
|
343
|
+
['null', null],
|
|
344
|
+
['false', false],
|
|
345
|
+
['true', true],
|
|
346
|
+
]) {
|
|
347
|
+
if (text.startsWith(word, i)) {
|
|
348
|
+
i += word.length;
|
|
349
|
+
return value;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const number = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/.exec(text.slice(i));
|
|
353
|
+
if (!number)
|
|
354
|
+
fail();
|
|
355
|
+
i += number[0].length;
|
|
356
|
+
return Number(number[0]);
|
|
357
|
+
};
|
|
358
|
+
try {
|
|
359
|
+
return parseValue(0);
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
return MISSING;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* URL-encodes a value, for `enc:` and `form_param`, as the platform does with
|
|
367
|
+
* FreeSWITCH's `switch_url_encode`: each byte of the UTF-8 text that is a
|
|
368
|
+
* control character, non-ASCII, or in `SWITCH_URL_UNSAFE` becomes `%XX`, and
|
|
369
|
+
* every other printable ASCII character (`/`, `,`, `$`, `!`, `(` and so on)
|
|
370
|
+
* stays. A `%` that already starts an uppercase `%XX` isn't encoded again.
|
|
371
|
+
*/
|
|
372
|
+
function urlEncode(value) {
|
|
373
|
+
const bytes = new TextEncoder().encode(value);
|
|
374
|
+
let out = '';
|
|
375
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
376
|
+
const b = bytes[i];
|
|
377
|
+
const ch = String.fromCharCode(b);
|
|
378
|
+
const escaped = ch === '%' &&
|
|
379
|
+
i + 2 < bytes.length &&
|
|
380
|
+
HEX.includes(String.fromCharCode(bytes[i + 1])) &&
|
|
381
|
+
HEX.includes(String.fromCharCode(bytes[i + 2]));
|
|
382
|
+
if (!escaped && (b < 0x20 || b > 0x7e || URL_UNSAFE.includes(ch))) {
|
|
383
|
+
out += `%${HEX[b >> 4]}${HEX[b & 0x0f]}`;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
out += ch;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return out;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* libphonenumber-js, when it's installed: a port of the libphonenumber the
|
|
393
|
+
* platform formats `fmt_ph` with. It's optional, so it's found at run time,
|
|
394
|
+
* from the SDK's own location or else from the working directory's project,
|
|
395
|
+
* with its full metadata (`/max`), which validates as libphonenumber does.
|
|
396
|
+
*/
|
|
397
|
+
async function loadPhoneNumbers() {
|
|
398
|
+
const specifier = 'libphonenumber-js/max';
|
|
399
|
+
const usable = (mod) => {
|
|
400
|
+
for (const candidate of [mod, mod?.default]) {
|
|
401
|
+
const parse = candidate
|
|
402
|
+
?.parsePhoneNumberFromString;
|
|
403
|
+
if (typeof parse === 'function')
|
|
404
|
+
return { parsePhoneNumberFromString: parse };
|
|
405
|
+
}
|
|
406
|
+
return null;
|
|
407
|
+
};
|
|
408
|
+
try {
|
|
409
|
+
return usable(await import(specifier));
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
// Not next to the SDK; try the project in the working directory
|
|
413
|
+
}
|
|
414
|
+
try {
|
|
415
|
+
const require = createRequire(join(process.cwd(), 'noop.js'));
|
|
416
|
+
return usable(await import(pathToFileURL(require.resolve(specifier)).href));
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
let phoneNumbers = await loadPhoneNumbers();
|
|
423
|
+
/**
|
|
424
|
+
* Replace the libphonenumber-js that `fmt_ph` uses, for tests: null simulates
|
|
425
|
+
* a project without it.
|
|
426
|
+
*
|
|
427
|
+
* @param lib - The library, or null for none.
|
|
428
|
+
* @returns The one it replaced.
|
|
429
|
+
* @internal
|
|
430
|
+
*/
|
|
431
|
+
export function _setPhoneNumbers(lib) {
|
|
432
|
+
const previous = phoneNumbers;
|
|
433
|
+
phoneNumbers = lib;
|
|
434
|
+
return previous;
|
|
435
|
+
}
|
|
436
|
+
// Google libphonenumber's parsing patterns (phonenumberutil.cc), for the
|
|
437
|
+
// alphabetic numbers libphonenumber-js leaves out.
|
|
438
|
+
const PHONE_PUNCTUATION = '\\-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F \u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C';
|
|
439
|
+
const EXTN_AFTER_LABEL = '[:.\uFF0E]?[ \u00A0\\t,\\-]*';
|
|
440
|
+
const EXTN_PATTERN = [
|
|
441
|
+
';ext=(\\p{Nd}{1,20})',
|
|
442
|
+
'[ \u00A0\\t,]*(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|(?:\uFF45)?\uFF58\uFF54(?:\uFF4E)?|\u0434\u043E\u0431|anexo)' +
|
|
443
|
+
`${EXTN_AFTER_LABEL}(\\p{Nd}{1,20})#?`,
|
|
444
|
+
`[ \u00A0\\t,]*(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)${EXTN_AFTER_LABEL}(\\p{Nd}{1,9})#?`,
|
|
445
|
+
'[\\- ]+(\\p{Nd}{1,6})#',
|
|
446
|
+
`[ \u00A0\\t]*(?:,{2}|;)${EXTN_AFTER_LABEL}(\\p{Nd}{1,15})#?`,
|
|
447
|
+
`[ \u00A0\\t]*(?:,)+${EXTN_AFTER_LABEL}(\\p{Nd}{1,9})#?`,
|
|
448
|
+
].join('|');
|
|
449
|
+
/** An extension at the end of a number (extn_pattern_). */
|
|
450
|
+
const PHONE_EXTENSION = new RegExp(`(?:${EXTN_PATTERN})$`, 'iu');
|
|
451
|
+
/** A string that could be a phone number (valid_phone_number_pattern_). */
|
|
452
|
+
const VIABLE_PHONE_NUMBER = new RegExp(`^(?:\\p{Nd}{2}|[+\uFF0B]*(?:[${PHONE_PUNCTUATION}*]*\\p{Nd}){3,}` +
|
|
453
|
+
`[${PHONE_PUNCTUATION}*a-z\\p{Nd}]*(?:${EXTN_PATTERN})?)$`, 'iu');
|
|
454
|
+
/** Three or more letters make a vanity number (valid_alpha_phone_pattern_). */
|
|
455
|
+
const VANITY_NUMBER = /(?:.*?[a-z]){3}/iu;
|
|
456
|
+
/** The ITU E.161 keypad, as libphonenumber maps a letter. */
|
|
457
|
+
const KEYPAD = {};
|
|
458
|
+
for (const [digit, letters] of Object.entries({
|
|
459
|
+
2: 'ABC',
|
|
460
|
+
3: 'DEF',
|
|
461
|
+
4: 'GHI',
|
|
462
|
+
5: 'JKL',
|
|
463
|
+
6: 'MNO',
|
|
464
|
+
7: 'PQRS',
|
|
465
|
+
8: 'TUV',
|
|
466
|
+
9: 'WXYZ',
|
|
467
|
+
})) {
|
|
468
|
+
for (const letter of letters)
|
|
469
|
+
KEYPAD[letter] = KEYPAD[letter.toLowerCase()] = digit;
|
|
470
|
+
}
|
|
471
|
+
function isViablePhoneNumber(text) {
|
|
472
|
+
return text.length >= 2 && VIABLE_PHONE_NUMBER.test(text);
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* A value as Google's libphonenumber, which the platform uses, reads it
|
|
476
|
+
* before parsing, for libphonenumber-js to parse. The number starts at its
|
|
477
|
+
* first `+` or digit, trailing punctuation and a second number after `/x`
|
|
478
|
+
* are dropped, and a value that couldn't be a phone number is empty. An
|
|
479
|
+
* extension is split off, as `;ext=`. The rest is normalized: when it has
|
|
480
|
+
* three or more letters, it's a vanity number, whose letters are keypad
|
|
481
|
+
* digits, so `+1 412 535 abcd` is `+14125352223`; otherwise only its digits
|
|
482
|
+
* are kept. libphonenumber-js leaves vanity numbers out, and reads some other
|
|
483
|
+
* letters differently.
|
|
484
|
+
*/
|
|
485
|
+
function phoneNumberText(value) {
|
|
486
|
+
if (value.includes(';phone-context='))
|
|
487
|
+
return value;
|
|
488
|
+
const start = value.search(/[+\uFF0B\p{Nd}]/u);
|
|
489
|
+
if (start < 0)
|
|
490
|
+
return '';
|
|
491
|
+
let number = value.slice(start).replace(/[^\p{N}\p{L}#]+$/u, '');
|
|
492
|
+
const second = /(.*)[\\/] *x/u.exec(number);
|
|
493
|
+
if (second)
|
|
494
|
+
number = second[1];
|
|
495
|
+
const isdn = number.indexOf(';isub=');
|
|
496
|
+
if (isdn > 0)
|
|
497
|
+
number = number.slice(0, isdn);
|
|
498
|
+
if (!isViablePhoneNumber(number))
|
|
499
|
+
return '';
|
|
500
|
+
let extension = '';
|
|
501
|
+
const ext = PHONE_EXTENSION.exec(number);
|
|
502
|
+
const extDigits = ext?.slice(1).find(Boolean);
|
|
503
|
+
if (ext && extDigits && isViablePhoneNumber(number.slice(0, ext.index))) {
|
|
504
|
+
extension = `;ext=${extDigits}`;
|
|
505
|
+
number = number.slice(0, ext.index);
|
|
506
|
+
}
|
|
507
|
+
const plus = /^[+\uFF0B]+/u.test(number) ? '+' : '';
|
|
508
|
+
const rest = number.replace(/^[+\uFF0B]+/u, '');
|
|
509
|
+
let digits = '';
|
|
510
|
+
if (VANITY_NUMBER.test(rest)) {
|
|
511
|
+
// Letters and ASCII digits, as keypad digits; anything else is dropped
|
|
512
|
+
for (const ch of rest)
|
|
513
|
+
digits += KEYPAD[ch] ?? (/[0-9]/.test(ch) ? ch : '');
|
|
514
|
+
}
|
|
515
|
+
else {
|
|
516
|
+
// Digits in any script, as ASCII digits; anything else is dropped
|
|
517
|
+
for (const ch of rest)
|
|
518
|
+
digits += asciiDigit(ch);
|
|
519
|
+
}
|
|
520
|
+
return `${plus}${digits}${extension}`;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* A decimal digit in any script as an ASCII digit, or an empty string. The
|
|
524
|
+
* digits of a script run from 0 to 9 in consecutive code points.
|
|
525
|
+
*/
|
|
526
|
+
function asciiDigit(ch) {
|
|
527
|
+
if (!/\p{Nd}/u.test(ch))
|
|
528
|
+
return '';
|
|
529
|
+
let zero = ch.codePointAt(0);
|
|
530
|
+
while (/\p{Nd}/u.test(String.fromCodePoint(zero - 1)))
|
|
531
|
+
zero--;
|
|
532
|
+
return String((ch.codePointAt(0) - zero) % 10);
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* The `fmt_ph` helper. The platform formats with libphonenumber in the
|
|
536
|
+
* national format, reading a number without a country code as a US number,
|
|
537
|
+
* and writes `INVALID NUMBER` for one it can't validate. With libphonenumber-js
|
|
538
|
+
* installed, the simulator does the same. Without it, it formats a ten-digit
|
|
539
|
+
* North American number, with or without its leading 1, as `(NPA) NXX-XXXX`,
|
|
540
|
+
* and returns null for anything else. Either way, the value is first read as
|
|
541
|
+
* libphonenumber reads it, the letters of a vanity number as keypad digits.
|
|
542
|
+
*/
|
|
543
|
+
function formatPhoneNational(value) {
|
|
544
|
+
const text = phoneNumberText(value);
|
|
545
|
+
if (phoneNumbers) {
|
|
546
|
+
try {
|
|
547
|
+
const number = phoneNumbers.parsePhoneNumberFromString(text, 'US');
|
|
548
|
+
return number?.isValid() ? number.formatNational() : 'INVALID NUMBER';
|
|
549
|
+
}
|
|
550
|
+
catch {
|
|
551
|
+
return 'INVALID NUMBER';
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
const [number = '', extension] = text.split(';ext=');
|
|
555
|
+
let digits = number.replace(/\D/g, '');
|
|
556
|
+
if (digits.length === 11 && digits.startsWith('1'))
|
|
557
|
+
digits = digits.slice(1);
|
|
558
|
+
// After a +, only country code 1 is North American
|
|
559
|
+
else if (number.startsWith('+'))
|
|
560
|
+
return null;
|
|
561
|
+
if (digits.length === 10 && /[2-9]/.test(digits[0]) && /[2-9]/.test(digits[3])) {
|
|
562
|
+
const formatted = `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
|
|
563
|
+
return extension ? `${formatted} ext. ${extension}` : formatted;
|
|
564
|
+
}
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
/** The index of the `}` matching the `{` at `start`, or -1. */
|
|
568
|
+
function findEndBrace(text, start) {
|
|
569
|
+
let depth = 0;
|
|
570
|
+
for (let i = start; i < text.length; i++) {
|
|
571
|
+
if (text[i] === '{')
|
|
572
|
+
depth++;
|
|
573
|
+
else if (text[i] === '}') {
|
|
574
|
+
depth--;
|
|
575
|
+
if (depth === 0)
|
|
576
|
+
return i;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return -1;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* The value at a template path, or MISSING, as the platform's
|
|
583
|
+
* get_json_object() finds it. Dots separate names, matched without regard to
|
|
584
|
+
* ASCII case. One `[n]` may end a name, and a negative `n` counts from the
|
|
585
|
+
* end. A path ending in a dot doesn't resolve, and an empty path is the whole
|
|
586
|
+
* data.
|
|
587
|
+
*/
|
|
588
|
+
function lookup(data, path) {
|
|
589
|
+
if (new TextEncoder().encode(path).length > MAX_PATH_LENGTH || path.endsWith('.')) {
|
|
590
|
+
return MISSING;
|
|
591
|
+
}
|
|
592
|
+
let current = data;
|
|
593
|
+
const tokens = path.split('.').filter(Boolean);
|
|
594
|
+
for (const [n, token] of tokens.entries()) {
|
|
595
|
+
if (n + 1 > MAX_PATH_DEPTH)
|
|
596
|
+
return MISSING;
|
|
597
|
+
const open = token.indexOf('[');
|
|
598
|
+
if (open < 0) {
|
|
599
|
+
current = objectItem(current, token);
|
|
600
|
+
if (current === MISSING)
|
|
601
|
+
return MISSING;
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
const rest = token.slice(open + 1);
|
|
605
|
+
const close = rest.indexOf(']');
|
|
606
|
+
if (close < 0)
|
|
607
|
+
return MISSING;
|
|
608
|
+
const indexText = rest.slice(0, close);
|
|
609
|
+
if (rest.slice(close + 1) || !/^[ \t\n\v\f\r]*[+-]?\d+$/.test(indexText))
|
|
610
|
+
return MISSING;
|
|
611
|
+
let index = Number.parseInt(indexText.trim(), 10);
|
|
612
|
+
if (index > INT_MAX)
|
|
613
|
+
return MISSING;
|
|
614
|
+
current = objectItem(current, token.slice(0, open));
|
|
615
|
+
if (!Array.isArray(current))
|
|
616
|
+
return MISSING;
|
|
617
|
+
if (index < 0)
|
|
618
|
+
index += current.length;
|
|
619
|
+
if (index < 0 || index >= current.length)
|
|
620
|
+
return MISSING;
|
|
621
|
+
current = current[index];
|
|
622
|
+
}
|
|
623
|
+
return current;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* A resolved value as a template inserts it: a string as it is, with `"` and
|
|
627
|
+
* `\` backslash-escaped when the template is JSON text, and anything else as
|
|
628
|
+
* cJSON prints it, without escaping.
|
|
629
|
+
*/
|
|
630
|
+
function valueText(value, escapeJson) {
|
|
631
|
+
if (typeof value === 'string') {
|
|
632
|
+
return escapeJson ? value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : value;
|
|
633
|
+
}
|
|
634
|
+
return cjsonPrint(value);
|
|
635
|
+
}
|
|
636
|
+
/** Expand `${...}` and `%{...}` templates as the platform's _expand_jsonvars() does. */
|
|
637
|
+
function expand(template, data, escapeJson = false, nested = true, notes) {
|
|
638
|
+
let out = '';
|
|
639
|
+
let i = 0;
|
|
640
|
+
while (i < template.length) {
|
|
641
|
+
const ch = template[i];
|
|
642
|
+
if ((ch !== '$' && ch !== '%') || template[i + 1] !== '{') {
|
|
643
|
+
out += ch;
|
|
644
|
+
i++;
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
const end = findEndBrace(template, i + 1);
|
|
648
|
+
if (end < 0) {
|
|
649
|
+
// No closing brace: the text stays as written
|
|
650
|
+
out += ch;
|
|
651
|
+
i++;
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (end === i + 2) {
|
|
655
|
+
// ${} expands to nothing
|
|
656
|
+
i = end + 1;
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
let body = template.slice(i + 2, end);
|
|
660
|
+
let lowercase = false;
|
|
661
|
+
let encode = false;
|
|
662
|
+
let phone = false;
|
|
663
|
+
for (;;) {
|
|
664
|
+
const head = asciiLower(body.slice(0, 7));
|
|
665
|
+
if (head.startsWith('lc:')) {
|
|
666
|
+
body = body.slice(3);
|
|
667
|
+
lowercase = true;
|
|
668
|
+
}
|
|
669
|
+
else if (head === 'fmt_ph:') {
|
|
670
|
+
body = body.slice(7);
|
|
671
|
+
phone = true;
|
|
672
|
+
}
|
|
673
|
+
else if (head.startsWith('enc:')) {
|
|
674
|
+
body = body.slice(4);
|
|
675
|
+
encode = true;
|
|
676
|
+
}
|
|
677
|
+
else {
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
let path = body;
|
|
682
|
+
if (nested && (path.includes('${') || path.includes('%{'))) {
|
|
683
|
+
path = expand(path, data, escapeJson, false);
|
|
684
|
+
}
|
|
685
|
+
const raw = template.slice(i, end + 1);
|
|
686
|
+
const value = lookup(data, path);
|
|
687
|
+
if (value === MISSING) {
|
|
688
|
+
notes?.push({ raw, path, kind: 'unresolved' });
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
let text = valueText(value, escapeJson);
|
|
692
|
+
// The helpers apply in this order, whatever order they are written in
|
|
693
|
+
if (phone && text) {
|
|
694
|
+
const formatted = formatPhoneNational(text);
|
|
695
|
+
if (formatted === null)
|
|
696
|
+
notes?.push({ raw, path, kind: 'fmt_ph', value: text });
|
|
697
|
+
else
|
|
698
|
+
text = formatted;
|
|
699
|
+
}
|
|
700
|
+
if (lowercase && text)
|
|
701
|
+
text = asciiLower(text);
|
|
702
|
+
if (encode && text)
|
|
703
|
+
text = urlEncode(text);
|
|
704
|
+
out += text;
|
|
705
|
+
}
|
|
706
|
+
i = end + 1;
|
|
707
|
+
}
|
|
708
|
+
return out;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Expand DataMap templates in a string as the platform does: `${path}` and
|
|
712
|
+
* `%{path}` read a value from `data`, names matched without regard to case,
|
|
713
|
+
* with the `lc:`, `enc:` and `fmt_ph:` helpers. A path that doesn't resolve
|
|
714
|
+
* expands to an empty string. A template nested in a path expands first, one
|
|
715
|
+
* level deep, and a value that isn't a string is inserted as cJSON prints it.
|
|
716
|
+
* `@{...}` functions are left as they are.
|
|
717
|
+
*
|
|
718
|
+
* @param template - Text with `${...}` or `%{...}` templates.
|
|
719
|
+
* @param data - The template data.
|
|
720
|
+
* @returns The expanded text.
|
|
721
|
+
*/
|
|
722
|
+
export function expandTemplate(template, data) {
|
|
723
|
+
if (!template)
|
|
724
|
+
return '';
|
|
725
|
+
return expand(template, data);
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Expand the templates in a value (an output object, say) as the platform
|
|
729
|
+
* does: printed as JSON text, expanded with `"` and `\` in string values
|
|
730
|
+
* escaped, and parsed again. A template that inserts an object or array
|
|
731
|
+
* into a string breaks the JSON.
|
|
732
|
+
*
|
|
733
|
+
* @param value - The value to expand.
|
|
734
|
+
* @param data - The template data.
|
|
735
|
+
* @returns The expanded value, or undefined when the expanded text isn't JSON.
|
|
736
|
+
*/
|
|
737
|
+
export function expandValue(value, data) {
|
|
738
|
+
const parsed = cjsonParse(expand(cjsonPrint(value), data, true));
|
|
739
|
+
return parsed === MISSING ? undefined : parsed;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* A pattern as the platform matches it, with FreeSWITCH's
|
|
743
|
+
* switch_regex_match(): one that doesn't start with `/` is wrapped as
|
|
744
|
+
* `/pattern/i`, so it is searched for without regard to case; one written
|
|
745
|
+
* `/pattern/flags` takes only its own `i` and `s` flags. A leading PCRE flag
|
|
746
|
+
* group such as `(?i)`, which JavaScript doesn't accept, becomes the same
|
|
747
|
+
* flags. Returns null for a pattern that isn't valid.
|
|
748
|
+
*/
|
|
749
|
+
function platformRegExp(pattern) {
|
|
750
|
+
let source = pattern;
|
|
751
|
+
let flags = 'i';
|
|
752
|
+
if (pattern.startsWith('/')) {
|
|
753
|
+
const end = pattern.lastIndexOf('/');
|
|
754
|
+
if (end === 0)
|
|
755
|
+
return null;
|
|
756
|
+
source = pattern.slice(1, end);
|
|
757
|
+
const opts = pattern.slice(end + 1);
|
|
758
|
+
flags = (opts.includes('i') ? 'i' : '') + (opts.includes('s') ? 's' : '');
|
|
759
|
+
}
|
|
760
|
+
const inline = /^\(\?([is]+)\)/.exec(source);
|
|
761
|
+
if (inline) {
|
|
762
|
+
source = source.slice(inline[0].length);
|
|
763
|
+
for (const flag of inline[1])
|
|
764
|
+
if (!flags.includes(flag))
|
|
765
|
+
flags += flag;
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
return new RegExp(source, flags);
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
/** A curl result code standing in for a request that didn't complete. */
|
|
775
|
+
function curlErrorCode(err) {
|
|
776
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
777
|
+
const code = String(err?.cause?.code ?? '');
|
|
778
|
+
if (/timed out|aborted/i.test(message) || err?.name === 'AbortError')
|
|
779
|
+
return 28;
|
|
780
|
+
if (/Too many redirects/.test(message))
|
|
781
|
+
return 47;
|
|
782
|
+
if (/CERT|TLS|SSL|SELF_SIGNED/i.test(code) || /certificate|TLS|SSL/i.test(message))
|
|
783
|
+
return 35;
|
|
784
|
+
if (/Refused|ECONNREFUSED|ECONNRESET|ENOTFOUND|EHOSTUNREACH|ENETUNREACH/.test(message + code)) {
|
|
785
|
+
return 7;
|
|
786
|
+
}
|
|
787
|
+
return 1;
|
|
788
|
+
}
|
|
789
|
+
/** One simulated call of a DataMap function. */
|
|
790
|
+
class Run {
|
|
791
|
+
verbose;
|
|
792
|
+
out;
|
|
793
|
+
notes = [];
|
|
794
|
+
constructor(verbose, out) {
|
|
795
|
+
this.verbose = verbose;
|
|
796
|
+
this.out = out;
|
|
797
|
+
}
|
|
798
|
+
say(line) {
|
|
799
|
+
if (this.verbose)
|
|
800
|
+
this.out(line);
|
|
801
|
+
}
|
|
802
|
+
expand(template, data, stage, escapeJson = false) {
|
|
803
|
+
const found = [];
|
|
804
|
+
const text = expand(template, data, escapeJson, true, found);
|
|
805
|
+
for (const note of found)
|
|
806
|
+
this.notes.push({ note, stage });
|
|
807
|
+
return text;
|
|
808
|
+
}
|
|
809
|
+
/** Expand an output or expression result as JSON text, then parse it, as the platform does. */
|
|
810
|
+
expandJson(value, data, stage) {
|
|
811
|
+
return cjsonParse(this.expand(cjsonPrint(value), data, stage, true));
|
|
812
|
+
}
|
|
813
|
+
/** Say which templates expanded to nothing, with a hint for common mistakes. */
|
|
814
|
+
report() {
|
|
815
|
+
const seen = new Set();
|
|
816
|
+
for (const { note, stage } of this.notes) {
|
|
817
|
+
const key = `${note.kind}\0${note.raw}\0${stage}`;
|
|
818
|
+
if (seen.has(key))
|
|
819
|
+
continue;
|
|
820
|
+
seen.add(key);
|
|
821
|
+
if (note.kind === 'fmt_ph') {
|
|
822
|
+
this.out(`Note: ${note.raw} in the ${stage}: the simulator formats only North American ` +
|
|
823
|
+
`numbers, so it left "${note.value}" as it is. The platform formats a valid number ` +
|
|
824
|
+
'in its national format, and writes INVALID NUMBER for one that is not valid; ' +
|
|
825
|
+
'install the libphonenumber-js package to simulate that.');
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
let line = `Note: ${note.raw} in the ${stage} expands to an empty string on the platform.`;
|
|
829
|
+
const lowered = asciiLower(note.path);
|
|
830
|
+
const prefix = /^([A-Za-z_]\w*):(.*)$/.exec(note.path);
|
|
831
|
+
if (lowered.startsWith('response.')) {
|
|
832
|
+
line +=
|
|
833
|
+
" The platform reads a webhook's JSON response from the root: " +
|
|
834
|
+
'write ${<field>}, not ${response.<field>}.';
|
|
835
|
+
}
|
|
836
|
+
else if (RESPONSE_STAGES.has(stage) && lowered.startsWith('args.')) {
|
|
837
|
+
line +=
|
|
838
|
+
" In a webhook's foreach, expressions and output, the arguments are under " +
|
|
839
|
+
`input: write \${input.${note.path}}.`;
|
|
840
|
+
}
|
|
841
|
+
else if (!RESPONSE_STAGES.has(stage) && lowered.startsWith('input.')) {
|
|
842
|
+
line +=
|
|
843
|
+
' input is empty until a webhook responds; read the call data directly here, ' +
|
|
844
|
+
`as \${${note.path.slice('input.'.length)}}.`;
|
|
845
|
+
}
|
|
846
|
+
else if (prefix) {
|
|
847
|
+
line +=
|
|
848
|
+
` "${prefix[1]}:" is not a template helper: the platform's helpers are lc:, enc: ` +
|
|
849
|
+
`and fmt_ph:, so it reads "${note.path}" as a path.` +
|
|
850
|
+
(asciiLower(prefix[1]) === 'url' ? ` To URL-encode, write \${enc:${prefix[2]}}.` : '');
|
|
851
|
+
}
|
|
852
|
+
this.out(line);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
/** The first expression result, or MISSING, as get_input_from_expressions() finds it. */
|
|
857
|
+
function runExpressions(run, expressions, data, stage) {
|
|
858
|
+
for (const item of Array.isArray(expressions) ? expressions : [expressions]) {
|
|
859
|
+
const reply = parseExpression(run, item, data, stage);
|
|
860
|
+
if (reply !== MISSING)
|
|
861
|
+
return reply;
|
|
862
|
+
}
|
|
863
|
+
return MISSING;
|
|
864
|
+
}
|
|
865
|
+
/** One expression's result, or MISSING when it produces none, as parse_expression() does. */
|
|
866
|
+
function parseExpression(run, item, data, stage) {
|
|
867
|
+
let subjectTemplate = stringItem(item, 'string');
|
|
868
|
+
const pattern = stringItem(item, 'pattern');
|
|
869
|
+
const expr = stringItem(item, 'expr');
|
|
870
|
+
if (subjectTemplate === null) {
|
|
871
|
+
// With neither string nor expr, an expression never matches
|
|
872
|
+
if (expr === null)
|
|
873
|
+
return MISSING;
|
|
874
|
+
subjectTemplate = expr;
|
|
875
|
+
}
|
|
876
|
+
const output = objectItem(item, 'output');
|
|
877
|
+
const nomatch = objectItem(item, 'nomatch-output');
|
|
878
|
+
if (output === MISSING)
|
|
879
|
+
return MISSING;
|
|
880
|
+
const subject = run.expand(subjectTemplate, data, stage);
|
|
881
|
+
let matched = false;
|
|
882
|
+
if (expr !== null) {
|
|
883
|
+
run.say(`An expression's expr isn't evaluated by the simulator: ${expr}`);
|
|
884
|
+
}
|
|
885
|
+
if (pattern !== null) {
|
|
886
|
+
const re = platformRegExp(pattern);
|
|
887
|
+
if (re)
|
|
888
|
+
matched = re.test(subject);
|
|
889
|
+
else
|
|
890
|
+
run.say(`Expression pattern isn't a valid regular expression: ${pattern}`);
|
|
891
|
+
run.say(`Expression "${subject}" against ${pattern}: ${matched ? 'match' : 'no match'}`);
|
|
892
|
+
}
|
|
893
|
+
if (matched)
|
|
894
|
+
return run.expandJson(output, data, stage);
|
|
895
|
+
if (nomatch !== MISSING)
|
|
896
|
+
return run.expandJson(nomatch, data, stage);
|
|
897
|
+
return MISSING;
|
|
898
|
+
}
|
|
899
|
+
/** The call data templates read before a webhook responds, as the platform builds it. */
|
|
900
|
+
function buildCallData(fn, args, callData) {
|
|
901
|
+
const extra = structuredClone(callData ?? {});
|
|
902
|
+
const rawPromptVars = extra['prompt_vars'];
|
|
903
|
+
delete extra['prompt_vars'];
|
|
904
|
+
const promptVars = isPlainObject(rawPromptVars) ? rawPromptVars : {};
|
|
905
|
+
const data = {};
|
|
906
|
+
if (typeof fn['function'] === 'string')
|
|
907
|
+
data['function'] = fn['function'];
|
|
908
|
+
for (const [key, value] of Object.entries(extra))
|
|
909
|
+
replaceItem(data, key, value);
|
|
910
|
+
// The platform merges the function's meta_data over the global data, key
|
|
911
|
+
// by key, when it loads the function (app_config.c, cJSON_Merge with
|
|
912
|
+
// replace); a call's meta_data is that object, not one from the call data.
|
|
913
|
+
const metaData = {};
|
|
914
|
+
for (const source of [objectItem(data, 'global_data'), fn['meta_data']]) {
|
|
915
|
+
if (!isPlainObject(source))
|
|
916
|
+
continue;
|
|
917
|
+
for (const [key, value] of Object.entries(source)) {
|
|
918
|
+
replaceItem(metaData, key, structuredClone(value));
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
replaceItem(data, 'meta_data', metaData);
|
|
922
|
+
// As on the platform, the prompt variables are merged into the root
|
|
923
|
+
for (const [key, value] of Object.entries(promptVars)) {
|
|
924
|
+
replaceItem(data, key, structuredClone(value));
|
|
925
|
+
}
|
|
926
|
+
addItem(data, 'args', structuredClone(args));
|
|
927
|
+
addItem(data, 'input', {});
|
|
928
|
+
return { data, promptVars, globalData: objectItem(data, 'global_data') };
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* Run a DataMap function locally, as the platform runs it.
|
|
932
|
+
*
|
|
933
|
+
* @param fn - The function's SWAIG entry (`{ function, data_map, meta_data, ... }`)
|
|
934
|
+
* or its `data_map` alone.
|
|
935
|
+
* @param args - The function's arguments.
|
|
936
|
+
* @param opts - Verbose output, the call data, and the fetch to use.
|
|
937
|
+
* @returns The function's result: the expanded output (an object or a
|
|
938
|
+
* string), `{ response: PLATFORM_ERROR_RESPONSE }` when nothing produced a
|
|
939
|
+
* result, as on the platform, or an `{ error }` object when the expanded
|
|
940
|
+
* output isn't JSON, where the platform gets no result.
|
|
941
|
+
*/
|
|
942
|
+
export async function executeDataMap(fn, args, opts = {}) {
|
|
943
|
+
const log = opts.log ?? ((line) => void process.stderr.write(`${line}\n`));
|
|
944
|
+
const run = new Run(opts.verbose === true, log);
|
|
945
|
+
try {
|
|
946
|
+
return await execute(run, fn, args, opts);
|
|
947
|
+
}
|
|
948
|
+
finally {
|
|
949
|
+
run.report();
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
async function execute(run, fn, args, opts) {
|
|
953
|
+
const dataMap = (isPlainObject(fn['data_map']) ? fn['data_map'] : fn);
|
|
954
|
+
const { data, promptVars, globalData } = buildCallData(fn, args, opts.callData);
|
|
955
|
+
run.say('=== DataMap Function Execution ===');
|
|
956
|
+
run.say(`Args: ${JSON.stringify(args)}`);
|
|
957
|
+
if (opts.callData)
|
|
958
|
+
run.say(`Call data: ${JSON.stringify(data)}`);
|
|
959
|
+
// 1. The top-level expressions, against the call data
|
|
960
|
+
const expressions = objectItem(dataMap, 'expressions');
|
|
961
|
+
if (expressions !== MISSING) {
|
|
962
|
+
const reply = runExpressions(run, expressions, data, 'top-level expressions');
|
|
963
|
+
if (reply !== MISSING)
|
|
964
|
+
return reply;
|
|
965
|
+
}
|
|
966
|
+
// 2. The first webhook requested
|
|
967
|
+
const webhooks = objectItem(dataMap, 'webhooks');
|
|
968
|
+
if (webhooks !== MISSING) {
|
|
969
|
+
const { reply, match } = await runWebhooks(run, webhooks, data, opts);
|
|
970
|
+
if (match) {
|
|
971
|
+
// The response is the root of the template data; the call data is under input
|
|
972
|
+
const rdata = isPlainObject(reply) ? reply : {};
|
|
973
|
+
addItem(rdata, 'prompt_vars', structuredClone(promptVars));
|
|
974
|
+
if (globalData !== MISSING)
|
|
975
|
+
addItem(rdata, 'global_data', structuredClone(globalData));
|
|
976
|
+
addItem(rdata, 'input', structuredClone(data));
|
|
977
|
+
const foreach = objectItem(match, 'foreach');
|
|
978
|
+
if (foreach !== MISSING)
|
|
979
|
+
processForeach(run, foreach, rdata);
|
|
980
|
+
let response = MISSING;
|
|
981
|
+
let processed = false;
|
|
982
|
+
const hookExpressions = objectItem(match, 'expressions');
|
|
983
|
+
if (hookExpressions !== MISSING) {
|
|
984
|
+
const result = runExpressions(run, hookExpressions, rdata, 'webhook expressions');
|
|
985
|
+
if (result !== MISSING) {
|
|
986
|
+
// The platform expands a matched result a second time
|
|
987
|
+
response = run.expandJson(result, rdata, 'webhook expressions');
|
|
988
|
+
processed = true;
|
|
989
|
+
}
|
|
990
|
+
else {
|
|
991
|
+
run.say('No webhook expression matched');
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
const output = objectItem(match, 'output');
|
|
995
|
+
if (response === MISSING && output !== MISSING) {
|
|
996
|
+
response = run.expandJson(output, rdata, 'webhook output');
|
|
997
|
+
processed = true;
|
|
998
|
+
}
|
|
999
|
+
if (processed)
|
|
1000
|
+
return finish(run, response);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
// 3. The data_map's own output
|
|
1004
|
+
const output = objectItem(dataMap, 'output');
|
|
1005
|
+
if (output !== MISSING) {
|
|
1006
|
+
run.say('No webhook produced a result; using the data_map output');
|
|
1007
|
+
addItem(data, 'prompt_vars', structuredClone(promptVars));
|
|
1008
|
+
return finish(run, run.expandJson(output, data, 'top-level output'));
|
|
1009
|
+
}
|
|
1010
|
+
// 4. The platform's generic error
|
|
1011
|
+
run.say('Nothing produced a result; the platform returns its generic error');
|
|
1012
|
+
return { response: PLATFORM_ERROR_RESPONSE };
|
|
1013
|
+
}
|
|
1014
|
+
function finish(run, response) {
|
|
1015
|
+
if (response === MISSING) {
|
|
1016
|
+
run.say("The expanded output isn't valid JSON");
|
|
1017
|
+
return {
|
|
1018
|
+
error: "The expanded output isn't valid JSON, so the platform gets no result from this " +
|
|
1019
|
+
'function. A template that inserts an object or array into a string causes this.',
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
return response;
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Request the first eligible webhook, as get_input_from_webhooks() does.
|
|
1026
|
+
* Returns the reply, with an array wrapped as `{ array: [...] }`, and the
|
|
1027
|
+
* webhook when its reply counts as a success.
|
|
1028
|
+
*/
|
|
1029
|
+
async function runWebhooks(run, webhooks, data, opts) {
|
|
1030
|
+
let reply = MISSING;
|
|
1031
|
+
let match = null;
|
|
1032
|
+
if (Array.isArray(webhooks)) {
|
|
1033
|
+
for (const [i, item] of webhooks.entries()) {
|
|
1034
|
+
run.say(`\n=== Webhook ${i + 1}/${webhooks.length} ===`);
|
|
1035
|
+
const requireArgs = objectItem(item, 'require_args');
|
|
1036
|
+
let eligible = true;
|
|
1037
|
+
if (requireArgs !== MISSING && !anyPresent(requireArgs, objectItem(data, 'args'))) {
|
|
1038
|
+
// Any one of the listed arguments is enough
|
|
1039
|
+
run.say('Skipped: none of its require_args is present');
|
|
1040
|
+
eligible = false;
|
|
1041
|
+
}
|
|
1042
|
+
if (!hasItem(item, 'output') && !hasItem(item, 'expressions')) {
|
|
1043
|
+
run.say('Skipped: a webhook must have output or expressions');
|
|
1044
|
+
eligible = false;
|
|
1045
|
+
}
|
|
1046
|
+
if (!eligible)
|
|
1047
|
+
continue;
|
|
1048
|
+
reply = await request(run, item, data, opts);
|
|
1049
|
+
if (reply === MISSING) {
|
|
1050
|
+
run.say('Skipped: the webhook has no url');
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
const reason = failure(reply, objectItem(item, 'error_keys'));
|
|
1054
|
+
if (reason) {
|
|
1055
|
+
run.say(`Webhook ${i + 1} failed: ${reason}. The platform tries no later webhook; ` +
|
|
1056
|
+
'the data_map output runs instead.');
|
|
1057
|
+
}
|
|
1058
|
+
else {
|
|
1059
|
+
match = item;
|
|
1060
|
+
}
|
|
1061
|
+
break;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
else if (isPlainObject(webhooks)) {
|
|
1065
|
+
// A single webhook object is never checked for errors
|
|
1066
|
+
run.say('\n=== Webhook ===');
|
|
1067
|
+
if (hasItem(webhooks, 'output') || hasItem(webhooks, 'expressions')) {
|
|
1068
|
+
reply = await request(run, webhooks, data, opts);
|
|
1069
|
+
if (reply !== MISSING)
|
|
1070
|
+
match = webhooks;
|
|
1071
|
+
}
|
|
1072
|
+
else {
|
|
1073
|
+
run.say('Skipped: a webhook must have output or expressions');
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
if (Array.isArray(reply))
|
|
1077
|
+
reply = { array: reply };
|
|
1078
|
+
return { reply, match };
|
|
1079
|
+
}
|
|
1080
|
+
/** mod_openai's args_present(): whether any of the named keys is present. */
|
|
1081
|
+
function anyPresent(keys, container) {
|
|
1082
|
+
const list = Array.isArray(keys) ? keys : [keys];
|
|
1083
|
+
return list.some((k) => typeof k === 'string' && hasItem(container, k));
|
|
1084
|
+
}
|
|
1085
|
+
/** Why a webhook's reply counts as a failure, or an empty string. */
|
|
1086
|
+
function failure(reply, errorKeys) {
|
|
1087
|
+
for (const key of ['parse_error', 'protocol_error']) {
|
|
1088
|
+
if (hasItem(reply, key))
|
|
1089
|
+
return `the response has ${key}`;
|
|
1090
|
+
}
|
|
1091
|
+
if (errorKeys === MISSING)
|
|
1092
|
+
return '';
|
|
1093
|
+
// A listed key fails the webhook when it is present, whatever its value
|
|
1094
|
+
for (const key of Array.isArray(errorKeys) ? errorKeys : [errorKeys]) {
|
|
1095
|
+
if (typeof key === 'string' && hasItem(reply, key)) {
|
|
1096
|
+
return `the response has the error key '${key}'`;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
return '';
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Send one webhook's request as parse_webhook() does, and return its reply,
|
|
1103
|
+
* or MISSING when the webhook has no url.
|
|
1104
|
+
*/
|
|
1105
|
+
async function request(run, webhook, data, opts) {
|
|
1106
|
+
let url = stringItem(webhook, 'url');
|
|
1107
|
+
if (url === null)
|
|
1108
|
+
return MISSING;
|
|
1109
|
+
const method = stringItem(webhook, 'method');
|
|
1110
|
+
const formParam = stringItem(webhook, 'form_param');
|
|
1111
|
+
let params = objectItem(webhook, 'params');
|
|
1112
|
+
const headers = objectItem(webhook, 'headers');
|
|
1113
|
+
if (isTrue(objectItem(webhook, 'input_args_as_params'))) {
|
|
1114
|
+
const args = objectItem(data, 'args');
|
|
1115
|
+
if (args !== MISSING) {
|
|
1116
|
+
if (isPlainObject(params) && isPlainObject(args)) {
|
|
1117
|
+
const merged = structuredClone(params);
|
|
1118
|
+
for (const [key, value] of Object.entries(args)) {
|
|
1119
|
+
replaceItem(merged, key, structuredClone(value));
|
|
1120
|
+
}
|
|
1121
|
+
params = merged;
|
|
1122
|
+
}
|
|
1123
|
+
else if (params === MISSING) {
|
|
1124
|
+
params = args;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
// Credentials in the url become basic authentication, sent only to their origin
|
|
1129
|
+
let authorization;
|
|
1130
|
+
const credentials = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#@]*)@/.exec(url);
|
|
1131
|
+
if (credentials) {
|
|
1132
|
+
const [user, ...rest] = credentials[2].split(':');
|
|
1133
|
+
const decode = (s) => {
|
|
1134
|
+
try {
|
|
1135
|
+
return decodeURIComponent(s);
|
|
1136
|
+
}
|
|
1137
|
+
catch {
|
|
1138
|
+
return s;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
const pair = `${decode(user)}:${decode(rest.join(':'))}`;
|
|
1142
|
+
authorization = `Basic ${Buffer.from(pair).toString('base64')}`;
|
|
1143
|
+
url = credentials[1] + url.slice(credentials[0].length);
|
|
1144
|
+
}
|
|
1145
|
+
url = run.expand(url, data, 'webhook url');
|
|
1146
|
+
let post = method !== null && method.toLowerCase() === 'post';
|
|
1147
|
+
let body;
|
|
1148
|
+
if (params !== MISSING) {
|
|
1149
|
+
// params are the request body, so a webhook with params is a POST
|
|
1150
|
+
post = true;
|
|
1151
|
+
body = run.expand(cjsonPrint(params), data, 'webhook params', true);
|
|
1152
|
+
if (formParam !== null)
|
|
1153
|
+
body = `${formParam}=${urlEncode(body)}`;
|
|
1154
|
+
}
|
|
1155
|
+
if (hasItem(webhook, 'body')) {
|
|
1156
|
+
run.say("The platform doesn't send a webhook's body key; params is the request body");
|
|
1157
|
+
}
|
|
1158
|
+
const requestHeaders = {
|
|
1159
|
+
'Content-Type': formParam !== null ? 'application/x-www-form-urlencoded' : 'application/json',
|
|
1160
|
+
'User-Agent': 'SignalWire-CallFabric/1.0',
|
|
1161
|
+
};
|
|
1162
|
+
if (authorization)
|
|
1163
|
+
requestHeaders['Authorization'] = authorization;
|
|
1164
|
+
if (isPlainObject(headers)) {
|
|
1165
|
+
// Header values are sent as written; templates in them aren't expanded
|
|
1166
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
1167
|
+
if (typeof value !== 'string')
|
|
1168
|
+
continue;
|
|
1169
|
+
for (const existing of Object.keys(requestHeaders)) {
|
|
1170
|
+
if (existing.toLowerCase() === name.toLowerCase())
|
|
1171
|
+
delete requestHeaders[existing];
|
|
1172
|
+
}
|
|
1173
|
+
requestHeaders[name] = value;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
const httpMethod = post ? 'POST' : 'GET';
|
|
1177
|
+
if (method !== null && method.toUpperCase() !== httpMethod) {
|
|
1178
|
+
run.say(`The platform sends ${httpMethod}, not ${method}`);
|
|
1179
|
+
}
|
|
1180
|
+
run.say(`${httpMethod} ${url}`);
|
|
1181
|
+
if (body !== undefined)
|
|
1182
|
+
run.say(`Request body: ${body}`);
|
|
1183
|
+
const fetchImpl = opts.fetchImpl ??
|
|
1184
|
+
((target, init) => _publicFetch(target, {
|
|
1185
|
+
method: init.method,
|
|
1186
|
+
headers: init.headers,
|
|
1187
|
+
body: init.body,
|
|
1188
|
+
signal: init.signal,
|
|
1189
|
+
// The platform's curl settings: up to 15 redirects, a POST sent again
|
|
1190
|
+
// with its body after any of them. Every hop is still checked.
|
|
1191
|
+
redirectMode: 'curl',
|
|
1192
|
+
onStatus: init.onStatus,
|
|
1193
|
+
}));
|
|
1194
|
+
// Each status received, redirects included
|
|
1195
|
+
const statuses = [];
|
|
1196
|
+
let status = 0;
|
|
1197
|
+
let text = '';
|
|
1198
|
+
let curlError = null;
|
|
1199
|
+
const controller = new AbortController();
|
|
1200
|
+
const timer = setTimeout(() => controller.abort(), (opts.timeoutSeconds ?? HTTP_REQUEST_TIMEOUT) * 1000);
|
|
1201
|
+
try {
|
|
1202
|
+
// The timeout covers the body too: headers can arrive and the body stall.
|
|
1203
|
+
const response = await fetchImpl(url, {
|
|
1204
|
+
method: httpMethod,
|
|
1205
|
+
headers: requestHeaders,
|
|
1206
|
+
body,
|
|
1207
|
+
signal: controller.signal,
|
|
1208
|
+
onStatus: (received) => void statuses.push(received),
|
|
1209
|
+
});
|
|
1210
|
+
status = response.status;
|
|
1211
|
+
text = await Promise.race([
|
|
1212
|
+
response.text(),
|
|
1213
|
+
new Promise((_resolve, reject) => {
|
|
1214
|
+
const abort = () => reject(new Error('webhook timed out'));
|
|
1215
|
+
if (controller.signal.aborted)
|
|
1216
|
+
abort();
|
|
1217
|
+
controller.signal.addEventListener('abort', abort, { once: true });
|
|
1218
|
+
}),
|
|
1219
|
+
]);
|
|
1220
|
+
run.say(`Response status: ${status}`);
|
|
1221
|
+
}
|
|
1222
|
+
catch (err) {
|
|
1223
|
+
// As curl reports it, the status is the last one received, redirects
|
|
1224
|
+
// included, or 0 when none was
|
|
1225
|
+
status = statuses.at(-1) ?? status;
|
|
1226
|
+
curlError = curlErrorCode(err);
|
|
1227
|
+
run.say(`Request failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1228
|
+
}
|
|
1229
|
+
finally {
|
|
1230
|
+
clearTimeout(timer);
|
|
1231
|
+
}
|
|
1232
|
+
let reply = text ? cjsonParse(text) : MISSING;
|
|
1233
|
+
const parseError = reply === MISSING;
|
|
1234
|
+
if (parseError || curlError !== null || status < 200 || status > 299) {
|
|
1235
|
+
if (reply === MISSING)
|
|
1236
|
+
reply = {};
|
|
1237
|
+
if (isPlainObject(reply)) {
|
|
1238
|
+
if (parseError) {
|
|
1239
|
+
setItem(reply, 'parse_error', true);
|
|
1240
|
+
setItem(reply, 'raw_response', text);
|
|
1241
|
+
}
|
|
1242
|
+
if (curlError !== null) {
|
|
1243
|
+
setItem(reply, 'protocol_error', true);
|
|
1244
|
+
setItem(reply, 'http_req_result', curlError);
|
|
1245
|
+
}
|
|
1246
|
+
setItem(reply, 'http_code', status);
|
|
1247
|
+
}
|
|
1248
|
+
run.say(`Response data: ${JSON.stringify(reply)}`);
|
|
1249
|
+
}
|
|
1250
|
+
return reply;
|
|
1251
|
+
}
|
|
1252
|
+
/** Build a foreach's text into its output_key, as process_foreach() does. */
|
|
1253
|
+
function processForeach(run, foreach, data) {
|
|
1254
|
+
const inputKey = stringItem(foreach, 'input_key');
|
|
1255
|
+
const outputKey = stringItem(foreach, 'output_key');
|
|
1256
|
+
const append = stringItem(foreach, 'append');
|
|
1257
|
+
if (inputKey === null || outputKey === null || append === null) {
|
|
1258
|
+
run.say('foreach needs input_key, output_key and append; skipping it');
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
const items = lookup(data, inputKey);
|
|
1262
|
+
if (!Array.isArray(items)) {
|
|
1263
|
+
run.say(`foreach: ${inputKey} isn't an array in the response; skipping it`);
|
|
1264
|
+
return;
|
|
1265
|
+
}
|
|
1266
|
+
let count = items.length;
|
|
1267
|
+
const limit = objectItem(foreach, 'max');
|
|
1268
|
+
if (limit !== MISSING) {
|
|
1269
|
+
const max = typeof limit === 'string' ? atoi(limit) : typeof limit === 'number' ? Math.trunc(limit) : 0;
|
|
1270
|
+
if (max > 0)
|
|
1271
|
+
count = Math.min(count, max);
|
|
1272
|
+
}
|
|
1273
|
+
const parts = [];
|
|
1274
|
+
for (const item of items.slice(0, count)) {
|
|
1275
|
+
// this is the current element, and everything else stays readable
|
|
1276
|
+
deleteItem(data, 'this');
|
|
1277
|
+
setItem(data, 'this', structuredClone(item));
|
|
1278
|
+
parts.push(run.expand(append, data, 'webhook foreach'));
|
|
1279
|
+
deleteItem(data, 'this');
|
|
1280
|
+
}
|
|
1281
|
+
addItem(data, outputKey, parts.join(''));
|
|
1282
|
+
run.say(`foreach: ${count} item(s) into ${outputKey}`);
|
|
1283
|
+
}
|
|
1284
|
+
//# sourceMappingURL=datamap-exec.js.map
|