@nodestackapp/server 2.0.0 → 2.1.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 (157) hide show
  1. package/README.md +4 -3
  2. package/dist/NodeStack.d.ts +9 -0
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +24 -3
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +9 -5
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/codemirror.css +98 -0
  10. package/dist/admin/ui/css/main.css +2309 -2189
  11. package/dist/admin/ui/index.html +8331 -5295
  12. package/dist/admin/ui/js/api.js +44 -14
  13. package/dist/admin/ui/js/app.js +480 -254
  14. package/dist/admin/ui/js/apps.js +29 -14
  15. package/dist/admin/ui/js/codemirror.js +15 -0
  16. package/dist/admin/ui/js/collections.js +38 -9
  17. package/dist/admin/ui/js/command-palette.js +12 -1
  18. package/dist/admin/ui/js/functions-tester.js +432 -0
  19. package/dist/admin/ui/js/functions-workbench.js +1038 -0
  20. package/dist/admin/ui/js/functions.js +765 -0
  21. package/dist/admin/ui/js/modals.js +6 -2
  22. package/dist/admin/ui/js/plugin-tester.js +562 -559
  23. package/dist/admin/ui/js/plugins.js +198 -77
  24. package/dist/admin/ui/js/records.js +89 -54
  25. package/dist/admin/ui/js/schema.js +23 -9
  26. package/dist/admin/ui/js/views.js +82 -34
  27. package/dist/admin/ui/js/webhooks.js +1111 -1104
  28. package/dist/apps/AppScope.d.ts +4 -0
  29. package/dist/apps/AppScope.d.ts.map +1 -1
  30. package/dist/apps/AppScope.js +33 -1
  31. package/dist/apps/AppScope.js.map +1 -1
  32. package/dist/auth/ApiKeyService.d.ts +91 -0
  33. package/dist/auth/ApiKeyService.d.ts.map +1 -0
  34. package/dist/auth/ApiKeyService.js +414 -0
  35. package/dist/auth/ApiKeyService.js.map +1 -0
  36. package/dist/auth/AuthService.d.ts +33 -1
  37. package/dist/auth/AuthService.d.ts.map +1 -1
  38. package/dist/auth/AuthService.js +219 -1
  39. package/dist/auth/AuthService.js.map +1 -1
  40. package/dist/auth/oauth/AppleProvider.d.ts +23 -0
  41. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -0
  42. package/dist/auth/oauth/AppleProvider.js +161 -0
  43. package/dist/auth/oauth/AppleProvider.js.map +1 -0
  44. package/dist/auth/oauth/BaseOAuthProvider.d.ts +18 -0
  45. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -0
  46. package/dist/auth/oauth/BaseOAuthProvider.js +79 -0
  47. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -0
  48. package/dist/auth/oauth/DiscordProvider.d.ts +11 -0
  49. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -0
  50. package/dist/auth/oauth/DiscordProvider.js +47 -0
  51. package/dist/auth/oauth/DiscordProvider.js.map +1 -0
  52. package/dist/auth/oauth/GitHubProvider.d.ts +13 -0
  53. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -0
  54. package/dist/auth/oauth/GitHubProvider.js +90 -0
  55. package/dist/auth/oauth/GitHubProvider.js.map +1 -0
  56. package/dist/auth/oauth/GoogleProvider.d.ts +11 -0
  57. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -0
  58. package/dist/auth/oauth/GoogleProvider.js +43 -0
  59. package/dist/auth/oauth/GoogleProvider.js.map +1 -0
  60. package/dist/auth/oauth/MicrosoftProvider.d.ts +11 -0
  61. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -0
  62. package/dist/auth/oauth/MicrosoftProvider.js +83 -0
  63. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -0
  64. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +32 -0
  65. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -0
  66. package/dist/auth/oauth/OAuthProviderRegistry.js +232 -0
  67. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -0
  68. package/dist/auth/oauth/types.d.ts +63 -0
  69. package/dist/auth/oauth/types.d.ts.map +1 -0
  70. package/dist/auth/oauth/types.js +3 -0
  71. package/dist/auth/oauth/types.js.map +1 -0
  72. package/dist/cli/cli.js +10 -10
  73. package/dist/cli/cli.js.map +1 -1
  74. package/dist/core/container/Tokens.d.ts +2 -0
  75. package/dist/core/container/Tokens.d.ts.map +1 -1
  76. package/dist/core/container/Tokens.js +2 -0
  77. package/dist/core/container/Tokens.js.map +1 -1
  78. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  79. package/dist/core/plugins/PluginManager.js +73 -19
  80. package/dist/core/plugins/PluginManager.js.map +1 -1
  81. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  82. package/dist/database/migrations/SystemMigrations.js +40 -0
  83. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  84. package/dist/functions/FunctionService.d.ts +80 -0
  85. package/dist/functions/FunctionService.d.ts.map +1 -0
  86. package/dist/functions/FunctionService.js +610 -0
  87. package/dist/functions/FunctionService.js.map +1 -0
  88. package/dist/functions/runtime/IFunctionRuntime.d.ts +23 -0
  89. package/dist/functions/runtime/IFunctionRuntime.d.ts.map +1 -0
  90. package/dist/functions/runtime/IFunctionRuntime.js +3 -0
  91. package/dist/functions/runtime/IFunctionRuntime.js.map +1 -0
  92. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts +21 -0
  93. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -0
  94. package/dist/functions/runtime/QuickJsWasmRuntime.js +418 -0
  95. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -0
  96. package/dist/functions/runtime/SandboxedRunner.d.ts +31 -0
  97. package/dist/functions/runtime/SandboxedRunner.d.ts.map +1 -0
  98. package/dist/functions/runtime/SandboxedRunner.js +61 -0
  99. package/dist/functions/runtime/SandboxedRunner.js.map +1 -0
  100. package/dist/functions/security/SsrfGuard.d.ts +41 -0
  101. package/dist/functions/security/SsrfGuard.d.ts.map +1 -0
  102. package/dist/functions/security/SsrfGuard.js +470 -0
  103. package/dist/functions/security/SsrfGuard.js.map +1 -0
  104. package/dist/functions/types.d.ts +109 -0
  105. package/dist/functions/types.d.ts.map +1 -0
  106. package/dist/functions/types.js +3 -0
  107. package/dist/functions/types.js.map +1 -0
  108. package/dist/http/HttpServer.d.ts +7 -1
  109. package/dist/http/HttpServer.d.ts.map +1 -1
  110. package/dist/http/HttpServer.js +66 -1
  111. package/dist/http/HttpServer.js.map +1 -1
  112. package/dist/http/controllers/ApiKeyController.d.ts +31 -0
  113. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -0
  114. package/dist/http/controllers/ApiKeyController.js +52 -0
  115. package/dist/http/controllers/ApiKeyController.js.map +1 -0
  116. package/dist/http/controllers/AuthController.d.ts +29 -1
  117. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  118. package/dist/http/controllers/AuthController.js +42 -1
  119. package/dist/http/controllers/AuthController.js.map +1 -1
  120. package/dist/http/controllers/FunctionController.d.ts +64 -0
  121. package/dist/http/controllers/FunctionController.d.ts.map +1 -0
  122. package/dist/http/controllers/FunctionController.js +202 -0
  123. package/dist/http/controllers/FunctionController.js.map +1 -0
  124. package/dist/http/controllers/RecordController.d.ts.map +1 -1
  125. package/dist/http/controllers/RecordController.js +4 -0
  126. package/dist/http/controllers/RecordController.js.map +1 -1
  127. package/dist/http/middleware/AuthMiddleware.d.ts +6 -1
  128. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  129. package/dist/http/middleware/AuthMiddleware.js +79 -8
  130. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  131. package/dist/index.d.ts +11 -1
  132. package/dist/index.d.ts.map +1 -1
  133. package/dist/index.js +22 -3
  134. package/dist/index.js.map +1 -1
  135. package/dist/plugins/chat-notifications.d.ts +51 -0
  136. package/dist/plugins/chat-notifications.d.ts.map +1 -0
  137. package/dist/plugins/chat-notifications.js +545 -0
  138. package/dist/plugins/chat-notifications.js.map +1 -0
  139. package/dist/plugins/index.d.ts +1 -1
  140. package/dist/plugins/index.d.ts.map +1 -1
  141. package/dist/plugins/index.js +1 -1
  142. package/dist/plugins/index.js.map +1 -1
  143. package/dist/plugins/webhooks.d.ts +5 -34
  144. package/dist/plugins/webhooks.d.ts.map +1 -1
  145. package/dist/plugins/webhooks.js +11 -412
  146. package/dist/plugins/webhooks.js.map +1 -1
  147. package/dist/records/MockDataService.d.ts.map +1 -1
  148. package/dist/records/MockDataService.js +3 -0
  149. package/dist/records/MockDataService.js.map +1 -1
  150. package/dist/records/RecordService.d.ts.map +1 -1
  151. package/dist/records/RecordService.js +39 -30
  152. package/dist/records/RecordService.js.map +1 -1
  153. package/dist/records/RecordValidator.d.ts +6 -0
  154. package/dist/records/RecordValidator.d.ts.map +1 -0
  155. package/dist/records/RecordValidator.js +100 -0
  156. package/dist/records/RecordValidator.js.map +1 -0
  157. package/package.json +89 -88
@@ -1,1104 +1,1111 @@
1
- // Webhooks Manager Module for NodeStack Admin UI
2
-
3
- let webhooksState = {
4
- subTab: 'webhooks', // 'webhooks' | 'deliveries'
5
- webhooks: [],
6
- stats: {
7
- totalWebhooks: 0,
8
- activeWebhooks: 0,
9
- totalDeliveries: 0,
10
- successDeliveries: 0,
11
- failedDeliveries: 0,
12
- successRate: '100%',
13
- },
14
- deliveries: [],
15
- deliveryFilter: {
16
- webhookId: '',
17
- collection: '',
18
- status: 'all',
19
- search: '',
20
- page: 1,
21
- perPage: 25,
22
- totalItems: 0,
23
- totalPages: 1,
24
- },
25
- activeWebhookForEdit: null,
26
- };
27
-
28
- if (typeof window !== 'undefined') {
29
- window.webhooksState = webhooksState;
30
- }
31
-
32
- function renderWebhooksView() {
33
- const container = document.getElementById('page-view-webhooks') || document.getElementById('main-body');
34
- if (!container) return;
35
-
36
- container.innerHTML = `
37
- <div class="webhooks-container">
38
- <!-- Header -->
39
- <div class="webhooks-header">
40
- <div class="webhooks-title-area">
41
- <h2>
42
- <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
43
- <path d="M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c0-2.21 1.79-4 4-4h5.99c1.1 0 1.95-.94 2.48-1.9A4 4 0 0 1 22 13c0 2.21-1.79 4-4 4z"/>
44
- <circle cx="6" cy="17" r="1"/>
45
- <circle cx="18" cy="13" r="1"/>
46
- </svg>
47
- Webhooks Manager
48
- </h2>
49
- <p>Configure outbound HTTP webhooks on collection mutations with HMAC signing and delivery tracking.</p>
50
- </div>
51
- <div style="display: flex; align-items: center; gap: 8px;">
52
- <button class="btn btn-secondary btn-sm" onclick="refreshWebhooksView()" title="Refresh Webhooks & Logs">
53
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
54
- Refresh
55
- </button>
56
- <button class="btn btn-primary btn-sm" onclick="openCreateWebhookModal()">
57
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
58
- + New Webhook
59
- </button>
60
- </div>
61
- </div>
62
-
63
- <!-- Stats Grid -->
64
- <div class="webhooks-stats-grid" id="webhooks-stats-grid">
65
- <div class="webhook-stat-card">
66
- <span class="webhook-stat-label">Active Webhooks</span>
67
- <div class="webhook-stat-value">
68
- <span id="wh-stat-active">0</span>
69
- <span class="webhook-stat-subtext" id="wh-stat-total">/ 0 total</span>
70
- </div>
71
- </div>
72
- <div class="webhook-stat-card">
73
- <span class="webhook-stat-label">Total Deliveries</span>
74
- <div class="webhook-stat-value" id="wh-stat-deliveries">0</div>
75
- </div>
76
- <div class="webhook-stat-card">
77
- <span class="webhook-stat-label">Success Rate</span>
78
- <div class="webhook-stat-value" style="color: var(--accent-success);" id="wh-stat-rate">100%</div>
79
- </div>
80
- <div class="webhook-stat-card">
81
- <span class="webhook-stat-label">Failed Deliveries</span>
82
- <div class="webhook-stat-value" style="color: var(--accent-danger);" id="wh-stat-failed">0</div>
83
- </div>
84
- </div>
85
-
86
- <!-- Subtabs Bar -->
87
- <div class="webhooks-tabs-bar">
88
- <button class="webhook-tab-btn ${webhooksState.subTab === 'webhooks' ? 'active' : ''}" id="tab-btn-wh-list" onclick="switchWebhooksTab('webhooks')">
89
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
90
- Configured Webhooks
91
- </button>
92
- <button class="webhook-tab-btn ${webhooksState.subTab === 'deliveries' ? 'active' : ''}" id="tab-btn-wh-deliveries" onclick="switchWebhooksTab('deliveries')">
93
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
94
- Delivery Logs
95
- </button>
96
- </div>
97
-
98
- <!-- Content Area -->
99
- <div id="webhooks-tab-content">
100
- <!-- Rendered by switchWebhooksTab() -->
101
- </div>
102
- </div>
103
- `;
104
-
105
- loadWebhookStats();
106
- if (webhooksState.subTab === 'webhooks') {
107
- loadWebhooksList();
108
- } else {
109
- loadWebhookDeliveries();
110
- }
111
- }
112
-
113
- async function refreshWebhooksView() {
114
- await loadWebhookStats();
115
- if (webhooksState.subTab === 'webhooks') {
116
- await loadWebhooksList();
117
- } else {
118
- await loadWebhookDeliveries();
119
- }
120
- if (typeof toast === 'function') toast('Webhooks updated', 'info');
121
- }
122
-
123
- function switchWebhooksTab(tab) {
124
- webhooksState.subTab = tab;
125
- const btnList = document.getElementById('tab-btn-wh-list');
126
- const btnDel = document.getElementById('tab-btn-wh-deliveries');
127
- if (btnList) btnList.classList.toggle('active', tab === 'webhooks');
128
- if (btnDel) btnDel.classList.toggle('active', tab === 'deliveries');
129
-
130
- if (tab === 'webhooks') {
131
- loadWebhooksList();
132
- } else {
133
- loadWebhookDeliveries();
134
- }
135
- if (typeof updateBreadcrumbs === 'function') updateBreadcrumbs();
136
- }
137
-
138
- async function loadWebhookStats() {
139
- try {
140
- const stats = await api('/api/webhooks/stats');
141
- if (stats) {
142
- webhooksState.stats = stats;
143
- const elActive = document.getElementById('wh-stat-active');
144
- const elTotal = document.getElementById('wh-stat-total');
145
- const elDeliveries = document.getElementById('wh-stat-deliveries');
146
- const elRate = document.getElementById('wh-stat-rate');
147
- const elFailed = document.getElementById('wh-stat-failed');
148
-
149
- if (elActive) elActive.textContent = stats.activeWebhooks;
150
- if (elTotal) elTotal.textContent = `/ ${stats.totalWebhooks} total`;
151
- if (elDeliveries) elDeliveries.textContent = stats.totalDeliveries.toLocaleString();
152
- if (elRate) elRate.textContent = stats.successRate;
153
- if (elFailed) elFailed.textContent = stats.failedDeliveries.toLocaleString();
154
-
155
- const sidebarBadge = document.getElementById('sidebar-webhooks-count');
156
- if (sidebarBadge) {
157
- const count = stats.totalWebhooks !== undefined ? stats.totalWebhooks : stats.activeWebhooks;
158
- sidebarBadge.textContent = String(count);
159
- sidebarBadge.title = `${stats.activeWebhooks || 0} active / ${stats.totalWebhooks || 0} total`;
160
- sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
161
- }
162
-
163
- const homeWhEl = document.getElementById('home-stat-webhooks');
164
- const homeWhSubEl = document.getElementById('home-stat-webhooks-sub');
165
- if (homeWhEl) {
166
- homeWhEl.textContent = (stats.totalWebhooks !== undefined ? stats.totalWebhooks : 0).toString();
167
- }
168
- if (homeWhSubEl) {
169
- const active = stats.activeWebhooks || 0;
170
- const deliveries = stats.totalDeliveries || 0;
171
- homeWhSubEl.textContent = `${active} active${deliveries > 0 ? ` • ${deliveries} delivered` : ' • 0 delivered'}`;
172
- }
173
- }
174
- } catch (err) {
175
- console.error('Failed to load webhook stats:', err);
176
- }
177
- }
178
-
179
- // ==========================================
180
- // Webhook List Rendering
181
- // ==========================================
182
-
183
- async function loadWebhooksList() {
184
- const content = document.getElementById('webhooks-tab-content');
185
- if (!content) return;
186
-
187
- content.innerHTML = `<div style="text-align:center; padding:3rem; color:var(--text-muted);">Loading webhooks...</div>`;
188
-
189
- try {
190
- const webhooks = await api('/api/webhooks');
191
- webhooksState.webhooks = webhooks || [];
192
-
193
- const sidebarBadge = document.getElementById('sidebar-webhooks-count');
194
- if (sidebarBadge) {
195
- const count = webhooksState.webhooks.length;
196
- sidebarBadge.textContent = String(count);
197
- sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
198
- }
199
-
200
- if (!webhooks || webhooks.length === 0) {
201
- content.innerHTML = `
202
- <div style="text-align:center; padding: 4rem 2rem; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px;">
203
- <div style="font-size: 2.5rem; margin-bottom: 0.75rem;">🔗</div>
204
- <h3 style="margin: 0 0 0.5rem 0; font-size: 1.1rem; color: var(--text-main);">No Outbound Webhooks Configured</h3>
205
- <p style="margin: 0 0 1.5rem 0; font-size: 0.85rem; color: var(--text-muted); max-width: 480px; margin-left: auto; margin-right: auto;">
206
- Send real-time HTTP payloads to external endpoints whenever database records in a collection are created, updated, or deleted.
207
- </p>
208
- <button class="btn btn-primary btn-sm" onclick="openCreateWebhookModal()">+ Create Your First Webhook</button>
209
- </div>
210
- `;
211
- return;
212
- }
213
-
214
- content.innerHTML = `
215
- <div class="webhook-table-wrapper">
216
- <table class="webhook-table">
217
- <thead>
218
- <tr>
219
- <th style="min-width: 180px; width: 25%;">Webhook Name</th>
220
- <th style="min-width: 150px; width: 20%;">Collection & Event</th>
221
- <th style="min-width: 200px; width: 30%;">Target Endpoint</th>
222
- <th style="min-width: 130px; width: 10%;">Security</th>
223
- <th style="min-width: 160px; width: 15%; text-align: right; white-space: nowrap;">Actions</th>
224
- </tr>
225
- </thead>
226
- <tbody>
227
- ${webhooks.map(wh => {
228
- const eventFormatted = wh.event.includes('.') ? wh.event : `${wh.collection}.${wh.event}`;
229
- const hasHeaders = wh.headers && Object.keys(wh.headers).length > 0;
230
- const headerCount = hasHeaders ? Object.keys(wh.headers).length : 0;
231
-
232
- return `
233
- <tr>
234
- <td>
235
- <div style="display: flex; align-items: center; gap: 8px;">
236
- <span class="webhook-status-dot ${wh.enabled ? 'active' : 'paused'}" style="display: inline-block; width: 8px; height: 8px; min-width: 8px; min-height: 8px; flex-shrink: 0; border-radius: 50%; background: ${wh.enabled ? '#10b981' : '#64748b'};" title="${wh.enabled ? 'Active' : 'Disabled'}"></span>
237
- <div style="min-width: 0;">
238
- <div style="font-weight: 600; color: var(--text-main); word-break: break-word;">${escapeHtml(wh.name)}</div>
239
- <div style="font-size: 11px; color: var(--text-muted);">${wh.enabled ? 'Active' : 'Paused'} • ${wh.method}</div>
240
- </div>
241
- </div>
242
- </td>
243
- <td>
244
- <div style="display: flex; flex-direction: column; gap: 4px; align-items: flex-start;">
245
- <span class="badge-event" title="Collection mutation event trigger">${escapeHtml(eventFormatted)}</span>
246
- <span style="font-size: 11px; color: var(--text-muted);">Collection: <strong>${escapeHtml(wh.collection)}</strong></span>
247
- </div>
248
- </td>
249
- <td>
250
- <div style="display: flex; align-items: center; gap: 6px;">
251
- <span style="font-family:'JetBrains Mono', monospace; font-size: 12px; color: var(--text-main); word-break: break-all;">${escapeHtml(wh.url)}</span>
252
- </div>
253
- ${hasHeaders ? `<div style="font-size: 11px; color: var(--text-muted); margin-top: 2px;">${headerCount} custom header${headerCount === 1 ? '' : 's'}</div>` : ''}
254
- </td>
255
- <td>
256
- ${wh.secret ? `
257
- <span class="badge-signature" title="Payloads signed with HMAC-SHA256 in X-NodeStack-Signature header">
258
- 🔒 X-NodeStack-Signature
259
- </span>
260
- ` : `
261
- <span style="font-size: 11px; color: var(--text-muted);">No secret</span>
262
- `}
263
- </td>
264
- <td style="text-align: right; white-space: nowrap;">
265
- <div style="display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
266
- <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="triggerTestWebhook(this.getAttribute('data-id'))" title="Test Webhook with Live Sample Event" style="padding: 3px 8px; font-size: 11px;">
267
- ⚡ Test
268
- </button>
269
- <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="viewWebhookDeliveries(this.getAttribute('data-id'))" title="View Delivery Logs" style="padding: 3px 8px; font-size: 11px;">
270
- Logs
271
- </button>
272
- <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="openEditWebhookModal(this.getAttribute('data-id'))" title="Edit Webhook" style="padding: 3px 8px; font-size: 11px;">
273
- Edit
274
- </button>
275
- <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" data-name="${escapeHtml(wh.name)}" onclick="handleDeleteWebhookClick(this)" title="Delete Webhook" style="padding: 3px 6px; font-size: 11px; color: var(--accent-danger);">
276
- ✕
277
- </button>
278
- </div>
279
- </td>
280
- </tr>
281
- `;
282
- }).join('')}
283
- </tbody>
284
- </table>
285
- </div>
286
- `;
287
- } catch (err) {
288
- content.innerHTML = `<div style="color: var(--accent-danger); padding:2rem; text-align:center;">Failed to load webhooks: ${escapeHtml(err.message || String(err))}</div>`;
289
- }
290
- }
291
-
292
- function viewWebhookDeliveries(webhookId) {
293
- webhooksState.deliveryFilter.webhookId = webhookId;
294
- webhooksState.deliveryFilter.page = 1;
295
- switchWebhooksTab('deliveries');
296
- }
297
-
298
- // ==========================================
299
- // Delivery Logs Rendering & Manual Retry
300
- // ==========================================
301
-
302
- async function loadWebhookDeliveries() {
303
- const content = document.getElementById('webhooks-tab-content');
304
- if (!content) return;
305
-
306
- const f = webhooksState.deliveryFilter;
307
- const collectionsList = (state.collections || []).map(c => c.name);
308
-
309
- content.innerHTML = `
310
- <!-- Filter Bar -->
311
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; margin-bottom: 1rem; background: var(--bg-card); border: 1px solid var(--border-subtle); padding: 10px 14px; border-radius: 8px;">
312
- <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px; font-size: 12px;">
313
- <select id="wh-filter-webhook" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
314
- <option value="">All Webhooks</option>
315
- ${webhooksState.webhooks.map(w => `<option value="${w.id}" ${f.webhookId === w.id ? 'selected' : ''}>${escapeHtml(w.name)}</option>`).join('')}
316
- </select>
317
-
318
- <select id="wh-filter-col" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
319
- <option value="">All Collections</option>
320
- ${collectionsList.map(c => `<option value="${c}" ${f.collection === c ? 'selected' : ''}>${c}</option>`).join('')}
321
- </select>
322
-
323
- <select id="wh-filter-status" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
324
- <option value="all" ${f.status === 'all' ? 'selected' : ''}>All Statuses</option>
325
- <option value="success" ${f.status === 'success' ? 'selected' : ''}>Success Only</option>
326
- <option value="failed" ${f.status === 'failed' ? 'selected' : ''}>Failed Only</option>
327
- </select>
328
-
329
- <input
330
- type="text"
331
- id="wh-filter-search"
332
- placeholder="Search url, event, or error..."
333
- value="${escapeHtml(f.search)}"
334
- class="form-control"
335
- style="width: 200px; padding: 4px 8px; font-size: 12px;"
336
- onkeyup="if(event.key==='Enter') handleDeliveryFilterChange()"
337
- />
338
- <button class="btn btn-secondary btn-sm" onclick="handleDeliveryFilterChange()" style="padding: 4px 8px;">Filter</button>
339
- ${(f.webhookId || f.collection || f.status !== 'all' || f.search) ? `
340
- <button class="btn btn-secondary btn-sm" onclick="clearDeliveryFilters()" style="padding: 4px 8px; font-size: 11px;">Clear Filters</button>
341
- ` : ''}
342
- </div>
343
-
344
- <div>
345
- <button class="btn btn-secondary btn-sm" onclick="clearAllDeliveryLogs()" style="color: var(--accent-danger); font-size: 11px; padding: 4px 8px;">
346
- Clear Logs
347
- </button>
348
- </div>
349
- </div>
350
-
351
- <!-- Deliveries Table Container -->
352
- <div class="webhook-table-wrapper">
353
- <table class="webhook-table">
354
- <thead>
355
- <tr>
356
- <th style="min-width: 130px; width: 14%; white-space: nowrap;">Response Code</th>
357
- <th style="min-width: 150px; width: 16%;">Event</th>
358
- <th style="min-width: 200px; width: 30%;">Target Endpoint</th>
359
- <th style="min-width: 120px; width: 14%; white-space: nowrap;">Duration / Attempt</th>
360
- <th style="min-width: 120px; width: 12%; white-space: nowrap;">Delivered At</th>
361
- <th style="min-width: 130px; width: 14%; text-align: right; white-space: nowrap;">Actions</th>
362
- </tr>
363
- </thead>
364
- <tbody id="wh-deliveries-table-body">
365
- <tr><td colspan="6" style="text-align:center; padding:2rem; color:var(--text-muted);">Loading deliveries...</td></tr>
366
- </tbody>
367
- </table>
368
- </div>
369
-
370
- <!-- Pagination Footer -->
371
- <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 1rem; font-size: 12px; color: var(--text-muted);" id="wh-deliveries-pagination">
372
- <span id="wh-page-info">Showing page 1 of 1</span>
373
- <div style="display: flex; gap: 6px;">
374
- <button class="btn btn-secondary btn-sm" id="btn-wh-prev" onclick="changeDeliveryPage(-1)">← Previous</button>
375
- <button class="btn btn-secondary btn-sm" id="btn-wh-next" onclick="changeDeliveryPage(1)">Next →</button>
376
- </div>
377
- </div>
378
- `;
379
-
380
- await fetchAndRenderDeliveriesRows();
381
- }
382
-
383
- async function fetchAndRenderDeliveriesRows() {
384
- const tbody = document.getElementById('wh-deliveries-table-body');
385
- if (!tbody) return;
386
-
387
- const f = webhooksState.deliveryFilter;
388
- const q = new URLSearchParams();
389
- q.set('page', String(f.page));
390
- q.set('perPage', String(f.perPage));
391
- if (f.webhookId) q.set('webhookId', f.webhookId);
392
- if (f.collection) q.set('collection', f.collection);
393
- if (f.status && f.status !== 'all') q.set('status', f.status);
394
- if (f.search) q.set('search', f.search);
395
-
396
- try {
397
- const res = await api('/api/webhooks/deliveries?' + q.toString());
398
- webhooksState.deliveries = res.items || [];
399
- f.totalItems = res.totalItems;
400
- f.totalPages = Math.max(1, res.totalPages);
401
-
402
- const pageInfo = document.getElementById('wh-page-info');
403
- const btnPrev = document.getElementById('btn-wh-prev');
404
- const btnNext = document.getElementById('btn-wh-next');
405
-
406
- if (pageInfo) {
407
- pageInfo.textContent = `Showing page ${res.page} of ${f.totalPages} (${res.totalItems} total deliver${res.totalItems === 1 ? 'y' : 'ies'})`;
408
- }
409
- if (btnPrev) btnPrev.disabled = res.page <= 1;
410
- if (btnNext) btnNext.disabled = res.page >= f.totalPages;
411
-
412
- if (!res.items || res.items.length === 0) {
413
- tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; padding:3rem; color:var(--text-muted);">No webhook delivery logs found matching filters.</td></tr>`;
414
- return;
415
- }
416
-
417
- tbody.innerHTML = res.items.map(del => {
418
- const is2xx = del.responseStatus >= 200 && del.responseStatus < 300;
419
- const is4xx = del.responseStatus >= 400 && del.responseStatus < 500;
420
- const badgeClass = is2xx ? 'badge-status-2xx' : is4xx ? 'badge-status-4xx' : 'badge-status-5xx';
421
- const statusText = del.responseStatus > 0 ? `${del.responseStatus} ${del.status.toUpperCase()}` : 'FAILED (NETWORK)';
422
-
423
- return `
424
- <tr>
425
- <td>
426
- <span class="badge-status-code ${badgeClass}">
427
- ${escapeHtml(statusText)}
428
- </span>
429
- </td>
430
- <td>
431
- <div style="display: flex; flex-direction: column; gap: 2px;">
432
- <span class="badge-event">${escapeHtml(del.event)}</span>
433
- <span style="font-size: 11px; color: var(--text-muted);">${escapeHtml(del.webhookName)}</span>
434
- </div>
435
- </td>
436
- <td>
437
- <div style="font-family:'JetBrains Mono', monospace; font-size: 12px; color: var(--text-main); word-break: break-all;">
438
- ${escapeHtml(del.url)}
439
- </div>
440
- ${del.error ? `<div style="font-size: 11px; color: var(--accent-danger); margin-top: 2px;">Error: ${escapeHtml(del.error)}</div>` : ''}
441
- </td>
442
- <td>
443
- <div style="font-size: 12px; color: var(--text-main);">${del.durationMs}ms</div>
444
- <div style="font-size: 11px; color: var(--text-muted);">Attempt #${del.attempt || 1}</div>
445
- </td>
446
- <td>
447
- <div style="font-size: 11px; color: var(--text-muted);" title="${del.created}">
448
- ${formatRelativeTime(del.created)}
449
- </div>
450
- </td>
451
- <td style="text-align: right; white-space: nowrap;">
452
- <div style="display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
453
- <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(del.id)}" onclick="openDeliveryDetailModal(this.getAttribute('data-id'))" title="Inspect Request Payload & Response" style="padding: 3px 8px; font-size: 11px;">
454
- 👁 View
455
- </button>
456
- <button class="btn-retry-action" id="btn-retry-${escapeHtml(del.id)}" data-id="${escapeHtml(del.id)}" onclick="retryWebhookDelivery(this.getAttribute('data-id'), this)" title="Manual Retry: Re-send Payload to Target Endpoint">
457
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
458
- Retry
459
- </button>
460
- </div>
461
- </td>
462
- </tr>
463
- `;
464
- }).join('');
465
- } catch (err) {
466
- tbody.innerHTML = `<tr><td colspan="6" style="color: var(--accent-danger); text-align:center; padding:2rem;">Failed to fetch deliveries: ${escapeHtml(err.message || String(err))}</td></tr>`;
467
- }
468
- }
469
-
470
- function handleDeliveryFilterChange() {
471
- const whEl = document.getElementById('wh-filter-webhook');
472
- const colEl = document.getElementById('wh-filter-col');
473
- const statusEl = document.getElementById('wh-filter-status');
474
- const searchEl = document.getElementById('wh-filter-search');
475
-
476
- if (whEl) webhooksState.deliveryFilter.webhookId = whEl.value;
477
- if (colEl) webhooksState.deliveryFilter.collection = colEl.value;
478
- if (statusEl) webhooksState.deliveryFilter.status = statusEl.value;
479
- if (searchEl) webhooksState.deliveryFilter.search = searchEl.value;
480
- webhooksState.deliveryFilter.page = 1;
481
-
482
- fetchAndRenderDeliveriesRows();
483
- }
484
-
485
- function clearDeliveryFilters() {
486
- webhooksState.deliveryFilter = {
487
- webhookId: '',
488
- collection: '',
489
- status: 'all',
490
- search: '',
491
- page: 1,
492
- perPage: 25,
493
- totalItems: 0,
494
- totalPages: 1,
495
- };
496
- loadWebhookDeliveries();
497
- }
498
-
499
- function changeDeliveryPage(delta) {
500
- const newPage = webhooksState.deliveryFilter.page + delta;
501
- if (newPage >= 1 && newPage <= webhooksState.deliveryFilter.totalPages) {
502
- webhooksState.deliveryFilter.page = newPage;
503
- fetchAndRenderDeliveriesRows();
504
- }
505
- }
506
-
507
- /**
508
- * Manual Retry Action: Re-delivers the exact payload and updates UI in real-time
509
- */
510
- async function retryWebhookDelivery(deliveryId, btnElement) {
511
- if (btnElement) {
512
- btnElement.disabled = true;
513
- btnElement.classList.add('retrying');
514
- btnElement.innerHTML = `
515
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
516
- Retrying...
517
- `;
518
- }
519
-
520
- try {
521
- const result = await api(`/api/webhooks/deliveries/${deliveryId}/retry`, { method: 'POST' });
522
- const is2xx = result && result.responseStatus >= 200 && result.responseStatus < 300;
523
-
524
- if (is2xx) {
525
- if (typeof toast === 'function') {
526
- toast(`Webhook retried successfully: HTTP ${result.responseStatus} (${result.durationMs}ms)`, 'success');
527
- }
528
- } else {
529
- if (typeof toast === 'function') {
530
- toast(`Retry completed with status: HTTP ${result.responseStatus || 0} (${result.error || 'Failed'})`, 'warning');
531
- }
532
- }
533
-
534
- await loadWebhookStats();
535
- await fetchAndRenderDeliveriesRows();
536
- } catch (err) {
537
- if (typeof toast === 'function') {
538
- toast(`Retry failed: ${err.message || String(err)}`, 'error');
539
- }
540
- } finally {
541
- if (btnElement) {
542
- btnElement.disabled = false;
543
- btnElement.classList.remove('retrying');
544
- btnElement.innerHTML = `
545
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
546
- Retry
547
- `;
548
- }
549
- }
550
- }
551
-
552
- async function triggerTestWebhook(webhookId) {
553
- try {
554
- if (typeof toast === 'function') toast('Dispatching live test webhook...', 'info');
555
- const result = await api(`/api/webhooks/${webhookId}/test`, { method: 'POST' });
556
- const is2xx = result.responseStatus >= 200 && result.responseStatus < 300;
557
-
558
- if (is2xx) {
559
- if (typeof toast === 'function') {
560
- toast(`Test successful! Received HTTP ${result.responseStatus} in ${result.durationMs}ms`, 'success');
561
- }
562
- } else {
563
- if (typeof toast === 'function') {
564
- toast(`Test received HTTP ${result.responseStatus || 0}: ${result.error || 'Failed'}`, 'warning');
565
- }
566
- }
567
-
568
- await loadWebhookStats();
569
- openDeliveryDetailModal(result.id);
570
- } catch (err) {
571
- if (typeof toast === 'function') {
572
- toast(`Test webhook dispatch failed: ${err.message || String(err)}`, 'error');
573
- }
574
- }
575
- }
576
-
577
- async function clearAllDeliveryLogs() {
578
- if (!confirm('Are you sure you want to clear all webhook delivery logs? This cannot be undone.')) {
579
- return;
580
- }
581
- try {
582
- const res = await api('/api/webhooks/deliveries', { method: 'DELETE' });
583
- if (typeof toast === 'function') toast(`Cleared ${res.deletedCount || 0} delivery log(s)`, 'success');
584
- await loadWebhookStats();
585
- await fetchAndRenderDeliveriesRows();
586
- } catch (err) {
587
- if (typeof toast === 'function') toast(`Failed to clear logs: ${err.message}`, 'error');
588
- }
589
- }
590
-
591
- // ==========================================
592
- // Modal: Create & Edit Webhook
593
- // ==========================================
594
-
595
- function openCreateWebhookModal(webhookToEdit = null) {
596
- webhooksState.activeWebhookForEdit = webhookToEdit;
597
- const isEdit = Boolean(webhookToEdit);
598
- const collections = state.collections || [];
599
-
600
- const initialName = webhookToEdit?.name || '';
601
- const initialUrl = webhookToEdit?.url || '';
602
- const initialCol = webhookToEdit?.collection || (collections[0]?.name || '*');
603
- const initialEvent = webhookToEdit?.event || 'created';
604
- const initialMethod = webhookToEdit?.method || 'POST';
605
- const initialSecret = webhookToEdit?.secret || '';
606
- const initialHeaders = webhookToEdit?.headers ? JSON.stringify(webhookToEdit.headers, null, 2) : '{\n "Content-Type": "application/json"\n}';
607
- const initialEnabled = webhookToEdit ? webhookToEdit.enabled : true;
608
-
609
- const modalHtml = `
610
- <div class="modal-backdrop" id="webhook-modal-backdrop" onclick="if(event.target===this)closeWebhookModal()">
611
- <div class="modal" style="max-width: 650px;">
612
- <div class="modal-header">
613
- <h3 class="modal-title">${isEdit ? 'Edit Webhook Configuration' : 'Create Outbound Webhook'}</h3>
614
- <button class="btn btn-secondary btn-sm" onclick="closeWebhookModal()">✕</button>
615
- </div>
616
-
617
- <div class="modal-body" style="display: flex; flex-direction: column; gap: 14px; max-height: 75vh; overflow-y: auto;">
618
- <!-- Name -->
619
- <div class="form-group">
620
- <label class="form-label" for="wh-form-name">Webhook Name *</label>
621
- <input type="text" id="wh-form-name" class="form-control" placeholder="e.g. Order Notification Service" value="${escapeHtml(initialName)}" />
622
- </div>
623
-
624
- <!-- Target Endpoint URL & Method -->
625
- <div style="display: grid; grid-template-columns: 130px 1fr; gap: 12px;">
626
- <div class="form-group">
627
- <label class="form-label" for="wh-form-method">Method *</label>
628
- <select id="wh-form-method" class="form-control">
629
- <option value="POST" ${initialMethod === 'POST' ? 'selected' : ''}>POST</option>
630
- <option value="PUT" ${initialMethod === 'PUT' ? 'selected' : ''}>PUT</option>
631
- <option value="PATCH" ${initialMethod === 'PATCH' ? 'selected' : ''}>PATCH</option>
632
- <option value="DELETE" ${initialMethod === 'DELETE' ? 'selected' : ''}>DELETE</option>
633
- <option value="GET" ${initialMethod === 'GET' ? 'selected' : ''}>GET</option>
634
- <option value="HEAD" ${initialMethod === 'HEAD' ? 'selected' : ''}>HEAD</option>
635
- </select>
636
- </div>
637
- <div class="form-group">
638
- <label class="form-label" for="wh-form-url">Target Endpoint URL *</label>
639
- <input type="url" id="wh-form-url" class="form-control" placeholder="https://api.example.com/webhooks" value="${escapeHtml(initialUrl)}" />
640
- </div>
641
- </div>
642
- <div style="font-size: 11px; color: var(--text-muted); margin-top: -6px;">Outbound request dispatched to this URL on matching events (POST/PUT/PATCH/DELETE carry JSON body, GET/HEAD are dispatched body-free with query encoding).</div>
643
-
644
- <!-- Collection & Event Selection -->
645
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
646
- <div class="form-group">
647
- <label class="form-label" for="wh-form-collection">Collection *</label>
648
- <select id="wh-form-collection" class="form-control" onchange="updateWebhookEventPreview()">
649
- <option value="*" ${initialCol === '*' ? 'selected' : ''}>* (All Collections)</option>
650
- ${collections.map(c => `<option value="${c.name}" ${initialCol === c.name ? 'selected' : ''}>${c.name}</option>`).join('')}
651
- </select>
652
- </div>
653
-
654
- <div class="form-group">
655
- <label class="form-label" for="wh-form-event">Trigger Event *</label>
656
- <select id="wh-form-event" class="form-control" onchange="updateWebhookEventPreview()">
657
- <option value="created" ${initialEvent === 'created' || initialEvent === 'create' ? 'selected' : ''}>Record Created (.created)</option>
658
- <option value="updated" ${initialEvent === 'updated' || initialEvent === 'update' ? 'selected' : ''}>Record Updated (.updated)</option>
659
- <option value="deleted" ${initialEvent === 'deleted' || initialEvent === 'delete' ? 'selected' : ''}>Record Deleted (.deleted)</option>
660
- <option value="*" ${initialEvent === '*' ? 'selected' : ''}>All Events (*)</option>
661
- </select>
662
- </div>
663
- </div>
664
-
665
- <!-- Event Preview Badge -->
666
- <div style="background: rgba(255, 255, 255, 0.03); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 8px 12px; display: flex; align-items: center; justify-content: space-between;">
667
- <span style="font-size: 12px; color: var(--text-muted);">Preview Matched Event:</span>
668
- <span class="badge-event" id="wh-form-event-preview">${initialCol === '*' ? '*' : initialCol}.${initialEvent}</span>
669
- </div>
670
-
671
- <!-- Secret Signature (X-NodeStack-Signature) -->
672
- <div class="form-group">
673
- <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
674
- <label class="form-label" for="wh-form-secret" style="margin-bottom:0;">Secret Signature Key (Optional)</label>
675
- <button type="button" class="btn btn-secondary btn-sm" onclick="generateRandomWebhookSecret()" style="padding: 2px 8px; font-size: 11px;">
676
- ⚡ Generate Secret
677
- </button>
678
- </div>
679
- <input type="text" id="wh-form-secret" class="form-control" placeholder="Enter signing secret or click Generate" value="${escapeHtml(initialSecret)}" style="font-family:'JetBrains Mono', monospace;" />
680
- <div style="font-size: 11px; color: var(--text-muted); margin-top: 3px;">
681
- When provided, NodeStack calculates HMAC-SHA256 of the payload and sends it in the <code>X-NodeStack-Signature</code> header.
682
- </div>
683
- </div>
684
-
685
- <!-- Custom Headers -->
686
- <div class="form-group">
687
- <label class="form-label" for="wh-form-headers">Custom HTTP Headers (JSON)</label>
688
- <textarea id="wh-form-headers" class="form-control" rows="3" style="font-family:'JetBrains Mono', monospace; font-size: 11px;">${escapeHtml(initialHeaders)}</textarea>
689
- <div style="font-size: 11px; color: var(--text-muted); margin-top: 3px;">
690
- Optional custom headers (e.g. <code>Authorization: Bearer ...</code>, <code>X-Api-Key</code>).
691
- </div>
692
- </div>
693
-
694
- <!-- Enabled Checkbox -->
695
- <div style="display: flex; align-items: center; gap: 8px; margin-top: 4px;">
696
- <input type="checkbox" id="wh-form-enabled" ${initialEnabled ? 'checked' : ''} style="cursor: pointer;" />
697
- <label for="wh-form-enabled" style="font-size: 13px; color: var(--text-main); cursor: pointer; user-select: none;">
698
- Enable this webhook for immediate outbound dispatch
699
- </label>
700
- </div>
701
- </div>
702
-
703
- <div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 8px;">
704
- <button class="btn btn-secondary btn-sm" onclick="closeWebhookModal()">Cancel</button>
705
- <button class="btn btn-primary btn-sm" id="btn-save-webhook" data-id="${escapeHtml(webhookToEdit?.id || '')}" onclick="submitWebhookForm(this.getAttribute('data-id'))">
706
- ${isEdit ? 'Save Changes' : 'Create Webhook'}
707
- </button>
708
- </div>
709
- </div>
710
- </div>
711
- `;
712
-
713
- const modalRoot = document.getElementById('modal-root');
714
- if (modalRoot) {
715
- modalRoot.innerHTML = modalHtml;
716
- }
717
- }
718
-
719
- function closeWebhookModal() {
720
- const modalRoot = document.getElementById('modal-root');
721
- if (modalRoot) {
722
- modalRoot.innerHTML = '';
723
- }
724
- }
725
-
726
- function updateWebhookEventPreview() {
727
- const colEl = document.getElementById('wh-form-collection');
728
- const evEl = document.getElementById('wh-form-event');
729
- const preview = document.getElementById('wh-form-event-preview');
730
- if (colEl && evEl && preview) {
731
- const col = colEl.value;
732
- const ev = evEl.value;
733
- preview.textContent = `${col}.${ev}`;
734
- }
735
- }
736
-
737
- function generateRandomWebhookSecret() {
738
- const secretEl = document.getElementById('wh-form-secret');
739
- if (!secretEl) return;
740
- const array = new Uint8Array(24);
741
- window.crypto.getRandomValues(array);
742
- const secret = Array.from(array, b => b.toString(16).padStart(2, '0')).join('');
743
- secretEl.value = 'whsec_' + secret;
744
- }
745
-
746
- async function submitWebhookForm(existingId) {
747
- const targetId = existingId || webhooksState.activeWebhookForEdit?.id || null;
748
- const nameEl = document.getElementById('wh-form-name');
749
- const urlEl = document.getElementById('wh-form-url');
750
- const methodEl = document.getElementById('wh-form-method');
751
- const colEl = document.getElementById('wh-form-collection');
752
- const evEl = document.getElementById('wh-form-event');
753
- const secretEl = document.getElementById('wh-form-secret');
754
- const headersEl = document.getElementById('wh-form-headers');
755
- const enabledEl = document.getElementById('wh-form-enabled');
756
- const saveBtn = document.getElementById('btn-save-webhook');
757
-
758
- const name = nameEl?.value?.trim();
759
- const url = urlEl?.value?.trim();
760
- const method = methodEl?.value || 'POST';
761
- const collection = colEl?.value || '*';
762
- const event = evEl?.value || 'created';
763
- const secret = secretEl?.value?.trim() || null;
764
- const enabled = Boolean(enabledEl?.checked);
765
-
766
- if (!name) {
767
- if (typeof toast === 'function') toast('Please enter a webhook name', 'warning');
768
- nameEl?.focus();
769
- return;
770
- }
771
- if (!url) {
772
- if (typeof toast === 'function') toast('Please enter a target HTTP URL', 'warning');
773
- urlEl?.focus();
774
- return;
775
- }
776
-
777
- let headers = {};
778
- if (headersEl && headersEl.value.trim()) {
779
- try {
780
- headers = JSON.parse(headersEl.value.trim());
781
- } catch {
782
- if (typeof toast === 'function') toast('Headers must be valid JSON', 'error');
783
- headersEl.focus();
784
- return;
785
- }
786
- }
787
-
788
- const payload = {
789
- name,
790
- url,
791
- method,
792
- collection,
793
- event,
794
- headers,
795
- secret,
796
- enabled,
797
- };
798
-
799
- if (saveBtn) {
800
- saveBtn.disabled = true;
801
- saveBtn.textContent = 'Saving...';
802
- }
803
-
804
- try {
805
- if (targetId) {
806
- await api(`/api/webhooks/${targetId}`, {
807
- method: 'PATCH',
808
- body: JSON.stringify(payload),
809
- });
810
- if (typeof toast === 'function') toast('Webhook updated successfully', 'success');
811
- } else {
812
- await api('/api/webhooks', {
813
- method: 'POST',
814
- body: JSON.stringify(payload),
815
- });
816
- if (typeof toast === 'function') toast('Webhook created successfully', 'success');
817
- }
818
-
819
- closeWebhookModal();
820
- await loadWebhookStats();
821
- await loadWebhooksList();
822
- } catch (err) {
823
- if (typeof toast === 'function') toast(err.message || 'Failed to save webhook', 'error');
824
- if (saveBtn) {
825
- saveBtn.disabled = false;
826
- saveBtn.textContent = targetId ? 'Save Changes' : 'Create Webhook';
827
- }
828
- }
829
- }
830
-
831
- async function openEditWebhookModal(id) {
832
- try {
833
- const webhook = await api(`/api/webhooks/${id}`);
834
- if (webhook) {
835
- openCreateWebhookModal(webhook);
836
- }
837
- } catch (err) {
838
- if (typeof toast === 'function') toast('Failed to load webhook: ' + err.message, 'error');
839
- }
840
- }
841
-
842
- function handleDeleteWebhookClick(btnEl) {
843
- if (!btnEl) return;
844
- const id = btnEl.getAttribute('data-id');
845
- const name = btnEl.getAttribute('data-name');
846
- deleteWebhook(id, name);
847
- }
848
-
849
- async function deleteWebhook(id, name) {
850
- const webhook = (webhooksState.webhooks || []).find(w => w.id === id);
851
- const webhookName = name || webhook?.name || 'this webhook';
852
- if (!confirm(`Are you sure you want to delete webhook "${webhookName}"?`)) {
853
- return;
854
- }
855
- try {
856
- await api(`/api/webhooks/${id}`, { method: 'DELETE' });
857
- if (typeof toast === 'function') toast('Webhook deleted', 'success');
858
- await loadWebhookStats();
859
- await loadWebhooksList();
860
- } catch (err) {
861
- if (typeof toast === 'function') toast('Failed to delete webhook: ' + err.message, 'error');
862
- }
863
- }
864
-
865
- // ==========================================
866
- // Slide-Over Drawer: Delivery Details Inspection
867
- // ==========================================
868
-
869
- async function openDeliveryDetailDrawer(deliveryId) {
870
- try {
871
- const del = await api(`/api/webhooks/deliveries/${deliveryId}`);
872
- if (!del) return;
873
-
874
- let root = document.getElementById('drawer-root');
875
- if (!root) {
876
- root = document.createElement('div');
877
- root.id = 'drawer-root';
878
- document.body.appendChild(root);
879
- }
880
-
881
- const is2xx = del.responseStatus >= 200 && del.responseStatus < 300;
882
- const is4xx = del.responseStatus >= 400 && del.responseStatus < 500;
883
- const badgeClass = is2xx ? 'badge-status-2xx' : is4xx ? 'badge-status-4xx' : 'badge-status-5xx';
884
- const statusText = del.responseStatus > 0 ? `${del.responseStatus} ${del.status.toUpperCase()}` : 'FAILED (NETWORK)';
885
-
886
- root.innerHTML = `
887
- <div id="webhook-drawer-backdrop" class="drawer-backdrop" onclick="closeWebhookDrawer()" aria-hidden="true"></div>
888
- <aside id="webhook-drawer-panel" class="record-drawer webhook-drawer" role="dialog" aria-modal="true" aria-labelledby="webhook-drawer-title" tabindex="-1">
889
- <!-- Drawer Header -->
890
- <div class="drawer-header">
891
- <div class="drawer-title-area">
892
- <span class="badge-status-code ${badgeClass}">${escapeHtml(statusText)}</span>
893
- <div>
894
- <h3 class="drawer-title" id="webhook-drawer-title" style="margin:0; font-size:1.05rem;">
895
- ${escapeHtml(del.event)}
896
- </h3>
897
- <span style="font-size:11px; color:var(--text-muted);">${escapeHtml(del.webhookName)} • Attempt #${del.attempt || 1}</span>
898
- </div>
899
- </div>
900
- <div class="drawer-header-actions" style="display:flex; align-items:center; gap:6px;">
901
- <button class="drawer-close-btn" id="webhook-drawer-close-btn" onclick="closeWebhookDrawer()" aria-label="Close drawer">✕</button>
902
- </div>
903
- </div>
904
-
905
- <!-- Drawer Body -->
906
- <div class="drawer-body" style="padding:1.25rem 1.5rem; overflow-y:auto; flex:1; display:flex; flex-direction:column; gap:1.15rem;">
907
- <!-- Meta Grid -->
908
- <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(110px, 1fr)); gap:8px; background:rgba(255,255,255,0.03); border:1px solid var(--border-subtle); border-radius:8px; padding:10px 14px; font-size:12px;">
909
- <div>
910
- <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Status</span>
911
- <strong style="color:${is2xx ? '#34d399' : '#f87171'};">${del.status.toUpperCase()} (${del.responseStatus || 0})</strong>
912
- </div>
913
- <div>
914
- <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Duration</span>
915
- <span>${del.durationMs}ms</span>
916
- </div>
917
- <div>
918
- <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Attempt</span>
919
- <span>#${del.attempt || 1}</span>
920
- </div>
921
- <div>
922
- <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Delivered</span>
923
- <span title="${del.created}">${formatRelativeTime(del.created)}</span>
924
- </div>
925
- </div>
926
-
927
- <!-- Error Alert Banner (if failed) -->
928
- ${del.error ? `
929
- <div style="background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.3); border-radius:6px; padding:10px 14px; font-size:12px; color: var(--accent-danger);">
930
- <strong>Delivery Error:</strong> ${escapeHtml(del.error)}
931
- </div>
932
- ` : ''}
933
-
934
- <!-- Target Endpoint URL -->
935
- <div>
936
- <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:4px;">
937
- <span style="font-size:11px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Target Endpoint URL</span>
938
- <button class="btn btn-secondary btn-sm" id="btn-copy-webhook-url" data-url="${escapeHtml(del.url)}" onclick="handleCopyWebhookUrl(this)" style="padding:2px 8px; font-size:10px;">Copy URL</button>
939
- </div>
940
- <div style="background:#090d16; border:1px solid var(--border-subtle); border-radius:6px; padding:8px 12px; font-family:'JetBrains Mono', monospace; font-size:12px; color:var(--text-main); word-break:break-all;">
941
- POST ${escapeHtml(del.url)}
942
- </div>
943
- </div>
944
-
945
- <!-- Outbound Request Card -->
946
- <div class="webhook-drawer-card">
947
- <div class="webhook-drawer-card-header">
948
- <span style="font-size:11px; font-weight:700; text-transform:uppercase; color: var(--accent-primary);">Outbound Request</span>
949
- <button class="btn btn-secondary btn-sm" id="btn-copy-webhook-payload" onclick="handleCopyWebhookPayload()" style="padding:2px 8px; font-size:10px;">Copy Payload</button>
950
- </div>
951
- <div class="webhook-drawer-card-body">
952
- <div>
953
- <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Request Headers</span>
954
- <pre class="webhook-code-preview" style="max-height:120px; margin-top:4px;">${escapeHtml(JSON.stringify(del.requestHeaders, null, 2))}</pre>
955
- </div>
956
- <div>
957
- <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Payload Body (JSON)</span>
958
- <pre class="webhook-code-preview" id="wh-req-payload-code" style="max-height:200px; margin-top:4px;">${escapeHtml(JSON.stringify(del.requestPayload, null, 2))}</pre>
959
- </div>
960
- </div>
961
- </div>
962
-
963
- <!-- Endpoint Response Card -->
964
- <div class="webhook-drawer-card">
965
- <div class="webhook-drawer-card-header">
966
- <span style="font-size:11px; font-weight:700; text-transform:uppercase; color:${is2xx ? '#34d399' : '#f87171'};">Endpoint Response</span>
967
- <span class="badge-status-code ${badgeClass}">${escapeHtml(statusText)}</span>
968
- </div>
969
- <div class="webhook-drawer-card-body">
970
- ${del.responseHeaders && Object.keys(del.responseHeaders).length > 0 ? `
971
- <div>
972
- <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Response Headers</span>
973
- <pre class="webhook-code-preview" style="max-height:120px; margin-top:4px;">${escapeHtml(JSON.stringify(del.responseHeaders, null, 2))}</pre>
974
- </div>
975
- ` : ''}
976
- <div>
977
- <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Response Body</span>
978
- <pre class="webhook-code-preview" style="max-height:200px; margin-top:4px;">${escapeHtml(del.responseBody || (del.error ? `Error: ${del.error}` : '(No response body)'))}</pre>
979
- </div>
980
- </div>
981
- </div>
982
- </div>
983
-
984
- <!-- Drawer Footer -->
985
- <div class="drawer-footer" style="padding:1rem 1.5rem; border-top:1px solid var(--border-subtle); display:flex; justify-content:space-between; align-items:center; background:#11141d; flex-shrink:0;">
986
- <button class="btn-retry-action" id="drawer-retry-btn" data-id="${escapeHtml(del.id)}" onclick="retryWebhookDelivery(this.getAttribute('data-id'), this)">
987
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
988
- Retry Delivery Now
989
- </button>
990
- <button class="btn btn-secondary btn-sm" onclick="closeWebhookDrawer()">Close</button>
991
- </div>
992
- </aside>
993
- `;
994
-
995
- // Smooth slide-in animation
996
- const triggerDrawerOpen = () => {
997
- const backdrop = document.getElementById('webhook-drawer-backdrop');
998
- const panel = document.getElementById('webhook-drawer-panel');
999
- if (backdrop) backdrop.classList.add('open');
1000
- if (panel) panel.classList.add('open');
1001
- };
1002
-
1003
- if (typeof requestAnimationFrame === 'function') {
1004
- requestAnimationFrame(triggerDrawerOpen);
1005
- } else {
1006
- triggerDrawerOpen();
1007
- }
1008
- } catch (err) {
1009
- if (typeof toast === 'function') toast('Failed to load delivery details: ' + err.message, 'error');
1010
- }
1011
- }
1012
-
1013
- function closeWebhookDrawer() {
1014
- const backdrop = document.getElementById('webhook-drawer-backdrop');
1015
- const panel = document.getElementById('webhook-drawer-panel');
1016
- if (backdrop) backdrop.classList.remove('open');
1017
- if (panel) panel.classList.remove('open');
1018
- setTimeout(() => {
1019
- const root = document.getElementById('drawer-root');
1020
- if (root && root.querySelector('#webhook-drawer-panel')) {
1021
- root.innerHTML = '';
1022
- }
1023
- }, 280);
1024
- }
1025
-
1026
- function handleCopyWebhookUrl(btnEl) {
1027
- if (!btnEl) return;
1028
- const url = btnEl.getAttribute('data-url') || '';
1029
- copyWebhookText(url, 'URL copied!');
1030
- }
1031
-
1032
- function handleCopyWebhookPayload() {
1033
- const codeEl = document.getElementById('wh-req-payload-code');
1034
- copyWebhookText(codeEl?.textContent || '', 'Payload copied!');
1035
- }
1036
-
1037
- function copyWebhookText(text, msg) {
1038
- if (!text) return;
1039
- if (navigator && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
1040
- navigator.clipboard.writeText(text).catch(() => {});
1041
- }
1042
- if (typeof toast === 'function') toast(msg || 'Copied to clipboard!', 'info');
1043
- }
1044
-
1045
- // Backward compatibility alias
1046
- const openDeliveryDetailModal = openDeliveryDetailDrawer;
1047
-
1048
- // Helpers
1049
- function closeModalDirect(modalId) {
1050
- const el = document.getElementById(modalId);
1051
- if (el) el.remove();
1052
- }
1053
-
1054
- function formatRelativeTime(isoString) {
1055
- if (!isoString) return '';
1056
- const date = new Date(isoString);
1057
- const now = new Date();
1058
- const diffSec = Math.floor((now.getTime() - date.getTime()) / 1000);
1059
-
1060
- if (diffSec < 5) return 'just now';
1061
- if (diffSec < 60) return `${diffSec}s ago`;
1062
- const diffMin = Math.floor(diffSec / 60);
1063
- if (diffMin < 60) return `${diffMin}m ago`;
1064
- const diffHour = Math.floor(diffMin / 60);
1065
- if (diffHour < 24) return `${diffHour}h ago`;
1066
- return date.toLocaleDateString();
1067
- }
1068
-
1069
- // Global Exports
1070
- if (typeof window !== 'undefined') {
1071
- window.renderWebhooksView = renderWebhooksView;
1072
- window.refreshWebhooksView = refreshWebhooksView;
1073
- window.switchWebhooksTab = switchWebhooksTab;
1074
- window.loadWebhookStats = loadWebhookStats;
1075
- window.loadWebhooksList = loadWebhooksList;
1076
- window.loadWebhookDeliveries = loadWebhookDeliveries;
1077
- window.openCreateWebhookModal = openCreateWebhookModal;
1078
- window.openEditWebhookModal = openEditWebhookModal;
1079
- window.deleteWebhook = deleteWebhook;
1080
- window.handleDeleteWebhookClick = handleDeleteWebhookClick;
1081
- window.updateWebhookEventPreview = updateWebhookEventPreview;
1082
- window.generateRandomWebhookSecret = generateRandomWebhookSecret;
1083
- window.submitWebhookForm = submitWebhookForm;
1084
- window.openDeliveryDetailModal = openDeliveryDetailModal;
1085
- window.openDeliveryDetailDrawer = openDeliveryDetailDrawer;
1086
- window.closeWebhookDrawer = closeWebhookDrawer;
1087
- window.closeWebhookModal = closeWebhookModal;
1088
- window.retryWebhookDelivery = retryWebhookDelivery;
1089
- window.triggerTestWebhook = triggerTestWebhook;
1090
- window.clearAllDeliveryLogs = clearAllDeliveryLogs;
1091
- window.handleDeliveryFilterChange = handleDeliveryFilterChange;
1092
- window.clearDeliveryFilters = clearDeliveryFilters;
1093
- window.changeDeliveryPage = changeDeliveryPage;
1094
- window.closeModalDirect = closeModalDirect;
1095
- window.viewWebhookDeliveries = viewWebhookDeliveries;
1096
- window.handleCopyWebhookUrl = handleCopyWebhookUrl;
1097
- window.handleCopyWebhookPayload = handleCopyWebhookPayload;
1098
- window.copyWebhookText = copyWebhookText;
1099
- }
1100
-
1101
- // Automatically load webhook stats if admin token exists
1102
- if (typeof state !== 'undefined' && state.token) {
1103
- loadWebhookStats();
1104
- }
1
+ // Webhooks Manager Module for NodeStack Admin UI
2
+
3
+ let webhooksState = {
4
+ subTab: 'webhooks', // 'webhooks' | 'deliveries'
5
+ webhooks: [],
6
+ stats: {
7
+ totalWebhooks: 0,
8
+ activeWebhooks: 0,
9
+ totalDeliveries: 0,
10
+ successDeliveries: 0,
11
+ failedDeliveries: 0,
12
+ successRate: '100%',
13
+ },
14
+ deliveries: [],
15
+ deliveryFilter: {
16
+ webhookId: '',
17
+ collection: '',
18
+ status: 'all',
19
+ search: '',
20
+ page: 1,
21
+ perPage: 25,
22
+ totalItems: 0,
23
+ totalPages: 1,
24
+ },
25
+ activeWebhookForEdit: null,
26
+ };
27
+
28
+ if (typeof window !== 'undefined') {
29
+ window.webhooksState = webhooksState;
30
+ }
31
+
32
+ function renderWebhooksView() {
33
+ const container = document.getElementById('page-view-webhooks') || document.getElementById('main-body');
34
+ if (!container) return;
35
+
36
+ container.innerHTML = `
37
+ <div class="webhooks-container">
38
+ <!-- Header -->
39
+ <div class="webhooks-header">
40
+ <div class="webhooks-title-area">
41
+ <h2>
42
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
43
+ <path d="M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c0-2.21 1.79-4 4-4h5.99c1.1 0 1.95-.94 2.48-1.9A4 4 0 0 1 22 13c0 2.21-1.79 4-4 4z"/>
44
+ <circle cx="6" cy="17" r="1"/>
45
+ <circle cx="18" cy="13" r="1"/>
46
+ </svg>
47
+ Webhooks Manager
48
+ </h2>
49
+ <p>Configure outbound HTTP webhooks on collection mutations with HMAC signing and delivery tracking.</p>
50
+ </div>
51
+ <div style="display: flex; align-items: center; gap: 8px;">
52
+ <button class="btn btn-secondary btn-sm" onclick="refreshWebhooksView()" title="Refresh Webhooks & Logs">
53
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
54
+ Refresh
55
+ </button>
56
+ <button class="btn btn-primary btn-sm" onclick="openCreateWebhookModal()">
57
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
58
+ New Webhook
59
+ </button>
60
+ </div>
61
+ </div>
62
+
63
+ <!-- Stats Grid -->
64
+ <div class="webhooks-stats-grid" id="webhooks-stats-grid">
65
+ <div class="webhook-stat-card">
66
+ <span class="webhook-stat-label">Active Webhooks</span>
67
+ <div class="webhook-stat-value">
68
+ <span id="wh-stat-active">0</span>
69
+ <span class="webhook-stat-subtext" id="wh-stat-total">/ 0 total</span>
70
+ </div>
71
+ </div>
72
+ <div class="webhook-stat-card">
73
+ <span class="webhook-stat-label">Total Deliveries</span>
74
+ <div class="webhook-stat-value" id="wh-stat-deliveries">0</div>
75
+ </div>
76
+ <div class="webhook-stat-card">
77
+ <span class="webhook-stat-label">Success Rate</span>
78
+ <div class="webhook-stat-value" style="color: var(--accent-success);" id="wh-stat-rate">100%</div>
79
+ </div>
80
+ <div class="webhook-stat-card">
81
+ <span class="webhook-stat-label">Failed Deliveries</span>
82
+ <div class="webhook-stat-value" style="color: var(--accent-danger);" id="wh-stat-failed">0</div>
83
+ </div>
84
+ </div>
85
+
86
+ <!-- Subtabs Bar -->
87
+ <div class="webhooks-tabs-bar">
88
+ <button class="webhook-tab-btn ${webhooksState.subTab === 'webhooks' ? 'active' : ''}" id="tab-btn-wh-list" onclick="switchWebhooksTab('webhooks')">
89
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
90
+ Configured Webhooks
91
+ </button>
92
+ <button class="webhook-tab-btn ${webhooksState.subTab === 'deliveries' ? 'active' : ''}" id="tab-btn-wh-deliveries" onclick="switchWebhooksTab('deliveries')">
93
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
94
+ Delivery Logs
95
+ </button>
96
+ </div>
97
+
98
+ <!-- Content Area -->
99
+ <div id="webhooks-tab-content">
100
+ <!-- Rendered by switchWebhooksTab() -->
101
+ </div>
102
+ </div>
103
+ `;
104
+
105
+ loadWebhookStats();
106
+ if (webhooksState.subTab === 'webhooks') {
107
+ loadWebhooksList();
108
+ } else {
109
+ loadWebhookDeliveries();
110
+ }
111
+ }
112
+
113
+ async function refreshWebhooksView() {
114
+ await loadWebhookStats();
115
+ if (webhooksState.subTab === 'webhooks') {
116
+ await loadWebhooksList();
117
+ } else {
118
+ await loadWebhookDeliveries();
119
+ }
120
+ if (typeof toast === 'function') toast('Webhooks updated', 'info');
121
+ }
122
+
123
+ function switchWebhooksTab(tab, pushState = true) {
124
+ webhooksState.subTab = tab;
125
+ const btnList = document.getElementById('tab-btn-wh-list');
126
+ const btnDel = document.getElementById('tab-btn-wh-deliveries');
127
+ if (btnList) btnList.classList.toggle('active', tab === 'webhooks');
128
+ if (btnDel) btnDel.classList.toggle('active', tab === 'deliveries');
129
+
130
+ if (pushState) {
131
+ const path = (tab === 'deliveries') ? '/_/webhooks/deliveries' : '/_/webhooks';
132
+ if (typeof updateUrl === 'function') {
133
+ updateUrl(path);
134
+ }
135
+ }
136
+
137
+ if (tab === 'webhooks') {
138
+ loadWebhooksList();
139
+ } else {
140
+ loadWebhookDeliveries();
141
+ }
142
+ if (typeof updateBreadcrumbs === 'function') updateBreadcrumbs();
143
+ }
144
+
145
+ async function loadWebhookStats() {
146
+ try {
147
+ const stats = await api('/api/webhooks/stats');
148
+ if (stats) {
149
+ webhooksState.stats = stats;
150
+ const elActive = document.getElementById('wh-stat-active');
151
+ const elTotal = document.getElementById('wh-stat-total');
152
+ const elDeliveries = document.getElementById('wh-stat-deliveries');
153
+ const elRate = document.getElementById('wh-stat-rate');
154
+ const elFailed = document.getElementById('wh-stat-failed');
155
+
156
+ if (elActive) elActive.textContent = (stats.activeWebhooks !== undefined ? stats.activeWebhooks : 0);
157
+ if (elTotal) elTotal.textContent = `/ ${stats.totalWebhooks !== undefined ? stats.totalWebhooks : 0} total`;
158
+ if (elDeliveries) elDeliveries.textContent = (stats.totalDeliveries !== undefined ? stats.totalDeliveries : 0).toLocaleString();
159
+ if (elRate) elRate.textContent = stats.successRate || '100%';
160
+ if (elFailed) elFailed.textContent = (stats.failedDeliveries !== undefined ? stats.failedDeliveries : 0).toLocaleString();
161
+
162
+ const sidebarBadge = document.getElementById('sidebar-webhooks-count');
163
+ if (sidebarBadge) {
164
+ const count = stats.totalWebhooks !== undefined ? stats.totalWebhooks : stats.activeWebhooks;
165
+ sidebarBadge.textContent = String(count);
166
+ sidebarBadge.title = `${stats.activeWebhooks || 0} active / ${stats.totalWebhooks || 0} total`;
167
+ sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
168
+ }
169
+
170
+ const homeWhEl = document.getElementById('home-stat-webhooks');
171
+ const homeWhSubEl = document.getElementById('home-stat-webhooks-sub');
172
+ if (homeWhEl) {
173
+ homeWhEl.textContent = (stats.totalWebhooks !== undefined ? stats.totalWebhooks : 0).toString();
174
+ }
175
+ if (homeWhSubEl) {
176
+ const active = stats.activeWebhooks || 0;
177
+ const deliveries = stats.totalDeliveries || 0;
178
+ homeWhSubEl.textContent = `${active} active${deliveries > 0 ? ` • ${deliveries} delivered` : ' • 0 delivered'}`;
179
+ }
180
+ }
181
+ } catch (err) {
182
+ console.error('Failed to load webhook stats:', err);
183
+ }
184
+ }
185
+
186
+ // ==========================================
187
+ // Webhook List Rendering
188
+ // ==========================================
189
+
190
+ async function loadWebhooksList() {
191
+ const content = document.getElementById('webhooks-tab-content');
192
+ if (!content) return;
193
+
194
+ content.innerHTML = `<div style="text-align:center; padding:3rem; color:var(--text-muted);">Loading webhooks...</div>`;
195
+
196
+ try {
197
+ const webhooks = await api('/api/webhooks');
198
+ webhooksState.webhooks = webhooks || [];
199
+
200
+ const sidebarBadge = document.getElementById('sidebar-webhooks-count');
201
+ if (sidebarBadge) {
202
+ const count = webhooksState.webhooks.length;
203
+ sidebarBadge.textContent = String(count);
204
+ sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
205
+ }
206
+
207
+ if (!webhooks || webhooks.length === 0) {
208
+ content.innerHTML = `
209
+ <div style="text-align:center; padding: 4rem 2rem; background: var(--bg-card); border: 1px dashed var(--border-subtle); border-radius: 8px;">
210
+ <div style="font-size: 2.5rem; margin-bottom: 0.75rem;">🔗</div>
211
+ <h3 style="margin: 0 0 0.5rem 0; font-size: 1.1rem; color: var(--text-main);">No Outbound Webhooks Configured</h3>
212
+ <p style="margin: 0 0 1.5rem 0; font-size: 0.85rem; color: var(--text-muted); max-width: 480px; margin-left: auto; margin-right: auto;">
213
+ Send real-time HTTP payloads to external endpoints whenever database records in a collection are created, updated, or deleted.
214
+ </p>
215
+ <button class="btn btn-primary btn-sm" onclick="openCreateWebhookModal()">+ Create Your First Webhook</button>
216
+ </div>
217
+ `;
218
+ return;
219
+ }
220
+
221
+ content.innerHTML = `
222
+ <div class="webhook-table-wrapper">
223
+ <table class="webhook-table">
224
+ <thead>
225
+ <tr>
226
+ <th style="min-width: 180px; width: 25%;">Webhook Name</th>
227
+ <th style="min-width: 150px; width: 20%;">Collection & Event</th>
228
+ <th style="min-width: 200px; width: 30%;">Target Endpoint</th>
229
+ <th style="min-width: 130px; width: 10%;">Security</th>
230
+ <th style="min-width: 160px; width: 15%; text-align: right; white-space: nowrap;">Actions</th>
231
+ </tr>
232
+ </thead>
233
+ <tbody>
234
+ ${webhooks.map(wh => {
235
+ const eventFormatted = wh.event.includes('.') ? wh.event : `${wh.collection}.${wh.event}`;
236
+ const hasHeaders = wh.headers && Object.keys(wh.headers).length > 0;
237
+ const headerCount = hasHeaders ? Object.keys(wh.headers).length : 0;
238
+
239
+ return `
240
+ <tr>
241
+ <td>
242
+ <div style="display: flex; align-items: center; gap: 8px;">
243
+ <span class="webhook-status-dot ${wh.enabled ? 'active' : 'paused'}" style="display: inline-block; width: 8px; height: 8px; min-width: 8px; min-height: 8px; flex-shrink: 0; border-radius: 50%; background: ${wh.enabled ? '#10b981' : '#64748b'};" title="${wh.enabled ? 'Active' : 'Disabled'}"></span>
244
+ <div style="min-width: 0;">
245
+ <div style="font-weight: 600; color: var(--text-main); word-break: break-word;">${escapeHtml(wh.name)}</div>
246
+ <div style="font-size: 11px; color: var(--text-muted);">${wh.enabled ? 'Active' : 'Paused'} • ${wh.method}</div>
247
+ </div>
248
+ </div>
249
+ </td>
250
+ <td>
251
+ <div style="display: flex; flex-direction: column; gap: 4px; align-items: flex-start;">
252
+ <span class="badge-event" title="Collection mutation event trigger">${escapeHtml(eventFormatted)}</span>
253
+ <span style="font-size: 11px; color: var(--text-muted);">Collection: <strong>${escapeHtml(wh.collection)}</strong></span>
254
+ </div>
255
+ </td>
256
+ <td>
257
+ <div style="display: flex; align-items: center; gap: 6px;">
258
+ <span style="font-family:'JetBrains Mono', monospace; font-size: 12px; color: var(--text-main); word-break: break-all;">${escapeHtml(wh.url)}</span>
259
+ </div>
260
+ ${hasHeaders ? `<div style="font-size: 11px; color: var(--text-muted); margin-top: 2px;">${headerCount} custom header${headerCount === 1 ? '' : 's'}</div>` : ''}
261
+ </td>
262
+ <td>
263
+ ${wh.secret ? `
264
+ <span class="badge-signature" title="Payloads signed with HMAC-SHA256 in X-NodeStack-Signature header">
265
+ 🔒 X-NodeStack-Signature
266
+ </span>
267
+ ` : `
268
+ <span style="font-size: 11px; color: var(--text-muted);">No secret</span>
269
+ `}
270
+ </td>
271
+ <td style="text-align: right; white-space: nowrap;">
272
+ <div style="display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
273
+ <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="triggerTestWebhook(this.getAttribute('data-id'))" title="Test Webhook with Live Sample Event" style="padding: 3px 8px; font-size: 11px;">
274
+ ⚡ Test
275
+ </button>
276
+ <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="viewWebhookDeliveries(this.getAttribute('data-id'))" title="View Delivery Logs" style="padding: 3px 8px; font-size: 11px;">
277
+ Logs
278
+ </button>
279
+ <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" onclick="openEditWebhookModal(this.getAttribute('data-id'))" title="Edit Webhook" style="padding: 3px 8px; font-size: 11px;">
280
+ Edit
281
+ </button>
282
+ <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(wh.id)}" data-name="${escapeHtml(wh.name)}" onclick="handleDeleteWebhookClick(this)" title="Delete Webhook" style="padding: 3px 6px; font-size: 11px; color: var(--accent-danger);">
283
+ ✕
284
+ </button>
285
+ </div>
286
+ </td>
287
+ </tr>
288
+ `;
289
+ }).join('')}
290
+ </tbody>
291
+ </table>
292
+ </div>
293
+ `;
294
+ } catch (err) {
295
+ content.innerHTML = `<div style="color: var(--accent-danger); padding:2rem; text-align:center;">Failed to load webhooks: ${escapeHtml(err.message || String(err))}</div>`;
296
+ }
297
+ }
298
+
299
+ function viewWebhookDeliveries(webhookId) {
300
+ webhooksState.deliveryFilter.webhookId = webhookId;
301
+ webhooksState.deliveryFilter.page = 1;
302
+ switchWebhooksTab('deliveries');
303
+ }
304
+
305
+ // ==========================================
306
+ // Delivery Logs Rendering & Manual Retry
307
+ // ==========================================
308
+
309
+ async function loadWebhookDeliveries() {
310
+ const content = document.getElementById('webhooks-tab-content');
311
+ if (!content) return;
312
+
313
+ const f = webhooksState.deliveryFilter;
314
+ const collectionsList = (state.collections || []).map(c => c.name);
315
+
316
+ content.innerHTML = `
317
+ <!-- Filter Bar -->
318
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; margin-bottom: 1rem; background: var(--bg-card); border: 1px solid var(--border-subtle); padding: 10px 14px; border-radius: 8px;">
319
+ <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px; font-size: 12px;">
320
+ <select id="wh-filter-webhook" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
321
+ <option value="">All Webhooks</option>
322
+ ${(Array.isArray(webhooksState.webhooks) ? webhooksState.webhooks : []).map(w => `<option value="${w.id}" ${f.webhookId === w.id ? 'selected' : ''}>${escapeHtml(w.name)}</option>`).join('')}
323
+ </select>
324
+
325
+ <select id="wh-filter-col" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
326
+ <option value="">All Collections</option>
327
+ ${collectionsList.map(c => `<option value="${c}" ${f.collection === c ? 'selected' : ''}>${c}</option>`).join('')}
328
+ </select>
329
+
330
+ <select id="wh-filter-status" class="form-control" style="width: auto; padding: 4px 8px; font-size: 12px;" onchange="handleDeliveryFilterChange()">
331
+ <option value="all" ${f.status === 'all' ? 'selected' : ''}>All Statuses</option>
332
+ <option value="success" ${f.status === 'success' ? 'selected' : ''}>Success Only</option>
333
+ <option value="failed" ${f.status === 'failed' ? 'selected' : ''}>Failed Only</option>
334
+ </select>
335
+
336
+ <input
337
+ type="text"
338
+ id="wh-filter-search"
339
+ placeholder="Search url, event, or error..."
340
+ value="${escapeHtml(f.search)}"
341
+ class="form-control"
342
+ style="width: 200px; padding: 4px 8px; font-size: 12px;"
343
+ onkeyup="if(event.key==='Enter') handleDeliveryFilterChange()"
344
+ />
345
+ <button class="btn btn-secondary btn-sm" onclick="handleDeliveryFilterChange()" style="padding: 4px 8px;">Filter</button>
346
+ ${(f.webhookId || f.collection || f.status !== 'all' || f.search) ? `
347
+ <button class="btn btn-secondary btn-sm" onclick="clearDeliveryFilters()" style="padding: 4px 8px; font-size: 11px;">Clear Filters</button>
348
+ ` : ''}
349
+ </div>
350
+
351
+ <div>
352
+ <button class="btn btn-secondary btn-sm" onclick="clearAllDeliveryLogs()" style="color: var(--accent-danger); font-size: 11px; padding: 4px 8px;">
353
+ Clear Logs
354
+ </button>
355
+ </div>
356
+ </div>
357
+
358
+ <!-- Deliveries Table Container -->
359
+ <div class="webhook-table-wrapper">
360
+ <table class="webhook-table">
361
+ <thead>
362
+ <tr>
363
+ <th style="min-width: 130px; width: 14%; white-space: nowrap;">Response Code</th>
364
+ <th style="min-width: 150px; width: 16%;">Event</th>
365
+ <th style="min-width: 200px; width: 30%;">Target Endpoint</th>
366
+ <th style="min-width: 120px; width: 14%; white-space: nowrap;">Duration / Attempt</th>
367
+ <th style="min-width: 120px; width: 12%; white-space: nowrap;">Delivered At</th>
368
+ <th style="min-width: 130px; width: 14%; text-align: right; white-space: nowrap;">Actions</th>
369
+ </tr>
370
+ </thead>
371
+ <tbody id="wh-deliveries-table-body">
372
+ <tr><td colspan="6" style="text-align:center; padding:2rem; color:var(--text-muted);">Loading deliveries...</td></tr>
373
+ </tbody>
374
+ </table>
375
+ </div>
376
+
377
+ <!-- Pagination Footer -->
378
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 1rem; font-size: 12px; color: var(--text-muted);" id="wh-deliveries-pagination">
379
+ <span id="wh-page-info">Showing page 1 of 1</span>
380
+ <div style="display: flex; gap: 6px;">
381
+ <button class="btn btn-secondary btn-sm" id="btn-wh-prev" onclick="changeDeliveryPage(-1)">← Previous</button>
382
+ <button class="btn btn-secondary btn-sm" id="btn-wh-next" onclick="changeDeliveryPage(1)">Next →</button>
383
+ </div>
384
+ </div>
385
+ `;
386
+
387
+ await fetchAndRenderDeliveriesRows();
388
+ }
389
+
390
+ async function fetchAndRenderDeliveriesRows() {
391
+ const tbody = document.getElementById('wh-deliveries-table-body');
392
+ if (!tbody) return;
393
+
394
+ const f = webhooksState.deliveryFilter;
395
+ const q = new URLSearchParams();
396
+ q.set('page', String(f.page));
397
+ q.set('perPage', String(f.perPage));
398
+ if (f.webhookId) q.set('webhookId', f.webhookId);
399
+ if (f.collection) q.set('collection', f.collection);
400
+ if (f.status && f.status !== 'all') q.set('status', f.status);
401
+ if (f.search) q.set('search', f.search);
402
+
403
+ try {
404
+ const res = await api('/api/webhooks/deliveries?' + q.toString());
405
+ webhooksState.deliveries = res.items || [];
406
+ f.totalItems = res.totalItems;
407
+ f.totalPages = Math.max(1, res.totalPages);
408
+
409
+ const pageInfo = document.getElementById('wh-page-info');
410
+ const btnPrev = document.getElementById('btn-wh-prev');
411
+ const btnNext = document.getElementById('btn-wh-next');
412
+
413
+ if (pageInfo) {
414
+ pageInfo.textContent = `Showing page ${res.page} of ${f.totalPages} (${res.totalItems} total deliver${res.totalItems === 1 ? 'y' : 'ies'})`;
415
+ }
416
+ if (btnPrev) btnPrev.disabled = res.page <= 1;
417
+ if (btnNext) btnNext.disabled = res.page >= f.totalPages;
418
+
419
+ if (!res.items || res.items.length === 0) {
420
+ tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; padding:3rem; color:var(--text-muted);">No webhook delivery logs found matching filters.</td></tr>`;
421
+ return;
422
+ }
423
+
424
+ tbody.innerHTML = res.items.map(del => {
425
+ const is2xx = del.responseStatus >= 200 && del.responseStatus < 300;
426
+ const is4xx = del.responseStatus >= 400 && del.responseStatus < 500;
427
+ const badgeClass = is2xx ? 'badge-status-2xx' : is4xx ? 'badge-status-4xx' : 'badge-status-5xx';
428
+ const statusText = del.responseStatus > 0 ? `${del.responseStatus} ${del.status.toUpperCase()}` : 'FAILED (NETWORK)';
429
+
430
+ return `
431
+ <tr>
432
+ <td>
433
+ <span class="badge-status-code ${badgeClass}">
434
+ ${escapeHtml(statusText)}
435
+ </span>
436
+ </td>
437
+ <td>
438
+ <div style="display: flex; flex-direction: column; gap: 2px;">
439
+ <span class="badge-event">${escapeHtml(del.event)}</span>
440
+ <span style="font-size: 11px; color: var(--text-muted);">${escapeHtml(del.webhookName)}</span>
441
+ </div>
442
+ </td>
443
+ <td>
444
+ <div style="font-family:'JetBrains Mono', monospace; font-size: 12px; color: var(--text-main); word-break: break-all;">
445
+ ${escapeHtml(del.url)}
446
+ </div>
447
+ ${del.error ? `<div style="font-size: 11px; color: var(--accent-danger); margin-top: 2px;">Error: ${escapeHtml(del.error)}</div>` : ''}
448
+ </td>
449
+ <td>
450
+ <div style="font-size: 12px; color: var(--text-main);">${del.durationMs}ms</div>
451
+ <div style="font-size: 11px; color: var(--text-muted);">Attempt #${del.attempt || 1}</div>
452
+ </td>
453
+ <td>
454
+ <div style="font-size: 11px; color: var(--text-muted);" title="${del.created}">
455
+ ${formatRelativeTime(del.created)}
456
+ </div>
457
+ </td>
458
+ <td style="text-align: right; white-space: nowrap;">
459
+ <div style="display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;">
460
+ <button class="btn btn-secondary btn-sm" data-id="${escapeHtml(del.id)}" onclick="openDeliveryDetailModal(this.getAttribute('data-id'))" title="Inspect Request Payload & Response" style="padding: 3px 8px; font-size: 11px;">
461
+ 👁 View
462
+ </button>
463
+ <button class="btn-retry-action" id="btn-retry-${escapeHtml(del.id)}" data-id="${escapeHtml(del.id)}" onclick="retryWebhookDelivery(this.getAttribute('data-id'), this)" title="Manual Retry: Re-send Payload to Target Endpoint">
464
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
465
+ Retry
466
+ </button>
467
+ </div>
468
+ </td>
469
+ </tr>
470
+ `;
471
+ }).join('');
472
+ } catch (err) {
473
+ tbody.innerHTML = `<tr><td colspan="6" style="color: var(--accent-danger); text-align:center; padding:2rem;">Failed to fetch deliveries: ${escapeHtml(err.message || String(err))}</td></tr>`;
474
+ }
475
+ }
476
+
477
+ function handleDeliveryFilterChange() {
478
+ const whEl = document.getElementById('wh-filter-webhook');
479
+ const colEl = document.getElementById('wh-filter-col');
480
+ const statusEl = document.getElementById('wh-filter-status');
481
+ const searchEl = document.getElementById('wh-filter-search');
482
+
483
+ if (whEl) webhooksState.deliveryFilter.webhookId = whEl.value;
484
+ if (colEl) webhooksState.deliveryFilter.collection = colEl.value;
485
+ if (statusEl) webhooksState.deliveryFilter.status = statusEl.value;
486
+ if (searchEl) webhooksState.deliveryFilter.search = searchEl.value;
487
+ webhooksState.deliveryFilter.page = 1;
488
+
489
+ fetchAndRenderDeliveriesRows();
490
+ }
491
+
492
+ function clearDeliveryFilters() {
493
+ webhooksState.deliveryFilter = {
494
+ webhookId: '',
495
+ collection: '',
496
+ status: 'all',
497
+ search: '',
498
+ page: 1,
499
+ perPage: 25,
500
+ totalItems: 0,
501
+ totalPages: 1,
502
+ };
503
+ loadWebhookDeliveries();
504
+ }
505
+
506
+ function changeDeliveryPage(delta) {
507
+ const newPage = webhooksState.deliveryFilter.page + delta;
508
+ if (newPage >= 1 && newPage <= webhooksState.deliveryFilter.totalPages) {
509
+ webhooksState.deliveryFilter.page = newPage;
510
+ fetchAndRenderDeliveriesRows();
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Manual Retry Action: Re-delivers the exact payload and updates UI in real-time
516
+ */
517
+ async function retryWebhookDelivery(deliveryId, btnElement) {
518
+ if (btnElement) {
519
+ btnElement.disabled = true;
520
+ btnElement.classList.add('retrying');
521
+ btnElement.innerHTML = `
522
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
523
+ Retrying...
524
+ `;
525
+ }
526
+
527
+ try {
528
+ const result = await api(`/api/webhooks/deliveries/${deliveryId}/retry`, { method: 'POST' });
529
+ const is2xx = result && result.responseStatus >= 200 && result.responseStatus < 300;
530
+
531
+ if (is2xx) {
532
+ if (typeof toast === 'function') {
533
+ toast(`Webhook retried successfully: HTTP ${result.responseStatus} (${result.durationMs}ms)`, 'success');
534
+ }
535
+ } else {
536
+ if (typeof toast === 'function') {
537
+ toast(`Retry completed with status: HTTP ${result.responseStatus || 0} (${result.error || 'Failed'})`, 'warning');
538
+ }
539
+ }
540
+
541
+ await loadWebhookStats();
542
+ await fetchAndRenderDeliveriesRows();
543
+ } catch (err) {
544
+ if (typeof toast === 'function') {
545
+ toast(`Retry failed: ${err.message || String(err)}`, 'error');
546
+ }
547
+ } finally {
548
+ if (btnElement) {
549
+ btnElement.disabled = false;
550
+ btnElement.classList.remove('retrying');
551
+ btnElement.innerHTML = `
552
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
553
+ Retry
554
+ `;
555
+ }
556
+ }
557
+ }
558
+
559
+ async function triggerTestWebhook(webhookId) {
560
+ try {
561
+ if (typeof toast === 'function') toast('Dispatching live test webhook...', 'info');
562
+ const result = await api(`/api/webhooks/${webhookId}/test`, { method: 'POST' });
563
+ const is2xx = result.responseStatus >= 200 && result.responseStatus < 300;
564
+
565
+ if (is2xx) {
566
+ if (typeof toast === 'function') {
567
+ toast(`Test successful! Received HTTP ${result.responseStatus} in ${result.durationMs}ms`, 'success');
568
+ }
569
+ } else {
570
+ if (typeof toast === 'function') {
571
+ toast(`Test received HTTP ${result.responseStatus || 0}: ${result.error || 'Failed'}`, 'warning');
572
+ }
573
+ }
574
+
575
+ await loadWebhookStats();
576
+ openDeliveryDetailModal(result.id);
577
+ } catch (err) {
578
+ if (typeof toast === 'function') {
579
+ toast(`Test webhook dispatch failed: ${err.message || String(err)}`, 'error');
580
+ }
581
+ }
582
+ }
583
+
584
+ async function clearAllDeliveryLogs() {
585
+ if (!confirm('Are you sure you want to clear all webhook delivery logs? This cannot be undone.')) {
586
+ return;
587
+ }
588
+ try {
589
+ const res = await api('/api/webhooks/deliveries', { method: 'DELETE' });
590
+ if (typeof toast === 'function') toast(`Cleared ${res.deletedCount || 0} delivery log(s)`, 'success');
591
+ await loadWebhookStats();
592
+ await fetchAndRenderDeliveriesRows();
593
+ } catch (err) {
594
+ if (typeof toast === 'function') toast(`Failed to clear logs: ${err.message}`, 'error');
595
+ }
596
+ }
597
+
598
+ // ==========================================
599
+ // Modal: Create & Edit Webhook
600
+ // ==========================================
601
+
602
+ function openCreateWebhookModal(webhookToEdit = null) {
603
+ webhooksState.activeWebhookForEdit = webhookToEdit;
604
+ const isEdit = Boolean(webhookToEdit);
605
+ const collections = state.collections || [];
606
+
607
+ const initialName = webhookToEdit?.name || '';
608
+ const initialUrl = webhookToEdit?.url || '';
609
+ const initialCol = webhookToEdit?.collection || (collections[0]?.name || '*');
610
+ const initialEvent = webhookToEdit?.event || 'created';
611
+ const initialMethod = webhookToEdit?.method || 'POST';
612
+ const initialSecret = webhookToEdit?.secret || '';
613
+ const initialHeaders = webhookToEdit?.headers ? JSON.stringify(webhookToEdit.headers, null, 2) : '{\n "Content-Type": "application/json"\n}';
614
+ const initialEnabled = webhookToEdit ? webhookToEdit.enabled : true;
615
+
616
+ const modalHtml = `
617
+ <div class="modal-backdrop" id="webhook-modal-backdrop" onclick="if(event.target===this)closeWebhookModal()">
618
+ <div class="modal" style="max-width: 650px;">
619
+ <div class="modal-header">
620
+ <h3 class="modal-title">${isEdit ? 'Edit Webhook Configuration' : 'Create Outbound Webhook'}</h3>
621
+ <button class="btn btn-secondary btn-sm" onclick="closeWebhookModal()">✕</button>
622
+ </div>
623
+
624
+ <div class="modal-body" style="display: flex; flex-direction: column; gap: 14px; max-height: 75vh; overflow-y: auto;">
625
+ <!-- Name -->
626
+ <div class="form-group">
627
+ <label class="form-label" for="wh-form-name">Webhook Name *</label>
628
+ <input type="text" id="wh-form-name" class="form-control" placeholder="e.g. Order Notification Service" value="${escapeHtml(initialName)}" />
629
+ </div>
630
+
631
+ <!-- Target Endpoint URL & Method -->
632
+ <div style="display: grid; grid-template-columns: 130px 1fr; gap: 12px;">
633
+ <div class="form-group">
634
+ <label class="form-label" for="wh-form-method">Method *</label>
635
+ <select id="wh-form-method" class="form-control">
636
+ <option value="POST" ${initialMethod === 'POST' ? 'selected' : ''}>POST</option>
637
+ <option value="PUT" ${initialMethod === 'PUT' ? 'selected' : ''}>PUT</option>
638
+ <option value="PATCH" ${initialMethod === 'PATCH' ? 'selected' : ''}>PATCH</option>
639
+ <option value="DELETE" ${initialMethod === 'DELETE' ? 'selected' : ''}>DELETE</option>
640
+ <option value="GET" ${initialMethod === 'GET' ? 'selected' : ''}>GET</option>
641
+ <option value="HEAD" ${initialMethod === 'HEAD' ? 'selected' : ''}>HEAD</option>
642
+ </select>
643
+ </div>
644
+ <div class="form-group">
645
+ <label class="form-label" for="wh-form-url">Target Endpoint URL *</label>
646
+ <input type="url" id="wh-form-url" class="form-control" placeholder="https://api.example.com/webhooks" value="${escapeHtml(initialUrl)}" />
647
+ </div>
648
+ </div>
649
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: -6px;">Outbound request dispatched to this URL on matching events (POST/PUT/PATCH/DELETE carry JSON body, GET/HEAD are dispatched body-free with query encoding).</div>
650
+
651
+ <!-- Collection & Event Selection -->
652
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
653
+ <div class="form-group">
654
+ <label class="form-label" for="wh-form-collection">Collection *</label>
655
+ <select id="wh-form-collection" class="form-control" onchange="updateWebhookEventPreview()">
656
+ <option value="*" ${initialCol === '*' ? 'selected' : ''}>* (All Collections)</option>
657
+ ${collections.map(c => `<option value="${c.name}" ${initialCol === c.name ? 'selected' : ''}>${c.name}</option>`).join('')}
658
+ </select>
659
+ </div>
660
+
661
+ <div class="form-group">
662
+ <label class="form-label" for="wh-form-event">Trigger Event *</label>
663
+ <select id="wh-form-event" class="form-control" onchange="updateWebhookEventPreview()">
664
+ <option value="created" ${initialEvent === 'created' || initialEvent === 'create' ? 'selected' : ''}>Record Created (.created)</option>
665
+ <option value="updated" ${initialEvent === 'updated' || initialEvent === 'update' ? 'selected' : ''}>Record Updated (.updated)</option>
666
+ <option value="deleted" ${initialEvent === 'deleted' || initialEvent === 'delete' ? 'selected' : ''}>Record Deleted (.deleted)</option>
667
+ <option value="*" ${initialEvent === '*' ? 'selected' : ''}>All Events (*)</option>
668
+ </select>
669
+ </div>
670
+ </div>
671
+
672
+ <!-- Event Preview Badge -->
673
+ <div style="background: rgba(255, 255, 255, 0.03); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 8px 12px; display: flex; align-items: center; justify-content: space-between;">
674
+ <span style="font-size: 12px; color: var(--text-muted);">Preview Matched Event:</span>
675
+ <span class="badge-event" id="wh-form-event-preview">${initialCol === '*' ? '*' : initialCol}.${initialEvent}</span>
676
+ </div>
677
+
678
+ <!-- Secret Signature (X-NodeStack-Signature) -->
679
+ <div class="form-group">
680
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
681
+ <label class="form-label" for="wh-form-secret" style="margin-bottom:0;">Secret Signature Key (Optional)</label>
682
+ <button type="button" class="btn btn-secondary btn-sm" onclick="generateRandomWebhookSecret()" style="padding: 2px 8px; font-size: 11px;">
683
+ ⚡ Generate Secret
684
+ </button>
685
+ </div>
686
+ <input type="text" id="wh-form-secret" class="form-control" placeholder="Enter signing secret or click Generate" value="${escapeHtml(initialSecret)}" style="font-family:'JetBrains Mono', monospace;" />
687
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 3px;">
688
+ When provided, NodeStack calculates HMAC-SHA256 of the payload and sends it in the <code>X-NodeStack-Signature</code> header.
689
+ </div>
690
+ </div>
691
+
692
+ <!-- Custom Headers -->
693
+ <div class="form-group">
694
+ <label class="form-label" for="wh-form-headers">Custom HTTP Headers (JSON)</label>
695
+ <textarea id="wh-form-headers" class="form-control" rows="3" style="font-family:'JetBrains Mono', monospace; font-size: 11px;">${escapeHtml(initialHeaders)}</textarea>
696
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 3px;">
697
+ Optional custom headers (e.g. <code>Authorization: Bearer ...</code>, <code>X-Api-Key</code>).
698
+ </div>
699
+ </div>
700
+
701
+ <!-- Enabled Checkbox -->
702
+ <div style="display: flex; align-items: center; gap: 8px; margin-top: 4px;">
703
+ <input type="checkbox" id="wh-form-enabled" ${initialEnabled ? 'checked' : ''} style="cursor: pointer;" />
704
+ <label for="wh-form-enabled" style="font-size: 13px; color: var(--text-main); cursor: pointer; user-select: none;">
705
+ Enable this webhook for immediate outbound dispatch
706
+ </label>
707
+ </div>
708
+ </div>
709
+
710
+ <div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 8px;">
711
+ <button class="btn btn-secondary btn-sm" onclick="closeWebhookModal()">Cancel</button>
712
+ <button class="btn btn-primary btn-sm" id="btn-save-webhook" data-id="${escapeHtml(webhookToEdit?.id || '')}" onclick="submitWebhookForm(this.getAttribute('data-id'))">
713
+ ${isEdit ? 'Save Changes' : 'Create Webhook'}
714
+ </button>
715
+ </div>
716
+ </div>
717
+ </div>
718
+ `;
719
+
720
+ const modalRoot = document.getElementById('modal-root');
721
+ if (modalRoot) {
722
+ modalRoot.innerHTML = modalHtml;
723
+ }
724
+ }
725
+
726
+ function closeWebhookModal() {
727
+ const modalRoot = document.getElementById('modal-root');
728
+ if (modalRoot) {
729
+ modalRoot.innerHTML = '';
730
+ }
731
+ }
732
+
733
+ function updateWebhookEventPreview() {
734
+ const colEl = document.getElementById('wh-form-collection');
735
+ const evEl = document.getElementById('wh-form-event');
736
+ const preview = document.getElementById('wh-form-event-preview');
737
+ if (colEl && evEl && preview) {
738
+ const col = colEl.value;
739
+ const ev = evEl.value;
740
+ preview.textContent = `${col}.${ev}`;
741
+ }
742
+ }
743
+
744
+ function generateRandomWebhookSecret() {
745
+ const secretEl = document.getElementById('wh-form-secret');
746
+ if (!secretEl) return;
747
+ const array = new Uint8Array(24);
748
+ window.crypto.getRandomValues(array);
749
+ const secret = Array.from(array, b => b.toString(16).padStart(2, '0')).join('');
750
+ secretEl.value = 'whsec_' + secret;
751
+ }
752
+
753
+ async function submitWebhookForm(existingId) {
754
+ const targetId = existingId || webhooksState.activeWebhookForEdit?.id || null;
755
+ const nameEl = document.getElementById('wh-form-name');
756
+ const urlEl = document.getElementById('wh-form-url');
757
+ const methodEl = document.getElementById('wh-form-method');
758
+ const colEl = document.getElementById('wh-form-collection');
759
+ const evEl = document.getElementById('wh-form-event');
760
+ const secretEl = document.getElementById('wh-form-secret');
761
+ const headersEl = document.getElementById('wh-form-headers');
762
+ const enabledEl = document.getElementById('wh-form-enabled');
763
+ const saveBtn = document.getElementById('btn-save-webhook');
764
+
765
+ const name = nameEl?.value?.trim();
766
+ const url = urlEl?.value?.trim();
767
+ const method = methodEl?.value || 'POST';
768
+ const collection = colEl?.value || '*';
769
+ const event = evEl?.value || 'created';
770
+ const secret = secretEl?.value?.trim() || null;
771
+ const enabled = Boolean(enabledEl?.checked);
772
+
773
+ if (!name) {
774
+ if (typeof toast === 'function') toast('Please enter a webhook name', 'warning');
775
+ nameEl?.focus();
776
+ return;
777
+ }
778
+ if (!url) {
779
+ if (typeof toast === 'function') toast('Please enter a target HTTP URL', 'warning');
780
+ urlEl?.focus();
781
+ return;
782
+ }
783
+
784
+ let headers = {};
785
+ if (headersEl && headersEl.value.trim()) {
786
+ try {
787
+ headers = JSON.parse(headersEl.value.trim());
788
+ } catch {
789
+ if (typeof toast === 'function') toast('Headers must be valid JSON', 'error');
790
+ headersEl.focus();
791
+ return;
792
+ }
793
+ }
794
+
795
+ const payload = {
796
+ name,
797
+ url,
798
+ method,
799
+ collection,
800
+ event,
801
+ headers,
802
+ secret,
803
+ enabled,
804
+ };
805
+
806
+ if (saveBtn) {
807
+ saveBtn.disabled = true;
808
+ saveBtn.textContent = 'Saving...';
809
+ }
810
+
811
+ try {
812
+ if (targetId) {
813
+ await api(`/api/webhooks/${targetId}`, {
814
+ method: 'PATCH',
815
+ body: JSON.stringify(payload),
816
+ });
817
+ if (typeof toast === 'function') toast('Webhook updated successfully', 'success');
818
+ } else {
819
+ await api('/api/webhooks', {
820
+ method: 'POST',
821
+ body: JSON.stringify(payload),
822
+ });
823
+ if (typeof toast === 'function') toast('Webhook created successfully', 'success');
824
+ }
825
+
826
+ closeWebhookModal();
827
+ await loadWebhookStats();
828
+ await loadWebhooksList();
829
+ } catch (err) {
830
+ if (typeof toast === 'function') toast(err.message || 'Failed to save webhook', 'error');
831
+ if (saveBtn) {
832
+ saveBtn.disabled = false;
833
+ saveBtn.textContent = targetId ? 'Save Changes' : 'Create Webhook';
834
+ }
835
+ }
836
+ }
837
+
838
+ async function openEditWebhookModal(id) {
839
+ try {
840
+ const webhook = await api(`/api/webhooks/${id}`);
841
+ if (webhook) {
842
+ openCreateWebhookModal(webhook);
843
+ }
844
+ } catch (err) {
845
+ if (typeof toast === 'function') toast('Failed to load webhook: ' + err.message, 'error');
846
+ }
847
+ }
848
+
849
+ function handleDeleteWebhookClick(btnEl) {
850
+ if (!btnEl) return;
851
+ const id = btnEl.getAttribute('data-id');
852
+ const name = btnEl.getAttribute('data-name');
853
+ deleteWebhook(id, name);
854
+ }
855
+
856
+ async function deleteWebhook(id, name) {
857
+ const webhook = (webhooksState.webhooks || []).find(w => w.id === id);
858
+ const webhookName = name || webhook?.name || 'this webhook';
859
+ if (!confirm(`Are you sure you want to delete webhook "${webhookName}"?`)) {
860
+ return;
861
+ }
862
+ try {
863
+ await api(`/api/webhooks/${id}`, { method: 'DELETE' });
864
+ if (typeof toast === 'function') toast('Webhook deleted', 'success');
865
+ await loadWebhookStats();
866
+ await loadWebhooksList();
867
+ } catch (err) {
868
+ if (typeof toast === 'function') toast('Failed to delete webhook: ' + err.message, 'error');
869
+ }
870
+ }
871
+
872
+ // ==========================================
873
+ // Slide-Over Drawer: Delivery Details Inspection
874
+ // ==========================================
875
+
876
+ async function openDeliveryDetailDrawer(deliveryId) {
877
+ try {
878
+ const del = await api(`/api/webhooks/deliveries/${deliveryId}`);
879
+ if (!del) return;
880
+
881
+ let root = document.getElementById('drawer-root');
882
+ if (!root) {
883
+ root = document.createElement('div');
884
+ root.id = 'drawer-root';
885
+ document.body.appendChild(root);
886
+ }
887
+
888
+ const is2xx = del.responseStatus >= 200 && del.responseStatus < 300;
889
+ const is4xx = del.responseStatus >= 400 && del.responseStatus < 500;
890
+ const badgeClass = is2xx ? 'badge-status-2xx' : is4xx ? 'badge-status-4xx' : 'badge-status-5xx';
891
+ const statusText = del.responseStatus > 0 ? `${del.responseStatus} ${del.status.toUpperCase()}` : 'FAILED (NETWORK)';
892
+
893
+ root.innerHTML = `
894
+ <div id="webhook-drawer-backdrop" class="drawer-backdrop" onclick="closeWebhookDrawer()" aria-hidden="true"></div>
895
+ <aside id="webhook-drawer-panel" class="record-drawer webhook-drawer" role="dialog" aria-modal="true" aria-labelledby="webhook-drawer-title" tabindex="-1">
896
+ <!-- Drawer Header -->
897
+ <div class="drawer-header">
898
+ <div class="drawer-title-area">
899
+ <span class="badge-status-code ${badgeClass}">${escapeHtml(statusText)}</span>
900
+ <div>
901
+ <h3 class="drawer-title" id="webhook-drawer-title" style="margin:0; font-size:1.05rem;">
902
+ ${escapeHtml(del.event)}
903
+ </h3>
904
+ <span style="font-size:11px; color:var(--text-muted);">${escapeHtml(del.webhookName)} • Attempt #${del.attempt || 1}</span>
905
+ </div>
906
+ </div>
907
+ <div class="drawer-header-actions" style="display:flex; align-items:center; gap:6px;">
908
+ <button class="drawer-close-btn" id="webhook-drawer-close-btn" onclick="closeWebhookDrawer()" aria-label="Close drawer">✕</button>
909
+ </div>
910
+ </div>
911
+
912
+ <!-- Drawer Body -->
913
+ <div class="drawer-body" style="padding:1.25rem 1.5rem; overflow-y:auto; flex:1; display:flex; flex-direction:column; gap:1.15rem;">
914
+ <!-- Meta Grid -->
915
+ <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(110px, 1fr)); gap:8px; background:rgba(255,255,255,0.03); border:1px solid var(--border-subtle); border-radius:8px; padding:10px 14px; font-size:12px;">
916
+ <div>
917
+ <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Status</span>
918
+ <strong style="color:${is2xx ? '#34d399' : '#f87171'};">${del.status.toUpperCase()} (${del.responseStatus || 0})</strong>
919
+ </div>
920
+ <div>
921
+ <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Duration</span>
922
+ <span>${del.durationMs}ms</span>
923
+ </div>
924
+ <div>
925
+ <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Attempt</span>
926
+ <span>#${del.attempt || 1}</span>
927
+ </div>
928
+ <div>
929
+ <span style="font-size:10px; text-transform:uppercase; color:var(--text-muted); font-weight:700; display:block;">Delivered</span>
930
+ <span title="${del.created}">${formatRelativeTime(del.created)}</span>
931
+ </div>
932
+ </div>
933
+
934
+ <!-- Error Alert Banner (if failed) -->
935
+ ${del.error ? `
936
+ <div style="background:rgba(239,68,68,0.1); border:1px solid rgba(239,68,68,0.3); border-radius:6px; padding:10px 14px; font-size:12px; color: var(--accent-danger);">
937
+ <strong>Delivery Error:</strong> ${escapeHtml(del.error)}
938
+ </div>
939
+ ` : ''}
940
+
941
+ <!-- Target Endpoint URL -->
942
+ <div>
943
+ <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:4px;">
944
+ <span style="font-size:11px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Target Endpoint URL</span>
945
+ <button class="btn btn-secondary btn-sm" id="btn-copy-webhook-url" data-url="${escapeHtml(del.url)}" onclick="handleCopyWebhookUrl(this)" style="padding:2px 8px; font-size:10px;">Copy URL</button>
946
+ </div>
947
+ <div style="background:#090d16; border:1px solid var(--border-subtle); border-radius:6px; padding:8px 12px; font-family:'JetBrains Mono', monospace; font-size:12px; color:var(--text-main); word-break:break-all;">
948
+ POST ${escapeHtml(del.url)}
949
+ </div>
950
+ </div>
951
+
952
+ <!-- Outbound Request Card -->
953
+ <div class="webhook-drawer-card">
954
+ <div class="webhook-drawer-card-header">
955
+ <span style="font-size:11px; font-weight:700; text-transform:uppercase; color: var(--accent-primary);">Outbound Request</span>
956
+ <button class="btn btn-secondary btn-sm" id="btn-copy-webhook-payload" onclick="handleCopyWebhookPayload()" style="padding:2px 8px; font-size:10px;">Copy Payload</button>
957
+ </div>
958
+ <div class="webhook-drawer-card-body">
959
+ <div>
960
+ <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Request Headers</span>
961
+ <pre class="webhook-code-preview" style="max-height:120px; margin-top:4px;">${escapeHtml(JSON.stringify(del.requestHeaders, null, 2))}</pre>
962
+ </div>
963
+ <div>
964
+ <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Payload Body (JSON)</span>
965
+ <pre class="webhook-code-preview" id="wh-req-payload-code" style="max-height:200px; margin-top:4px;">${escapeHtml(JSON.stringify(del.requestPayload, null, 2))}</pre>
966
+ </div>
967
+ </div>
968
+ </div>
969
+
970
+ <!-- Endpoint Response Card -->
971
+ <div class="webhook-drawer-card">
972
+ <div class="webhook-drawer-card-header">
973
+ <span style="font-size:11px; font-weight:700; text-transform:uppercase; color:${is2xx ? '#34d399' : '#f87171'};">Endpoint Response</span>
974
+ <span class="badge-status-code ${badgeClass}">${escapeHtml(statusText)}</span>
975
+ </div>
976
+ <div class="webhook-drawer-card-body">
977
+ ${del.responseHeaders && Object.keys(del.responseHeaders).length > 0 ? `
978
+ <div>
979
+ <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Response Headers</span>
980
+ <pre class="webhook-code-preview" style="max-height:120px; margin-top:4px;">${escapeHtml(JSON.stringify(del.responseHeaders, null, 2))}</pre>
981
+ </div>
982
+ ` : ''}
983
+ <div>
984
+ <span style="font-size:10px; font-weight:700; text-transform:uppercase; color:var(--text-muted);">Response Body</span>
985
+ <pre class="webhook-code-preview" style="max-height:200px; margin-top:4px;">${escapeHtml(del.responseBody || (del.error ? `Error: ${del.error}` : '(No response body)'))}</pre>
986
+ </div>
987
+ </div>
988
+ </div>
989
+ </div>
990
+
991
+ <!-- Drawer Footer -->
992
+ <div class="drawer-footer" style="padding:1rem 1.5rem; border-top:1px solid var(--border-subtle); display:flex; justify-content:space-between; align-items:center; background:#11141d; flex-shrink:0;">
993
+ <button class="btn-retry-action" id="drawer-retry-btn" data-id="${escapeHtml(del.id)}" onclick="retryWebhookDelivery(this.getAttribute('data-id'), this)">
994
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg>
995
+ Retry Delivery Now
996
+ </button>
997
+ <button class="btn btn-secondary btn-sm" onclick="closeWebhookDrawer()">Close</button>
998
+ </div>
999
+ </aside>
1000
+ `;
1001
+
1002
+ // Smooth slide-in animation
1003
+ const triggerDrawerOpen = () => {
1004
+ const backdrop = document.getElementById('webhook-drawer-backdrop');
1005
+ const panel = document.getElementById('webhook-drawer-panel');
1006
+ if (backdrop) backdrop.classList.add('open');
1007
+ if (panel) panel.classList.add('open');
1008
+ };
1009
+
1010
+ if (typeof requestAnimationFrame === 'function') {
1011
+ requestAnimationFrame(triggerDrawerOpen);
1012
+ } else {
1013
+ triggerDrawerOpen();
1014
+ }
1015
+ } catch (err) {
1016
+ if (typeof toast === 'function') toast('Failed to load delivery details: ' + err.message, 'error');
1017
+ }
1018
+ }
1019
+
1020
+ function closeWebhookDrawer() {
1021
+ const backdrop = document.getElementById('webhook-drawer-backdrop');
1022
+ const panel = document.getElementById('webhook-drawer-panel');
1023
+ if (backdrop) backdrop.classList.remove('open');
1024
+ if (panel) panel.classList.remove('open');
1025
+ setTimeout(() => {
1026
+ const root = document.getElementById('drawer-root');
1027
+ if (root && root.querySelector('#webhook-drawer-panel')) {
1028
+ root.innerHTML = '';
1029
+ }
1030
+ }, 280);
1031
+ }
1032
+
1033
+ function handleCopyWebhookUrl(btnEl) {
1034
+ if (!btnEl) return;
1035
+ const url = btnEl.getAttribute('data-url') || '';
1036
+ copyWebhookText(url, 'URL copied!');
1037
+ }
1038
+
1039
+ function handleCopyWebhookPayload() {
1040
+ const codeEl = document.getElementById('wh-req-payload-code');
1041
+ copyWebhookText(codeEl?.textContent || '', 'Payload copied!');
1042
+ }
1043
+
1044
+ function copyWebhookText(text, msg) {
1045
+ if (!text) return;
1046
+ if (navigator && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
1047
+ navigator.clipboard.writeText(text).catch(() => {});
1048
+ }
1049
+ if (typeof toast === 'function') toast(msg || 'Copied to clipboard!', 'info');
1050
+ }
1051
+
1052
+ // Backward compatibility alias
1053
+ const openDeliveryDetailModal = openDeliveryDetailDrawer;
1054
+
1055
+ // Helpers
1056
+ function closeModalDirect(modalId) {
1057
+ const el = document.getElementById(modalId);
1058
+ if (el) el.remove();
1059
+ }
1060
+
1061
+ function formatRelativeTime(isoString) {
1062
+ if (!isoString) return '';
1063
+ const date = new Date(isoString);
1064
+ const now = new Date();
1065
+ const diffSec = Math.floor((now.getTime() - date.getTime()) / 1000);
1066
+
1067
+ if (diffSec < 5) return 'just now';
1068
+ if (diffSec < 60) return `${diffSec}s ago`;
1069
+ const diffMin = Math.floor(diffSec / 60);
1070
+ if (diffMin < 60) return `${diffMin}m ago`;
1071
+ const diffHour = Math.floor(diffMin / 60);
1072
+ if (diffHour < 24) return `${diffHour}h ago`;
1073
+ return date.toLocaleDateString();
1074
+ }
1075
+
1076
+ // Global Exports
1077
+ if (typeof window !== 'undefined') {
1078
+ window.renderWebhooksView = renderWebhooksView;
1079
+ window.refreshWebhooksView = refreshWebhooksView;
1080
+ window.switchWebhooksTab = switchWebhooksTab;
1081
+ window.loadWebhookStats = loadWebhookStats;
1082
+ window.loadWebhooksList = loadWebhooksList;
1083
+ window.loadWebhookDeliveries = loadWebhookDeliveries;
1084
+ window.openCreateWebhookModal = openCreateWebhookModal;
1085
+ window.openEditWebhookModal = openEditWebhookModal;
1086
+ window.deleteWebhook = deleteWebhook;
1087
+ window.handleDeleteWebhookClick = handleDeleteWebhookClick;
1088
+ window.updateWebhookEventPreview = updateWebhookEventPreview;
1089
+ window.generateRandomWebhookSecret = generateRandomWebhookSecret;
1090
+ window.submitWebhookForm = submitWebhookForm;
1091
+ window.openDeliveryDetailModal = openDeliveryDetailModal;
1092
+ window.openDeliveryDetailDrawer = openDeliveryDetailDrawer;
1093
+ window.closeWebhookDrawer = closeWebhookDrawer;
1094
+ window.closeWebhookModal = closeWebhookModal;
1095
+ window.retryWebhookDelivery = retryWebhookDelivery;
1096
+ window.triggerTestWebhook = triggerTestWebhook;
1097
+ window.clearAllDeliveryLogs = clearAllDeliveryLogs;
1098
+ window.handleDeliveryFilterChange = handleDeliveryFilterChange;
1099
+ window.clearDeliveryFilters = clearDeliveryFilters;
1100
+ window.changeDeliveryPage = changeDeliveryPage;
1101
+ window.closeModalDirect = closeModalDirect;
1102
+ window.viewWebhookDeliveries = viewWebhookDeliveries;
1103
+ window.handleCopyWebhookUrl = handleCopyWebhookUrl;
1104
+ window.handleCopyWebhookPayload = handleCopyWebhookPayload;
1105
+ window.copyWebhookText = copyWebhookText;
1106
+ }
1107
+
1108
+ // Automatically load webhook stats if admin token exists
1109
+ if (typeof state !== 'undefined' && state.token) {
1110
+ loadWebhookStats();
1111
+ }