@nodestackapp/server 0.0.0-stage → 1.3.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 (348) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/bin/nodebase.js +4 -0
  4. package/bin/nodestack.js +21 -0
  5. package/dist/NodeBase.d.ts +2 -0
  6. package/dist/NodeBase.d.ts.map +1 -0
  7. package/dist/NodeBase.js +8 -0
  8. package/dist/NodeBase.js.map +1 -0
  9. package/dist/NodeStack.d.ts +106 -0
  10. package/dist/NodeStack.d.ts.map +1 -0
  11. package/dist/NodeStack.js +298 -0
  12. package/dist/NodeStack.js.map +1 -0
  13. package/dist/admin/AdminUIBundler.d.ts +8 -0
  14. package/dist/admin/AdminUIBundler.d.ts.map +1 -0
  15. package/dist/admin/AdminUIBundler.js +103 -0
  16. package/dist/admin/AdminUIBundler.js.map +1 -0
  17. package/dist/admin/AdminUIService.d.ts +30 -0
  18. package/dist/admin/AdminUIService.d.ts.map +1 -0
  19. package/dist/admin/AdminUIService.js +210 -0
  20. package/dist/admin/AdminUIService.js.map +1 -0
  21. package/dist/admin/DocsService.d.ts +29 -0
  22. package/dist/admin/DocsService.d.ts.map +1 -0
  23. package/dist/admin/DocsService.js +564 -0
  24. package/dist/admin/DocsService.js.map +1 -0
  25. package/dist/admin/ui/css/analytics.css +325 -0
  26. package/dist/admin/ui/css/main.css +2015 -0
  27. package/dist/admin/ui/css/rules.css +264 -0
  28. package/dist/admin/ui/css/webhooks.css +336 -0
  29. package/dist/admin/ui/favicon.svg +17 -0
  30. package/dist/admin/ui/icon.svg +17 -0
  31. package/dist/admin/ui/index.html +14584 -0
  32. package/dist/admin/ui/js/analytics.js +624 -0
  33. package/dist/admin/ui/js/api.js +353 -0
  34. package/dist/admin/ui/js/app.js +263 -0
  35. package/dist/admin/ui/js/apps.js +436 -0
  36. package/dist/admin/ui/js/collections.js +436 -0
  37. package/dist/admin/ui/js/command-palette.js +600 -0
  38. package/dist/admin/ui/js/demo.js +559 -0
  39. package/dist/admin/ui/js/modals.js +2379 -0
  40. package/dist/admin/ui/js/plugin-tester.js +559 -0
  41. package/dist/admin/ui/js/plugins.js +768 -0
  42. package/dist/admin/ui/js/records.js +1270 -0
  43. package/dist/admin/ui/js/rules.js +775 -0
  44. package/dist/admin/ui/js/schema.js +290 -0
  45. package/dist/admin/ui/js/state.js +140 -0
  46. package/dist/admin/ui/js/views.js +714 -0
  47. package/dist/admin/ui/js/webhooks.js +1086 -0
  48. package/dist/analytics/AnalyticsService.d.ts +62 -0
  49. package/dist/analytics/AnalyticsService.d.ts.map +1 -0
  50. package/dist/analytics/AnalyticsService.js +196 -0
  51. package/dist/analytics/AnalyticsService.js.map +1 -0
  52. package/dist/apps/AppManager.d.ts +28 -0
  53. package/dist/apps/AppManager.d.ts.map +1 -0
  54. package/dist/apps/AppManager.js +211 -0
  55. package/dist/apps/AppManager.js.map +1 -0
  56. package/dist/apps/AppRegistry.d.ts +27 -0
  57. package/dist/apps/AppRegistry.d.ts.map +1 -0
  58. package/dist/apps/AppRegistry.js +220 -0
  59. package/dist/apps/AppRegistry.js.map +1 -0
  60. package/dist/apps/AppScope.d.ts +55 -0
  61. package/dist/apps/AppScope.d.ts.map +1 -0
  62. package/dist/apps/AppScope.js +295 -0
  63. package/dist/apps/AppScope.js.map +1 -0
  64. package/dist/apps/index.d.ts +5 -0
  65. package/dist/apps/index.d.ts.map +1 -0
  66. package/dist/apps/index.js +21 -0
  67. package/dist/apps/index.js.map +1 -0
  68. package/dist/apps/models/App.d.ts +29 -0
  69. package/dist/apps/models/App.d.ts.map +1 -0
  70. package/dist/apps/models/App.js +3 -0
  71. package/dist/apps/models/App.js.map +1 -0
  72. package/dist/audit/AuditLogService.d.ts +68 -0
  73. package/dist/audit/AuditLogService.d.ts.map +1 -0
  74. package/dist/audit/AuditLogService.js +243 -0
  75. package/dist/audit/AuditLogService.js.map +1 -0
  76. package/dist/auth/AuthService.d.ts +35 -0
  77. package/dist/auth/AuthService.d.ts.map +1 -0
  78. package/dist/auth/AuthService.js +276 -0
  79. package/dist/auth/AuthService.js.map +1 -0
  80. package/dist/cli/cli.d.ts +3 -0
  81. package/dist/cli/cli.d.ts.map +1 -0
  82. package/dist/cli/cli.js +477 -0
  83. package/dist/cli/cli.js.map +1 -0
  84. package/dist/core/config/ConfigService.d.ts +41 -0
  85. package/dist/core/config/ConfigService.d.ts.map +1 -0
  86. package/dist/core/config/ConfigService.js +139 -0
  87. package/dist/core/config/ConfigService.js.map +1 -0
  88. package/dist/core/config/EnvLoader.d.ts +7 -0
  89. package/dist/core/config/EnvLoader.d.ts.map +1 -0
  90. package/dist/core/config/EnvLoader.js +84 -0
  91. package/dist/core/config/EnvLoader.js.map +1 -0
  92. package/dist/core/container/Container.d.ts +34 -0
  93. package/dist/core/container/Container.d.ts.map +1 -0
  94. package/dist/core/container/Container.js +98 -0
  95. package/dist/core/container/Container.js.map +1 -0
  96. package/dist/core/container/Tokens.d.ts +40 -0
  97. package/dist/core/container/Tokens.d.ts.map +1 -0
  98. package/dist/core/container/Tokens.js +40 -0
  99. package/dist/core/container/Tokens.js.map +1 -0
  100. package/dist/core/errors/AppError.d.ts +24 -0
  101. package/dist/core/errors/AppError.d.ts.map +1 -0
  102. package/dist/core/errors/AppError.js +52 -0
  103. package/dist/core/errors/AppError.js.map +1 -0
  104. package/dist/core/events/EventBus.d.ts +45 -0
  105. package/dist/core/events/EventBus.d.ts.map +1 -0
  106. package/dist/core/events/EventBus.js +360 -0
  107. package/dist/core/events/EventBus.js.map +1 -0
  108. package/dist/core/events/types.d.ts +35 -0
  109. package/dist/core/events/types.d.ts.map +1 -0
  110. package/dist/core/events/types.js +3 -0
  111. package/dist/core/events/types.js.map +1 -0
  112. package/dist/core/maintenance/MaintenanceGate.d.ts +65 -0
  113. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -0
  114. package/dist/core/maintenance/MaintenanceGate.js +162 -0
  115. package/dist/core/maintenance/MaintenanceGate.js.map +1 -0
  116. package/dist/core/plugins/PluginManager.d.ts +150 -0
  117. package/dist/core/plugins/PluginManager.d.ts.map +1 -0
  118. package/dist/core/plugins/PluginManager.js +1592 -0
  119. package/dist/core/plugins/PluginManager.js.map +1 -0
  120. package/dist/core/plugins/types.d.ts +170 -0
  121. package/dist/core/plugins/types.d.ts.map +1 -0
  122. package/dist/core/plugins/types.js +3 -0
  123. package/dist/core/plugins/types.js.map +1 -0
  124. package/dist/database/DatabaseService.d.ts +27 -0
  125. package/dist/database/DatabaseService.d.ts.map +1 -0
  126. package/dist/database/DatabaseService.js +97 -0
  127. package/dist/database/DatabaseService.js.map +1 -0
  128. package/dist/database/drivers/IDatabaseDriver.d.ts +17 -0
  129. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -0
  130. package/dist/database/drivers/IDatabaseDriver.js +3 -0
  131. package/dist/database/drivers/IDatabaseDriver.js.map +1 -0
  132. package/dist/database/drivers/NodeSqliteDriver.d.ts +16 -0
  133. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -0
  134. package/dist/database/drivers/NodeSqliteDriver.js +115 -0
  135. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -0
  136. package/dist/database/migrations/SystemMigrations.d.ts +5 -0
  137. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -0
  138. package/dist/database/migrations/SystemMigrations.js +164 -0
  139. package/dist/database/migrations/SystemMigrations.js.map +1 -0
  140. package/dist/demo/DemoService.d.ts +115 -0
  141. package/dist/demo/DemoService.d.ts.map +1 -0
  142. package/dist/demo/DemoService.js +427 -0
  143. package/dist/demo/DemoService.js.map +1 -0
  144. package/dist/files/FileStorageService.d.ts +35 -0
  145. package/dist/files/FileStorageService.d.ts.map +1 -0
  146. package/dist/files/FileStorageService.js +126 -0
  147. package/dist/files/FileStorageService.js.map +1 -0
  148. package/dist/http/HttpServer.d.ts +61 -0
  149. package/dist/http/HttpServer.d.ts.map +1 -0
  150. package/dist/http/HttpServer.js +478 -0
  151. package/dist/http/HttpServer.js.map +1 -0
  152. package/dist/http/controllers/AnalyticsController.d.ts +9 -0
  153. package/dist/http/controllers/AnalyticsController.d.ts.map +1 -0
  154. package/dist/http/controllers/AnalyticsController.js +18 -0
  155. package/dist/http/controllers/AnalyticsController.js.map +1 -0
  156. package/dist/http/controllers/AppController.d.ts +29 -0
  157. package/dist/http/controllers/AppController.d.ts.map +1 -0
  158. package/dist/http/controllers/AppController.js +36 -0
  159. package/dist/http/controllers/AppController.js.map +1 -0
  160. package/dist/http/controllers/AuditLogController.d.ts +26 -0
  161. package/dist/http/controllers/AuditLogController.d.ts.map +1 -0
  162. package/dist/http/controllers/AuditLogController.js +32 -0
  163. package/dist/http/controllers/AuditLogController.js.map +1 -0
  164. package/dist/http/controllers/AuthController.d.ts +18 -0
  165. package/dist/http/controllers/AuthController.d.ts.map +1 -0
  166. package/dist/http/controllers/AuthController.js +84 -0
  167. package/dist/http/controllers/AuthController.js.map +1 -0
  168. package/dist/http/controllers/BaseController.d.ts +7 -0
  169. package/dist/http/controllers/BaseController.d.ts.map +1 -0
  170. package/dist/http/controllers/BaseController.js +20 -0
  171. package/dist/http/controllers/BaseController.js.map +1 -0
  172. package/dist/http/controllers/CollectionController.d.ts +44 -0
  173. package/dist/http/controllers/CollectionController.d.ts.map +1 -0
  174. package/dist/http/controllers/CollectionController.js +89 -0
  175. package/dist/http/controllers/CollectionController.js.map +1 -0
  176. package/dist/http/controllers/DemoController.d.ts +34 -0
  177. package/dist/http/controllers/DemoController.d.ts.map +1 -0
  178. package/dist/http/controllers/DemoController.js +55 -0
  179. package/dist/http/controllers/DemoController.js.map +1 -0
  180. package/dist/http/controllers/FileController.d.ts +29 -0
  181. package/dist/http/controllers/FileController.d.ts.map +1 -0
  182. package/dist/http/controllers/FileController.js +172 -0
  183. package/dist/http/controllers/FileController.js.map +1 -0
  184. package/dist/http/controllers/HealthController.d.ts +10 -0
  185. package/dist/http/controllers/HealthController.d.ts.map +1 -0
  186. package/dist/http/controllers/HealthController.js +28 -0
  187. package/dist/http/controllers/HealthController.js.map +1 -0
  188. package/dist/http/controllers/LogController.d.ts +15 -0
  189. package/dist/http/controllers/LogController.d.ts.map +1 -0
  190. package/dist/http/controllers/LogController.js +25 -0
  191. package/dist/http/controllers/LogController.js.map +1 -0
  192. package/dist/http/controllers/RealtimeController.d.ts +13 -0
  193. package/dist/http/controllers/RealtimeController.d.ts.map +1 -0
  194. package/dist/http/controllers/RealtimeController.js +54 -0
  195. package/dist/http/controllers/RealtimeController.js.map +1 -0
  196. package/dist/http/controllers/RecordController.d.ts +74 -0
  197. package/dist/http/controllers/RecordController.d.ts.map +1 -0
  198. package/dist/http/controllers/RecordController.js +202 -0
  199. package/dist/http/controllers/RecordController.js.map +1 -0
  200. package/dist/http/controllers/TemplateController.d.ts +29 -0
  201. package/dist/http/controllers/TemplateController.d.ts.map +1 -0
  202. package/dist/http/controllers/TemplateController.js +63 -0
  203. package/dist/http/controllers/TemplateController.js.map +1 -0
  204. package/dist/http/controllers/WebhookController.d.ts +78 -0
  205. package/dist/http/controllers/WebhookController.d.ts.map +1 -0
  206. package/dist/http/controllers/WebhookController.js +113 -0
  207. package/dist/http/controllers/WebhookController.js.map +1 -0
  208. package/dist/http/middleware/AppResolutionMiddleware.d.ts +8 -0
  209. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -0
  210. package/dist/http/middleware/AppResolutionMiddleware.js +98 -0
  211. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -0
  212. package/dist/http/middleware/AuthMiddleware.d.ts +17 -0
  213. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -0
  214. package/dist/http/middleware/AuthMiddleware.js +97 -0
  215. package/dist/http/middleware/AuthMiddleware.js.map +1 -0
  216. package/dist/http/middleware/ChaosMiddleware.d.ts +130 -0
  217. package/dist/http/middleware/ChaosMiddleware.d.ts.map +1 -0
  218. package/dist/http/middleware/ChaosMiddleware.js +434 -0
  219. package/dist/http/middleware/ChaosMiddleware.js.map +1 -0
  220. package/dist/index.d.ts +52 -0
  221. package/dist/index.d.ts.map +1 -0
  222. package/dist/index.js +141 -0
  223. package/dist/index.js.map +1 -0
  224. package/dist/logger/LogService.d.ts +31 -0
  225. package/dist/logger/LogService.d.ts.map +1 -0
  226. package/dist/logger/LogService.js +104 -0
  227. package/dist/logger/LogService.js.map +1 -0
  228. package/dist/plugins/algolia.d.ts +76 -0
  229. package/dist/plugins/algolia.d.ts.map +1 -0
  230. package/dist/plugins/algolia.js +532 -0
  231. package/dist/plugins/algolia.js.map +1 -0
  232. package/dist/plugins/index.d.ts +6 -0
  233. package/dist/plugins/index.d.ts.map +1 -0
  234. package/dist/plugins/index.js +22 -0
  235. package/dist/plugins/index.js.map +1 -0
  236. package/dist/plugins/resend.d.ts +42 -0
  237. package/dist/plugins/resend.d.ts.map +1 -0
  238. package/dist/plugins/resend.js +335 -0
  239. package/dist/plugins/resend.js.map +1 -0
  240. package/dist/plugins/s3.d.ts +35 -0
  241. package/dist/plugins/s3.d.ts.map +1 -0
  242. package/dist/plugins/s3.js +425 -0
  243. package/dist/plugins/s3.js.map +1 -0
  244. package/dist/plugins/stripe.d.ts +45 -0
  245. package/dist/plugins/stripe.d.ts.map +1 -0
  246. package/dist/plugins/stripe.js +470 -0
  247. package/dist/plugins/stripe.js.map +1 -0
  248. package/dist/plugins/webhooks.d.ts +35 -0
  249. package/dist/plugins/webhooks.d.ts.map +1 -0
  250. package/dist/plugins/webhooks.js +415 -0
  251. package/dist/plugins/webhooks.js.map +1 -0
  252. package/dist/realtime/RealtimeService.d.ts +26 -0
  253. package/dist/realtime/RealtimeService.d.ts.map +1 -0
  254. package/dist/realtime/RealtimeService.js +165 -0
  255. package/dist/realtime/RealtimeService.js.map +1 -0
  256. package/dist/records/CsvHelper.d.ts +27 -0
  257. package/dist/records/CsvHelper.d.ts.map +1 -0
  258. package/dist/records/CsvHelper.js +195 -0
  259. package/dist/records/CsvHelper.js.map +1 -0
  260. package/dist/records/FakerEngine.d.ts +73 -0
  261. package/dist/records/FakerEngine.d.ts.map +1 -0
  262. package/dist/records/FakerEngine.js +644 -0
  263. package/dist/records/FakerEngine.js.map +1 -0
  264. package/dist/records/FilterCodec.d.ts +22 -0
  265. package/dist/records/FilterCodec.d.ts.map +1 -0
  266. package/dist/records/FilterCodec.js +57 -0
  267. package/dist/records/FilterCodec.js.map +1 -0
  268. package/dist/records/FtsService.d.ts +63 -0
  269. package/dist/records/FtsService.d.ts.map +1 -0
  270. package/dist/records/FtsService.js +310 -0
  271. package/dist/records/FtsService.js.map +1 -0
  272. package/dist/records/MockDataService.d.ts +31 -0
  273. package/dist/records/MockDataService.d.ts.map +1 -0
  274. package/dist/records/MockDataService.js +222 -0
  275. package/dist/records/MockDataService.js.map +1 -0
  276. package/dist/records/QueryFilterParser.d.ts +35 -0
  277. package/dist/records/QueryFilterParser.d.ts.map +1 -0
  278. package/dist/records/QueryFilterParser.js +262 -0
  279. package/dist/records/QueryFilterParser.js.map +1 -0
  280. package/dist/records/RecordService.d.ts +77 -0
  281. package/dist/records/RecordService.d.ts.map +1 -0
  282. package/dist/records/RecordService.js +686 -0
  283. package/dist/records/RecordService.js.map +1 -0
  284. package/dist/rules/RuleBuilder.d.ts +72 -0
  285. package/dist/rules/RuleBuilder.d.ts.map +1 -0
  286. package/dist/rules/RuleBuilder.js +383 -0
  287. package/dist/rules/RuleBuilder.js.map +1 -0
  288. package/dist/rules/RuleEngine.d.ts +28 -0
  289. package/dist/rules/RuleEngine.d.ts.map +1 -0
  290. package/dist/rules/RuleEngine.js +204 -0
  291. package/dist/rules/RuleEngine.js.map +1 -0
  292. package/dist/schema/OpenApiGenerator.d.ts +32 -0
  293. package/dist/schema/OpenApiGenerator.d.ts.map +1 -0
  294. package/dist/schema/OpenApiGenerator.js +1836 -0
  295. package/dist/schema/OpenApiGenerator.js.map +1 -0
  296. package/dist/schema/SchemaInferenceService.d.ts +82 -0
  297. package/dist/schema/SchemaInferenceService.d.ts.map +1 -0
  298. package/dist/schema/SchemaInferenceService.js +622 -0
  299. package/dist/schema/SchemaInferenceService.js.map +1 -0
  300. package/dist/schema/SchemaService.d.ts +33 -0
  301. package/dist/schema/SchemaService.d.ts.map +1 -0
  302. package/dist/schema/SchemaService.js +338 -0
  303. package/dist/schema/SchemaService.js.map +1 -0
  304. package/dist/schema/TypeGenerator.d.ts +19 -0
  305. package/dist/schema/TypeGenerator.d.ts.map +1 -0
  306. package/dist/schema/TypeGenerator.js +173 -0
  307. package/dist/schema/TypeGenerator.js.map +1 -0
  308. package/dist/schema/models/Collection.d.ts +44 -0
  309. package/dist/schema/models/Collection.d.ts.map +1 -0
  310. package/dist/schema/models/Collection.js +3 -0
  311. package/dist/schema/models/Collection.js.map +1 -0
  312. package/dist/schema/models/Field.d.ts +25 -0
  313. package/dist/schema/models/Field.d.ts.map +1 -0
  314. package/dist/schema/models/Field.js +3 -0
  315. package/dist/schema/models/Field.js.map +1 -0
  316. package/dist/templates/TemplateImageGenerator.d.ts +43 -0
  317. package/dist/templates/TemplateImageGenerator.d.ts.map +1 -0
  318. package/dist/templates/TemplateImageGenerator.js +350 -0
  319. package/dist/templates/TemplateImageGenerator.js.map +1 -0
  320. package/dist/templates/TemplateService.d.ts +31 -0
  321. package/dist/templates/TemplateService.d.ts.map +1 -0
  322. package/dist/templates/TemplateService.js +209 -0
  323. package/dist/templates/TemplateService.js.map +1 -0
  324. package/dist/templates/definitions/blog.d.ts +3 -0
  325. package/dist/templates/definitions/blog.d.ts.map +1 -0
  326. package/dist/templates/definitions/blog.js +386 -0
  327. package/dist/templates/definitions/blog.js.map +1 -0
  328. package/dist/templates/definitions/crm.d.ts +3 -0
  329. package/dist/templates/definitions/crm.d.ts.map +1 -0
  330. package/dist/templates/definitions/crm.js +456 -0
  331. package/dist/templates/definitions/crm.js.map +1 -0
  332. package/dist/templates/definitions/ecommerce.d.ts +3 -0
  333. package/dist/templates/definitions/ecommerce.d.ts.map +1 -0
  334. package/dist/templates/definitions/ecommerce.js +781 -0
  335. package/dist/templates/definitions/ecommerce.js.map +1 -0
  336. package/dist/templates/definitions/index.d.ts +7 -0
  337. package/dist/templates/definitions/index.d.ts.map +1 -0
  338. package/dist/templates/definitions/index.js +15 -0
  339. package/dist/templates/definitions/index.js.map +1 -0
  340. package/dist/templates/types.d.ts +65 -0
  341. package/dist/templates/types.d.ts.map +1 -0
  342. package/dist/templates/types.js +3 -0
  343. package/dist/templates/types.js.map +1 -0
  344. package/dist/webhooks/WebhookService.d.ts +149 -0
  345. package/dist/webhooks/WebhookService.d.ts.map +1 -0
  346. package/dist/webhooks/WebhookService.js +781 -0
  347. package/dist/webhooks/WebhookService.js.map +1 -0
  348. package/package.json +86 -4
@@ -0,0 +1,781 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.WebhookService = exports.ALLOWED_WEBHOOK_METHODS = void 0;
37
+ const crypto = __importStar(require("crypto"));
38
+ const AppError_1 = require("../core/errors/AppError");
39
+ exports.ALLOWED_WEBHOOK_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET', 'HEAD'];
40
+ class WebhookService {
41
+ db;
42
+ eventBus;
43
+ fetchFn;
44
+ requestTimeoutMs;
45
+ constructor(db, eventBus, options = {}) {
46
+ this.db = db;
47
+ this.eventBus = eventBus;
48
+ this.fetchFn = options.fetch || globalThis.fetch;
49
+ this.requestTimeoutMs = options.requestTimeoutMs || 10000;
50
+ this.initTables();
51
+ }
52
+ setFetch(customFetch) {
53
+ this.fetchFn = customFetch;
54
+ }
55
+ /**
56
+ * Ensures SQLite tables and indices for webhooks and deliveries exist.
57
+ */
58
+ initTables() {
59
+ try {
60
+ this.db.exec(`
61
+ CREATE TABLE IF NOT EXISTS _webhooks (
62
+ id TEXT PRIMARY KEY,
63
+ name TEXT NOT NULL,
64
+ url TEXT NOT NULL,
65
+ event TEXT NOT NULL,
66
+ collection TEXT NOT NULL,
67
+ action TEXT NOT NULL DEFAULT '*',
68
+ method TEXT NOT NULL DEFAULT 'POST',
69
+ headers TEXT,
70
+ secret TEXT,
71
+ enabled INTEGER NOT NULL DEFAULT 1,
72
+ created TEXT NOT NULL,
73
+ updated TEXT NOT NULL
74
+ );
75
+ CREATE INDEX IF NOT EXISTS idx_webhooks_collection ON _webhooks(collection);
76
+ CREATE INDEX IF NOT EXISTS idx_webhooks_enabled ON _webhooks(enabled);
77
+
78
+ CREATE TABLE IF NOT EXISTS _webhook_deliveries (
79
+ id TEXT PRIMARY KEY,
80
+ webhookId TEXT NOT NULL,
81
+ webhookName TEXT NOT NULL,
82
+ url TEXT NOT NULL,
83
+ event TEXT NOT NULL,
84
+ collection TEXT NOT NULL,
85
+ recordId TEXT,
86
+ requestHeaders TEXT NOT NULL,
87
+ requestPayload TEXT NOT NULL,
88
+ responseStatus INTEGER NOT NULL DEFAULT 0,
89
+ responseHeaders TEXT,
90
+ responseBody TEXT,
91
+ durationMs INTEGER NOT NULL DEFAULT 0,
92
+ status TEXT NOT NULL,
93
+ error TEXT,
94
+ attempt INTEGER NOT NULL DEFAULT 1,
95
+ created TEXT NOT NULL
96
+ );
97
+ CREATE INDEX IF NOT EXISTS idx_webhook_del_wh ON _webhook_deliveries(webhookId, created DESC);
98
+ CREATE INDEX IF NOT EXISTS idx_webhook_del_created ON _webhook_deliveries(created DESC);
99
+ CREATE INDEX IF NOT EXISTS idx_webhook_del_status ON _webhook_deliveries(status);
100
+ `);
101
+ }
102
+ catch {
103
+ // Ignored if already initialized
104
+ }
105
+ }
106
+ // ==========================================
107
+ // Webhook Configuration CRUD
108
+ // ==========================================
109
+ createWebhook(data) {
110
+ if (!data.name || typeof data.name !== 'string' || !data.name.trim()) {
111
+ throw new AppError_1.AppError('Webhook name is required', 400);
112
+ }
113
+ if (!data.url || typeof data.url !== 'string' || !data.url.trim()) {
114
+ throw new AppError_1.AppError('Target HTTP endpoint URL is required', 400);
115
+ }
116
+ try {
117
+ const parsed = new URL(data.url.trim());
118
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
119
+ throw new Error('URL must start with http:// or https://');
120
+ }
121
+ }
122
+ catch {
123
+ throw new AppError_1.AppError('A valid HTTP or HTTPS endpoint URL is required', 400);
124
+ }
125
+ let collection = (data.collection || '*').trim();
126
+ let event = (data.event || '*').trim();
127
+ // If event is formatted as collection.event (e.g. "post.created"), split cleanly
128
+ if (event.includes('.')) {
129
+ const [colPart, actPart] = event.split('.');
130
+ if ((!collection || collection === '*') && colPart && colPart !== '*') {
131
+ collection = colPart;
132
+ }
133
+ if (actPart) {
134
+ event = actPart;
135
+ }
136
+ }
137
+ const action = data.action ? data.action.trim() : event !== '*' ? event : '*';
138
+ const id = `whk_${crypto.randomBytes(6).toString('hex')}`;
139
+ const now = new Date().toISOString();
140
+ let normalizedHeaders = {};
141
+ if (typeof data.headers === 'string') {
142
+ try {
143
+ normalizedHeaders = JSON.parse(data.headers);
144
+ }
145
+ catch {
146
+ normalizedHeaders = {};
147
+ }
148
+ }
149
+ else if (data.headers && typeof data.headers === 'object') {
150
+ normalizedHeaders = { ...data.headers };
151
+ }
152
+ const enabled = data.enabled !== undefined ? (data.enabled ? 1 : 0) : 1;
153
+ const secret = data.secret && data.secret.trim() ? data.secret.trim() : null;
154
+ const method = (data.method || 'POST').trim().toUpperCase();
155
+ if (!exports.ALLOWED_WEBHOOK_METHODS.includes(method)) {
156
+ throw new AppError_1.AppError(`Invalid HTTP method '${method}'. Allowed methods are: ${exports.ALLOWED_WEBHOOK_METHODS.join(', ')}`, 400);
157
+ }
158
+ this.db.prepare(`
159
+ INSERT INTO _webhooks (
160
+ id, name, url, event, collection, action, method, headers, secret, enabled, created, updated
161
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
162
+ `).run(id, data.name.trim(), data.url.trim(), event, collection, action, method, JSON.stringify(normalizedHeaders), secret, enabled, now, now);
163
+ return {
164
+ id,
165
+ name: data.name.trim(),
166
+ url: data.url.trim(),
167
+ collection,
168
+ event,
169
+ action,
170
+ method,
171
+ headers: normalizedHeaders,
172
+ secret,
173
+ enabled: Boolean(enabled),
174
+ created: now,
175
+ updated: now,
176
+ };
177
+ }
178
+ getWebhooks(options = {}) {
179
+ const whereClauses = [];
180
+ const params = [];
181
+ if (options.collection) {
182
+ whereClauses.push('(collection = ? OR collection = "*")');
183
+ params.push(options.collection);
184
+ }
185
+ if (options.event) {
186
+ whereClauses.push('(event = ? OR event = "*")');
187
+ params.push(options.event);
188
+ }
189
+ if (options.enabled !== undefined) {
190
+ whereClauses.push('enabled = ?');
191
+ params.push(options.enabled ? 1 : 0);
192
+ }
193
+ const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';
194
+ const rows = this.db.all(`SELECT * FROM _webhooks ${whereSql} ORDER BY created DESC`, params);
195
+ return rows.map((r) => this.mapWebhookRow(r));
196
+ }
197
+ getWebhookById(id) {
198
+ const row = this.db.get('SELECT * FROM _webhooks WHERE id = ?', [id]);
199
+ if (!row)
200
+ return null;
201
+ return this.mapWebhookRow(row);
202
+ }
203
+ updateWebhook(id, updates) {
204
+ const existing = this.getWebhookById(id);
205
+ if (!existing) {
206
+ throw new AppError_1.AppError('Webhook not found', 404);
207
+ }
208
+ let url = existing.url;
209
+ if (updates.url !== undefined) {
210
+ try {
211
+ const parsed = new URL(updates.url.trim());
212
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
213
+ throw new Error('URL must start with http:// or https://');
214
+ }
215
+ url = updates.url.trim();
216
+ }
217
+ catch {
218
+ throw new AppError_1.AppError('A valid HTTP or HTTPS endpoint URL is required', 400);
219
+ }
220
+ }
221
+ const name = updates.name !== undefined ? updates.name.trim() : existing.name;
222
+ if (!name)
223
+ throw new AppError_1.AppError('Webhook name cannot be empty', 400);
224
+ let collection = updates.collection !== undefined ? updates.collection.trim() : existing.collection;
225
+ let event = updates.event !== undefined ? updates.event.trim() : existing.event;
226
+ if (event.includes('.')) {
227
+ const [colPart, actPart] = event.split('.');
228
+ if (colPart && colPart !== '*')
229
+ collection = colPart;
230
+ if (actPart)
231
+ event = actPart;
232
+ }
233
+ const action = updates.action !== undefined ? updates.action.trim() : event !== '*' ? event : existing.action;
234
+ let method = existing.method;
235
+ if (updates.method !== undefined) {
236
+ method = updates.method.trim().toUpperCase();
237
+ if (!exports.ALLOWED_WEBHOOK_METHODS.includes(method)) {
238
+ throw new AppError_1.AppError(`Invalid HTTP method '${method}'. Allowed methods are: ${exports.ALLOWED_WEBHOOK_METHODS.join(', ')}`, 400);
239
+ }
240
+ }
241
+ let headers = existing.headers;
242
+ if (updates.headers !== undefined) {
243
+ if (typeof updates.headers === 'string') {
244
+ try {
245
+ headers = JSON.parse(updates.headers);
246
+ }
247
+ catch {
248
+ headers = {};
249
+ }
250
+ }
251
+ else if (updates.headers && typeof updates.headers === 'object') {
252
+ headers = { ...updates.headers };
253
+ }
254
+ }
255
+ let secret = existing.secret;
256
+ if (updates.secret !== undefined) {
257
+ secret = updates.secret && updates.secret.trim() ? updates.secret.trim() : null;
258
+ }
259
+ const enabled = updates.enabled !== undefined ? (updates.enabled ? 1 : 0) : existing.enabled ? 1 : 0;
260
+ const now = new Date().toISOString();
261
+ this.db.prepare(`
262
+ UPDATE _webhooks SET
263
+ name = ?, url = ?, collection = ?, event = ?, action = ?, method = ?,
264
+ headers = ?, secret = ?, enabled = ?, updated = ?
265
+ WHERE id = ?
266
+ `).run(name, url, collection, event, action, method, JSON.stringify(headers), secret, enabled, now, id);
267
+ return {
268
+ id,
269
+ name,
270
+ url,
271
+ collection,
272
+ event,
273
+ action,
274
+ method,
275
+ headers,
276
+ secret,
277
+ enabled: Boolean(enabled),
278
+ created: existing.created,
279
+ updated: now,
280
+ };
281
+ }
282
+ deleteWebhook(id) {
283
+ const existing = this.getWebhookById(id);
284
+ if (!existing) {
285
+ throw new AppError_1.AppError('Webhook not found', 404);
286
+ }
287
+ const result = this.db.prepare('DELETE FROM _webhooks WHERE id = ?').run(id);
288
+ return Number(result.changes) > 0;
289
+ }
290
+ // ==========================================
291
+ // Delivery Logs & Retries
292
+ // ==========================================
293
+ getDeliveries(options = {}) {
294
+ const page = Math.max(1, Number(options.page) || 1);
295
+ const perPage = Math.min(100, Math.max(1, Number(options.perPage) || 25));
296
+ const offset = (page - 1) * perPage;
297
+ const whereClauses = [];
298
+ const params = [];
299
+ if (options.webhookId) {
300
+ whereClauses.push('webhookId = ?');
301
+ params.push(options.webhookId);
302
+ }
303
+ if (options.collection) {
304
+ whereClauses.push('collection = ?');
305
+ params.push(options.collection);
306
+ }
307
+ if (options.status && options.status !== 'all') {
308
+ whereClauses.push('status = ?');
309
+ params.push(options.status);
310
+ }
311
+ if (options.search && options.search.trim()) {
312
+ const term = `%${options.search.trim()}%`;
313
+ whereClauses.push('(url LIKE ? OR event LIKE ? OR webhookName LIKE ? OR error LIKE ?)');
314
+ params.push(term, term, term, term);
315
+ }
316
+ const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';
317
+ const countRow = this.db.get(`SELECT COUNT(*) as count FROM _webhook_deliveries ${whereSql}`, params);
318
+ const totalItems = countRow?.count || 0;
319
+ const totalPages = Math.ceil(totalItems / perPage);
320
+ const rows = this.db.all(`SELECT * FROM _webhook_deliveries ${whereSql} ORDER BY created DESC LIMIT ? OFFSET ?`, [...params, perPage, offset]);
321
+ const items = rows.map((r) => this.mapDeliveryRow(r));
322
+ return {
323
+ items,
324
+ totalItems,
325
+ totalPages,
326
+ page,
327
+ perPage,
328
+ };
329
+ }
330
+ getDeliveryById(id) {
331
+ const row = this.db.get('SELECT * FROM _webhook_deliveries WHERE id = ?', [id]);
332
+ if (!row)
333
+ return null;
334
+ return this.mapDeliveryRow(row);
335
+ }
336
+ clearDeliveries(olderThanDays) {
337
+ if (olderThanDays !== undefined && olderThanDays !== null) {
338
+ const days = typeof olderThanDays === 'number' ? olderThanDays : Number(olderThanDays);
339
+ if (!Number.isFinite(days) || days < 0) {
340
+ throw new Error('Invalid olderThanDays parameter: must be a non-negative finite number');
341
+ }
342
+ const cutoff = new Date(Date.now() - days * 86400000).toISOString();
343
+ const res = this.db.prepare('DELETE FROM _webhook_deliveries WHERE created < ?').run(cutoff);
344
+ return Number(res.changes);
345
+ }
346
+ const res = this.db.prepare('DELETE FROM _webhook_deliveries').run();
347
+ return Number(res.changes);
348
+ }
349
+ getStats() {
350
+ const totalRow = this.db.get(`
351
+ SELECT COUNT(*) as total, SUM(CASE WHEN enabled = 1 THEN 1 ELSE 0 END) as active FROM _webhooks
352
+ `);
353
+ const deliveriesRow = this.db.get(`
354
+ SELECT COUNT(*) as total,
355
+ SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success,
356
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
357
+ FROM _webhook_deliveries
358
+ `);
359
+ const totalWebhooks = totalRow?.total || 0;
360
+ const activeWebhooks = totalRow?.active || 0;
361
+ const totalDeliveries = deliveriesRow?.total || 0;
362
+ const successDeliveries = deliveriesRow?.success || 0;
363
+ const failedDeliveries = deliveriesRow?.failed || 0;
364
+ let successRate = '100%';
365
+ if (totalDeliveries > 0) {
366
+ const rate = ((successDeliveries / totalDeliveries) * 100).toFixed(1);
367
+ successRate = `${rate}%`;
368
+ }
369
+ return {
370
+ totalWebhooks,
371
+ activeWebhooks,
372
+ totalDeliveries,
373
+ successDeliveries,
374
+ failedDeliveries,
375
+ successRate,
376
+ };
377
+ }
378
+ // ==========================================
379
+ // Dispatch & Manual Retry
380
+ // ==========================================
381
+ /**
382
+ * Outbound HTTP dispatch engine for a single webhook.
383
+ */
384
+ async dispatch(webhook, payload, attempt = 1) {
385
+ const deliveryId = `whd_${crypto.randomBytes(8).toString('hex')}`;
386
+ const timestamp = new Date().toISOString();
387
+ const eventName = payload?.event || 'custom';
388
+ const collectionName = payload?.collection || (payload?.event?.includes('.') ? payload.event.split('.')[0] : 'default');
389
+ const recordId = payload?.record?.id || payload?.recordId || null;
390
+ const payloadString = typeof payload === 'string' ? payload : JSON.stringify(payload);
391
+ const method = (webhook.method || 'POST').trim().toUpperCase();
392
+ const isBodyAllowed = method !== 'GET' && method !== 'HEAD';
393
+ let targetUrl = webhook.url;
394
+ if (!isBodyAllowed) {
395
+ try {
396
+ const urlObj = new URL(webhook.url);
397
+ if (!urlObj.searchParams.has('event') && eventName) {
398
+ urlObj.searchParams.set('event', eventName);
399
+ }
400
+ if (!urlObj.searchParams.has('collection') && collectionName) {
401
+ urlObj.searchParams.set('collection', collectionName);
402
+ }
403
+ if (!urlObj.searchParams.has('action') && payload?.action) {
404
+ urlObj.searchParams.set('action', String(payload.action));
405
+ }
406
+ if (!urlObj.searchParams.has('recordId') && recordId) {
407
+ urlObj.searchParams.set('recordId', String(recordId));
408
+ }
409
+ if (!urlObj.searchParams.has('timestamp') && payload?.timestamp) {
410
+ urlObj.searchParams.set('timestamp', String(payload.timestamp));
411
+ }
412
+ targetUrl = urlObj.toString();
413
+ }
414
+ catch {
415
+ targetUrl = webhook.url;
416
+ }
417
+ }
418
+ // Prepare Request Headers
419
+ const requestHeaders = {
420
+ 'User-Agent': 'NodeStack-Webhooks/1.3.0',
421
+ ...(webhook.headers || {}),
422
+ };
423
+ if (isBodyAllowed) {
424
+ if (!requestHeaders['Content-Type']) {
425
+ requestHeaders['Content-Type'] = 'application/json';
426
+ }
427
+ }
428
+ else {
429
+ // For body-free methods (GET/HEAD), avoid default Content-Type unless explicitly supplied in custom headers
430
+ if (!webhook.headers || !webhook.headers['Content-Type']) {
431
+ delete requestHeaders['Content-Type'];
432
+ }
433
+ }
434
+ // Calculate HMAC-SHA256 Secret Signature (X-NodeStack-Signature)
435
+ if (webhook.secret) {
436
+ let signContent = payloadString;
437
+ if (!isBodyAllowed) {
438
+ try {
439
+ const u = new URL(targetUrl);
440
+ signContent = u.search ? u.search.slice(1) : '';
441
+ }
442
+ catch {
443
+ signContent = '';
444
+ }
445
+ }
446
+ const signature = WebhookService.computeSignature(signContent, webhook.secret);
447
+ requestHeaders['X-NodeStack-Signature'] = signature;
448
+ }
449
+ const startTime = Date.now();
450
+ let responseStatus = 0;
451
+ let responseHeaders = {};
452
+ let responseBody = '';
453
+ let status = 'failed';
454
+ let errorMessage = null;
455
+ const fetchFn = this.fetchFn || globalThis.fetch;
456
+ if (!fetchFn) {
457
+ errorMessage = 'Global fetch is not available';
458
+ }
459
+ else {
460
+ let timeoutId = null;
461
+ try {
462
+ const controller = new AbortController();
463
+ timeoutId = setTimeout(() => controller.abort(), this.requestTimeoutMs);
464
+ const fetchOptions = {
465
+ method,
466
+ headers: requestHeaders,
467
+ signal: controller.signal,
468
+ };
469
+ if (isBodyAllowed) {
470
+ fetchOptions.body = payloadString;
471
+ }
472
+ const res = await fetchFn(targetUrl, fetchOptions);
473
+ responseStatus = res.status;
474
+ res.headers.forEach((val, key) => {
475
+ responseHeaders[key] = val;
476
+ });
477
+ responseBody = await res.text().catch(() => '');
478
+ // Keep body reasonable for SQLite storage (first 10,000 characters)
479
+ if (responseBody.length > 10000) {
480
+ responseBody = responseBody.substring(0, 10000) + '... [truncated]';
481
+ }
482
+ if (res.ok) {
483
+ status = 'success';
484
+ }
485
+ else {
486
+ status = 'failed';
487
+ errorMessage = `HTTP ${res.status}: ${res.statusText || 'Response not OK'}`;
488
+ }
489
+ }
490
+ catch (err) {
491
+ status = 'failed';
492
+ errorMessage = err.name === 'AbortError' ? `Request timed out after ${this.requestTimeoutMs}ms` : (err.message || String(err));
493
+ }
494
+ finally {
495
+ if (timeoutId)
496
+ clearTimeout(timeoutId);
497
+ }
498
+ }
499
+ const durationMs = Date.now() - startTime;
500
+ // Record Delivery Log in SQLite
501
+ try {
502
+ this.db.prepare(`
503
+ INSERT INTO _webhook_deliveries (
504
+ id, webhookId, webhookName, url, event, collection, recordId,
505
+ requestHeaders, requestPayload, responseStatus, responseHeaders,
506
+ responseBody, durationMs, status, error, attempt, created
507
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
508
+ `).run(deliveryId, webhook.id, webhook.name, targetUrl, eventName, collectionName, recordId, JSON.stringify(requestHeaders), payloadString, responseStatus, JSON.stringify(responseHeaders), responseBody, durationMs, status, errorMessage, attempt, timestamp);
509
+ }
510
+ catch (dbErr) {
511
+ console.error('[WebhookService] Failed to record delivery log:', dbErr);
512
+ }
513
+ const deliveryRecord = {
514
+ id: deliveryId,
515
+ webhookId: webhook.id,
516
+ webhookName: webhook.name,
517
+ url: targetUrl,
518
+ event: eventName,
519
+ collection: collectionName,
520
+ recordId,
521
+ requestHeaders,
522
+ requestPayload: this.safeParseJson(payloadString, payload),
523
+ responseStatus,
524
+ responseHeaders,
525
+ responseBody,
526
+ durationMs,
527
+ status,
528
+ error: errorMessage,
529
+ attempt,
530
+ created: timestamp,
531
+ };
532
+ if (this.eventBus) {
533
+ const eventName = status === 'success' ? 'webhook:delivered' : 'webhook:failed';
534
+ this.eventBus.emit(eventName, {
535
+ webhook,
536
+ delivery: deliveryRecord,
537
+ });
538
+ }
539
+ return deliveryRecord;
540
+ }
541
+ /**
542
+ * Manual Retry Button handler:
543
+ * Retries an existing delivery by ID, re-delivering the exact original payload.
544
+ */
545
+ async retryDelivery(deliveryId) {
546
+ const original = this.getDeliveryById(deliveryId);
547
+ if (!original) {
548
+ throw new AppError_1.AppError('Delivery log not found', 404);
549
+ }
550
+ const webhook = this.getWebhookById(original.webhookId);
551
+ const targetWebhook = webhook || {
552
+ id: original.webhookId,
553
+ name: original.webhookName,
554
+ url: original.url,
555
+ method: 'POST',
556
+ headers: original.requestHeaders,
557
+ secret: null,
558
+ };
559
+ const nextAttempt = (original.attempt || 1) + 1;
560
+ return this.dispatch(targetWebhook, original.requestPayload, nextAttempt);
561
+ }
562
+ /**
563
+ * Dispatches a live test event to verify the target webhook endpoint.
564
+ */
565
+ async testWebhook(webhookId, customPayload) {
566
+ const webhook = this.getWebhookById(webhookId);
567
+ if (!webhook) {
568
+ throw new AppError_1.AppError('Webhook not found', 404);
569
+ }
570
+ const eventName = webhook.event !== '*' ? (webhook.event.includes('.') ? webhook.event : `${webhook.collection}.${webhook.event}`) : `${webhook.collection}.test`;
571
+ const testPayload = customPayload || {
572
+ event: eventName,
573
+ collection: webhook.collection,
574
+ action: 'test',
575
+ record: {
576
+ id: `test_${crypto.randomBytes(4).toString('hex')}`,
577
+ title: 'NodeStack Webhook Verification',
578
+ description: 'Verifying outbound webhook connectivity, headers, and secret signature.',
579
+ status: 'verified',
580
+ created: new Date().toISOString(),
581
+ },
582
+ timestamp: new Date().toISOString(),
583
+ };
584
+ return this.dispatch(webhook, testPayload, 1);
585
+ }
586
+ // ==========================================
587
+ // EventBus Lifecycle Hook Matching
588
+ // ==========================================
589
+ /**
590
+ * Evaluates if a webhook matches a given collection and mutation event.
591
+ * Handles formats:
592
+ * - collection: 'posts', event: 'post.created'
593
+ * - collection: 'orders', event: 'order.updated'
594
+ * - collection: '*', event: '*'
595
+ */
596
+ matchesEvent(webhook, collection, action) {
597
+ if (!webhook.enabled)
598
+ return false;
599
+ const colLower = collection.toLowerCase();
600
+ const actLower = action.toLowerCase();
601
+ // Explicitly normalize the three lifecycle names to both past ('created') and present ('create')
602
+ let pastAction = actLower;
603
+ let presentAction = actLower;
604
+ if (actLower === 'create' || actLower === 'created') {
605
+ pastAction = 'created';
606
+ presentAction = 'create';
607
+ }
608
+ else if (actLower === 'update' || actLower === 'updated') {
609
+ pastAction = 'updated';
610
+ presentAction = 'update';
611
+ }
612
+ else if (actLower === 'delete' || actLower === 'deleted') {
613
+ pastAction = 'deleted';
614
+ presentAction = 'delete';
615
+ }
616
+ // 1. Check Collection Match
617
+ const webhookCol = (webhook.collection || '*').toLowerCase();
618
+ let colMatches = webhookCol === '*' || webhookCol === colLower;
619
+ if (!colMatches) {
620
+ // Tolerate singular/plural differences (e.g. 'post' vs 'posts', 'order' vs 'orders')
621
+ if (colLower.endsWith('s') && colLower.slice(0, -1) === webhookCol) {
622
+ colMatches = true;
623
+ }
624
+ else if (webhookCol.endsWith('s') && webhookCol.slice(0, -1) === colLower) {
625
+ colMatches = true;
626
+ }
627
+ }
628
+ if (!colMatches)
629
+ return false;
630
+ // 2. Check Action Constraint (if explicitly specified and non-wildcard)
631
+ if (webhook.action && webhook.action !== '*') {
632
+ const act = webhook.action.toLowerCase();
633
+ if (act !== pastAction && act !== presentAction) {
634
+ return false;
635
+ }
636
+ }
637
+ // 3. Check Event Match
638
+ const webhookEvent = (webhook.event || '*').toLowerCase();
639
+ if (webhookEvent === '*' || webhookEvent === '*.*')
640
+ return true;
641
+ // Direct action match (e.g. event = 'created' or 'create')
642
+ if (webhookEvent === pastAction || webhookEvent === presentAction)
643
+ return true;
644
+ // Composite event match (e.g. 'post.created', 'order.updated', 'posts.create')
645
+ if (webhookEvent.includes('.')) {
646
+ const [eCol, eAct] = webhookEvent.split('.');
647
+ const eColMatches = eCol === '*' ||
648
+ eCol === colLower ||
649
+ (colLower.endsWith('s') && colLower.slice(0, -1) === eCol) ||
650
+ (eCol.endsWith('s') && eCol.slice(0, -1) === colLower);
651
+ const eActMatches = eAct === '*' || eAct === pastAction || eAct === presentAction;
652
+ return eColMatches && eActMatches;
653
+ }
654
+ return false;
655
+ }
656
+ /**
657
+ * Invoked automatically by EventBus when database mutations occur.
658
+ */
659
+ async handleRecordEvent(action, ctx) {
660
+ try {
661
+ if (!ctx || !ctx.collection)
662
+ return;
663
+ // Skip internal system collections
664
+ if (ctx.collection.startsWith('_'))
665
+ return;
666
+ // Skip if database is closed or locked for maintenance / reset
667
+ if (this.db.isDatabaseLocked() || !this.db.isOpen())
668
+ return;
669
+ const normalizedAction = action === 'create' ? 'created' : action === 'update' ? 'updated' : 'deleted';
670
+ const allWebhooks = this.getWebhooks({ enabled: true });
671
+ const matchingWebhooks = allWebhooks.filter((w) => this.matchesEvent(w, ctx.collection, normalizedAction));
672
+ if (matchingWebhooks.length === 0)
673
+ return;
674
+ const payload = {
675
+ event: `${ctx.collection}.${normalizedAction}`,
676
+ collection: ctx.collection,
677
+ action: normalizedAction,
678
+ record: ctx.record,
679
+ previous: ctx.originalRecord || null,
680
+ timestamp: new Date().toISOString(),
681
+ };
682
+ // Dispatch asynchronously without blocking caller
683
+ for (const webhook of matchingWebhooks) {
684
+ this.dispatch(webhook, payload).catch((err) => {
685
+ console.error(`[WebhookService] Error dispatching webhook ${webhook.id}:`, err);
686
+ });
687
+ }
688
+ }
689
+ catch (err) {
690
+ console.error('[WebhookService] Error in handleRecordEvent:', err);
691
+ }
692
+ }
693
+ // ==========================================
694
+ // Cryptographic Signature Utilities
695
+ // ==========================================
696
+ /**
697
+ * Computes HMAC-SHA256 signature for X-NodeStack-Signature header.
698
+ */
699
+ static computeSignature(payload, secret) {
700
+ const str = typeof payload === 'string' ? payload : JSON.stringify(payload);
701
+ return crypto.createHmac('sha256', secret).update(str, 'utf8').digest('hex');
702
+ }
703
+ /**
704
+ * Verifies an incoming X-NodeStack-Signature header against the expected secret.
705
+ * Tolerates both raw 64-char hex strings and "sha256=" / "sha256:" prefixes.
706
+ */
707
+ static verifySignature(payload, signatureHeader, secret) {
708
+ if (!signatureHeader || !secret)
709
+ return false;
710
+ const expected = WebhookService.computeSignature(payload, secret);
711
+ let cleanHeader = signatureHeader.trim();
712
+ if (cleanHeader.startsWith('sha256=')) {
713
+ cleanHeader = cleanHeader.substring(7);
714
+ }
715
+ else if (cleanHeader.startsWith('sha256:')) {
716
+ cleanHeader = cleanHeader.substring(7);
717
+ }
718
+ try {
719
+ const a = Buffer.from(cleanHeader, 'utf8');
720
+ const b = Buffer.from(expected, 'utf8');
721
+ if (a.length !== b.length)
722
+ return false;
723
+ return crypto.timingSafeEqual(a, b);
724
+ }
725
+ catch {
726
+ return false;
727
+ }
728
+ }
729
+ // ==========================================
730
+ // Helpers
731
+ // ==========================================
732
+ mapWebhookRow(r) {
733
+ return {
734
+ id: r.id,
735
+ name: r.name,
736
+ url: r.url,
737
+ collection: r.collection,
738
+ event: r.event,
739
+ action: r.action,
740
+ method: r.method,
741
+ headers: this.safeParseJson(r.headers, {}),
742
+ secret: r.secret || null,
743
+ enabled: Boolean(r.enabled),
744
+ created: r.created,
745
+ updated: r.updated,
746
+ };
747
+ }
748
+ mapDeliveryRow(r) {
749
+ return {
750
+ id: r.id,
751
+ webhookId: r.webhookId,
752
+ webhookName: r.webhookName,
753
+ url: r.url,
754
+ event: r.event,
755
+ collection: r.collection,
756
+ recordId: r.recordId || null,
757
+ requestHeaders: this.safeParseJson(r.requestHeaders, {}),
758
+ requestPayload: this.safeParseJson(r.requestPayload, r.requestPayload),
759
+ responseStatus: r.responseStatus,
760
+ responseHeaders: this.safeParseJson(r.responseHeaders, {}),
761
+ responseBody: r.responseBody || '',
762
+ durationMs: r.durationMs,
763
+ status: r.status,
764
+ error: r.error || null,
765
+ attempt: r.attempt || 1,
766
+ created: r.created,
767
+ };
768
+ }
769
+ safeParseJson(raw, fallback) {
770
+ if (!raw || typeof raw !== 'string')
771
+ return fallback;
772
+ try {
773
+ return JSON.parse(raw);
774
+ }
775
+ catch {
776
+ return fallback;
777
+ }
778
+ }
779
+ }
780
+ exports.WebhookService = WebhookService;
781
+ //# sourceMappingURL=WebhookService.js.map