@nodestackapp/server 1.3.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 (201) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +14 -13
  3. package/dist/NodeStack.d.ts +14 -0
  4. package/dist/NodeStack.d.ts.map +1 -1
  5. package/dist/NodeStack.js +42 -3
  6. package/dist/NodeStack.js.map +1 -1
  7. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  8. package/dist/admin/AdminUIBundler.js +10 -5
  9. package/dist/admin/AdminUIBundler.js.map +1 -1
  10. package/dist/admin/ui/css/analytics.css +68 -11
  11. package/dist/admin/ui/css/codemirror.css +98 -0
  12. package/dist/admin/ui/css/main.css +372 -78
  13. package/dist/admin/ui/css/rules.css +292 -264
  14. package/dist/admin/ui/css/webhooks.css +34 -10
  15. package/dist/admin/ui/index.html +9326 -5706
  16. package/dist/admin/ui/js/analytics.js +673 -624
  17. package/dist/admin/ui/js/api.js +60 -14
  18. package/dist/admin/ui/js/app.js +480 -263
  19. package/dist/admin/ui/js/apps.js +50 -17
  20. package/dist/admin/ui/js/codemirror.js +15 -0
  21. package/dist/admin/ui/js/collections.js +41 -13
  22. package/dist/admin/ui/js/command-palette.js +61 -19
  23. package/dist/admin/ui/js/demo.js +373 -271
  24. package/dist/admin/ui/js/functions-tester.js +432 -0
  25. package/dist/admin/ui/js/functions-workbench.js +1038 -0
  26. package/dist/admin/ui/js/functions.js +765 -0
  27. package/dist/admin/ui/js/modals.js +20 -16
  28. package/dist/admin/ui/js/plugin-tester.js +562 -559
  29. package/dist/admin/ui/js/plugins.js +221 -90
  30. package/dist/admin/ui/js/records.js +96 -61
  31. package/dist/admin/ui/js/rules.js +1 -1
  32. package/dist/admin/ui/js/schema.js +23 -9
  33. package/dist/admin/ui/js/theme.js +120 -0
  34. package/dist/admin/ui/js/views.js +680 -714
  35. package/dist/admin/ui/js/webhooks.js +1111 -1086
  36. package/dist/apps/AppScope.d.ts +6 -0
  37. package/dist/apps/AppScope.d.ts.map +1 -1
  38. package/dist/apps/AppScope.js +40 -4
  39. package/dist/apps/AppScope.js.map +1 -1
  40. package/dist/auth/ApiKeyService.d.ts +91 -0
  41. package/dist/auth/ApiKeyService.d.ts.map +1 -0
  42. package/dist/auth/ApiKeyService.js +414 -0
  43. package/dist/auth/ApiKeyService.js.map +1 -0
  44. package/dist/auth/AuthService.d.ts +33 -1
  45. package/dist/auth/AuthService.d.ts.map +1 -1
  46. package/dist/auth/AuthService.js +255 -10
  47. package/dist/auth/AuthService.js.map +1 -1
  48. package/dist/auth/oauth/AppleProvider.d.ts +23 -0
  49. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -0
  50. package/dist/auth/oauth/AppleProvider.js +161 -0
  51. package/dist/auth/oauth/AppleProvider.js.map +1 -0
  52. package/dist/auth/oauth/BaseOAuthProvider.d.ts +18 -0
  53. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -0
  54. package/dist/auth/oauth/BaseOAuthProvider.js +79 -0
  55. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -0
  56. package/dist/auth/oauth/DiscordProvider.d.ts +11 -0
  57. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -0
  58. package/dist/auth/oauth/DiscordProvider.js +47 -0
  59. package/dist/auth/oauth/DiscordProvider.js.map +1 -0
  60. package/dist/auth/oauth/GitHubProvider.d.ts +13 -0
  61. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -0
  62. package/dist/auth/oauth/GitHubProvider.js +90 -0
  63. package/dist/auth/oauth/GitHubProvider.js.map +1 -0
  64. package/dist/auth/oauth/GoogleProvider.d.ts +11 -0
  65. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -0
  66. package/dist/auth/oauth/GoogleProvider.js +43 -0
  67. package/dist/auth/oauth/GoogleProvider.js.map +1 -0
  68. package/dist/auth/oauth/MicrosoftProvider.d.ts +11 -0
  69. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -0
  70. package/dist/auth/oauth/MicrosoftProvider.js +83 -0
  71. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -0
  72. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +32 -0
  73. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -0
  74. package/dist/auth/oauth/OAuthProviderRegistry.js +232 -0
  75. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -0
  76. package/dist/auth/oauth/types.d.ts +63 -0
  77. package/dist/auth/oauth/types.d.ts.map +1 -0
  78. package/dist/auth/oauth/types.js +3 -0
  79. package/dist/auth/oauth/types.js.map +1 -0
  80. package/dist/cli/cli.d.ts.map +1 -1
  81. package/dist/cli/cli.js +74 -10
  82. package/dist/cli/cli.js.map +1 -1
  83. package/dist/core/config/ConfigService.d.ts +1 -0
  84. package/dist/core/config/ConfigService.d.ts.map +1 -1
  85. package/dist/core/config/ConfigService.js +4 -1
  86. package/dist/core/config/ConfigService.js.map +1 -1
  87. package/dist/core/container/Tokens.d.ts +4 -0
  88. package/dist/core/container/Tokens.d.ts.map +1 -1
  89. package/dist/core/container/Tokens.js +4 -0
  90. package/dist/core/container/Tokens.js.map +1 -1
  91. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  92. package/dist/core/plugins/PluginManager.js +73 -19
  93. package/dist/core/plugins/PluginManager.js.map +1 -1
  94. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  95. package/dist/database/migrations/SystemMigrations.js +41 -1
  96. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  97. package/dist/demo/DemoService.d.ts +15 -103
  98. package/dist/demo/DemoService.d.ts.map +1 -1
  99. package/dist/demo/DemoService.js +14 -419
  100. package/dist/demo/DemoService.js.map +1 -1
  101. package/dist/functions/FunctionService.d.ts +80 -0
  102. package/dist/functions/FunctionService.d.ts.map +1 -0
  103. package/dist/functions/FunctionService.js +610 -0
  104. package/dist/functions/FunctionService.js.map +1 -0
  105. package/dist/functions/runtime/IFunctionRuntime.d.ts +23 -0
  106. package/dist/functions/runtime/IFunctionRuntime.d.ts.map +1 -0
  107. package/dist/functions/runtime/IFunctionRuntime.js +3 -0
  108. package/dist/functions/runtime/IFunctionRuntime.js.map +1 -0
  109. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts +21 -0
  110. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -0
  111. package/dist/functions/runtime/QuickJsWasmRuntime.js +418 -0
  112. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -0
  113. package/dist/functions/runtime/SandboxedRunner.d.ts +31 -0
  114. package/dist/functions/runtime/SandboxedRunner.d.ts.map +1 -0
  115. package/dist/functions/runtime/SandboxedRunner.js +61 -0
  116. package/dist/functions/runtime/SandboxedRunner.js.map +1 -0
  117. package/dist/functions/security/SsrfGuard.d.ts +41 -0
  118. package/dist/functions/security/SsrfGuard.d.ts.map +1 -0
  119. package/dist/functions/security/SsrfGuard.js +470 -0
  120. package/dist/functions/security/SsrfGuard.js.map +1 -0
  121. package/dist/functions/types.d.ts +109 -0
  122. package/dist/functions/types.d.ts.map +1 -0
  123. package/dist/functions/types.js +3 -0
  124. package/dist/functions/types.js.map +1 -0
  125. package/dist/http/HttpServer.d.ts +9 -1
  126. package/dist/http/HttpServer.d.ts.map +1 -1
  127. package/dist/http/HttpServer.js +108 -8
  128. package/dist/http/HttpServer.js.map +1 -1
  129. package/dist/http/controllers/ApiKeyController.d.ts +31 -0
  130. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -0
  131. package/dist/http/controllers/ApiKeyController.js +52 -0
  132. package/dist/http/controllers/ApiKeyController.js.map +1 -0
  133. package/dist/http/controllers/AuthController.d.ts +29 -1
  134. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  135. package/dist/http/controllers/AuthController.js +42 -1
  136. package/dist/http/controllers/AuthController.js.map +1 -1
  137. package/dist/http/controllers/DemoController.d.ts.map +1 -1
  138. package/dist/http/controllers/DemoController.js +1 -0
  139. package/dist/http/controllers/DemoController.js.map +1 -1
  140. package/dist/http/controllers/FunctionController.d.ts +64 -0
  141. package/dist/http/controllers/FunctionController.d.ts.map +1 -0
  142. package/dist/http/controllers/FunctionController.js +202 -0
  143. package/dist/http/controllers/FunctionController.js.map +1 -0
  144. package/dist/http/controllers/HealthController.js +2 -2
  145. package/dist/http/controllers/RecordController.d.ts.map +1 -1
  146. package/dist/http/controllers/RecordController.js +4 -0
  147. package/dist/http/controllers/RecordController.js.map +1 -1
  148. package/dist/http/controllers/SnapshotController.d.ts +58 -0
  149. package/dist/http/controllers/SnapshotController.d.ts.map +1 -0
  150. package/dist/http/controllers/SnapshotController.js +79 -0
  151. package/dist/http/controllers/SnapshotController.js.map +1 -0
  152. package/dist/http/middleware/AuthMiddleware.d.ts +6 -1
  153. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  154. package/dist/http/middleware/AuthMiddleware.js +79 -8
  155. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  156. package/dist/index.d.ts +15 -2
  157. package/dist/index.d.ts.map +1 -1
  158. package/dist/index.js +28 -3
  159. package/dist/index.js.map +1 -1
  160. package/dist/plugins/chat-notifications.d.ts +51 -0
  161. package/dist/plugins/chat-notifications.d.ts.map +1 -0
  162. package/dist/plugins/chat-notifications.js +545 -0
  163. package/dist/plugins/chat-notifications.js.map +1 -0
  164. package/dist/plugins/index.d.ts +1 -1
  165. package/dist/plugins/index.d.ts.map +1 -1
  166. package/dist/plugins/index.js +1 -1
  167. package/dist/plugins/index.js.map +1 -1
  168. package/dist/plugins/webhooks.d.ts +5 -34
  169. package/dist/plugins/webhooks.d.ts.map +1 -1
  170. package/dist/plugins/webhooks.js +11 -412
  171. package/dist/plugins/webhooks.js.map +1 -1
  172. package/dist/records/MockDataService.d.ts.map +1 -1
  173. package/dist/records/MockDataService.js +3 -0
  174. package/dist/records/MockDataService.js.map +1 -1
  175. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  176. package/dist/records/QueryFilterParser.js +2 -1
  177. package/dist/records/QueryFilterParser.js.map +1 -1
  178. package/dist/records/RecordService.d.ts.map +1 -1
  179. package/dist/records/RecordService.js +70 -43
  180. package/dist/records/RecordService.js.map +1 -1
  181. package/dist/records/RecordValidator.d.ts +6 -0
  182. package/dist/records/RecordValidator.d.ts.map +1 -0
  183. package/dist/records/RecordValidator.js +100 -0
  184. package/dist/records/RecordValidator.js.map +1 -0
  185. package/dist/rules/RuleEngine.d.ts +14 -0
  186. package/dist/rules/RuleEngine.d.ts.map +1 -1
  187. package/dist/rules/RuleEngine.js +144 -1
  188. package/dist/rules/RuleEngine.js.map +1 -1
  189. package/dist/schema/OpenApiGenerator.js +3 -3
  190. package/dist/snapshots/SnapshotService.d.ts +75 -0
  191. package/dist/snapshots/SnapshotService.d.ts.map +1 -0
  192. package/dist/snapshots/SnapshotService.js +775 -0
  193. package/dist/snapshots/SnapshotService.js.map +1 -0
  194. package/dist/snapshots/types.d.ts +63 -0
  195. package/dist/snapshots/types.d.ts.map +1 -0
  196. package/dist/snapshots/types.js +5 -0
  197. package/dist/snapshots/types.js.map +1 -0
  198. package/dist/templates/definitions/ecommerce.js +13 -13
  199. package/dist/templates/definitions/ecommerce.js.map +1 -1
  200. package/dist/webhooks/WebhookService.js +1 -1
  201. package/package.json +4 -3
@@ -0,0 +1,765 @@
1
+ // Serverless Functions Manager Module for NodeStack Admin UI
2
+ // Core state, functions overview list, and global execution logs
3
+
4
+ // ==========================================
5
+ // 1. State & Constants
6
+ // ==========================================
7
+
8
+ let functionsState = {
9
+ currentView: 'list', // 'list' | 'editor'
10
+ subTab: 'functions', // 'functions' | 'logs'
11
+ editorTab: 'code', // 'code' | 'test' | 'config' | 'logs'
12
+ isCtxRefExpanded: false, // vertically collapsible, collapsed by default
13
+ cmEditor: null, // active CodeMirror instance
14
+ functions: [],
15
+ stats: {
16
+ totalFunctions: 0,
17
+ activeFunctions: 0,
18
+ totalExecutions: 0,
19
+ successExecutions: 0,
20
+ failedExecutions: 0,
21
+ successRate: '100%',
22
+ },
23
+ logs: [],
24
+ editorLogs: [],
25
+ logFilter: {
26
+ functionId: '',
27
+ status: 'all',
28
+ page: 1,
29
+ perPage: 25,
30
+ totalItems: 0,
31
+ totalPages: 1,
32
+ },
33
+ activeFunctionForEdit: null,
34
+ };
35
+
36
+ if (typeof window !== 'undefined') {
37
+ window.functionsState = functionsState;
38
+ }
39
+
40
+ const STARTER_RECIPES = {
41
+ starter: `// Serverless Function Starter
42
+ export default async function(ctx) {
43
+ ctx.log("Invoked function in app:", ctx.app.slug);
44
+ const name = ctx.request.body?.name || "World";
45
+ return {
46
+ status: 200,
47
+ body: { message: "Hello, " + name + "!" }
48
+ };
49
+ }`,
50
+ discount: `// Calculate cart discount with RuleEngine access rules preserved
51
+ export default async function(ctx) {
52
+ const { cartTotal, couponCode } = ctx.request.body || {};
53
+ let discountRate = 0;
54
+
55
+ if (couponCode === "SAVE20") {
56
+ discountRate = 0.20;
57
+ } else if (couponCode === "VIP50" && ctx.request.auth) {
58
+ discountRate = 0.50;
59
+ }
60
+
61
+ const discount = (cartTotal || 0) * discountRate;
62
+ const finalTotal = Math.max(0, (cartTotal || 0) - discount);
63
+
64
+ return {
65
+ status: 200,
66
+ headers: { 'x-applied-rate': (discountRate * 100) + '%' },
67
+ body: {
68
+ originalTotal: cartTotal,
69
+ discount: discount,
70
+ finalTotal: finalTotal
71
+ }
72
+ };
73
+ }`,
74
+ hook: `// Lifecycle Hook: validate and enrich records before creation
75
+ export default async function(ctx) {
76
+ if (ctx.event && ctx.event.record) {
77
+ const record = ctx.event.record;
78
+
79
+ // 1. Validation guardrail
80
+ if (record.amount !== undefined && record.amount < 0) {
81
+ return { status: 400, body: { cancel: true, reason: "Amount cannot be negative" } };
82
+ }
83
+
84
+ // 2. Data enrichment / normalization
85
+ if (record.title) {
86
+ record.slug = record.title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
87
+ }
88
+ record.status = "processed";
89
+
90
+ return { status: 200, body: { record: record } };
91
+ }
92
+ return { status: 200 };
93
+ }`,
94
+ fetch: `// Outbound HTTP Integration with SSRF Guardrails
95
+ export default async function(ctx) {
96
+ // Guarded fetch rejects private IPs, loopback, and cloud metadata
97
+ const res = await ctx.fetch('https://httpbin.org/json');
98
+ const data = await res.json();
99
+
100
+ return {
101
+ status: 200,
102
+ body: {
103
+ origin: data.origin,
104
+ url: data.url,
105
+ timestamp: new Date().toISOString()
106
+ }
107
+ };
108
+ }`
109
+ };
110
+
111
+ if (typeof window !== 'undefined') {
112
+ window.STARTER_RECIPES = STARTER_RECIPES;
113
+ }
114
+
115
+ // ==========================================
116
+ // 2. Functions Overview Page & Statistics
117
+ // ==========================================
118
+
119
+ function renderFunctionsView() {
120
+ if (functionsState.currentView === 'editor' && functionsState.activeFunctionForEdit) {
121
+ if (typeof renderFunctionEditorView === 'function') {
122
+ renderFunctionEditorView(functionsState.activeFunctionForEdit);
123
+ }
124
+ return;
125
+ }
126
+
127
+ const container = document.getElementById('page-view-functions') || document.getElementById('main-body');
128
+ if (!container) return;
129
+
130
+ container.innerHTML = `
131
+ <div class="webhooks-container" style="max-width: 1400px; margin: 0 auto; padding: 1.5rem; display: flex; flex-direction: column; gap: 1.25rem;">
132
+ <!-- Header -->
133
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem;">
134
+ <div>
135
+ <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0 0 0.25rem 0; display: flex; align-items: center; gap: 0.5rem;">
136
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
137
+ <polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
138
+ </svg>
139
+ Serverless Functions
140
+ </h2>
141
+ <p style="font-size: 0.85rem; color: var(--text-muted); margin: 0;">
142
+ Sandboxed in-engine JavaScript/TypeScript lambda functions wired to API endpoints and lifecycle hooks.
143
+ </p>
144
+ </div>
145
+ <div style="display: flex; align-items: center; gap: 8px;">
146
+ <button class="btn btn-secondary btn-sm" onclick="refreshFunctionsView()" title="Refresh Functions & Stats">
147
+ <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>
148
+ Refresh
149
+ </button>
150
+ <button class="btn btn-primary btn-sm" onclick="openCreateFunctionPage()">
151
+ <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>
152
+ New Function
153
+ </button>
154
+ </div>
155
+ </div>
156
+
157
+ <!-- Stats Grid -->
158
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
159
+ <div class="webhook-stat-card">
160
+ <span class="webhook-stat-label">Active Functions</span>
161
+ <div class="webhook-stat-value">
162
+ <span id="fn-stat-active">0</span>
163
+ <span class="webhook-stat-subtext" id="fn-stat-total">/ 0 total</span>
164
+ </div>
165
+ </div>
166
+ <div class="webhook-stat-card">
167
+ <span class="webhook-stat-label">Total Executions</span>
168
+ <div class="webhook-stat-value" id="fn-stat-executions">0</div>
169
+ </div>
170
+ <div class="webhook-stat-card">
171
+ <span class="webhook-stat-label">Success Rate</span>
172
+ <div class="webhook-stat-value" style="color: var(--accent-success);" id="fn-stat-rate">100%</div>
173
+ </div>
174
+ <div class="webhook-stat-card">
175
+ <span class="webhook-stat-label">Failed Runs</span>
176
+ <div class="webhook-stat-value" style="color: var(--accent-danger);" id="fn-stat-failed">0</div>
177
+ </div>
178
+ </div>
179
+
180
+ <!-- Subtabs Bar -->
181
+ <div class="webhooks-tabs-bar" style="display: flex; align-items: center; gap: 0.5rem; border-bottom: 1px solid var(--border-subtle); padding-bottom: 0.5rem;">
182
+ <button class="webhook-tab-btn ${functionsState.subTab === 'functions' ? 'active' : ''}" id="tab-btn-fn-list" onclick="switchFunctionsTab('functions')">
183
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
184
+ Configured Functions
185
+ </button>
186
+ <button class="webhook-tab-btn ${functionsState.subTab === 'logs' ? 'active' : ''}" id="tab-btn-fn-logs" onclick="switchFunctionsTab('logs')">
187
+ <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>
188
+ Execution History & Logs
189
+ </button>
190
+ </div>
191
+
192
+ <!-- Tab Content Area -->
193
+ <div id="functions-tab-content"></div>
194
+ </div>
195
+ `;
196
+
197
+ loadFunctionStats();
198
+ if (functionsState.subTab === 'functions') {
199
+ loadFunctionsList();
200
+ } else {
201
+ loadFunctionLogs();
202
+ }
203
+ }
204
+
205
+ function switchFunctionsTab(tab, pushState = true) {
206
+ functionsState.subTab = tab;
207
+ document.getElementById('tab-btn-fn-list')?.classList.toggle('active', tab === 'functions');
208
+ document.getElementById('tab-btn-fn-logs')?.classList.toggle('active', tab === 'logs');
209
+
210
+ if (pushState) {
211
+ const path = (tab === 'logs') ? '/_/functions/logs' : '/_/functions';
212
+ if (typeof updateUrl === 'function') {
213
+ updateUrl(path);
214
+ }
215
+ }
216
+
217
+ if (typeof updateBreadcrumbs === 'function') {
218
+ updateBreadcrumbs();
219
+ }
220
+
221
+ if (tab === 'functions') {
222
+ loadFunctionsList();
223
+ } else {
224
+ loadFunctionLogs();
225
+ }
226
+ }
227
+
228
+ async function refreshFunctionsView() {
229
+ await loadFunctionStats();
230
+ if (functionsState.subTab === 'functions') {
231
+ await loadFunctionsList();
232
+ } else {
233
+ await loadFunctionLogs();
234
+ }
235
+ toast('Functions data refreshed', 'info');
236
+ }
237
+
238
+ async function loadFunctionStats() {
239
+ try {
240
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
241
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/stats` : '/api/functions/stats';
242
+ const res = await api(endpoint);
243
+ if (res) {
244
+ functionsState.stats = res;
245
+ const elActive = document.getElementById('fn-stat-active');
246
+ const elTotal = document.getElementById('fn-stat-total');
247
+ const elExec = document.getElementById('fn-stat-executions');
248
+ const elRate = document.getElementById('fn-stat-rate');
249
+ const elFailed = document.getElementById('fn-stat-failed');
250
+
251
+ if (elActive) elActive.textContent = res.activeFunctions || 0;
252
+ if (elTotal) elTotal.textContent = `/ ${res.totalFunctions || 0} total`;
253
+ if (elExec) elExec.textContent = res.totalExecutions || 0;
254
+ if (elRate) elRate.textContent = res.successRate || '100%';
255
+ if (elFailed) elFailed.textContent = res.failedExecutions || 0;
256
+
257
+ // Update sidebar counter badge
258
+ const sidebarBadge = document.getElementById('sidebar-functions-count');
259
+ if (sidebarBadge) {
260
+ sidebarBadge.textContent = res.totalFunctions || 0;
261
+ sidebarBadge.style.display = (res.totalFunctions > 0) ? 'inline-block' : 'none';
262
+ }
263
+ }
264
+ } catch (err) {
265
+ console.warn('Failed to load function stats:', err);
266
+ }
267
+ }
268
+
269
+ async function loadFunctionsList() {
270
+ const container = document.getElementById('functions-tab-content');
271
+ if (!container) return;
272
+
273
+ container.innerHTML = `
274
+ <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
275
+ <span class="spinner" style="margin-right: 8px;"></span> Loading serverless functions...
276
+ </div>
277
+ `;
278
+
279
+ try {
280
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
281
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
282
+ const list = await api(endpoint);
283
+ functionsState.functions = Array.isArray(list) ? list : [];
284
+
285
+ // Sync count badge
286
+ const count = functionsState.functions.length;
287
+ const sidebarBadge = document.getElementById('sidebar-functions-count');
288
+ if (sidebarBadge) {
289
+ sidebarBadge.textContent = count;
290
+ sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
291
+ }
292
+
293
+ renderFunctionsTable(functionsState.functions);
294
+ } catch (err) {
295
+ container.innerHTML = `
296
+ <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
297
+ <p>Failed to load functions: ${escapeHtml(err.message || String(err))}</p>
298
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionsList()">Try Again</button>
299
+ </div>
300
+ `;
301
+ }
302
+ }
303
+
304
+ function renderFunctionsTable(functions) {
305
+ const container = document.getElementById('functions-tab-content');
306
+ if (!container) return;
307
+
308
+ if (!functions || functions.length === 0) {
309
+ container.innerHTML = `
310
+ <div class="card" style="padding: 3.5rem 1.5rem; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 1rem;">
311
+ <div style="width: 56px; height: 56px; border-radius: 50%; background: var(--bg-card-hover); display: flex; align-items: center; justify-content: center; color: var(--accent-primary);">
312
+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
313
+ </div>
314
+ <div>
315
+ <h3 style="margin: 0 0 0.5rem 0; font-size: 1.25rem; font-weight: 600;">No Serverless Functions Yet</h3>
316
+ <p style="margin: 0; color: var(--text-muted); font-size: 0.875rem; max-width: 480px;">
317
+ Create lightweight, sandboxed functions to implement custom backend logic, third-party webhooks, and database triggers.
318
+ </p>
319
+ </div>
320
+ <button class="btn btn-primary btn-sm" onclick="openCreateFunctionPage()">
321
+ <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>
322
+ Create First Function
323
+ </button>
324
+ </div>
325
+ `;
326
+ return;
327
+ }
328
+
329
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
330
+ const invokePrefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
331
+
332
+ const rows = functions.map(fn => {
333
+ const isEnabled = fn.enabled !== false;
334
+ const authBadgeClass = fn.authPolicy === 'public' ? 'badge-success' : (fn.authPolicy === 'admin' ? 'badge-danger' : 'badge-primary');
335
+ const authLabel = (fn.authPolicy || 'public').toUpperCase();
336
+ const invokePath = `${invokePrefix}/${fn.name}/invoke`;
337
+
338
+ return `
339
+ <tr style="border-bottom: 1px solid var(--border-subtle); transition: background 0.15s ease;">
340
+ <td style="padding: 12px 16px;">
341
+ <div style="display: flex; align-items: center; gap: 8px;">
342
+ <span class="status-indicator ${isEnabled ? 'status-active' : 'status-inactive'}" title="${isEnabled ? 'Active' : 'Disabled'}"></span>
343
+ <div>
344
+ <a href="javascript:void(0)" onclick="openFunctionEditor('${fn.id}')" style="font-weight: 600; color: var(--accent-primary); text-decoration: none; font-size: 13.5px; font-family: monospace;">
345
+ ${escapeHtml(fn.name)}
346
+ </a>
347
+ ${fn.description ? `<div style="font-size: 11.5px; color: var(--text-muted); margin-top: 2px;">${escapeHtml(fn.description)}</div>` : ''}
348
+ </div>
349
+ </div>
350
+ </td>
351
+ <td style="padding: 12px 16px;">
352
+ <span class="badge ${authBadgeClass}" style="font-size: 11px;">${authLabel}</span>
353
+ ${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444; font-size: 10px; margin-left: 4px;" title="Runs with elevated privileges">Elevated</span>' : ''}
354
+ </td>
355
+ <td style="padding: 12px 16px; font-size: 12px;">
356
+ ${fn.eventTrigger ? `<code style="font-size: 11.5px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-heading);">${escapeHtml(fn.eventTrigger)}</code>` : '<span style="color: var(--text-muted);">None (HTTP only)</span>'}
357
+ </td>
358
+ <td style="padding: 12px 16px; font-size: 11.5px; font-family: monospace; color: var(--text-muted);">
359
+ <div style="display: flex; align-items: center; gap: 6px;">
360
+ <span>ANY ${escapeHtml(invokePath)}</span>
361
+ <button class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="padding: 1px 6px; font-size: 10px;" title="Copy endpoint">
362
+ 📋
363
+ </button>
364
+ </div>
365
+ </td>
366
+ <td style="padding: 12px 16px; font-size: 12px; color: var(--text-muted);">
367
+ ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB
368
+ </td>
369
+ <td style="padding: 12px 16px; text-align: right;">
370
+ <div style="display: inline-flex; align-items: center; gap: 6px;">
371
+ <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'test')" title="Test Function in Sandbox">
372
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
373
+ Test
374
+ </button>
375
+ <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'code')" title="Edit Code & Configuration">
376
+ Edit
377
+ </button>
378
+ <button class="btn btn-secondary btn-sm" onclick="toggleFunctionEnabled('${fn.id}', ${!isEnabled})" title="${isEnabled ? 'Disable function' : 'Enable function'}">
379
+ ${isEnabled ? 'Disable' : 'Enable'}
380
+ </button>
381
+ <button class="btn btn-secondary btn-sm" onclick="deleteFunctionPrompt('${fn.id}', '${escapeHtml(fn.name)}')" style="color: var(--accent-danger);" title="Delete function">
382
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
383
+ </button>
384
+ </div>
385
+ </td>
386
+ </tr>
387
+ `;
388
+ }).join('');
389
+
390
+ container.innerHTML = `
391
+ <div class="card" style="padding: 0; overflow: hidden;">
392
+ <div style="overflow-x: auto;">
393
+ <table class="table" style="width: 100%; border-collapse: collapse; text-align: left;">
394
+ <thead>
395
+ <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
396
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
397
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Auth Policy</th>
398
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Hook Trigger</th>
399
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Invoke Endpoint</th>
400
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Limits</th>
401
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Actions</th>
402
+ </tr>
403
+ </thead>
404
+ <tbody>
405
+ ${rows}
406
+ </tbody>
407
+ </table>
408
+ </div>
409
+ </div>
410
+ `;
411
+ }
412
+
413
+ async function toggleFunctionEnabled(id, enabled) {
414
+ try {
415
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
416
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
417
+ await api(endpoint, {
418
+ method: 'PATCH',
419
+ headers: { 'Content-Type': 'application/json' },
420
+ body: JSON.stringify({ enabled }),
421
+ });
422
+ toast(`Function ${enabled ? 'enabled' : 'disabled'}`, 'info');
423
+ await loadFunctionStats();
424
+ await loadFunctionsList();
425
+ } catch (err) {
426
+ toast(err.message || 'Failed to toggle status', 'error');
427
+ }
428
+ }
429
+
430
+ async function deleteFunctionPrompt(id, name) {
431
+ if (!confirm(`Are you sure you want to delete function '${name}'? All invocation history will be removed.`)) {
432
+ return;
433
+ }
434
+ try {
435
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
436
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
437
+ await api(endpoint, { method: 'DELETE' });
438
+ toast(`Function '${name}' deleted`, 'info');
439
+ await loadFunctionStats();
440
+ await loadFunctionsList();
441
+ } catch (err) {
442
+ toast(err.message || 'Failed to delete function', 'error');
443
+ }
444
+ }
445
+
446
+ function copyFunctionEndpoint(path) {
447
+ const fullUrl = window.location.origin + path;
448
+ if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
449
+ navigator.clipboard.writeText(fullUrl).then(() => {
450
+ toast('Copied function endpoint URL to clipboard', 'info');
451
+ }).catch(() => {
452
+ prompt('Copy function endpoint URL:', fullUrl);
453
+ });
454
+ } else {
455
+ prompt('Copy function endpoint URL:', fullUrl);
456
+ }
457
+ }
458
+
459
+ // ==========================================
460
+ // 3. Global Execution History & Logs
461
+ // ==========================================
462
+
463
+ async function loadFunctionLogs(page = 1) {
464
+ const container = document.getElementById('functions-tab-content');
465
+ if (!container) return;
466
+
467
+ container.innerHTML = `
468
+ <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
469
+ <span class="spinner" style="margin-right: 8px;"></span> Loading invocation logs...
470
+ </div>
471
+ `;
472
+
473
+ try {
474
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
475
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
476
+ const params = new URLSearchParams({
477
+ page: String(page),
478
+ perPage: String(functionsState.logFilter.perPage || 25),
479
+ });
480
+ if (functionsState.logFilter.functionId) {
481
+ params.append('functionId', functionsState.logFilter.functionId);
482
+ }
483
+ if (functionsState.logFilter.status && functionsState.logFilter.status !== 'all') {
484
+ params.append('status', functionsState.logFilter.status);
485
+ }
486
+
487
+ const res = await api(`${baseUrl}?${params.toString()}`);
488
+ functionsState.logs = res.items || [];
489
+ functionsState.logFilter.page = res.page || 1;
490
+ functionsState.logFilter.totalItems = res.totalItems || 0;
491
+ functionsState.logFilter.totalPages = res.totalPages || 1;
492
+
493
+ renderFunctionLogsTable(functionsState.logs);
494
+ } catch (err) {
495
+ container.innerHTML = `
496
+ <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
497
+ <p>Failed to load logs: ${escapeHtml(err.message || String(err))}</p>
498
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs()">Try Again</button>
499
+ </div>
500
+ `;
501
+ }
502
+ }
503
+
504
+ function renderFunctionLogsTable(logs) {
505
+ const container = document.getElementById('functions-tab-content');
506
+ if (!container) return;
507
+
508
+ const fnOptions = (functionsState.functions || []).map(f => `
509
+ <option value="${f.id}" ${functionsState.logFilter.functionId === f.id ? 'selected' : ''}>
510
+ ${escapeHtml(f.name)}
511
+ </option>
512
+ `).join('');
513
+
514
+ if (!logs || logs.length === 0) {
515
+ container.innerHTML = `
516
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
517
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
518
+ <div style="display: flex; align-items: center; gap: 8px;">
519
+ <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
520
+ <option value="">All Functions</option>
521
+ ${fnOptions}
522
+ </select>
523
+ </div>
524
+ </div>
525
+ <div style="padding: 3rem 1rem; text-align: center; color: var(--text-muted);">
526
+ No execution logs recorded yet.
527
+ </div>
528
+ </div>
529
+ `;
530
+ return;
531
+ }
532
+
533
+ const rows = logs.map(l => {
534
+ const isOk = l.status === 'success';
535
+ const statusBadge = isOk
536
+ ? `<span class="badge" style="background: rgba(16, 185, 129, 0.15); color: #10b981; font-size: 11px;">${l.statusCode || 200} OK</span>`
537
+ : `<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444; font-size: 11px;">${escapeHtml(l.status.toUpperCase())}</span>`;
538
+
539
+ return `
540
+ <tr style="border-bottom: 1px solid var(--border-subtle);">
541
+ <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${formatTimestamp(l.timestamp || l.createdAt)}</td>
542
+ <td style="padding: 10px 14px;">
543
+ <a href="javascript:void(0)" onclick="openFunctionEditor('${l.functionId}', true, 'logs')" style="font-weight: 600; color: var(--accent-primary); text-decoration: none; font-family: monospace; font-size: 12px;">
544
+ ${escapeHtml(l.functionName || l.functionId)}
545
+ </a>
546
+ </td>
547
+ <td style="padding: 10px 14px;">${statusBadge}</td>
548
+ <td style="padding: 10px 14px; font-size: 12px; font-weight: 600;">${l.durationMs}ms</td>
549
+ <td style="padding: 10px 14px;"><code style="font-size: 11px;">${escapeHtml(l.method || 'POST')}</code></td>
550
+ <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${escapeHtml(l.actorId || 'public')}</td>
551
+ <td style="padding: 10px 14px; text-align: right;">
552
+ <button class="btn btn-secondary btn-sm" onclick="viewLogPayload('${l.id}')" title="Inspect Request/Response payload" style="font-size: 11px; padding: 2px 8px;">
553
+ Inspect
554
+ </button>
555
+ </td>
556
+ </tr>
557
+ `;
558
+ }).join('');
559
+
560
+ container.innerHTML = `
561
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
562
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
563
+ <div style="display: flex; align-items: center; gap: 8px;">
564
+ <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
565
+ <option value="">All Functions</option>
566
+ ${fnOptions}
567
+ </select>
568
+ <span style="font-size: 12px; color: var(--text-muted);">
569
+ Showing ${logs.length} of ${functionsState.logFilter.totalItems || logs.length} logs
570
+ </span>
571
+ </div>
572
+ <div style="display: flex; align-items: center; gap: 8px;">
573
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs(${functionsState.logFilter.page || 1})">
574
+ Refresh
575
+ </button>
576
+ </div>
577
+ </div>
578
+
579
+ <div style="overflow-x: auto; border: 1px solid var(--border-subtle); border-radius: 6px;">
580
+ <table class="table" style="width: 100%; border-collapse: collapse; text-align: left; font-size: 13px;">
581
+ <thead>
582
+ <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
583
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Timestamp</th>
584
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
585
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Status</th>
586
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Latency</th>
587
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Method</th>
588
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Caller</th>
589
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Payload</th>
590
+ </tr>
591
+ </thead>
592
+ <tbody>
593
+ ${rows}
594
+ </tbody>
595
+ </table>
596
+ </div>
597
+ </div>
598
+ `;
599
+ }
600
+
601
+ function filterFunctionLogs(fnId) {
602
+ functionsState.logFilter.functionId = fnId || '';
603
+ loadFunctionLogs(1);
604
+ }
605
+
606
+ function viewFunctionLogs(functionId) {
607
+ switchFunctionsTab('logs');
608
+ filterFunctionLogs(functionId);
609
+ }
610
+
611
+ async function viewLogPayload(logId) {
612
+ let log = (functionsState.editorLogs || []).find(l => l.id === logId)
613
+ || (functionsState.logs || []).find(l => l.id === logId);
614
+
615
+ if (!log) {
616
+ try {
617
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
618
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
619
+ const res = await api(`${baseUrl}?perPage=100`);
620
+ if (res && res.items) {
621
+ log = res.items.find(l => l.id === logId);
622
+ }
623
+ } catch (_) {}
624
+ }
625
+
626
+ if (!log) {
627
+ if (typeof toast === 'function') toast('Execution log details not found', 'warning');
628
+ return;
629
+ }
630
+
631
+ let modalRoot = document.getElementById('modal-root');
632
+ if (!modalRoot) {
633
+ modalRoot = document.createElement('div');
634
+ modalRoot.id = 'modal-root';
635
+ document.body.appendChild(modalRoot);
636
+ }
637
+
638
+ let consoleOutput = '(No console output logged)';
639
+ if (log.logs) {
640
+ if (Array.isArray(log.logs) && log.logs.length > 0) {
641
+ consoleOutput = log.logs.join('\n');
642
+ } else if (typeof log.logs === 'string' && log.logs.trim().length > 0) {
643
+ consoleOutput = log.logs;
644
+ }
645
+ }
646
+
647
+ let reqFormatted = '{}';
648
+ if (log.requestPayload) {
649
+ try {
650
+ reqFormatted = JSON.stringify(typeof log.requestPayload === 'string' ? JSON.parse(log.requestPayload) : log.requestPayload, null, 2);
651
+ } catch {
652
+ reqFormatted = String(log.requestPayload);
653
+ }
654
+ }
655
+
656
+ let resFormatted = '{}';
657
+ if (log.responsePayload) {
658
+ try {
659
+ resFormatted = JSON.stringify(typeof log.responsePayload === 'string' ? JSON.parse(log.responsePayload) : log.responsePayload, null, 2);
660
+ } catch {
661
+ resFormatted = String(log.error || log.responsePayload);
662
+ }
663
+ } else if (log.error) {
664
+ resFormatted = String(log.error);
665
+ }
666
+
667
+ modalRoot.innerHTML = `
668
+ <div class="modal-backdrop" onclick="this.remove()">
669
+ <div class="modal-dialog" style="max-width: 720px; width: 95%; max-height: 85vh; display: flex; flex-direction: column; background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-subtle); overflow: hidden;" onclick="event.stopPropagation()">
670
+ <div style="display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; border-bottom: 1px solid var(--border-subtle);">
671
+ <div style="display: flex; align-items: center; gap: 8px;">
672
+ <h3 style="margin: 0; font-size: 1.1rem; font-weight: 600;">Execution Payload Inspector</h3>
673
+ <span class="badge" style="font-size: 11px;">${log.durationMs}ms</span>
674
+ </div>
675
+ <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()" style="border: none; font-size: 18px; line-height: 1;">✕</button>
676
+ </div>
677
+ <div style="flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 14px;">
678
+ <div>
679
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Console Output Logs</label>
680
+ <pre style="background: #0f172a; color: #38bdf8; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 11px; max-height: 140px; overflow-y: auto; margin: 0; white-space: pre-wrap;">${escapeHtml(consoleOutput)}</pre>
681
+ </div>
682
+ <div>
683
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Request Payload</label>
684
+ <pre style="background: var(--bg-card-hover); padding: 10px; border-radius: 6px; font-family: monospace; font-size: 11px; max-height: 160px; overflow-y: auto; margin: 0;">${escapeHtml(reqFormatted)}</pre>
685
+ </div>
686
+ <div>
687
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Response Payload</label>
688
+ <pre style="background: var(--bg-card-hover); padding: 10px; border-radius: 6px; font-family: monospace; font-size: 11px; max-height: 180px; overflow-y: auto; margin: 0; color: ${log.status === 'success' ? '#a7f3d0' : '#f87171'};">${escapeHtml(resFormatted)}</pre>
689
+ </div>
690
+ </div>
691
+ <div style="padding: 12px 20px; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end;">
692
+ <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()">Close</button>
693
+ </div>
694
+ </div>
695
+ </div>
696
+ `;
697
+ }
698
+
699
+ async function clearAllFunctionLogs() {
700
+ if (!confirm('Are you sure you want to clear execution logs? This cannot be undone.')) return;
701
+ try {
702
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
703
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
704
+ await api(endpoint, { method: 'DELETE' });
705
+ toast('Execution logs cleared', 'info');
706
+ await loadFunctionLogs();
707
+ } catch (err) {
708
+ toast(err.message || 'Failed to clear logs', 'error');
709
+ }
710
+ }
711
+
712
+ function formatTimestamp(iso) {
713
+ if (!iso) return '-';
714
+ try {
715
+ const d = new Date(iso);
716
+ if (isNaN(d.getTime())) return iso;
717
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) + ' ' + d.toLocaleDateString();
718
+ } catch {
719
+ return iso;
720
+ }
721
+ }
722
+
723
+ // Forwarders for workbench functions
724
+ function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
725
+ if (typeof window.openFunctionEditor === 'function' && window.openFunctionEditor !== openFunctionEditor) {
726
+ return window.openFunctionEditor(idOrName, pushState, initialTab);
727
+ }
728
+ }
729
+
730
+ function openCreateFunctionPage() {
731
+ if (typeof window.openCreateFunctionPage === 'function' && window.openCreateFunctionPage !== openCreateFunctionPage) {
732
+ return window.openCreateFunctionPage();
733
+ }
734
+ }
735
+
736
+ // ==========================================
737
+ // 4. Global Exports & Startup Hook
738
+ // ==========================================
739
+
740
+ if (typeof window !== 'undefined') {
741
+ window.functionsState = functionsState;
742
+ window.STARTER_RECIPES = STARTER_RECIPES;
743
+ window.renderFunctionsView = renderFunctionsView;
744
+ window.switchFunctionsTab = switchFunctionsTab;
745
+ window.refreshFunctionsView = refreshFunctionsView;
746
+ window.loadFunctionStats = loadFunctionStats;
747
+ window.loadFunctionsList = loadFunctionsList;
748
+ window.renderFunctionsTable = renderFunctionsTable;
749
+ window.toggleFunctionEnabled = toggleFunctionEnabled;
750
+ window.deleteFunctionPrompt = deleteFunctionPrompt;
751
+ window.copyFunctionEndpoint = copyFunctionEndpoint;
752
+ window.openFunctionEditor = window.openFunctionEditor || openFunctionEditor;
753
+ window.openCreateFunctionPage = window.openCreateFunctionPage || openCreateFunctionPage;
754
+ window.loadFunctionLogs = loadFunctionLogs;
755
+ window.renderFunctionLogsTable = renderFunctionLogsTable;
756
+ window.filterFunctionLogs = filterFunctionLogs;
757
+ window.viewFunctionLogs = viewFunctionLogs;
758
+ window.viewLogPayload = viewLogPayload;
759
+ window.clearAllFunctionLogs = clearAllFunctionLogs;
760
+ window.formatTimestamp = formatTimestamp;
761
+ }
762
+
763
+ if (typeof state !== 'undefined' && state.token && typeof loadFunctionStats === 'function') {
764
+ loadFunctionStats();
765
+ }