@fonoster/apiserver 0.27.0 → 0.31.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.
Files changed (376) hide show
  1. package/dist/applications/buildService.d.ts +5 -1
  2. package/dist/applications/buildService.js +10 -7
  3. package/dist/applications/createCreateApplication.d.ts +6 -2
  4. package/dist/applications/createCreateApplication.js +24 -16
  5. package/dist/applications/createCreateTestToken.d.ts +3 -1
  6. package/dist/applications/createCreateTestToken.js +18 -13
  7. package/dist/applications/createGetApplication.js +2 -2
  8. package/dist/applications/createGetFnUtil.d.ts +22 -18
  9. package/dist/applications/createGetFnUtil.js +3 -5
  10. package/dist/applications/createListApplications.js +3 -4
  11. package/dist/applications/createRotateSigningSecret.d.ts +9 -0
  12. package/dist/{calls/createFetchSingleCall.js → applications/createRotateSigningSecret.js} +23 -20
  13. package/dist/applications/createUpdateApplication.d.ts +6 -2
  14. package/dist/applications/createUpdateApplication.js +35 -36
  15. package/dist/applications/evalKeys.d.ts +9 -0
  16. package/dist/{voice/handlers/dial/recordChannel.js → applications/evalKeys.js} +17 -12
  17. package/dist/applications/session/appModel.d.ts +225 -0
  18. package/dist/applications/session/appModel.js +331 -0
  19. package/dist/applications/types.d.ts +1 -27
  20. package/dist/billing/buildService.d.ts +24 -0
  21. package/dist/billing/buildService.js +116 -0
  22. package/dist/bin/entrypoint.d.ts +1 -0
  23. package/dist/bin/entrypoint.js +180 -0
  24. package/dist/bin/healthcheck.d.ts +2 -0
  25. package/dist/{voice/utils/VoiceServiceClientConstructor.js → bin/healthcheck.js} +24 -9
  26. package/dist/bin/regionHubSetup.d.ts +2 -0
  27. package/dist/bin/regionHubSetup.js +67 -0
  28. package/dist/bin/usage.d.ts +2 -0
  29. package/dist/bin/usage.js +119 -0
  30. package/dist/calls/buildService.d.ts +1 -20
  31. package/dist/calls/buildService.js +59 -6
  32. package/dist/calls/createCall.d.ts +17 -2
  33. package/dist/calls/createCall.js +64 -11
  34. package/dist/calls/createCallPublisher.d.ts +40 -2
  35. package/dist/calls/createCallPublisher.js +43 -9
  36. package/dist/calls/createIsWorkspaceNumber.d.ts +41 -0
  37. package/dist/calls/createIsWorkspaceNumber.js +39 -0
  38. package/dist/calls/createTrackCall.d.ts +55 -2
  39. package/dist/calls/createTrackCall.js +230 -16
  40. package/dist/calls/getCall.d.ts +4 -2
  41. package/dist/calls/getCall.js +2 -3
  42. package/dist/calls/listCalls.d.ts +4 -2
  43. package/dist/calls/listCalls.js +2 -3
  44. package/dist/calls/types.d.ts +11 -2
  45. package/dist/calls/types.js +10 -0
  46. package/dist/{core/buildWelcomeDemoService.d.ts → capabilities/buildService.d.ts} +8 -8
  47. package/dist/capabilities/buildService.js +17 -0
  48. package/dist/capabilities/createGetCapabilities.d.ts +78 -0
  49. package/dist/capabilities/createGetCapabilities.js +98 -0
  50. package/dist/{voice/handlers/utils → capabilities}/index.d.ts +2 -3
  51. package/dist/{voice/handlers/utils → capabilities}/index.js +4 -3
  52. package/dist/config/index.d.ts +23 -0
  53. package/dist/config/index.js +102 -0
  54. package/dist/config/schema.d.ts +1919 -0
  55. package/dist/config/schema.js +357 -0
  56. package/dist/core/allowList.js +2 -1
  57. package/dist/core/applyCatalog.d.ts +10 -0
  58. package/dist/{voice/client/GrpcClientHandler.js → core/applyCatalog.js} +45 -51
  59. package/dist/core/db.d.ts +3 -1
  60. package/dist/core/db.js +2 -1
  61. package/dist/core/durableConsumer.d.ts +41 -0
  62. package/dist/core/durableConsumer.js +104 -0
  63. package/dist/core/httpBridge.d.ts +24 -6
  64. package/dist/core/httpBridge.js +3 -25
  65. package/dist/core/identityConfig.d.ts +2 -35
  66. package/dist/core/identityConfig.js +3 -36
  67. package/dist/core/regionHooks.d.ts +15 -0
  68. package/dist/{calls/influxdb.js → core/regionHooks.js} +4 -8
  69. package/dist/core/runServices.js +98 -15
  70. package/dist/core/services.d.ts +96 -6
  71. package/dist/core/services.js +49 -10
  72. package/dist/{voice/errors/index.d.ts → core/telemetry.d.ts} +2 -2
  73. package/dist/core/telemetry.js +42 -0
  74. package/dist/{applications/utils/convertToApplicationData.d.ts → core/telemetryInterceptor.d.ts} +10 -4
  75. package/dist/core/telemetryInterceptor.js +57 -0
  76. package/dist/core/testTokenConfig.js +4 -1
  77. package/dist/core/upsertRoomrPeer.d.ts +6 -0
  78. package/dist/core/{upsertDefaultPeer.js → upsertRoomrPeer.js} +31 -30
  79. package/dist/envs.d.ts +136 -23
  80. package/dist/envs.js +108 -143
  81. package/dist/index.js +39 -21
  82. package/dist/outbound/createNodeDirectory.d.ts +86 -0
  83. package/dist/outbound/createNodeDirectory.js +140 -0
  84. package/dist/{voice/integrations → outbound}/index.d.ts +4 -1
  85. package/dist/{voice/errors → outbound}/index.js +4 -2
  86. package/dist/outbound/placeOutboundCall.d.ts +96 -0
  87. package/dist/outbound/placeOutboundCall.js +172 -0
  88. package/dist/outbound/placementSweep.d.ts +56 -0
  89. package/dist/outbound/placementSweep.js +127 -0
  90. package/dist/outbound/runOutboundCalls.d.ts +52 -0
  91. package/dist/outbound/runOutboundCalls.js +171 -0
  92. package/dist/providers/createProvidersHandlers.d.ts +39 -0
  93. package/dist/providers/createProvidersHandlers.js +229 -0
  94. package/dist/providers/index.d.ts +47 -0
  95. package/dist/{voice/client → providers}/index.js +15 -6
  96. package/dist/providers/registryUsage.d.ts +48 -0
  97. package/dist/providers/registryUsage.js +236 -0
  98. package/dist/records/createIndexRecord.d.ts +42 -0
  99. package/dist/records/createIndexRecord.js +185 -0
  100. package/dist/records/createRecordsRouter.d.ts +61 -0
  101. package/dist/records/createRecordsRouter.js +330 -0
  102. package/dist/records/createSearchRecords.d.ts +51 -0
  103. package/dist/records/createSearchRecords.js +134 -0
  104. package/dist/{voice/filters → records}/index.d.ts +6 -6
  105. package/dist/{voice/filters → records}/index.js +6 -6
  106. package/dist/records/maintenance.d.ts +33 -0
  107. package/dist/records/maintenance.js +166 -0
  108. package/dist/records/runCallRecords.d.ts +48 -0
  109. package/dist/records/runCallRecords.js +49 -0
  110. package/dist/{events/createPerCallCache.d.ts → records/stores.d.ts} +4 -7
  111. package/dist/{voice/handlers/utils/isDtmf.js → records/stores.js} +9 -3
  112. package/dist/records/types.d.ts +104 -0
  113. package/dist/regions/configSync.d.ts +130 -0
  114. package/dist/regions/configSync.js +316 -0
  115. package/dist/regions/createRegionsRouter.d.ts +151 -0
  116. package/dist/regions/createRegionsRouter.js +391 -0
  117. package/dist/regions/endpoints.d.ts +41 -0
  118. package/dist/regions/endpoints.js +90 -0
  119. package/dist/regions/enrollmentToken.d.ts +41 -0
  120. package/dist/regions/enrollmentToken.js +94 -0
  121. package/dist/regions/httpAuth.d.ts +39 -0
  122. package/dist/regions/httpAuth.js +78 -0
  123. package/dist/regions/ids.d.ts +15 -0
  124. package/dist/regions/ids.js +81 -0
  125. package/dist/{voice/client → regions}/index.d.ts +17 -6
  126. package/dist/regions/index.js +51 -0
  127. package/dist/regions/link.d.ts +17 -0
  128. package/dist/regions/link.js +170 -0
  129. package/dist/regions/natsAuth.d.ts +41 -0
  130. package/dist/regions/natsAuth.js +64 -0
  131. package/dist/regions/natsJwt.d.ts +23 -0
  132. package/dist/regions/natsJwt.js +26 -0
  133. package/dist/regions/relay.d.ts +45 -0
  134. package/dist/regions/relay.js +203 -0
  135. package/dist/regions/relayHttp.d.ts +7 -0
  136. package/dist/regions/relayHttp.js +107 -0
  137. package/dist/regions/relaySlots.d.ts +18 -0
  138. package/dist/regions/relaySlots.js +118 -0
  139. package/dist/regions/runRegions.d.ts +111 -0
  140. package/dist/regions/runRegions.js +235 -0
  141. package/dist/regions/service.d.ts +129 -0
  142. package/dist/regions/service.js +558 -0
  143. package/dist/regions/sources.d.ts +20 -0
  144. package/dist/regions/sources.js +191 -0
  145. package/dist/regions/status.d.ts +35 -0
  146. package/dist/regions/status.js +63 -0
  147. package/dist/regions/types.d.ts +123 -0
  148. package/dist/regions/types.js +41 -0
  149. package/dist/{voice/integrations/getSttConfig.d.ts → regions/withConfigChangeHook.d.ts} +13 -7
  150. package/dist/regions/withConfigChangeHook.js +44 -0
  151. package/dist/secrets/createGetFnUtil.d.ts +2 -2
  152. package/dist/session/createSessionRouter.d.ts +49 -0
  153. package/dist/session/createSessionRouter.js +206 -0
  154. package/dist/{voice/handlers/dial → session}/index.d.ts +1 -1
  155. package/dist/{voice/handlers/dial → session}/index.js +1 -1
  156. package/dist/usage/buildService.d.ts +16 -0
  157. package/dist/{voice/integrations/getTtsConfig.js → usage/buildService.js} +13 -7
  158. package/dist/{voice/tts/utils/convertUlawToPCM16.d.ts → usage/createGetUsage.d.ts} +7 -6
  159. package/dist/usage/createGetUsage.js +118 -0
  160. package/dist/usage/ingestUsage.d.ts +7 -0
  161. package/dist/usage/ingestUsage.js +87 -0
  162. package/dist/usage/publishRecordedUsage.d.ts +52 -0
  163. package/dist/usage/publishRecordedUsage.js +103 -0
  164. package/dist/{utils/createHandleDialEventsWithNats.d.ts → usage/publishUsage.d.ts} +10 -4
  165. package/dist/usage/publishUsage.js +50 -0
  166. package/dist/usage/rebuildUsage.d.ts +48 -0
  167. package/dist/usage/rebuildUsage.js +104 -0
  168. package/dist/usage/runUsageConsumer.d.ts +22 -0
  169. package/dist/usage/runUsageConsumer.js +78 -0
  170. package/dist/usage/snapshotStorage.d.ts +14 -0
  171. package/dist/usage/snapshotStorage.js +95 -0
  172. package/dist/{voice/integrations/getTtsConfig.d.ts → usage/types.d.ts} +17 -6
  173. package/dist/utils/createCheckNumberPreconditions.js +4 -0
  174. package/dist/utils/index.d.ts +0 -2
  175. package/dist/utils/index.js +0 -2
  176. package/dist/voice/stt/Deepgram.d.ts +4 -57
  177. package/dist/voice/stt/Deepgram.js +15 -286
  178. package/dist/voice/stt/Google.d.ts +4 -15
  179. package/dist/voice/stt/Google.js +7 -103
  180. package/dist/voice/stt/types.d.ts +2 -38
  181. package/dist/voice/stt/types.js +25 -3
  182. package/dist/voice/tts/Azure.d.ts +4 -34
  183. package/dist/voice/tts/Azure.js +25 -105
  184. package/dist/voice/tts/Deepgram.d.ts +4 -38
  185. package/dist/voice/tts/Deepgram.js +25 -82
  186. package/dist/voice/tts/ElevenLabs.d.ts +4 -18
  187. package/dist/voice/tts/ElevenLabs.js +6 -97
  188. package/dist/voice/tts/Google.d.ts +4 -38
  189. package/dist/voice/tts/Google.js +25 -91
  190. package/dist/webhooks/createWebhooksHandlers.d.ts +37 -0
  191. package/dist/webhooks/createWebhooksHandlers.js +217 -0
  192. package/dist/webhooks/index.d.ts +37 -0
  193. package/dist/webhooks/index.js +51 -0
  194. package/dist/webhooks/lostCalls.d.ts +49 -0
  195. package/dist/webhooks/lostCalls.js +147 -0
  196. package/dist/webhooks/nodeCallEvents.d.ts +73 -0
  197. package/dist/webhooks/nodeCallEvents.js +177 -0
  198. package/dist/webhooks/runWebhookFanout.d.ts +44 -0
  199. package/dist/webhooks/runWebhookFanout.js +202 -0
  200. package/package.json +21 -31
  201. package/dist/applications/utils/applicationWithEncodedStruct.d.ts +0 -3
  202. package/dist/applications/utils/applicationWithEncodedStruct.js +0 -50
  203. package/dist/applications/utils/convertToApplicationData.js +0 -37
  204. package/dist/applications/validation/assistantWithoutApiKeySchema.d.ts +0 -786
  205. package/dist/applications/validation/assistantWithoutApiKeySchema.js +0 -35
  206. package/dist/applications/validation/createValidationSchema.d.ts +0 -1474
  207. package/dist/applications/validation/createValidationSchema.js +0 -67
  208. package/dist/applications/validation/prepareForValidation.d.ts +0 -21
  209. package/dist/applications/validation/prepareForValidation.js +0 -35
  210. package/dist/applications/validation/speechValidators.d.ts +0 -47
  211. package/dist/applications/validation/speechValidators.js +0 -50
  212. package/dist/applications/validation/validOrThrow.d.ts +0 -21
  213. package/dist/applications/validation/validOrThrow.js +0 -15
  214. package/dist/calls/createFetchCalls.d.ts +0 -22
  215. package/dist/calls/createFetchCalls.js +0 -88
  216. package/dist/calls/createFetchSingleCall.d.ts +0 -22
  217. package/dist/calls/influxdb.d.ts +0 -2
  218. package/dist/calls/runCallManager.d.ts +0 -8
  219. package/dist/calls/runCallManager.js +0 -75
  220. package/dist/core/buildWelcomeDemoService.js +0 -97
  221. package/dist/core/upsertDefaultPeer.d.ts +0 -2
  222. package/dist/events/amdResultCache.d.ts +0 -23
  223. package/dist/events/amdResultCache.js +0 -35
  224. package/dist/events/createInfluxDbPub.d.ts +0 -13
  225. package/dist/events/createInfluxDbPub.js +0 -89
  226. package/dist/events/createPerCallCache.js +0 -46
  227. package/dist/events/mapCallDirectionToEnum.d.ts +0 -21
  228. package/dist/events/mapCallDirectionToEnum.js +0 -37
  229. package/dist/events/nats.d.ts +0 -10
  230. package/dist/events/nats.js +0 -82
  231. package/dist/events/transformEvent.d.ts +0 -2
  232. package/dist/events/transformEvent.js +0 -87
  233. package/dist/events/types.d.ts +0 -26
  234. package/dist/utils/createHandleDialEventsWithNats.js +0 -24
  235. package/dist/utils/createHandleDialEventsWithVoiceClient.d.ts +0 -23
  236. package/dist/utils/createHandleDialEventsWithVoiceClient.js +0 -27
  237. package/dist/utils/getIntegrationsFromFile.d.ts +0 -2
  238. package/dist/utils/getIntegrationsFromFile.js +0 -49
  239. package/dist/utils/mapDialStatus.d.ts +0 -21
  240. package/dist/utils/mapDialStatus.js +0 -38
  241. package/dist/voice/VoiceDispatcher.d.ts +0 -21
  242. package/dist/voice/VoiceDispatcher.js +0 -122
  243. package/dist/voice/amd/mapAsteriskAmd.d.ts +0 -38
  244. package/dist/voice/amd/mapAsteriskAmd.js +0 -68
  245. package/dist/voice/client/AudioSocketHandler.d.ts +0 -38
  246. package/dist/voice/client/AudioSocketHandler.js +0 -70
  247. package/dist/voice/client/AuthorizationHandler.d.ts +0 -13
  248. package/dist/voice/client/AuthorizationHandler.js +0 -78
  249. package/dist/voice/client/ExternalMediaHandler.d.ts +0 -32
  250. package/dist/voice/client/ExternalMediaHandler.js +0 -59
  251. package/dist/voice/client/GrpcClientHandler.d.ts +0 -36
  252. package/dist/voice/client/SpeechHandler.d.ts +0 -60
  253. package/dist/voice/client/SpeechHandler.js +0 -120
  254. package/dist/voice/client/VoiceClientImpl.d.ts +0 -79
  255. package/dist/voice/client/VoiceClientImpl.js +0 -198
  256. package/dist/voice/connectToAri.d.ts +0 -2
  257. package/dist/voice/connectToAri.js +0 -81
  258. package/dist/voice/createCreateVoiceClient.d.ts +0 -9
  259. package/dist/voice/createCreateVoiceClient.js +0 -97
  260. package/dist/voice/errors/ChannelVarNotFoundError.d.ts +0 -23
  261. package/dist/voice/errors/ChannelVarNotFoundError.js +0 -10
  262. package/dist/voice/errors/MethodNotImplementedError.d.ts +0 -22
  263. package/dist/voice/errors/MethodNotImplementedError.js +0 -27
  264. package/dist/voice/filters/AudioFilterFactory.d.ts +0 -35
  265. package/dist/voice/filters/AudioFilterFactory.js +0 -94
  266. package/dist/voice/filters/aiCoustics/createAiCousticsFilter.d.ts +0 -64
  267. package/dist/voice/filters/aiCoustics/createAiCousticsFilter.js +0 -252
  268. package/dist/voice/filters/aiCoustics/types.d.ts +0 -45
  269. package/dist/voice/filters/aiCoustics/types.js +0 -29
  270. package/dist/voice/filters/createAudioFilterChain.d.ts +0 -9
  271. package/dist/voice/filters/createAudioFilterChain.js +0 -171
  272. package/dist/voice/filters/createAudioFilterSession.d.ts +0 -15
  273. package/dist/voice/filters/createAudioFilterSession.js +0 -114
  274. package/dist/voice/filters/pcm.d.ts +0 -21
  275. package/dist/voice/filters/pcm.js +0 -37
  276. package/dist/voice/filters/types.d.ts +0 -61
  277. package/dist/voice/filters/types.js +0 -26
  278. package/dist/voice/handlers/createAnswerHandler.d.ts +0 -23
  279. package/dist/voice/handlers/createAnswerHandler.js +0 -24
  280. package/dist/voice/handlers/createHangupHandler.d.ts +0 -23
  281. package/dist/voice/handlers/createHangupHandler.js +0 -28
  282. package/dist/voice/handlers/createMuteHandler.d.ts +0 -4
  283. package/dist/voice/handlers/createMuteHandler.js +0 -27
  284. package/dist/voice/handlers/createPlayDtmfHandler.d.ts +0 -4
  285. package/dist/voice/handlers/createPlayDtmfHandler.js +0 -27
  286. package/dist/voice/handlers/createPlayHandler.d.ts +0 -4
  287. package/dist/voice/handlers/createPlayHandler.js +0 -33
  288. package/dist/voice/handlers/createPlaybackControlHandler.d.ts +0 -4
  289. package/dist/voice/handlers/createPlaybackControlHandler.js +0 -62
  290. package/dist/voice/handlers/createRecordHandler.d.ts +0 -4
  291. package/dist/voice/handlers/createRecordHandler.js +0 -58
  292. package/dist/voice/handlers/createSayHandler.d.ts +0 -4
  293. package/dist/voice/handlers/createSayHandler.js +0 -31
  294. package/dist/voice/handlers/createSetAudioFiltersHandler.d.ts +0 -11
  295. package/dist/voice/handlers/createSetAudioFiltersHandler.js +0 -74
  296. package/dist/voice/handlers/createStopSayHandler.d.ts +0 -3
  297. package/dist/voice/handlers/createStopSayHandler.js +0 -34
  298. package/dist/voice/handlers/createStreamGatherHandler.d.ts +0 -3
  299. package/dist/voice/handlers/createStreamGatherHandler.js +0 -74
  300. package/dist/voice/handlers/createStreamHandler.d.ts +0 -3
  301. package/dist/voice/handlers/createStreamHandler.js +0 -70
  302. package/dist/voice/handlers/createUnmuteHandler.d.ts +0 -4
  303. package/dist/voice/handlers/createUnmuteHandler.js +0 -27
  304. package/dist/voice/handlers/dial/createDialHandler.d.ts +0 -23
  305. package/dist/voice/handlers/dial/createDialHandler.js +0 -78
  306. package/dist/voice/handlers/dial/handleChannelLeftBridge.d.ts +0 -24
  307. package/dist/voice/handlers/dial/handleChannelLeftBridge.js +0 -29
  308. package/dist/voice/handlers/dial/handleStasisEnd.d.ts +0 -21
  309. package/dist/voice/handlers/dial/handleStasisEnd.js +0 -19
  310. package/dist/voice/handlers/dial/handleStasisStart.d.ts +0 -27
  311. package/dist/voice/handlers/dial/handleStasisStart.js +0 -52
  312. package/dist/voice/handlers/dial/recordChannel.d.ts +0 -22
  313. package/dist/voice/handlers/gather/createGatherHandler.d.ts +0 -3
  314. package/dist/voice/handlers/gather/createGatherHandler.js +0 -86
  315. package/dist/voice/handlers/gather/getTimeoutPromise.d.ts +0 -26
  316. package/dist/voice/handlers/gather/getTimeoutPromise.js +0 -18
  317. package/dist/voice/handlers/index.d.ts +0 -33
  318. package/dist/voice/handlers/index.js +0 -49
  319. package/dist/voice/handlers/utils/awaitForPlaybackFinished.d.ts +0 -21
  320. package/dist/voice/handlers/utils/awaitForPlaybackFinished.js +0 -25
  321. package/dist/voice/handlers/utils/awaitForRecordingFinished.d.ts +0 -5
  322. package/dist/voice/handlers/utils/awaitForRecordingFinished.js +0 -53
  323. package/dist/voice/handlers/utils/isDtmf.d.ts +0 -20
  324. package/dist/voice/handlers/utils/textChunksByClause.d.ts +0 -2
  325. package/dist/voice/handlers/utils/textChunksByClause.js +0 -41
  326. package/dist/voice/handlers/utils/textChunksByFirstNaturalPause.d.ts +0 -2
  327. package/dist/voice/handlers/utils/textChunksByFirstNaturalPause.js +0 -34
  328. package/dist/voice/handlers/utils/withErrorHandling.d.ts +0 -22
  329. package/dist/voice/handlers/utils/withErrorHandling.js +0 -38
  330. package/dist/voice/integrations/ApplicationNotFoundError.d.ts +0 -22
  331. package/dist/voice/integrations/ApplicationNotFoundError.js +0 -28
  332. package/dist/voice/integrations/createCreateContainer.d.ts +0 -4
  333. package/dist/voice/integrations/createCreateContainer.js +0 -76
  334. package/dist/voice/integrations/getSttConfig.js +0 -30
  335. package/dist/voice/integrations/index.js +0 -35
  336. package/dist/voice/integrations/types.d.ts +0 -29
  337. package/dist/voice/stt/AbstractSpeechToText.d.ts +0 -33
  338. package/dist/voice/stt/AbstractSpeechToText.js +0 -19
  339. package/dist/voice/stt/SpeechToTextFactory.d.ts +0 -9
  340. package/dist/voice/stt/SpeechToTextFactory.js +0 -43
  341. package/dist/voice/transcribeOnConnection.d.ts +0 -35
  342. package/dist/voice/transcribeOnConnection.js +0 -91
  343. package/dist/voice/tts/AbstractTextToSpeech.d.ts +0 -40
  344. package/dist/voice/tts/AbstractTextToSpeech.js +0 -50
  345. package/dist/voice/tts/TextToSpeechFactory.d.ts +0 -8
  346. package/dist/voice/tts/TextToSpeechFactory.js +0 -47
  347. package/dist/voice/tts/types.d.ts +0 -48
  348. package/dist/voice/tts/types.js +0 -2
  349. package/dist/voice/tts/utils/convertUlawToPCM16.js +0 -40
  350. package/dist/voice/tts/utils/createChunkedSynthesisStream.d.ts +0 -28
  351. package/dist/voice/tts/utils/createChunkedSynthesisStream.js +0 -78
  352. package/dist/voice/tts/utils/createErrorStream.d.ts +0 -21
  353. package/dist/voice/tts/utils/createErrorStream.js +0 -28
  354. package/dist/voice/tts/utils/index.d.ts +0 -23
  355. package/dist/voice/tts/utils/index.js +0 -39
  356. package/dist/voice/tts/utils/isSsml.d.ts +0 -20
  357. package/dist/voice/tts/utils/isSsml.js +0 -25
  358. package/dist/voice/tts/utils/streamToBuffer.d.ts +0 -20
  359. package/dist/voice/tts/utils/streamToBuffer.js +0 -60
  360. package/dist/voice/types/ari.d.ts +0 -43
  361. package/dist/voice/types/ari.js +0 -48
  362. package/dist/voice/types/index.d.ts +0 -20
  363. package/dist/voice/types/index.js +0 -36
  364. package/dist/voice/types/voice.d.ts +0 -67
  365. package/dist/voice/types/voice.js +0 -2
  366. package/dist/voice/utils/VoiceServiceClientConstructor.d.ts +0 -3
  367. package/dist/voice/utils/createExternalMediaConfig.d.ts +0 -12
  368. package/dist/voice/utils/createExternalMediaConfig.js +0 -37
  369. package/dist/voice/utils/createGetChannelVar.d.ts +0 -22
  370. package/dist/voice/utils/createGetChannelVar.js +0 -27
  371. package/dist/voice/utils/createGetChannelVarWithoutThrow.d.ts +0 -22
  372. package/dist/voice/utils/createGetChannelVarWithoutThrow.js +0 -26
  373. package/dist/voice/utils/index.d.ts +0 -22
  374. package/dist/voice/utils/index.js +0 -38
  375. /package/dist/{events → records}/types.js +0 -0
  376. /package/dist/{voice/integrations → usage}/types.js +0 -0
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SessionIdentityError = exports.CSRF_HEADER = exports.SESSION_COOKIE = exports.SESSION_PATH = void 0;
16
+ exports.createSessionRouter = createSessionRouter;
17
+ exports.identityFromHandlers = identityFromHandlers;
18
+ /**
19
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
20
+ * http://github.com/fonoster/fonoster
21
+ *
22
+ * This file is part of Fonoster
23
+ *
24
+ * Licensed under the MIT License (the "License");
25
+ * you may not use this file except in compliance with
26
+ * the License. You may obtain a copy of the License at
27
+ *
28
+ * https://opensource.org/licenses/MIT
29
+ *
30
+ * Unless required by applicable law or agreed to in writing, software
31
+ * distributed under the License is distributed on an "AS IS" BASIS,
32
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
+ * See the License for the specific language governing permissions and
34
+ * limitations under the License.
35
+ */
36
+ const logger_1 = require("@fonoster/logger");
37
+ const grpc_js_1 = require("@grpc/grpc-js");
38
+ const express_1 = __importDefault(require("express"));
39
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
40
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
41
+ /** Where the router is mounted; the cookie is scoped to this path (M4). */
42
+ exports.SESSION_PATH = "/api/session";
43
+ /** The httpOnly cookie that holds the dashboard's refresh token. */
44
+ exports.SESSION_COOKIE = "fonoster_session";
45
+ /** Required on every request, so a plain cross-site form or link can't use the cookie. */
46
+ exports.CSRF_HEADER = "x-requested-with";
47
+ /** Rejection from Identity: a gRPC status code. */
48
+ class SessionIdentityError extends Error {
49
+ constructor(code, message) {
50
+ super(message);
51
+ this.code = code;
52
+ }
53
+ }
54
+ exports.SessionIdentityError = SessionIdentityError;
55
+ /** Codes that mean "this refresh token is no good", not "Identity is down". */
56
+ const REFUSED = new Set([
57
+ grpc_js_1.status.UNAUTHENTICATED,
58
+ grpc_js_1.status.PERMISSION_DENIED,
59
+ grpc_js_1.status.INVALID_ARGUMENT,
60
+ grpc_js_1.status.NOT_FOUND
61
+ ]);
62
+ function readCookie(req, name) {
63
+ var _a;
64
+ const part = ((_a = req.headers.cookie) !== null && _a !== void 0 ? _a : "")
65
+ .split(";")
66
+ .map((p) => p.trim())
67
+ .find((p) => p.startsWith(`${name}=`));
68
+ if (!part)
69
+ return undefined;
70
+ try {
71
+ return decodeURIComponent(part.slice(name.length + 1)) || undefined;
72
+ }
73
+ catch (_b) {
74
+ return undefined;
75
+ }
76
+ }
77
+ /** Seconds until the token's `exp`, or undefined when it has none. */
78
+ function secondsLeft(token) {
79
+ const claims = jsonwebtoken_1.default.decode(token);
80
+ if (!claims || typeof claims === "string" || typeof claims.exp !== "number")
81
+ return undefined;
82
+ return Math.max(0, claims.exp - Math.floor(Date.now() / 1000));
83
+ }
84
+ /**
85
+ * The dashboard's session (security review M4): the refresh token lives in an httpOnly,
86
+ * SameSite=Strict cookie scoped to /api/session, so page scripts (and any XSS) never read it;
87
+ * the dashboard keeps only the access and id tokens, in memory.
88
+ *
89
+ * POST /api/session {refreshToken}: adopts a token from a fresh sign-in. It is
90
+ * rotated at once, so the copy the page saw is already spent.
91
+ * POST /api/session/refresh rotates the cookie's token, returns new access and id tokens
92
+ * POST /api/session/logout revokes the cookie's token family and clears the cookie
93
+ *
94
+ * Every request needs the `X-Requested-With` header (CSRF, besides SameSite=Strict); without
95
+ * it the answer is 403. The responses carry {accessToken, idToken, expiresAt}, never the
96
+ * refresh token. Envoy serves this on the dashboard's origin (its existing /api route), so no
97
+ * CORS is involved. SDK and API clients are unaffected: they keep exchanging refresh tokens
98
+ * over gRPC.
99
+ */
100
+ function createSessionRouter(deps) {
101
+ const router = express_1.default.Router();
102
+ const cookieOptions = {
103
+ httpOnly: true,
104
+ secure: deps.secureCookie,
105
+ sameSite: "strict",
106
+ path: exports.SESSION_PATH
107
+ };
108
+ const setSession = (res, refreshToken) => {
109
+ const left = secondsLeft(refreshToken);
110
+ res.cookie(exports.SESSION_COOKIE, refreshToken, Object.assign(Object.assign({}, cookieOptions), (left !== undefined ? { maxAge: left * 1000 } : {})));
111
+ };
112
+ const clearSession = (res) => res.clearCookie(exports.SESSION_COOKIE, cookieOptions);
113
+ const body = (tokens) => {
114
+ const claims = jsonwebtoken_1.default.decode(tokens.accessToken);
115
+ const exp = claims && typeof claims !== "string" && typeof claims.exp === "number"
116
+ ? claims.exp
117
+ : undefined;
118
+ return Object.assign({ accessToken: tokens.accessToken, idToken: tokens.idToken }, (exp !== undefined ? { expiresAt: exp } : {}));
119
+ };
120
+ /** Rotates `refreshToken` and answers with the new session (or 401/503). */
121
+ const rotate = (res, refreshToken) => __awaiter(this, void 0, void 0, function* () {
122
+ try {
123
+ const tokens = yield deps.identity.exchangeRefreshToken(refreshToken);
124
+ setSession(res, tokens.refreshToken);
125
+ res.json(body(tokens));
126
+ }
127
+ catch (error) {
128
+ if (error instanceof SessionIdentityError && REFUSED.has(error.code)) {
129
+ clearSession(res);
130
+ res.status(401).json({ error: "invalid_session" });
131
+ return;
132
+ }
133
+ logger.warn("session refresh failed", {
134
+ error: error.message
135
+ });
136
+ res.status(503).json({ error: "unavailable" });
137
+ }
138
+ });
139
+ router.use((req, res, next) => {
140
+ res.setHeader("cache-control", "no-store");
141
+ if (req.method !== "POST") {
142
+ res.status(405).json({ error: "method_not_allowed" });
143
+ return;
144
+ }
145
+ if (!req.get(exports.CSRF_HEADER)) {
146
+ res.status(403).json({ error: "missing_csrf_header" });
147
+ return;
148
+ }
149
+ next();
150
+ });
151
+ router.post("/", express_1.default.json({ limit: "16kb" }), (req, res) => __awaiter(this, void 0, void 0, function* () {
152
+ var _a;
153
+ const refreshToken = (_a = req.body) === null || _a === void 0 ? void 0 : _a.refreshToken;
154
+ if (typeof refreshToken !== "string" || !refreshToken) {
155
+ res.status(400).json({ error: "refresh_token_required" });
156
+ return;
157
+ }
158
+ yield rotate(res, refreshToken);
159
+ }));
160
+ router.post("/refresh", (req, res) => __awaiter(this, void 0, void 0, function* () {
161
+ const refreshToken = readCookie(req, exports.SESSION_COOKIE);
162
+ if (!refreshToken) {
163
+ res.status(401).json({ error: "no_session" });
164
+ return;
165
+ }
166
+ yield rotate(res, refreshToken);
167
+ }));
168
+ router.post("/logout", (req, res) => __awaiter(this, void 0, void 0, function* () {
169
+ const refreshToken = readCookie(req, exports.SESSION_COOKIE);
170
+ clearSession(res);
171
+ if (refreshToken) {
172
+ // Best effort, like the SDK's logout: an already-refused token has nothing to revoke.
173
+ yield deps.identity.revokeToken(refreshToken).catch((error) => {
174
+ logger.verbose("session revoke failed", {
175
+ error: error.message
176
+ });
177
+ });
178
+ }
179
+ res.status(204).end();
180
+ }));
181
+ return router;
182
+ }
183
+ function unary(handler, request) {
184
+ return new Promise((resolve, reject) => {
185
+ Promise.resolve(handler({ request }, (error, response) => {
186
+ var _a, _b;
187
+ if (error)
188
+ reject(new SessionIdentityError((_a = error.code) !== null && _a !== void 0 ? _a : grpc_js_1.status.UNKNOWN, (_b = error.message) !== null && _b !== void 0 ? _b : "identity error"));
189
+ else
190
+ resolve(response);
191
+ })).catch(reject);
192
+ });
193
+ }
194
+ /** Binds the router to the in-process Identity service's gRPC handlers. */
195
+ function identityFromHandlers(handlers) {
196
+ const exchange = handlers.exchangeRefreshToken;
197
+ const revoke = handlers.revokeToken;
198
+ if (!exchange || !revoke)
199
+ throw new Error("the Identity service is not loaded in this apiserver");
200
+ return {
201
+ exchangeRefreshToken: (refreshToken) => unary(exchange, { refreshToken }),
202
+ revokeToken: (token) => __awaiter(this, void 0, void 0, function* () {
203
+ yield unary(revoke, { token });
204
+ })
205
+ };
206
+ }
@@ -16,4 +16,4 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
- export * from "./createDialHandler";
19
+ export * from "./createSessionRouter";
@@ -32,4 +32,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
32
32
  * See the License for the specific language governing permissions and
33
33
  * limitations under the License.
34
34
  */
35
- __exportStar(require("./createDialHandler"), exports);
35
+ __exportStar(require("./createSessionRouter"), exports);
@@ -0,0 +1,16 @@
1
+ import { UsageSql } from "./types";
2
+ /** The Usage gRPC service (usage.proto): what a workspace consumed, never money. */
3
+ declare function buildService(db: UsageSql): {
4
+ definition: {
5
+ serviceName: string;
6
+ pckg: string;
7
+ version: string;
8
+ proto: string;
9
+ };
10
+ handlers: {
11
+ getUsage: (call: {
12
+ request: unknown;
13
+ }, callback: (error?: import("@fonoster/common").GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
14
+ };
15
+ };
16
+ export { buildService };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTtsConfig = getTtsConfig;
3
+ exports.buildService = buildService;
4
4
  /**
5
5
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
6
6
  * http://github.com/fonoster/fonoster
@@ -19,12 +19,18 @@ exports.getTtsConfig = getTtsConfig;
19
19
  * See the License for the specific language governing permissions and
20
20
  * limitations under the License.
21
21
  */
22
- const common_1 = require("@fonoster/common");
23
- function getTtsConfig(integrations, app) {
24
- const config = app.textToSpeech.config;
25
- const credentials = (0, common_1.findIntegrationsCredentials)(integrations, app.textToSpeech.productRef);
22
+ const createGetUsage_1 = require("./createGetUsage");
23
+ /** The Usage gRPC service (usage.proto): what a workspace consumed, never money. */
24
+ function buildService(db) {
26
25
  return {
27
- config,
28
- credentials
26
+ definition: {
27
+ serviceName: "Usage",
28
+ pckg: "usage",
29
+ version: "v1beta2",
30
+ proto: "usage.proto"
31
+ },
32
+ handlers: {
33
+ getUsage: (0, createGetUsage_1.createGetUsage)(db)
34
+ }
29
35
  };
30
36
  }
@@ -16,11 +16,12 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
- import { Readable } from "stream";
19
+ import { GrpcErrorMessage } from "@fonoster/common";
20
+ import { UsageSql } from "./types";
20
21
  /**
21
- * Converts a ulaw stream to PCM 16-bit at 8kHz
22
- *
23
- * @param readableStream - The input ulaw audio stream to convert
24
- * @returns A Promise that resolves to a Buffer containing PCM 16-bit audio data at 8kHz
22
+ * Usage totals (usage-metering "Usage API"): quantities from usage_daily, never money. Each day is
23
+ * totalled first; across days counted meters add up and snapshot meters (storage) take the peak.
25
24
  */
26
- export declare function convertUlawToPCM16(readableStream: Readable): Promise<Buffer>;
25
+ export declare function createGetUsage(db: UsageSql): (call: {
26
+ request: unknown;
27
+ }, callback: (error?: import("@fonoster/common").GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createGetUsage = createGetUsage;
13
+ /**
14
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
15
+ * http://github.com/fonoster/fonoster
16
+ *
17
+ * This file is part of Fonoster
18
+ *
19
+ * Licensed under the MIT License (the "License");
20
+ * you may not use this file except in compliance with
21
+ * the License. You may obtain a copy of the License at
22
+ *
23
+ * https://opensource.org/licenses/MIT
24
+ *
25
+ * Unless required by applicable law or agreed to in writing, software
26
+ * distributed under the License is distributed on an "AS IS" BASIS,
27
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
+ * See the License for the specific language governing permissions and
29
+ * limitations under the License.
30
+ */
31
+ const common_1 = require("@fonoster/common");
32
+ const logger_1 = require("@fonoster/logger");
33
+ const types_1 = require("@fonoster/types");
34
+ const grpc_js_1 = require("@grpc/grpc-js");
35
+ const zod_1 = require("zod");
36
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
37
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
38
+ const MAX_DAYS = 400;
39
+ /** Dimension → its usage_daily column. Totals are always split by meter. */
40
+ const COLUMNS = {
41
+ day: "day",
42
+ workspace: "workspace_ref",
43
+ meter: "meter",
44
+ provider: "provider",
45
+ model: "model",
46
+ key_source: "key_source",
47
+ origin: "origin"
48
+ };
49
+ const schema = zod_1.z
50
+ .object({
51
+ fromDay: zod_1.z.string().regex(DAY, "fromDay must be YYYY-MM-DD"),
52
+ toDay: zod_1.z.string().regex(DAY, "toDay must be YYYY-MM-DD"),
53
+ groupBy: zod_1.z
54
+ .array(zod_1.z.enum(Object.keys(COLUMNS)))
55
+ .optional(),
56
+ allOwned: zod_1.z.boolean().optional()
57
+ })
58
+ .refine((r) => r.fromDay <= r.toDay, "fromDay must not be after toDay")
59
+ .refine((r) => (Date.parse(r.toDay) - Date.parse(r.fromDay)) / 86400000 < MAX_DAYS, `the range must be shorter than ${MAX_DAYS} days`);
60
+ const SNAPSHOT_METERS = common_1.Usage.METER_NAMES.filter((m) => common_1.Usage.METERS[m].aggregation === "snapshot");
61
+ /** The workspaces the caller may read: theirs, or (all_owned) every one their token says they own. */
62
+ function workspacesOf(call, allOwned) {
63
+ var _a;
64
+ const grpcCall = call;
65
+ if (!allOwned)
66
+ return [(0, common_1.getAccessKeyIdFromCall)(grpcCall)];
67
+ const token = (0, common_1.decodeToken)((0, common_1.getTokenFromCall)(grpcCall));
68
+ const owned = ((_a = token.access) !== null && _a !== void 0 ? _a : [])
69
+ .filter((a) => a.role === types_1.Role.WORKSPACE_OWNER)
70
+ .map((a) => a.accessKeyId);
71
+ if (!owned.length)
72
+ throw new common_1.GrpcError(grpc_js_1.status.PERMISSION_DENIED, "all_owned needs a workspace owner");
73
+ return owned;
74
+ }
75
+ /**
76
+ * Usage totals (usage-metering "Usage API"): quantities from usage_daily, never money. Each day is
77
+ * totalled first; across days counted meters add up and snapshot meters (storage) take the peak.
78
+ */
79
+ function createGetUsage(db) {
80
+ const fn = (call, callback) => __awaiter(this, void 0, void 0, function* () {
81
+ const { fromDay, toDay, groupBy = [], allOwned = false } = call.request;
82
+ const workspaces = workspacesOf(call, allOwned);
83
+ const dims = Array.from(new Set([...groupBy, "meter"]));
84
+ const others = dims.filter((d) => d !== "day").map((d) => COLUMNS[d]);
85
+ const perDay = ["day", ...others].join(", ");
86
+ const outer = dims.map((d) => COLUMNS[d]).join(", ");
87
+ logger.verbose("call to getUsage", { workspaces, fromDay, toDay, dims });
88
+ const rows = yield db.$queryRawUnsafe(`WITH per_day AS (
89
+ SELECT ${perDay}, SUM(quantity) AS q FROM usage_daily
90
+ WHERE workspace_ref = ANY($1::text[]) AND day BETWEEN $2::date AND $3::date
91
+ GROUP BY ${perDay}
92
+ )
93
+ SELECT ${outer},
94
+ CASE WHEN meter = ANY($4::text[]) THEN MAX(q) ELSE SUM(q) END AS quantity
95
+ FROM per_day GROUP BY ${outer} ORDER BY ${outer}`, workspaces, fromDay, toDay, SNAPSHOT_METERS);
96
+ const text = (v) => v instanceof Date
97
+ ? v.toISOString().slice(0, 10)
98
+ : v === undefined || v === null
99
+ ? ""
100
+ : String(v);
101
+ callback(null, {
102
+ rows: rows.map((r) => ({
103
+ day: text(r.day),
104
+ workspaceRef: text(r.workspace_ref),
105
+ meter: String(r.meter),
106
+ unit: common_1.Usage.isMeter(String(r.meter))
107
+ ? common_1.Usage.METERS[r.meter].unit
108
+ : "",
109
+ provider: text(r.provider),
110
+ model: text(r.model),
111
+ keySource: text(r.key_source),
112
+ origin: text(r.origin),
113
+ quantity: Number(r.quantity)
114
+ }))
115
+ });
116
+ });
117
+ return (0, common_1.withErrorHandlingAndValidation)(fn, schema);
118
+ }
@@ -0,0 +1,7 @@
1
+ import { UsageDirectory, UsageSql } from "./types";
2
+ /**
3
+ * Stores usage events in a transaction the caller owns (design D7): each event once, by its id,
4
+ * and the day's total grows only when the event was new, so a replay changes nothing. Events that
5
+ * fail validation are logged and skipped. Returns how many events were new.
6
+ */
7
+ export declare function ingestUsageIn(tx: UsageSql, directory: UsageDirectory, events: unknown[]): Promise<number>;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ingestUsageIn = ingestUsageIn;
13
+ /**
14
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
15
+ * http://github.com/fonoster/fonoster
16
+ *
17
+ * This file is part of Fonoster
18
+ *
19
+ * Licensed under the MIT License (the "License");
20
+ * you may not use this file except in compliance with
21
+ * the License. You may obtain a copy of the License at
22
+ *
23
+ * https://opensource.org/licenses/MIT
24
+ *
25
+ * Unless required by applicable law or agreed to in writing, software
26
+ * distributed under the License is distributed on an "AS IS" BASIS,
27
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28
+ * See the License for the specific language governing permissions and
29
+ * limitations under the License.
30
+ */
31
+ const common_1 = require("@fonoster/common");
32
+ const logger_1 = require("@fonoster/logger");
33
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
34
+ const INSERT_EVENT = `
35
+ INSERT INTO usage_events (id, owner_ref, workspace_ref, app_ref, call_ref, region, region_kind,
36
+ origin, meter, unit, quantity, provider, model, key_source, occurred_at)
37
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
38
+ ON CONFLICT (id) DO NOTHING
39
+ RETURNING id`;
40
+ const upsertDaily = (aggregation) => `
41
+ INSERT INTO usage_daily (owner_ref, workspace_ref, day, meter, provider, model, key_source,
42
+ origin, region_kind, quantity, updated_at)
43
+ VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, $10, now())
44
+ ON CONFLICT (owner_ref, workspace_ref, day, meter, provider, model, key_source, origin, region_kind)
45
+ DO UPDATE SET quantity = ${aggregation === "sum"
46
+ ? "usage_daily.quantity + EXCLUDED.quantity"
47
+ : "EXCLUDED.quantity"}, updated_at = now()`;
48
+ /**
49
+ * Stores usage events in a transaction the caller owns (design D7): each event once, by its id,
50
+ * and the day's total grows only when the event was new, so a replay changes nothing. Events that
51
+ * fail validation are logged and skipped. Returns how many events were new.
52
+ */
53
+ function ingestUsageIn(tx, directory, events) {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
56
+ const owners = new Map();
57
+ const ownerOf = (workspaceRef) => __awaiter(this, void 0, void 0, function* () {
58
+ var _a;
59
+ if (!owners.has(workspaceRef)) {
60
+ const ws = yield directory.workspace(workspaceRef).catch(() => undefined);
61
+ if (!ws)
62
+ logger.warn(`usage for unknown workspace ${workspaceRef}; owner left empty`);
63
+ owners.set(workspaceRef, (_a = ws === null || ws === void 0 ? void 0 : ws.ownerRef) !== null && _a !== void 0 ? _a : "");
64
+ }
65
+ return owners.get(workspaceRef);
66
+ });
67
+ let inserted = 0;
68
+ for (const input of events) {
69
+ let event;
70
+ try {
71
+ event = common_1.Usage.parseUsageEvent(input);
72
+ }
73
+ catch (e) {
74
+ logger.warn(`usage line rejected: ${e.message}`);
75
+ continue;
76
+ }
77
+ const meter = common_1.Usage.meterOf(event.meter);
78
+ const ownerRef = (_a = event.ownerRef) !== null && _a !== void 0 ? _a : (yield ownerOf(event.workspaceRef));
79
+ const rows = yield tx.$queryRawUnsafe(INSERT_EVENT, event.id, ownerRef, event.workspaceRef, (_b = event.appRef) !== null && _b !== void 0 ? _b : null, (_c = event.callRef) !== null && _c !== void 0 ? _c : null, event.region, event.regionKind, event.origin, event.meter, meter.unit, BigInt(Math.round(event.quantity)), (_d = event.provider) !== null && _d !== void 0 ? _d : null, (_e = event.model) !== null && _e !== void 0 ? _e : null, (_f = event.keySource) !== null && _f !== void 0 ? _f : null, new Date(event.occurredAt));
80
+ if (rows.length === 0)
81
+ continue;
82
+ inserted++;
83
+ yield tx.$executeRawUnsafe(upsertDaily(meter.aggregation), ownerRef, event.workspaceRef, event.occurredAt.slice(0, 10), event.meter, (_g = event.provider) !== null && _g !== void 0 ? _g : "", (_h = event.model) !== null && _h !== void 0 ? _h : "", (_j = event.keySource) !== null && _j !== void 0 ? _j : "", event.origin, event.regionKind, BigInt(Math.round(event.quantity)));
84
+ }
85
+ return inserted;
86
+ });
87
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { Usage } from "@fonoster/common";
20
+ import { NatsConnection } from "nats";
21
+ import { UsageSql } from "./types";
22
+ /**
23
+ * Stored usage for billing (add-billing-service D2). Not under `usage.>`, which FONOSTER_USAGE
24
+ * owns: these are facts already stored, not usage to store.
25
+ */
26
+ export declare const RECORDED_USAGE_STREAM = "FONOSTER_USAGE_RECORDED";
27
+ export declare const RECORDED_USAGE_SUBJECTS = "billing.usage.>";
28
+ /** Kept this long while billing is not consuming. */
29
+ export declare const RECORDED_USAGE_MAX_AGE_MS: number;
30
+ /** The subject an owner's stored usage is published on. */
31
+ export declare const recordedUsageSubject: (ownerRef: string) => string;
32
+ /** A stored usage event as billing receives it: the usage.v1 event plus its owner. */
33
+ export type RecordedUsage = Usage.UsageEvent & {
34
+ ownerRef: string;
35
+ };
36
+ /** Creates the stream billing consumes, if it does not exist. */
37
+ export declare function ensureRecordedUsageStream(nc: NatsConnection): Promise<void>;
38
+ /**
39
+ * Publishes one batch of unpublished usage, oldest first, each with its usage id as the message id
40
+ * (JetStream drops a repeat), then marks the batch published. A crash between the two only
41
+ * publishes the batch again. Returns how many were published.
42
+ */
43
+ export declare function publishRecordedUsageOnce(nc: NatsConnection, db: UsageSql, batch?: number): Promise<number>;
44
+ /**
45
+ * Runs the billing outbox (only when billing is enabled): publishes stored usage until none is
46
+ * left, then waits `intervalMs`. Errors are logged and retried. Returns a stop function.
47
+ */
48
+ export declare function runRecordedUsagePublisher(deps: {
49
+ nc: NatsConnection;
50
+ db: UsageSql;
51
+ intervalMs?: number;
52
+ }): Promise<() => void>;
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.recordedUsageSubject = exports.RECORDED_USAGE_MAX_AGE_MS = exports.RECORDED_USAGE_SUBJECTS = exports.RECORDED_USAGE_STREAM = void 0;
13
+ exports.ensureRecordedUsageStream = ensureRecordedUsageStream;
14
+ exports.publishRecordedUsageOnce = publishRecordedUsageOnce;
15
+ exports.runRecordedUsagePublisher = runRecordedUsagePublisher;
16
+ const logger_1 = require("@fonoster/logger");
17
+ const nats_1 = require("nats");
18
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
19
+ const sc = (0, nats_1.StringCodec)();
20
+ /**
21
+ * Stored usage for billing (add-billing-service D2). Not under `usage.>`, which FONOSTER_USAGE
22
+ * owns: these are facts already stored, not usage to store.
23
+ */
24
+ exports.RECORDED_USAGE_STREAM = "FONOSTER_USAGE_RECORDED";
25
+ exports.RECORDED_USAGE_SUBJECTS = "billing.usage.>";
26
+ /** Kept this long while billing is not consuming. */
27
+ exports.RECORDED_USAGE_MAX_AGE_MS = 7 * 24 * 3600000;
28
+ /** The subject an owner's stored usage is published on. */
29
+ const recordedUsageSubject = (ownerRef) => `billing.usage.${ownerRef}`;
30
+ exports.recordedUsageSubject = recordedUsageSubject;
31
+ const toRecorded = (r) => (Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ id: r.id, ownerRef: r.owner_ref, workspaceRef: r.workspace_ref }, (r.app_ref ? { appRef: r.app_ref } : {})), (r.call_ref ? { callRef: r.call_ref } : {})), { region: r.region, regionKind: r.region_kind, origin: r.origin, meter: r.meter, quantity: Number(r.quantity) }), (r.provider ? { provider: r.provider } : {})), (r.model ? { model: r.model } : {})), (r.key_source ? { keySource: r.key_source } : {})), { occurredAt: r.occurred_at.toISOString() }));
32
+ const inUse = (e) => { var _a; return /already in use|already exists/i.test((_a = e.message) !== null && _a !== void 0 ? _a : ""); };
33
+ /** Creates the stream billing consumes, if it does not exist. */
34
+ function ensureRecordedUsageStream(nc) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ const jsm = yield nc.jetstreamManager();
37
+ try {
38
+ yield jsm.streams.info(exports.RECORDED_USAGE_STREAM);
39
+ }
40
+ catch (_a) {
41
+ yield jsm.streams
42
+ .add({
43
+ name: exports.RECORDED_USAGE_STREAM,
44
+ subjects: [exports.RECORDED_USAGE_SUBJECTS],
45
+ retention: nats_1.RetentionPolicy.Workqueue,
46
+ storage: nats_1.StorageType.File,
47
+ max_age: (0, nats_1.nanos)(exports.RECORDED_USAGE_MAX_AGE_MS)
48
+ })
49
+ .catch((e) => {
50
+ // Another replica created it at the same moment.
51
+ if (!inUse(e))
52
+ throw e;
53
+ });
54
+ }
55
+ });
56
+ }
57
+ /**
58
+ * Publishes one batch of unpublished usage, oldest first, each with its usage id as the message id
59
+ * (JetStream drops a repeat), then marks the batch published. A crash between the two only
60
+ * publishes the batch again. Returns how many were published.
61
+ */
62
+ function publishRecordedUsageOnce(nc_1, db_1) {
63
+ return __awaiter(this, arguments, void 0, function* (nc, db, batch = 500) {
64
+ const rows = yield db.$queryRawUnsafe(`SELECT id, owner_ref, workspace_ref, app_ref, call_ref, region, region_kind, origin, meter,
65
+ quantity, provider, model, key_source, occurred_at
66
+ FROM usage_events WHERE published_at IS NULL ORDER BY recorded_at, id LIMIT $1`, batch);
67
+ if (!rows.length)
68
+ return 0;
69
+ const js = nc.jetstream();
70
+ for (const row of rows)
71
+ yield js.publish((0, exports.recordedUsageSubject)(row.owner_ref), sc.encode(JSON.stringify(toRecorded(row))), { msgID: row.id });
72
+ yield db.$executeRawUnsafe(`UPDATE usage_events SET published_at = now() WHERE id = ANY($1::varchar[])`, rows.map((r) => r.id));
73
+ return rows.length;
74
+ });
75
+ }
76
+ /**
77
+ * Runs the billing outbox (only when billing is enabled): publishes stored usage until none is
78
+ * left, then waits `intervalMs`. Errors are logged and retried. Returns a stop function.
79
+ */
80
+ function runRecordedUsagePublisher(deps) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ yield ensureRecordedUsageStream(deps.nc);
83
+ let stopped = false;
84
+ let timer;
85
+ const tick = () => __awaiter(this, void 0, void 0, function* () {
86
+ var _a;
87
+ try {
88
+ while (!stopped && (yield publishRecordedUsageOnce(deps.nc, deps.db)))
89
+ ;
90
+ }
91
+ catch (e) {
92
+ logger.warn(`usage not published for billing yet: ${e.message}`);
93
+ }
94
+ if (!stopped)
95
+ timer = setTimeout(tick, (_a = deps.intervalMs) !== null && _a !== void 0 ? _a : 1000);
96
+ });
97
+ void tick();
98
+ return () => {
99
+ stopped = true;
100
+ clearTimeout(timer);
101
+ };
102
+ });
103
+ }