@nodestackapp/server 2.5.0 → 2.6.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 (221) hide show
  1. package/README.md +40 -28
  2. package/dist/NodeStack.d.ts +1 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +73 -12
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +1 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +34 -0
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +19150 -17212
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/app.js +667 -641
  14. package/dist/admin/ui/js/apps.js +496 -489
  15. package/dist/admin/ui/js/collections.js +486 -484
  16. package/dist/admin/ui/js/command-palette.js +683 -673
  17. package/dist/admin/ui/js/flows-designer.js +1125 -1076
  18. package/dist/admin/ui/js/flows.js +908 -890
  19. package/dist/admin/ui/js/functions-tester.js +1 -1
  20. package/dist/admin/ui/js/functions-workbench.js +1144 -1101
  21. package/dist/admin/ui/js/functions.js +980 -979
  22. package/dist/admin/ui/js/rules.js +1080 -775
  23. package/dist/admin/ui/js/schema.js +346 -304
  24. package/dist/admin/ui/js/views.js +1 -1
  25. package/dist/apps/AppManager.d.ts +1 -1
  26. package/dist/apps/AppManager.d.ts.map +1 -1
  27. package/dist/apps/AppManager.js +4 -18
  28. package/dist/apps/AppManager.js.map +1 -1
  29. package/dist/apps/AppRegistry.d.ts +1 -0
  30. package/dist/apps/AppRegistry.d.ts.map +1 -1
  31. package/dist/apps/AppRegistry.js +78 -23
  32. package/dist/apps/AppRegistry.js.map +1 -1
  33. package/dist/apps/AppScope.d.ts +0 -1
  34. package/dist/apps/AppScope.d.ts.map +1 -1
  35. package/dist/apps/AppScope.js +5 -15
  36. package/dist/apps/AppScope.js.map +1 -1
  37. package/dist/auth/ApiKeyService.d.ts +62 -2
  38. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  39. package/dist/auth/ApiKeyService.js +503 -8
  40. package/dist/auth/ApiKeyService.js.map +1 -1
  41. package/dist/auth/AuthService.d.ts +30 -1
  42. package/dist/auth/AuthService.d.ts.map +1 -1
  43. package/dist/auth/AuthService.js +468 -65
  44. package/dist/auth/AuthService.js.map +1 -1
  45. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  46. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  47. package/dist/auth/oauth/AppleProvider.js +40 -3
  48. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  49. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  50. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  52. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  53. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  54. package/dist/auth/oauth/DiscordProvider.js +4 -1
  55. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  56. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  57. package/dist/auth/oauth/GitHubProvider.js +4 -1
  58. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  59. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  60. package/dist/auth/oauth/GoogleProvider.js +4 -1
  61. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  62. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  63. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  64. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  65. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  66. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  67. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  68. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  69. package/dist/auth/oauth/types.d.ts +4 -2
  70. package/dist/auth/oauth/types.d.ts.map +1 -1
  71. package/dist/cli/cli.d.ts.map +1 -1
  72. package/dist/cli/cli.js +228 -12
  73. package/dist/cli/cli.js.map +1 -1
  74. package/dist/core/config/ConfigService.d.ts.map +1 -1
  75. package/dist/core/config/ConfigService.js +5 -3
  76. package/dist/core/config/ConfigService.js.map +1 -1
  77. package/dist/core/config/EnvLoader.d.ts +14 -0
  78. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  79. package/dist/core/config/EnvLoader.js +44 -0
  80. package/dist/core/config/EnvLoader.js.map +1 -1
  81. package/dist/core/container/Container.d.ts +14 -0
  82. package/dist/core/container/Container.d.ts.map +1 -1
  83. package/dist/core/container/Container.js +32 -0
  84. package/dist/core/container/Container.js.map +1 -1
  85. package/dist/core/errors/AppError.d.ts +7 -7
  86. package/dist/core/errors/AppError.d.ts.map +1 -1
  87. package/dist/core/errors/AppError.js +18 -14
  88. package/dist/core/errors/AppError.js.map +1 -1
  89. package/dist/core/events/EventBus.d.ts.map +1 -1
  90. package/dist/core/events/EventBus.js +36 -6
  91. package/dist/core/events/EventBus.js.map +1 -1
  92. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  93. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  94. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  95. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  96. package/dist/core/plugins/PluginManager.d.ts +20 -1
  97. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  98. package/dist/core/plugins/PluginManager.js +231 -146
  99. package/dist/core/plugins/PluginManager.js.map +1 -1
  100. package/dist/core/plugins/types.d.ts +48 -31
  101. package/dist/core/plugins/types.d.ts.map +1 -1
  102. package/dist/database/DatabaseService.d.ts +1 -0
  103. package/dist/database/DatabaseService.d.ts.map +1 -1
  104. package/dist/database/DatabaseService.js +24 -6
  105. package/dist/database/DatabaseService.js.map +1 -1
  106. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  107. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  108. package/dist/database/drivers/DriverRegistry.js +29 -0
  109. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  110. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  111. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  112. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  113. package/dist/database/drivers/MssqlDriver.js +8 -2
  114. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  115. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  116. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  117. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  118. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  119. package/dist/database/migrations/SystemMigrations.js +62 -5
  120. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  121. package/dist/flows/FlowEngine.js.map +1 -1
  122. package/dist/flows/FlowService.d.ts +7 -1
  123. package/dist/flows/FlowService.d.ts.map +1 -1
  124. package/dist/flows/FlowService.js +126 -12
  125. package/dist/flows/FlowService.js.map +1 -1
  126. package/dist/flows/FlowValidator.d.ts +1 -0
  127. package/dist/flows/FlowValidator.d.ts.map +1 -1
  128. package/dist/flows/FlowValidator.js +76 -1
  129. package/dist/flows/FlowValidator.js.map +1 -1
  130. package/dist/flows/types.d.ts +14 -2
  131. package/dist/flows/types.d.ts.map +1 -1
  132. package/dist/functions/FunctionService.d.ts +5 -1
  133. package/dist/functions/FunctionService.d.ts.map +1 -1
  134. package/dist/functions/FunctionService.js +84 -33
  135. package/dist/functions/FunctionService.js.map +1 -1
  136. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  137. package/dist/functions/runtime/QuickJsWasmRuntime.js +19 -10
  138. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  139. package/dist/functions/types.d.ts +16 -2
  140. package/dist/functions/types.d.ts.map +1 -1
  141. package/dist/http/HttpServer.d.ts +3 -0
  142. package/dist/http/HttpServer.d.ts.map +1 -1
  143. package/dist/http/HttpServer.js +153 -6
  144. package/dist/http/HttpServer.js.map +1 -1
  145. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  146. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  147. package/dist/http/controllers/ApiKeyController.js +47 -1
  148. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  149. package/dist/http/controllers/AuthController.d.ts +12 -0
  150. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  151. package/dist/http/controllers/AuthController.js +40 -2
  152. package/dist/http/controllers/AuthController.js.map +1 -1
  153. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  154. package/dist/http/controllers/FlowController.js +45 -4
  155. package/dist/http/controllers/FlowController.js.map +1 -1
  156. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  157. package/dist/http/controllers/FunctionController.js +16 -2
  158. package/dist/http/controllers/FunctionController.js.map +1 -1
  159. package/dist/http/controllers/HealthController.js +2 -2
  160. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  161. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  162. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  163. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  164. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  165. package/dist/http/middleware/AuthMiddleware.js +6 -3
  166. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  167. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  168. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  169. package/dist/index.d.ts +2 -2
  170. package/dist/index.d.ts.map +1 -1
  171. package/dist/index.js +6 -2
  172. package/dist/index.js.map +1 -1
  173. package/dist/queue/QueueService.d.ts +9 -0
  174. package/dist/queue/QueueService.d.ts.map +1 -1
  175. package/dist/queue/QueueService.js +143 -60
  176. package/dist/queue/QueueService.js.map +1 -1
  177. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  178. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  179. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  180. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  181. package/dist/records/FtsService.d.ts +7 -3
  182. package/dist/records/FtsService.d.ts.map +1 -1
  183. package/dist/records/FtsService.js +69 -5
  184. package/dist/records/FtsService.js.map +1 -1
  185. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  186. package/dist/records/QueryFilterParser.js +58 -20
  187. package/dist/records/QueryFilterParser.js.map +1 -1
  188. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  189. package/dist/records/RecordSanitizer.js +32 -4
  190. package/dist/records/RecordSanitizer.js.map +1 -1
  191. package/dist/records/RecordService.d.ts +6 -0
  192. package/dist/records/RecordService.d.ts.map +1 -1
  193. package/dist/records/RecordService.js +95 -14
  194. package/dist/records/RecordService.js.map +1 -1
  195. package/dist/records/RecordValidator.d.ts +10 -0
  196. package/dist/records/RecordValidator.d.ts.map +1 -1
  197. package/dist/records/RecordValidator.js +110 -2
  198. package/dist/records/RecordValidator.js.map +1 -1
  199. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  200. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  201. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  202. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  203. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  204. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  205. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  206. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  207. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  208. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  209. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  210. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  211. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  212. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  213. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  214. package/dist/schema/OpenApiGenerator.js +103 -3
  215. package/dist/schema/OpenApiGenerator.js.map +1 -1
  216. package/dist/schema/models/Field.d.ts +1 -0
  217. package/dist/schema/models/Field.d.ts.map +1 -1
  218. package/dist/templates/definitions/ecommerce.js +6 -6
  219. package/dist/templates/definitions/ecommerce.js.map +1 -1
  220. package/dist/webhooks/WebhookService.js +1 -1
  221. package/package.json +4 -3
@@ -1,979 +1,980 @@
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(core, context) {
43
- core.observability.log("Invoked function in app:", context.app.slug);
44
- const name = context.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(core, context) {
52
- const { cartTotal, couponCode } = context.request?.body || {};
53
- let discountRate = 0;
54
-
55
- if (couponCode === "SAVE20") {
56
- discountRate = 0.20;
57
- } else if (couponCode === "VIP50" && context.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(core, context) {
76
- if (context.event && context.event.record) {
77
- const record = context.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(core, context) {
96
- // Guarded fetch rejects private IPs, loopback, and cloud metadata
97
- const res = await core.network.http.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
- const homeFnEl = document.getElementById('home-stat-functions');
265
- const homeFnSubEl = document.getElementById('home-stat-functions-sub');
266
- if (homeFnEl) {
267
- homeFnEl.textContent = (res.totalFunctions !== undefined ? res.totalFunctions : (res.activeFunctions || 0)).toString();
268
- }
269
- if (homeFnSubEl) {
270
- const active = res.activeFunctions || 0;
271
- const execs = res.totalExecutions || 0;
272
- homeFnSubEl.textContent = `${active} active${execs > 0 ? ` • ${execs} runs` : ' • 0 runs'}`;
273
- }
274
- }
275
- } catch (err) {
276
- console.warn('Failed to load function stats:', err);
277
- }
278
- }
279
-
280
- async function loadFunctionsList() {
281
- const container = document.getElementById('functions-tab-content');
282
- if (!container) return;
283
-
284
- container.innerHTML = `
285
- <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
286
- <span class="spinner" style="margin-right: 8px;"></span> Loading serverless functions...
287
- </div>
288
- `;
289
-
290
- try {
291
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
292
- const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
293
- const list = await api(endpoint);
294
- functionsState.functions = Array.isArray(list) ? list : [];
295
-
296
- // Sync count badge
297
- const count = functionsState.functions.length;
298
- const sidebarBadge = document.getElementById('sidebar-functions-count');
299
- if (sidebarBadge) {
300
- sidebarBadge.textContent = count;
301
- sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
302
- }
303
-
304
- renderFunctionsTable(functionsState.functions);
305
- } catch (err) {
306
- container.innerHTML = `
307
- <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
308
- <p>Failed to load functions: ${escapeHtml(err.message || String(err))}</p>
309
- <button class="btn btn-secondary btn-sm" onclick="loadFunctionsList()">Try Again</button>
310
- </div>
311
- `;
312
- }
313
- }
314
-
315
- function renderFunctionsTable(functions) {
316
- const container = document.getElementById('functions-tab-content');
317
- if (!container) return;
318
-
319
- if (!functions || functions.length === 0) {
320
- container.innerHTML = `
321
- <div class="card" style="padding: 3.5rem 1.5rem; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 1rem;">
322
- <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);">
323
- <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>
324
- </div>
325
- <div>
326
- <h3 style="margin: 0 0 0.5rem 0; font-size: 1.25rem; font-weight: 600;">No Serverless Functions Yet</h3>
327
- <p style="margin: 0; color: var(--text-muted); font-size: 0.875rem; max-width: 480px;">
328
- Create lightweight, sandboxed functions to implement custom backend logic, third-party webhooks, and database triggers.
329
- </p>
330
- </div>
331
- <button class="btn btn-primary btn-sm" onclick="openCreateFunctionPage()">
332
- <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>
333
- Create First Function
334
- </button>
335
- </div>
336
- `;
337
- return;
338
- }
339
-
340
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
341
- const invokePrefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
342
-
343
- const rows = functions.map(fn => {
344
- const isEnabled = fn.enabled !== false;
345
- const authBadgeClass = fn.authPolicy === 'public' ? 'badge-success' : (fn.authPolicy === 'admin' ? 'badge-danger' : 'badge-primary');
346
- const authLabel = (fn.authPolicy || 'public').toUpperCase();
347
- const invokePath = `${invokePrefix}/${fn.name}/invoke`;
348
-
349
- return `
350
- <tr style="border-bottom: 1px solid var(--border-subtle); transition: background 0.15s ease;">
351
- <td style="padding: 12px 16px;">
352
- <div style="display: flex; align-items: center; gap: 8px;">
353
- <span class="status-indicator ${isEnabled ? 'status-active' : 'status-inactive'}" title="${isEnabled ? 'Active' : 'Disabled'}"></span>
354
- <div>
355
- <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;">
356
- ${escapeHtml(fn.name)}
357
- </a>
358
- ${fn.description ? `<div style="font-size: 11.5px; color: var(--text-muted); margin-top: 2px;">${escapeHtml(fn.description)}</div>` : ''}
359
- </div>
360
- </div>
361
- </td>
362
- <td style="padding: 12px 16px;">
363
- <span class="badge ${authBadgeClass}" style="font-size: 11px;">${authLabel}</span>
364
- ${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>' : ''}
365
- </td>
366
- <td style="padding: 12px 16px; font-size: 12px;">
367
- ${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>'}
368
- </td>
369
- <td style="padding: 12px 16px; font-size: 11.5px; font-family: monospace; color: var(--text-muted);">
370
- <div style="display: flex; align-items: center; gap: 6px;">
371
- <span>ANY ${escapeHtml(invokePath)}</span>
372
- <button class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="padding: 1px 6px; font-size: 10px;" title="Copy endpoint">
373
- 📋
374
- </button>
375
- </div>
376
- </td>
377
- <td style="padding: 12px 16px; font-size: 12px; color: var(--text-muted);">
378
- ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB
379
- </td>
380
- <td style="padding: 12px 16px; text-align: right;">
381
- <div style="display: inline-flex; align-items: center; gap: 6px;">
382
- <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'test')" title="Test Function in Sandbox">
383
- <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>
384
- Test
385
- </button>
386
- <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'code')" title="Edit Code & Configuration">
387
- Edit
388
- </button>
389
- <button class="btn btn-secondary btn-sm" onclick="toggleFunctionEnabled('${fn.id}', ${!isEnabled})" title="${isEnabled ? 'Disable function' : 'Enable function'}">
390
- ${isEnabled ? 'Disable' : 'Enable'}
391
- </button>
392
- <button class="btn btn-secondary btn-sm" data-fn-id="${escapeHtml(fn.id)}" data-fn-name="${escapeHtml(fn.name)}" onclick="deleteFunctionPrompt(this.getAttribute('data-fn-id'), this.getAttribute('data-fn-name'))" style="color: var(--accent-danger);" title="Delete function">
393
- <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>
394
- </button>
395
- </div>
396
- </td>
397
- </tr>
398
- `;
399
- }).join('');
400
-
401
- container.innerHTML = `
402
- <div class="card" style="padding: 0; overflow: hidden;">
403
- <div style="overflow-x: auto;">
404
- <table class="table" style="width: 100%; border-collapse: collapse; text-align: left;">
405
- <thead>
406
- <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
407
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
408
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Auth Policy</th>
409
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Hook Trigger</th>
410
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Invoke Endpoint</th>
411
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Limits</th>
412
- <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Actions</th>
413
- </tr>
414
- </thead>
415
- <tbody>
416
- ${rows}
417
- </tbody>
418
- </table>
419
- </div>
420
- </div>
421
- `;
422
- }
423
-
424
- async function toggleFunctionEnabled(id, enabled) {
425
- try {
426
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
427
- const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
428
- await api(endpoint, {
429
- method: 'PATCH',
430
- headers: { 'Content-Type': 'application/json' },
431
- body: JSON.stringify({ enabled }),
432
- });
433
- toast(`Function ${enabled ? 'enabled' : 'disabled'}`, 'info');
434
- await loadFunctionStats();
435
- await loadFunctionsList();
436
- } catch (err) {
437
- toast(err.message || 'Failed to toggle status', 'error');
438
- }
439
- }
440
-
441
- function openDeleteFunctionModal(id, name) {
442
- let modalRoot = document.getElementById('modal-root');
443
- if (!modalRoot) {
444
- modalRoot = document.createElement('div');
445
- modalRoot.id = 'modal-root';
446
- document.body.appendChild(modalRoot);
447
- }
448
-
449
- const safeId = typeof escapeHtml === 'function' ? escapeHtml(id) : id;
450
- const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
451
-
452
- modalRoot.innerHTML = `
453
- <div class="modal-backdrop" id="delete-function-backdrop" onclick="if(event.target===this)closeDeleteFunctionModal()">
454
- <div class="modal confirm-dialog">
455
- <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
456
- <div style="display: flex; align-items: center; gap: 0.5rem;">
457
- <span style="font-size: 18px;">⚠️</span>
458
- <h2 class="modal-title danger" style="font-size: 16px;">Delete Function</h2>
459
- </div>
460
- <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFunctionModal()" aria-label="Close">✕</button>
461
- </div>
462
- <div class="modal-body" id="delete-function-modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
463
- <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
464
- Are you sure you want to delete function <strong style="color: var(--text-heading); font-family: var(--font-mono);">${safeName}</strong>? All invocation history and logs will be permanently removed.
465
- </p>
466
- <div class="confirm-dialog-banner danger">
467
- This action cannot be undone. Invocations to <code>/api/functions/${safeName}/invoke</code> will return 404 Not Found.
468
- </div>
469
- </div>
470
- <div class="modal-footer" id="delete-function-modal-footer" style="padding: 0.75rem 1.25rem;">
471
- <button type="button" class="btn btn-secondary" onclick="closeDeleteFunctionModal()">Cancel</button>
472
- <button type="button" class="btn btn-danger" id="btn-confirm-delete-function" data-fn-id="${safeId}">
473
- Delete Function
474
- </button>
475
- </div>
476
- </div>
477
- </div>
478
- `;
479
-
480
- const deleteBtn = document.getElementById('btn-confirm-delete-function');
481
- if (deleteBtn) {
482
- deleteBtn.addEventListener('click', () => confirmDeleteFunction(id, name, false));
483
- }
484
-
485
- setTimeout(() => {
486
- document.getElementById('btn-confirm-delete-function')?.focus();
487
- }, 50);
488
- }
489
-
490
- function closeDeleteFunctionModal() {
491
- const modalRoot = document.getElementById('modal-root');
492
- if (modalRoot) modalRoot.innerHTML = '';
493
- }
494
-
495
- async function confirmDeleteFunction(id, name, force = false) {
496
- const actionBtnId = force ? 'btn-force-delete-function' : 'btn-confirm-delete-function';
497
- const btn = document.getElementById(actionBtnId);
498
- if (btn) {
499
- btn.disabled = true;
500
- btn.textContent = force ? 'Force Deleting...' : 'Deleting...';
501
- }
502
-
503
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
504
- const basePath = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
505
- const endpoint = force ? `${basePath}?force=true` : basePath;
506
-
507
- try {
508
- await api(endpoint, { method: 'DELETE' });
509
- closeDeleteFunctionModal();
510
- toast(`Function '${name}' deleted${force ? ' (forced)' : ''}`, 'info');
511
- if (typeof closeFunctionEditor === 'function') {
512
- closeFunctionEditor();
513
- }
514
- await loadFunctionStats();
515
- await loadFunctionsList();
516
- } catch (err) {
517
- if (err.status === 409 && !force) {
518
- renderConflictModalState(id, name, err.message);
519
- return;
520
- }
521
- if (btn) {
522
- btn.disabled = false;
523
- btn.textContent = force ? 'Force Delete Anyway' : 'Delete Function';
524
- }
525
- const body = document.getElementById('delete-function-modal-body');
526
- if (body) {
527
- const errBox = document.createElement('div');
528
- errBox.style.cssText = 'background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.35); border-radius: 6px; padding: 0.75rem; font-size: 12px; color: #ef4444;';
529
- errBox.textContent = err.message || 'Failed to delete function';
530
- body.prepend(errBox);
531
- }
532
- toast(err.message || 'Failed to delete function', 'error');
533
- }
534
- }
535
-
536
- function renderConflictModalState(id, name, conflictMessage) {
537
- const safeId = typeof escapeHtml === 'function' ? escapeHtml(id) : id;
538
- const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
539
- const safeMsg = typeof escapeHtml === 'function' ? escapeHtml(conflictMessage) : conflictMessage;
540
-
541
- const modal = document.querySelector('#modal-root .modal');
542
- if (!modal) return;
543
-
544
- const header = modal.querySelector('.modal-header');
545
- if (header) {
546
- header.style.borderBottomColor = 'rgba(245, 158, 11, 0.3)';
547
- header.innerHTML = `
548
- <div style="display: flex; align-items: center; gap: 0.5rem;">
549
- <span style="font-size: 18px;">⚠️</span>
550
- <h2 class="modal-title warning" style="font-size: 16px;">Cannot Delete: Flow Dependencies</h2>
551
- </div>
552
- <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFunctionModal()" aria-label="Close">✕</button>
553
- `;
554
- }
555
-
556
- const body = document.getElementById('delete-function-modal-body');
557
- if (body) {
558
- body.innerHTML = `
559
- <div class="confirm-dialog-banner warning">
560
- <div class="confirm-dialog-banner-title">Cannot Delete: Function in Use</div>
561
- <div>${safeMsg}</div>
562
- </div>
563
- <div class="confirm-dialog-banner danger">
564
- <strong>Warning:</strong> Force deleting function <strong style="font-family: var(--font-mono);">${safeName}</strong> will remove it immediately. Subsequent executions of referencing flows will fail during state execution.
565
- </div>
566
- `;
567
- }
568
-
569
- const footer = document.getElementById('delete-function-modal-footer');
570
- if (footer) {
571
- footer.innerHTML = `
572
- <button type="button" class="btn btn-secondary" onclick="closeDeleteFunctionModal()">Cancel (Keep Function)</button>
573
- <button type="button" class="btn btn-danger" id="btn-force-delete-function" data-fn-id="${safeId}">
574
- Force Delete Anyway
575
- </button>
576
- `;
577
- const forceBtn = document.getElementById('btn-force-delete-function');
578
- if (forceBtn) {
579
- forceBtn.addEventListener('click', () => confirmDeleteFunction(id, name, true));
580
- }
581
- setTimeout(() => {
582
- document.getElementById('btn-force-delete-function')?.focus();
583
- }, 50);
584
- }
585
- }
586
-
587
- function deleteFunctionPrompt(id, name) {
588
- openDeleteFunctionModal(id, name);
589
- }
590
-
591
- function copyFunctionEndpoint(path) {
592
- const fullUrl = window.location.origin + path;
593
- if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
594
- navigator.clipboard.writeText(fullUrl).then(() => {
595
- toast('Copied function endpoint URL to clipboard', 'info');
596
- }).catch(() => {
597
- prompt('Copy function endpoint URL:', fullUrl);
598
- });
599
- } else {
600
- prompt('Copy function endpoint URL:', fullUrl);
601
- }
602
- }
603
-
604
- // ==========================================
605
- // 3. Global Execution History & Logs
606
- // ==========================================
607
-
608
- async function loadFunctionLogs(page = 1) {
609
- const container = document.getElementById('functions-tab-content');
610
- if (!container) return;
611
-
612
- container.innerHTML = `
613
- <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
614
- <span class="spinner" style="margin-right: 8px;"></span> Loading invocation logs...
615
- </div>
616
- `;
617
-
618
- try {
619
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
620
- const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
621
- const params = new URLSearchParams({
622
- page: String(page),
623
- perPage: String(functionsState.logFilter.perPage || 25),
624
- });
625
- if (functionsState.logFilter.functionId) {
626
- params.append('functionId', functionsState.logFilter.functionId);
627
- }
628
- if (functionsState.logFilter.status && functionsState.logFilter.status !== 'all') {
629
- params.append('status', functionsState.logFilter.status);
630
- }
631
-
632
- const res = await api(`${baseUrl}?${params.toString()}`);
633
- functionsState.logs = res.items || [];
634
- functionsState.logFilter.page = res.page || 1;
635
- functionsState.logFilter.totalItems = res.totalItems || 0;
636
- functionsState.logFilter.totalPages = res.totalPages || 1;
637
-
638
- renderFunctionLogsTable(functionsState.logs);
639
- } catch (err) {
640
- container.innerHTML = `
641
- <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
642
- <p>Failed to load logs: ${escapeHtml(err.message || String(err))}</p>
643
- <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs()">Try Again</button>
644
- </div>
645
- `;
646
- }
647
- }
648
-
649
- function renderFunctionLogsTable(logs) {
650
- const container = document.getElementById('functions-tab-content');
651
- if (!container) return;
652
-
653
- const fnOptions = (functionsState.functions || []).map(f => `
654
- <option value="${f.id}" ${functionsState.logFilter.functionId === f.id ? 'selected' : ''}>
655
- ${escapeHtml(f.name)}
656
- </option>
657
- `).join('');
658
-
659
- if (!logs || logs.length === 0) {
660
- container.innerHTML = `
661
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
662
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
663
- <div style="display: flex; align-items: center; gap: 8px;">
664
- <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
665
- <option value="">All Functions</option>
666
- ${fnOptions}
667
- </select>
668
- </div>
669
- </div>
670
- <div style="padding: 3rem 1rem; text-align: center; color: var(--text-muted);">
671
- No execution logs recorded yet.
672
- </div>
673
- </div>
674
- `;
675
- return;
676
- }
677
-
678
- const rows = logs.map(l => {
679
- const isOk = l.status === 'success';
680
- const statusBadge = isOk
681
- ? `<span class="badge" style="background: rgba(16, 185, 129, 0.15); color: #10b981; font-size: 11px;">${l.statusCode || 200} OK</span>`
682
- : `<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444; font-size: 11px;">${escapeHtml(l.status.toUpperCase())}</span>`;
683
-
684
- return `
685
- <tr style="border-bottom: 1px solid var(--border-subtle);">
686
- <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${formatTimestamp(l.timestamp || l.createdAt)}</td>
687
- <td style="padding: 10px 14px;">
688
- <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;">
689
- ${escapeHtml(l.functionName || l.functionId)}
690
- </a>
691
- </td>
692
- <td style="padding: 10px 14px;">${statusBadge}</td>
693
- <td style="padding: 10px 14px; font-size: 12px; font-weight: 600;">${l.durationMs}ms</td>
694
- <td style="padding: 10px 14px;"><code style="font-size: 11px;">${escapeHtml(l.trigger || l.method || 'http')}</code></td>
695
- <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${escapeHtml(l.actorId || 'public')}</td>
696
- <td style="padding: 10px 14px; text-align: right;">
697
- <button class="btn btn-secondary btn-sm" onclick="viewLogPayload('${l.id}')" title="Inspect Request/Response payload" style="font-size: 11px; padding: 2px 8px;">
698
- Inspect
699
- </button>
700
- </td>
701
- </tr>
702
- `;
703
- }).join('');
704
-
705
- container.innerHTML = `
706
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
707
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
708
- <div style="display: flex; align-items: center; gap: 8px;">
709
- <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
710
- <option value="">All Functions</option>
711
- ${fnOptions}
712
- </select>
713
- <span style="font-size: 12px; color: var(--text-muted);">
714
- Showing ${logs.length} of ${functionsState.logFilter.totalItems || logs.length} logs
715
- </span>
716
- </div>
717
- <div style="display: flex; align-items: center; gap: 8px;">
718
- <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs(${functionsState.logFilter.page || 1})">
719
- Refresh
720
- </button>
721
- <button class="btn btn-danger btn-sm" onclick="openClearLogsModal()">
722
- Clear Logs
723
- </button>
724
- </div>
725
- </div>
726
-
727
- <div style="overflow-x: auto; border: 1px solid var(--border-subtle); border-radius: 6px;">
728
- <table class="table" style="width: 100%; border-collapse: collapse; text-align: left; font-size: 13px;">
729
- <thead>
730
- <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
731
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Timestamp</th>
732
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
733
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Status</th>
734
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Latency</th>
735
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Trigger / Method</th>
736
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Caller</th>
737
- <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Payload</th>
738
- </tr>
739
- </thead>
740
- <tbody>
741
- ${rows}
742
- </tbody>
743
- </table>
744
- </div>
745
- </div>
746
- `;
747
- }
748
-
749
- function filterFunctionLogs(fnId) {
750
- functionsState.logFilter.functionId = fnId || '';
751
- loadFunctionLogs(1);
752
- }
753
-
754
- function viewFunctionLogs(functionId) {
755
- switchFunctionsTab('logs');
756
- filterFunctionLogs(functionId);
757
- }
758
-
759
- async function viewLogPayload(logId) {
760
- let log = (functionsState.editorLogs || []).find(l => l.id === logId)
761
- || (functionsState.logs || []).find(l => l.id === logId);
762
-
763
- if (!log) {
764
- try {
765
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
766
- const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
767
- const res = await api(`${baseUrl}?perPage=100`);
768
- if (res && res.items) {
769
- log = res.items.find(l => l.id === logId);
770
- }
771
- } catch (_) {}
772
- }
773
-
774
- if (!log) {
775
- if (typeof toast === 'function') toast('Execution log details not found', 'warning');
776
- return;
777
- }
778
-
779
- let modalRoot = document.getElementById('modal-root');
780
- if (!modalRoot) {
781
- modalRoot = document.createElement('div');
782
- modalRoot.id = 'modal-root';
783
- document.body.appendChild(modalRoot);
784
- }
785
-
786
- let consoleOutput = '(No console output logged)';
787
- if (log.logs) {
788
- if (Array.isArray(log.logs) && log.logs.length > 0) {
789
- consoleOutput = log.logs.join('\n');
790
- } else if (typeof log.logs === 'string' && log.logs.trim().length > 0) {
791
- consoleOutput = log.logs;
792
- }
793
- }
794
-
795
- let reqFormatted = '{}';
796
- if (log.requestPayload) {
797
- try {
798
- reqFormatted = JSON.stringify(typeof log.requestPayload === 'string' ? JSON.parse(log.requestPayload) : log.requestPayload, null, 2);
799
- } catch {
800
- reqFormatted = String(log.requestPayload);
801
- }
802
- }
803
-
804
- let resFormatted = '{}';
805
- if (log.responsePayload) {
806
- try {
807
- resFormatted = JSON.stringify(typeof log.responsePayload === 'string' ? JSON.parse(log.responsePayload) : log.responsePayload, null, 2);
808
- } catch {
809
- resFormatted = String(log.error || log.responsePayload);
810
- }
811
- } else if (log.error) {
812
- resFormatted = String(log.error);
813
- }
814
-
815
- modalRoot.innerHTML = `
816
- <div class="modal-backdrop" onclick="this.remove()">
817
- <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()">
818
- <div style="display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; border-bottom: 1px solid var(--border-subtle);">
819
- <div style="display: flex; align-items: center; gap: 8px;">
820
- <h3 style="margin: 0; font-size: 1.1rem; font-weight: 600;">Execution Payload Inspector</h3>
821
- <span class="badge" style="font-size: 11px;">${log.durationMs}ms</span>
822
- </div>
823
- <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()" style="border: none; font-size: 18px; line-height: 1;">✕</button>
824
- </div>
825
- <div style="flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 14px;">
826
- <div>
827
- <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Console Output Logs</label>
828
- <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>
829
- </div>
830
- <div>
831
- <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Request Payload</label>
832
- <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>
833
- </div>
834
- <div>
835
- <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Response Payload</label>
836
- <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>
837
- </div>
838
- </div>
839
- <div style="padding: 12px 20px; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end;">
840
- <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()">Close</button>
841
- </div>
842
- </div>
843
- </div>
844
- `;
845
- }
846
-
847
- function openClearLogsModal() {
848
- let modalRoot = document.getElementById('modal-root');
849
- if (!modalRoot) {
850
- modalRoot = document.createElement('div');
851
- modalRoot.id = 'modal-root';
852
- document.body.appendChild(modalRoot);
853
- }
854
-
855
- modalRoot.innerHTML = `
856
- <div class="modal-backdrop" id="clear-logs-backdrop" onclick="if(event.target===this)closeClearLogsModal()">
857
- <div class="modal confirm-dialog">
858
- <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
859
- <div style="display: flex; align-items: center; gap: 0.5rem;">
860
- <span style="font-size: 18px;">⚠️</span>
861
- <h2 class="modal-title danger" style="font-size: 16px;">Clear Execution Logs</h2>
862
- </div>
863
- <button type="button" class="btn btn-secondary btn-sm" onclick="closeClearLogsModal()" aria-label="Close">✕</button>
864
- </div>
865
- <div class="modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
866
- <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
867
- Are you sure you want to permanently clear all function invocation logs?
868
- </p>
869
- <div class="confirm-dialog-banner danger">
870
- This will delete all historical logs, timestamps, status codes, and console logs. This action cannot be undone.
871
- </div>
872
- </div>
873
- <div class="modal-footer" style="padding: 0.75rem 1.25rem;">
874
- <button type="button" class="btn btn-secondary" onclick="closeClearLogsModal()">Cancel</button>
875
- <button type="button" class="btn btn-danger" id="btn-confirm-clear-logs" onclick="confirmClearAllLogs()">
876
- Clear All Logs
877
- </button>
878
- </div>
879
- </div>
880
- </div>
881
- `;
882
-
883
- setTimeout(() => {
884
- document.getElementById('btn-confirm-clear-logs')?.focus();
885
- }, 50);
886
- }
887
-
888
- function closeClearLogsModal() {
889
- const modalRoot = document.getElementById('modal-root');
890
- if (modalRoot) modalRoot.innerHTML = '';
891
- }
892
-
893
- async function confirmClearAllLogs() {
894
- const btn = document.getElementById('btn-confirm-clear-logs');
895
- if (btn) {
896
- btn.disabled = true;
897
- btn.textContent = 'Clearing...';
898
- }
899
- try {
900
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
901
- const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
902
- await api(endpoint, { method: 'DELETE' });
903
- closeClearLogsModal();
904
- toast('Execution logs cleared', 'info');
905
- await loadFunctionLogs();
906
- } catch (err) {
907
- if (btn) {
908
- btn.disabled = false;
909
- btn.textContent = 'Clear All Logs';
910
- }
911
- toast(err.message || 'Failed to clear logs', 'error');
912
- }
913
- }
914
-
915
- function clearAllFunctionLogs() {
916
- openClearLogsModal();
917
- }
918
-
919
- function formatTimestamp(iso) {
920
- if (!iso) return '-';
921
- try {
922
- const d = new Date(iso);
923
- if (isNaN(d.getTime())) return iso;
924
- return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) + ' ' + d.toLocaleDateString();
925
- } catch {
926
- return iso;
927
- }
928
- }
929
-
930
- // Forwarders for workbench functions
931
- function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
932
- if (typeof window.openFunctionEditor === 'function' && window.openFunctionEditor !== openFunctionEditor) {
933
- return window.openFunctionEditor(idOrName, pushState, initialTab);
934
- }
935
- }
936
-
937
- function openCreateFunctionPage() {
938
- if (typeof window.openCreateFunctionPage === 'function' && window.openCreateFunctionPage !== openCreateFunctionPage) {
939
- return window.openCreateFunctionPage();
940
- }
941
- }
942
-
943
- // ==========================================
944
- // 4. Global Exports & Startup Hook
945
- // ==========================================
946
-
947
- if (typeof window !== 'undefined') {
948
- window.functionsState = functionsState;
949
- window.STARTER_RECIPES = STARTER_RECIPES;
950
- window.renderFunctionsView = renderFunctionsView;
951
- window.switchFunctionsTab = switchFunctionsTab;
952
- window.refreshFunctionsView = refreshFunctionsView;
953
- window.loadFunctionStats = loadFunctionStats;
954
- window.loadFunctionsList = loadFunctionsList;
955
- window.renderFunctionsTable = renderFunctionsTable;
956
- window.toggleFunctionEnabled = toggleFunctionEnabled;
957
- window.deleteFunctionPrompt = deleteFunctionPrompt;
958
- window.openDeleteFunctionModal = openDeleteFunctionModal;
959
- window.closeDeleteFunctionModal = closeDeleteFunctionModal;
960
- window.confirmDeleteFunction = confirmDeleteFunction;
961
- window.renderConflictModalState = renderConflictModalState;
962
- window.openClearLogsModal = openClearLogsModal;
963
- window.closeClearLogsModal = closeClearLogsModal;
964
- window.confirmClearAllLogs = confirmClearAllLogs;
965
- window.copyFunctionEndpoint = copyFunctionEndpoint;
966
- window.openFunctionEditor = window.openFunctionEditor || openFunctionEditor;
967
- window.openCreateFunctionPage = window.openCreateFunctionPage || openCreateFunctionPage;
968
- window.loadFunctionLogs = loadFunctionLogs;
969
- window.renderFunctionLogsTable = renderFunctionLogsTable;
970
- window.filterFunctionLogs = filterFunctionLogs;
971
- window.viewFunctionLogs = viewFunctionLogs;
972
- window.viewLogPayload = viewLogPayload;
973
- window.clearAllFunctionLogs = clearAllFunctionLogs;
974
- window.formatTimestamp = formatTimestamp;
975
- }
976
-
977
- if (typeof state !== 'undefined' && state.token && typeof loadFunctionStats === 'function') {
978
- loadFunctionStats();
979
- }
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(core, context) {
43
+ const logger = core.observability.logger;
44
+ logger.log("Invoked function in app:", context.app.slug);
45
+ const name = context.request?.body?.name || "World";
46
+ return {
47
+ status: 200,
48
+ body: { message: "Hello, " + name + "!" }
49
+ };
50
+ }`,
51
+ discount: `// Calculate cart discount with RuleEngine access rules preserved
52
+ export default async function(core, context) {
53
+ const { cartTotal, couponCode } = context.request?.body || {};
54
+ let discountRate = 0;
55
+
56
+ if (couponCode === "SAVE20") {
57
+ discountRate = 0.20;
58
+ } else if (couponCode === "VIP50" && context.request?.auth) {
59
+ discountRate = 0.50;
60
+ }
61
+
62
+ const discount = (cartTotal || 0) * discountRate;
63
+ const finalTotal = Math.max(0, (cartTotal || 0) - discount);
64
+
65
+ return {
66
+ status: 200,
67
+ headers: { 'x-applied-rate': (discountRate * 100) + '%' },
68
+ body: {
69
+ originalTotal: cartTotal,
70
+ discount: discount,
71
+ finalTotal: finalTotal
72
+ }
73
+ };
74
+ }`,
75
+ hook: `// Lifecycle Hook: validate and enrich records before creation
76
+ export default async function(core, context) {
77
+ if (context.event && context.event.record) {
78
+ const record = context.event.record;
79
+
80
+ // 1. Validation guardrail
81
+ if (record.amount !== undefined && record.amount < 0) {
82
+ return { status: 400, body: { cancel: true, reason: "Amount cannot be negative" } };
83
+ }
84
+
85
+ // 2. Data enrichment / normalization
86
+ if (record.title) {
87
+ record.slug = record.title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
88
+ }
89
+ record.status = "processed";
90
+
91
+ return { status: 200, body: { record: record } };
92
+ }
93
+ return { status: 200 };
94
+ }`,
95
+ fetch: `// Outbound HTTP Integration with SSRF Guardrails
96
+ export default async function(core, context) {
97
+ // Guarded fetch rejects private IPs, loopback, and cloud metadata
98
+ const res = await core.network.http.fetch('https://httpbin.org/json');
99
+ const data = await res.json();
100
+
101
+ return {
102
+ status: 200,
103
+ body: {
104
+ origin: data.origin,
105
+ url: data.url,
106
+ timestamp: new Date().toISOString()
107
+ }
108
+ };
109
+ }`
110
+ };
111
+
112
+ if (typeof window !== 'undefined') {
113
+ window.STARTER_RECIPES = STARTER_RECIPES;
114
+ }
115
+
116
+ // ==========================================
117
+ // 2. Functions Overview Page & Statistics
118
+ // ==========================================
119
+
120
+ function renderFunctionsView() {
121
+ if (functionsState.currentView === 'editor' && functionsState.activeFunctionForEdit) {
122
+ if (typeof renderFunctionEditorView === 'function') {
123
+ renderFunctionEditorView(functionsState.activeFunctionForEdit);
124
+ }
125
+ return;
126
+ }
127
+
128
+ const container = document.getElementById('page-view-functions') || document.getElementById('main-body');
129
+ if (!container) return;
130
+
131
+ container.innerHTML = `
132
+ <div class="webhooks-container" style="max-width: 1400px; margin: 0 auto; padding: 1.5rem; display: flex; flex-direction: column; gap: 1.25rem;">
133
+ <!-- Header -->
134
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem;">
135
+ <div>
136
+ <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;">
137
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
138
+ <polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
139
+ </svg>
140
+ Serverless Functions
141
+ </h2>
142
+ <p style="font-size: 0.85rem; color: var(--text-muted); margin: 0;">
143
+ Sandboxed in-engine JavaScript/TypeScript lambda functions wired to API endpoints and lifecycle hooks.
144
+ </p>
145
+ </div>
146
+ <div style="display: flex; align-items: center; gap: 8px;">
147
+ <button class="btn btn-secondary btn-sm" onclick="refreshFunctionsView()" title="Refresh Functions & Stats">
148
+ <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>
149
+ Refresh
150
+ </button>
151
+ <button class="btn btn-primary btn-sm" onclick="openCreateFunctionPage()">
152
+ <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>
153
+ New Function
154
+ </button>
155
+ </div>
156
+ </div>
157
+
158
+ <!-- Stats Grid -->
159
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem;">
160
+ <div class="webhook-stat-card">
161
+ <span class="webhook-stat-label">Active Functions</span>
162
+ <div class="webhook-stat-value">
163
+ <span id="fn-stat-active">0</span>
164
+ <span class="webhook-stat-subtext" id="fn-stat-total">/ 0 total</span>
165
+ </div>
166
+ </div>
167
+ <div class="webhook-stat-card">
168
+ <span class="webhook-stat-label">Total Executions</span>
169
+ <div class="webhook-stat-value" id="fn-stat-executions">0</div>
170
+ </div>
171
+ <div class="webhook-stat-card">
172
+ <span class="webhook-stat-label">Success Rate</span>
173
+ <div class="webhook-stat-value" style="color: var(--accent-success);" id="fn-stat-rate">100%</div>
174
+ </div>
175
+ <div class="webhook-stat-card">
176
+ <span class="webhook-stat-label">Failed Runs</span>
177
+ <div class="webhook-stat-value" style="color: var(--accent-danger);" id="fn-stat-failed">0</div>
178
+ </div>
179
+ </div>
180
+
181
+ <!-- Subtabs Bar -->
182
+ <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;">
183
+ <button class="webhook-tab-btn ${functionsState.subTab === 'functions' ? 'active' : ''}" id="tab-btn-fn-list" onclick="switchFunctionsTab('functions')">
184
+ <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>
185
+ Configured Functions
186
+ </button>
187
+ <button class="webhook-tab-btn ${functionsState.subTab === 'logs' ? 'active' : ''}" id="tab-btn-fn-logs" onclick="switchFunctionsTab('logs')">
188
+ <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>
189
+ Execution History & Logs
190
+ </button>
191
+ </div>
192
+
193
+ <!-- Tab Content Area -->
194
+ <div id="functions-tab-content"></div>
195
+ </div>
196
+ `;
197
+
198
+ loadFunctionStats();
199
+ if (functionsState.subTab === 'functions') {
200
+ loadFunctionsList();
201
+ } else {
202
+ loadFunctionLogs();
203
+ }
204
+ }
205
+
206
+ function switchFunctionsTab(tab, pushState = true) {
207
+ functionsState.subTab = tab;
208
+ document.getElementById('tab-btn-fn-list')?.classList.toggle('active', tab === 'functions');
209
+ document.getElementById('tab-btn-fn-logs')?.classList.toggle('active', tab === 'logs');
210
+
211
+ if (pushState) {
212
+ const path = (tab === 'logs') ? '/_/functions/logs' : '/_/functions';
213
+ if (typeof updateUrl === 'function') {
214
+ updateUrl(path);
215
+ }
216
+ }
217
+
218
+ if (typeof updateBreadcrumbs === 'function') {
219
+ updateBreadcrumbs();
220
+ }
221
+
222
+ if (tab === 'functions') {
223
+ loadFunctionsList();
224
+ } else {
225
+ loadFunctionLogs();
226
+ }
227
+ }
228
+
229
+ async function refreshFunctionsView() {
230
+ await loadFunctionStats();
231
+ if (functionsState.subTab === 'functions') {
232
+ await loadFunctionsList();
233
+ } else {
234
+ await loadFunctionLogs();
235
+ }
236
+ toast('Functions data refreshed', 'info');
237
+ }
238
+
239
+ async function loadFunctionStats() {
240
+ try {
241
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
242
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/stats` : '/api/functions/stats';
243
+ const res = await api(endpoint);
244
+ if (res) {
245
+ functionsState.stats = res;
246
+ const elActive = document.getElementById('fn-stat-active');
247
+ const elTotal = document.getElementById('fn-stat-total');
248
+ const elExec = document.getElementById('fn-stat-executions');
249
+ const elRate = document.getElementById('fn-stat-rate');
250
+ const elFailed = document.getElementById('fn-stat-failed');
251
+
252
+ if (elActive) elActive.textContent = res.activeFunctions || 0;
253
+ if (elTotal) elTotal.textContent = `/ ${res.totalFunctions || 0} total`;
254
+ if (elExec) elExec.textContent = res.totalExecutions || 0;
255
+ if (elRate) elRate.textContent = res.successRate || '100%';
256
+ if (elFailed) elFailed.textContent = res.failedExecutions || 0;
257
+
258
+ // Update sidebar counter badge
259
+ const sidebarBadge = document.getElementById('sidebar-functions-count');
260
+ if (sidebarBadge) {
261
+ sidebarBadge.textContent = res.totalFunctions || 0;
262
+ sidebarBadge.style.display = (res.totalFunctions > 0) ? 'inline-block' : 'none';
263
+ }
264
+
265
+ const homeFnEl = document.getElementById('home-stat-functions');
266
+ const homeFnSubEl = document.getElementById('home-stat-functions-sub');
267
+ if (homeFnEl) {
268
+ homeFnEl.textContent = (res.totalFunctions !== undefined ? res.totalFunctions : (res.activeFunctions || 0)).toString();
269
+ }
270
+ if (homeFnSubEl) {
271
+ const active = res.activeFunctions || 0;
272
+ const execs = res.totalExecutions || 0;
273
+ homeFnSubEl.textContent = `${active} active${execs > 0 ? ` • ${execs} runs` : ' • 0 runs'}`;
274
+ }
275
+ }
276
+ } catch (err) {
277
+ console.warn('Failed to load function stats:', err);
278
+ }
279
+ }
280
+
281
+ async function loadFunctionsList() {
282
+ const container = document.getElementById('functions-tab-content');
283
+ if (!container) return;
284
+
285
+ container.innerHTML = `
286
+ <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
287
+ <span class="spinner" style="margin-right: 8px;"></span> Loading serverless functions...
288
+ </div>
289
+ `;
290
+
291
+ try {
292
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
293
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
294
+ const list = await api(endpoint);
295
+ functionsState.functions = Array.isArray(list) ? list : [];
296
+
297
+ // Sync count badge
298
+ const count = functionsState.functions.length;
299
+ const sidebarBadge = document.getElementById('sidebar-functions-count');
300
+ if (sidebarBadge) {
301
+ sidebarBadge.textContent = count;
302
+ sidebarBadge.style.display = count > 0 ? 'inline-block' : 'none';
303
+ }
304
+
305
+ renderFunctionsTable(functionsState.functions);
306
+ } catch (err) {
307
+ container.innerHTML = `
308
+ <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
309
+ <p>Failed to load functions: ${escapeHtml(err.message || String(err))}</p>
310
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionsList()">Try Again</button>
311
+ </div>
312
+ `;
313
+ }
314
+ }
315
+
316
+ function renderFunctionsTable(functions) {
317
+ const container = document.getElementById('functions-tab-content');
318
+ if (!container) return;
319
+
320
+ if (!functions || functions.length === 0) {
321
+ container.innerHTML = `
322
+ <div class="card" style="padding: 3.5rem 1.5rem; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 1rem;">
323
+ <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);">
324
+ <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>
325
+ </div>
326
+ <div>
327
+ <h3 style="margin: 0 0 0.5rem 0; font-size: 1.25rem; font-weight: 600;">No Serverless Functions Yet</h3>
328
+ <p style="margin: 0; color: var(--text-muted); font-size: 0.875rem; max-width: 480px;">
329
+ Create lightweight, sandboxed functions to implement custom backend logic, third-party webhooks, and database triggers.
330
+ </p>
331
+ </div>
332
+ <button class="btn btn-primary btn-sm" onclick="openCreateFunctionPage()">
333
+ <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>
334
+ Create First Function
335
+ </button>
336
+ </div>
337
+ `;
338
+ return;
339
+ }
340
+
341
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
342
+ const invokePrefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
343
+
344
+ const rows = functions.map(fn => {
345
+ const isEnabled = fn.enabled !== false;
346
+ const authBadgeClass = fn.authPolicy === 'public' ? 'badge-success' : (fn.authPolicy === 'admin' ? 'badge-danger' : (fn.authPolicy === 'custom' ? 'badge-warning' : 'badge-primary'));
347
+ const authLabel = fn.authPolicy === 'custom' ? 'CUSTOM RULE' : (fn.authPolicy || 'public').toUpperCase();
348
+ const invokePath = `${invokePrefix}/${fn.name}/invoke`;
349
+
350
+ return `
351
+ <tr style="border-bottom: 1px solid var(--border-subtle); transition: background 0.15s ease;">
352
+ <td style="padding: 12px 16px;">
353
+ <div style="display: flex; align-items: center; gap: 8px;">
354
+ <span class="status-indicator ${isEnabled ? 'status-active' : 'status-inactive'}" title="${isEnabled ? 'Active' : 'Disabled'}"></span>
355
+ <div>
356
+ <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;">
357
+ ${escapeHtml(fn.name)}
358
+ </a>
359
+ ${fn.description ? `<div style="font-size: 11.5px; color: var(--text-muted); margin-top: 2px;">${escapeHtml(fn.description)}</div>` : ''}
360
+ </div>
361
+ </div>
362
+ </td>
363
+ <td style="padding: 12px 16px;">
364
+ <span class="badge ${authBadgeClass}" style="font-size: 11px;">${authLabel}</span>
365
+ ${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>' : ''}
366
+ </td>
367
+ <td style="padding: 12px 16px; font-size: 12px;">
368
+ ${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>'}
369
+ </td>
370
+ <td style="padding: 12px 16px; font-size: 11.5px; font-family: monospace; color: var(--text-muted);">
371
+ <div style="display: flex; align-items: center; gap: 6px;">
372
+ <span>ANY ${escapeHtml(invokePath)}</span>
373
+ <button class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="padding: 1px 6px; font-size: 10px;" title="Copy endpoint">
374
+ 📋
375
+ </button>
376
+ </div>
377
+ </td>
378
+ <td style="padding: 12px 16px; font-size: 12px; color: var(--text-muted);">
379
+ ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB
380
+ </td>
381
+ <td style="padding: 12px 16px; text-align: right;">
382
+ <div style="display: inline-flex; align-items: center; gap: 6px;">
383
+ <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'test')" title="Test Function in Sandbox">
384
+ <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>
385
+ Test
386
+ </button>
387
+ <button class="btn btn-secondary btn-sm" onclick="openFunctionEditor('${fn.id}', true, 'code')" title="Edit Code & Configuration">
388
+ Edit
389
+ </button>
390
+ <button class="btn btn-secondary btn-sm" onclick="toggleFunctionEnabled('${fn.id}', ${!isEnabled})" title="${isEnabled ? 'Disable function' : 'Enable function'}">
391
+ ${isEnabled ? 'Disable' : 'Enable'}
392
+ </button>
393
+ <button class="btn btn-secondary btn-sm" data-fn-id="${escapeHtml(fn.id)}" data-fn-name="${escapeHtml(fn.name)}" onclick="deleteFunctionPrompt(this.getAttribute('data-fn-id'), this.getAttribute('data-fn-name'))" style="color: var(--accent-danger);" title="Delete function">
394
+ <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>
395
+ </button>
396
+ </div>
397
+ </td>
398
+ </tr>
399
+ `;
400
+ }).join('');
401
+
402
+ container.innerHTML = `
403
+ <div class="card" style="padding: 0; overflow: hidden;">
404
+ <div style="overflow-x: auto;">
405
+ <table class="table" style="width: 100%; border-collapse: collapse; text-align: left;">
406
+ <thead>
407
+ <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
408
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
409
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Auth Policy</th>
410
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Hook Trigger</th>
411
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Invoke Endpoint</th>
412
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Limits</th>
413
+ <th style="padding: 12px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Actions</th>
414
+ </tr>
415
+ </thead>
416
+ <tbody>
417
+ ${rows}
418
+ </tbody>
419
+ </table>
420
+ </div>
421
+ </div>
422
+ `;
423
+ }
424
+
425
+ async function toggleFunctionEnabled(id, enabled) {
426
+ try {
427
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
428
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
429
+ await api(endpoint, {
430
+ method: 'PATCH',
431
+ headers: { 'Content-Type': 'application/json' },
432
+ body: JSON.stringify({ enabled }),
433
+ });
434
+ toast(`Function ${enabled ? 'enabled' : 'disabled'}`, 'info');
435
+ await loadFunctionStats();
436
+ await loadFunctionsList();
437
+ } catch (err) {
438
+ toast(err.message || 'Failed to toggle status', 'error');
439
+ }
440
+ }
441
+
442
+ function openDeleteFunctionModal(id, name) {
443
+ let modalRoot = document.getElementById('modal-root');
444
+ if (!modalRoot) {
445
+ modalRoot = document.createElement('div');
446
+ modalRoot.id = 'modal-root';
447
+ document.body.appendChild(modalRoot);
448
+ }
449
+
450
+ const safeId = typeof escapeHtml === 'function' ? escapeHtml(id) : id;
451
+ const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
452
+
453
+ modalRoot.innerHTML = `
454
+ <div class="modal-backdrop" id="delete-function-backdrop" onclick="if(event.target===this)closeDeleteFunctionModal()">
455
+ <div class="modal confirm-dialog">
456
+ <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
457
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
458
+ <span style="font-size: 18px;">⚠️</span>
459
+ <h2 class="modal-title danger" style="font-size: 16px;">Delete Function</h2>
460
+ </div>
461
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFunctionModal()" aria-label="Close">✕</button>
462
+ </div>
463
+ <div class="modal-body" id="delete-function-modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
464
+ <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
465
+ Are you sure you want to delete function <strong style="color: var(--text-heading); font-family: var(--font-mono);">${safeName}</strong>? All invocation history and logs will be permanently removed.
466
+ </p>
467
+ <div class="confirm-dialog-banner danger">
468
+ This action cannot be undone. Invocations to <code>/api/functions/${safeName}/invoke</code> will return 404 Not Found.
469
+ </div>
470
+ </div>
471
+ <div class="modal-footer" id="delete-function-modal-footer" style="padding: 0.75rem 1.25rem;">
472
+ <button type="button" class="btn btn-secondary" onclick="closeDeleteFunctionModal()">Cancel</button>
473
+ <button type="button" class="btn btn-danger" id="btn-confirm-delete-function" data-fn-id="${safeId}">
474
+ Delete Function
475
+ </button>
476
+ </div>
477
+ </div>
478
+ </div>
479
+ `;
480
+
481
+ const deleteBtn = document.getElementById('btn-confirm-delete-function');
482
+ if (deleteBtn) {
483
+ deleteBtn.addEventListener('click', () => confirmDeleteFunction(id, name, false));
484
+ }
485
+
486
+ setTimeout(() => {
487
+ document.getElementById('btn-confirm-delete-function')?.focus();
488
+ }, 50);
489
+ }
490
+
491
+ function closeDeleteFunctionModal() {
492
+ const modalRoot = document.getElementById('modal-root');
493
+ if (modalRoot) modalRoot.innerHTML = '';
494
+ }
495
+
496
+ async function confirmDeleteFunction(id, name, force = false) {
497
+ const actionBtnId = force ? 'btn-force-delete-function' : 'btn-confirm-delete-function';
498
+ const btn = document.getElementById(actionBtnId);
499
+ if (btn) {
500
+ btn.disabled = true;
501
+ btn.textContent = force ? 'Force Deleting...' : 'Deleting...';
502
+ }
503
+
504
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
505
+ const basePath = slug && slug !== 'default' ? `/api/apps/${slug}/functions/${id}` : `/api/functions/${id}`;
506
+ const endpoint = force ? `${basePath}?force=true` : basePath;
507
+
508
+ try {
509
+ await api(endpoint, { method: 'DELETE' });
510
+ closeDeleteFunctionModal();
511
+ toast(`Function '${name}' deleted${force ? ' (forced)' : ''}`, 'info');
512
+ if (typeof closeFunctionEditor === 'function') {
513
+ closeFunctionEditor();
514
+ }
515
+ await loadFunctionStats();
516
+ await loadFunctionsList();
517
+ } catch (err) {
518
+ if (err.status === 409 && !force) {
519
+ renderConflictModalState(id, name, err.message);
520
+ return;
521
+ }
522
+ if (btn) {
523
+ btn.disabled = false;
524
+ btn.textContent = force ? 'Force Delete Anyway' : 'Delete Function';
525
+ }
526
+ const body = document.getElementById('delete-function-modal-body');
527
+ if (body) {
528
+ const errBox = document.createElement('div');
529
+ errBox.style.cssText = 'background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.35); border-radius: 6px; padding: 0.75rem; font-size: 12px; color: #ef4444;';
530
+ errBox.textContent = err.message || 'Failed to delete function';
531
+ body.prepend(errBox);
532
+ }
533
+ toast(err.message || 'Failed to delete function', 'error');
534
+ }
535
+ }
536
+
537
+ function renderConflictModalState(id, name, conflictMessage) {
538
+ const safeId = typeof escapeHtml === 'function' ? escapeHtml(id) : id;
539
+ const safeName = typeof escapeHtml === 'function' ? escapeHtml(name) : name;
540
+ const safeMsg = typeof escapeHtml === 'function' ? escapeHtml(conflictMessage) : conflictMessage;
541
+
542
+ const modal = document.querySelector('#modal-root .modal');
543
+ if (!modal) return;
544
+
545
+ const header = modal.querySelector('.modal-header');
546
+ if (header) {
547
+ header.style.borderBottomColor = 'rgba(245, 158, 11, 0.3)';
548
+ header.innerHTML = `
549
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
550
+ <span style="font-size: 18px;">⚠️</span>
551
+ <h2 class="modal-title warning" style="font-size: 16px;">Cannot Delete: Flow Dependencies</h2>
552
+ </div>
553
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeDeleteFunctionModal()" aria-label="Close">✕</button>
554
+ `;
555
+ }
556
+
557
+ const body = document.getElementById('delete-function-modal-body');
558
+ if (body) {
559
+ body.innerHTML = `
560
+ <div class="confirm-dialog-banner warning">
561
+ <div class="confirm-dialog-banner-title">Cannot Delete: Function in Use</div>
562
+ <div>${safeMsg}</div>
563
+ </div>
564
+ <div class="confirm-dialog-banner danger">
565
+ <strong>Warning:</strong> Force deleting function <strong style="font-family: var(--font-mono);">${safeName}</strong> will remove it immediately. Subsequent executions of referencing flows will fail during state execution.
566
+ </div>
567
+ `;
568
+ }
569
+
570
+ const footer = document.getElementById('delete-function-modal-footer');
571
+ if (footer) {
572
+ footer.innerHTML = `
573
+ <button type="button" class="btn btn-secondary" onclick="closeDeleteFunctionModal()">Cancel (Keep Function)</button>
574
+ <button type="button" class="btn btn-danger" id="btn-force-delete-function" data-fn-id="${safeId}">
575
+ Force Delete Anyway
576
+ </button>
577
+ `;
578
+ const forceBtn = document.getElementById('btn-force-delete-function');
579
+ if (forceBtn) {
580
+ forceBtn.addEventListener('click', () => confirmDeleteFunction(id, name, true));
581
+ }
582
+ setTimeout(() => {
583
+ document.getElementById('btn-force-delete-function')?.focus();
584
+ }, 50);
585
+ }
586
+ }
587
+
588
+ function deleteFunctionPrompt(id, name) {
589
+ openDeleteFunctionModal(id, name);
590
+ }
591
+
592
+ function copyFunctionEndpoint(path) {
593
+ const fullUrl = window.location.origin + path;
594
+ if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
595
+ navigator.clipboard.writeText(fullUrl).then(() => {
596
+ toast('Copied function endpoint URL to clipboard', 'info');
597
+ }).catch(() => {
598
+ prompt('Copy function endpoint URL:', fullUrl);
599
+ });
600
+ } else {
601
+ prompt('Copy function endpoint URL:', fullUrl);
602
+ }
603
+ }
604
+
605
+ // ==========================================
606
+ // 3. Global Execution History & Logs
607
+ // ==========================================
608
+
609
+ async function loadFunctionLogs(page = 1) {
610
+ const container = document.getElementById('functions-tab-content');
611
+ if (!container) return;
612
+
613
+ container.innerHTML = `
614
+ <div style="display: flex; align-items: center; justify-content: center; padding: 4rem; color: var(--text-muted);">
615
+ <span class="spinner" style="margin-right: 8px;"></span> Loading invocation logs...
616
+ </div>
617
+ `;
618
+
619
+ try {
620
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
621
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
622
+ const params = new URLSearchParams({
623
+ page: String(page),
624
+ perPage: String(functionsState.logFilter.perPage || 25),
625
+ });
626
+ if (functionsState.logFilter.functionId) {
627
+ params.append('functionId', functionsState.logFilter.functionId);
628
+ }
629
+ if (functionsState.logFilter.status && functionsState.logFilter.status !== 'all') {
630
+ params.append('status', functionsState.logFilter.status);
631
+ }
632
+
633
+ const res = await api(`${baseUrl}?${params.toString()}`);
634
+ functionsState.logs = res.items || [];
635
+ functionsState.logFilter.page = res.page || 1;
636
+ functionsState.logFilter.totalItems = res.totalItems || 0;
637
+ functionsState.logFilter.totalPages = res.totalPages || 1;
638
+
639
+ renderFunctionLogsTable(functionsState.logs);
640
+ } catch (err) {
641
+ container.innerHTML = `
642
+ <div class="card" style="padding: 2rem; text-align: center; color: var(--accent-danger);">
643
+ <p>Failed to load logs: ${escapeHtml(err.message || String(err))}</p>
644
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs()">Try Again</button>
645
+ </div>
646
+ `;
647
+ }
648
+ }
649
+
650
+ function renderFunctionLogsTable(logs) {
651
+ const container = document.getElementById('functions-tab-content');
652
+ if (!container) return;
653
+
654
+ const fnOptions = (functionsState.functions || []).map(f => `
655
+ <option value="${f.id}" ${functionsState.logFilter.functionId === f.id ? 'selected' : ''}>
656
+ ${escapeHtml(f.name)}
657
+ </option>
658
+ `).join('');
659
+
660
+ if (!logs || logs.length === 0) {
661
+ container.innerHTML = `
662
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
663
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
664
+ <div style="display: flex; align-items: center; gap: 8px;">
665
+ <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
666
+ <option value="">All Functions</option>
667
+ ${fnOptions}
668
+ </select>
669
+ </div>
670
+ </div>
671
+ <div style="padding: 3rem 1rem; text-align: center; color: var(--text-muted);">
672
+ No execution logs recorded yet.
673
+ </div>
674
+ </div>
675
+ `;
676
+ return;
677
+ }
678
+
679
+ const rows = logs.map(l => {
680
+ const isOk = l.status === 'success';
681
+ const statusBadge = isOk
682
+ ? `<span class="badge" style="background: rgba(16, 185, 129, 0.15); color: #10b981; font-size: 11px;">${l.statusCode || 200} OK</span>`
683
+ : `<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444; font-size: 11px;">${escapeHtml(l.status.toUpperCase())}</span>`;
684
+
685
+ return `
686
+ <tr style="border-bottom: 1px solid var(--border-subtle);">
687
+ <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${formatTimestamp(l.timestamp || l.createdAt)}</td>
688
+ <td style="padding: 10px 14px;">
689
+ <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;">
690
+ ${escapeHtml(l.functionName || l.functionId)}
691
+ </a>
692
+ </td>
693
+ <td style="padding: 10px 14px;">${statusBadge}</td>
694
+ <td style="padding: 10px 14px; font-size: 12px; font-weight: 600;">${l.durationMs}ms</td>
695
+ <td style="padding: 10px 14px;"><code style="font-size: 11px;">${escapeHtml(l.trigger || l.method || 'http')}</code></td>
696
+ <td style="padding: 10px 14px; font-size: 12px; color: var(--text-muted);">${escapeHtml(l.actorId || 'public')}</td>
697
+ <td style="padding: 10px 14px; text-align: right;">
698
+ <button class="btn btn-secondary btn-sm" onclick="viewLogPayload('${l.id}')" title="Inspect Request/Response payload" style="font-size: 11px; padding: 2px 8px;">
699
+ Inspect
700
+ </button>
701
+ </td>
702
+ </tr>
703
+ `;
704
+ }).join('');
705
+
706
+ container.innerHTML = `
707
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
708
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
709
+ <div style="display: flex; align-items: center; gap: 8px;">
710
+ <select class="input" style="font-size: 12px; padding: 4px 8px;" onchange="filterFunctionLogs(this.value)">
711
+ <option value="">All Functions</option>
712
+ ${fnOptions}
713
+ </select>
714
+ <span style="font-size: 12px; color: var(--text-muted);">
715
+ Showing ${logs.length} of ${functionsState.logFilter.totalItems || logs.length} logs
716
+ </span>
717
+ </div>
718
+ <div style="display: flex; align-items: center; gap: 8px;">
719
+ <button class="btn btn-secondary btn-sm" onclick="loadFunctionLogs(${functionsState.logFilter.page || 1})">
720
+ Refresh
721
+ </button>
722
+ <button class="btn btn-danger btn-sm" onclick="openClearLogsModal()">
723
+ Clear Logs
724
+ </button>
725
+ </div>
726
+ </div>
727
+
728
+ <div style="overflow-x: auto; border: 1px solid var(--border-subtle); border-radius: 6px;">
729
+ <table class="table" style="width: 100%; border-collapse: collapse; text-align: left; font-size: 13px;">
730
+ <thead>
731
+ <tr style="border-bottom: 1px solid var(--border-subtle); background: var(--bg-card-hover);">
732
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Timestamp</th>
733
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Function</th>
734
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Status</th>
735
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Latency</th>
736
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Trigger / Method</th>
737
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;">Caller</th>
738
+ <th style="padding: 10px 14px; font-size: 11.5px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; text-align: right;">Payload</th>
739
+ </tr>
740
+ </thead>
741
+ <tbody>
742
+ ${rows}
743
+ </tbody>
744
+ </table>
745
+ </div>
746
+ </div>
747
+ `;
748
+ }
749
+
750
+ function filterFunctionLogs(fnId) {
751
+ functionsState.logFilter.functionId = fnId || '';
752
+ loadFunctionLogs(1);
753
+ }
754
+
755
+ function viewFunctionLogs(functionId) {
756
+ switchFunctionsTab('logs');
757
+ filterFunctionLogs(functionId);
758
+ }
759
+
760
+ async function viewLogPayload(logId) {
761
+ let log = (functionsState.editorLogs || []).find(l => l.id === logId)
762
+ || (functionsState.logs || []).find(l => l.id === logId);
763
+
764
+ if (!log) {
765
+ try {
766
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
767
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
768
+ const res = await api(`${baseUrl}?perPage=100`);
769
+ if (res && res.items) {
770
+ log = res.items.find(l => l.id === logId);
771
+ }
772
+ } catch (_) {}
773
+ }
774
+
775
+ if (!log) {
776
+ if (typeof toast === 'function') toast('Execution log details not found', 'warning');
777
+ return;
778
+ }
779
+
780
+ let modalRoot = document.getElementById('modal-root');
781
+ if (!modalRoot) {
782
+ modalRoot = document.createElement('div');
783
+ modalRoot.id = 'modal-root';
784
+ document.body.appendChild(modalRoot);
785
+ }
786
+
787
+ let consoleOutput = '(No console output logged)';
788
+ if (log.logs) {
789
+ if (Array.isArray(log.logs) && log.logs.length > 0) {
790
+ consoleOutput = log.logs.join('\n');
791
+ } else if (typeof log.logs === 'string' && log.logs.trim().length > 0) {
792
+ consoleOutput = log.logs;
793
+ }
794
+ }
795
+
796
+ let reqFormatted = '{}';
797
+ if (log.requestPayload) {
798
+ try {
799
+ reqFormatted = JSON.stringify(typeof log.requestPayload === 'string' ? JSON.parse(log.requestPayload) : log.requestPayload, null, 2);
800
+ } catch {
801
+ reqFormatted = String(log.requestPayload);
802
+ }
803
+ }
804
+
805
+ let resFormatted = '{}';
806
+ if (log.responsePayload) {
807
+ try {
808
+ resFormatted = JSON.stringify(typeof log.responsePayload === 'string' ? JSON.parse(log.responsePayload) : log.responsePayload, null, 2);
809
+ } catch {
810
+ resFormatted = String(log.error || log.responsePayload);
811
+ }
812
+ } else if (log.error) {
813
+ resFormatted = String(log.error);
814
+ }
815
+
816
+ modalRoot.innerHTML = `
817
+ <div class="modal-backdrop" onclick="this.remove()">
818
+ <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()">
819
+ <div style="display: flex; align-items: center; justify-content: space-between; padding: 14px 20px; border-bottom: 1px solid var(--border-subtle);">
820
+ <div style="display: flex; align-items: center; gap: 8px;">
821
+ <h3 style="margin: 0; font-size: 1.1rem; font-weight: 600;">Execution Payload Inspector</h3>
822
+ <span class="badge" style="font-size: 11px;">${log.durationMs}ms</span>
823
+ </div>
824
+ <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()" style="border: none; font-size: 18px; line-height: 1;">✕</button>
825
+ </div>
826
+ <div style="flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 14px;">
827
+ <div>
828
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Console Output Logs</label>
829
+ <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>
830
+ </div>
831
+ <div>
832
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Request Payload</label>
833
+ <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>
834
+ </div>
835
+ <div>
836
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px; color: var(--text-muted);">Response Payload</label>
837
+ <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>
838
+ </div>
839
+ </div>
840
+ <div style="padding: 12px 20px; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end;">
841
+ <button class="btn btn-secondary btn-sm" onclick="this.closest('.modal-backdrop').remove()">Close</button>
842
+ </div>
843
+ </div>
844
+ </div>
845
+ `;
846
+ }
847
+
848
+ function openClearLogsModal() {
849
+ let modalRoot = document.getElementById('modal-root');
850
+ if (!modalRoot) {
851
+ modalRoot = document.createElement('div');
852
+ modalRoot.id = 'modal-root';
853
+ document.body.appendChild(modalRoot);
854
+ }
855
+
856
+ modalRoot.innerHTML = `
857
+ <div class="modal-backdrop" id="clear-logs-backdrop" onclick="if(event.target===this)closeClearLogsModal()">
858
+ <div class="modal confirm-dialog">
859
+ <div class="modal-header" style="border-bottom-color: rgba(239, 68, 68, 0.2);">
860
+ <div style="display: flex; align-items: center; gap: 0.5rem;">
861
+ <span style="font-size: 18px;">⚠️</span>
862
+ <h2 class="modal-title danger" style="font-size: 16px;">Clear Execution Logs</h2>
863
+ </div>
864
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeClearLogsModal()" aria-label="Close">✕</button>
865
+ </div>
866
+ <div class="modal-body" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
867
+ <p style="font-size: 13px; color: var(--text-main, #cbd5e1); line-height: 1.5; margin: 0;">
868
+ Are you sure you want to permanently clear all function invocation logs?
869
+ </p>
870
+ <div class="confirm-dialog-banner danger">
871
+ This will delete all historical logs, timestamps, status codes, and console logs. This action cannot be undone.
872
+ </div>
873
+ </div>
874
+ <div class="modal-footer" style="padding: 0.75rem 1.25rem;">
875
+ <button type="button" class="btn btn-secondary" onclick="closeClearLogsModal()">Cancel</button>
876
+ <button type="button" class="btn btn-danger" id="btn-confirm-clear-logs" onclick="confirmClearAllLogs()">
877
+ Clear All Logs
878
+ </button>
879
+ </div>
880
+ </div>
881
+ </div>
882
+ `;
883
+
884
+ setTimeout(() => {
885
+ document.getElementById('btn-confirm-clear-logs')?.focus();
886
+ }, 50);
887
+ }
888
+
889
+ function closeClearLogsModal() {
890
+ const modalRoot = document.getElementById('modal-root');
891
+ if (modalRoot) modalRoot.innerHTML = '';
892
+ }
893
+
894
+ async function confirmClearAllLogs() {
895
+ const btn = document.getElementById('btn-confirm-clear-logs');
896
+ if (btn) {
897
+ btn.disabled = true;
898
+ btn.textContent = 'Clearing...';
899
+ }
900
+ try {
901
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
902
+ const endpoint = slug && slug !== 'default' ? `/api/apps/${slug}/functions/logs` : '/api/functions/logs';
903
+ await api(endpoint, { method: 'DELETE' });
904
+ closeClearLogsModal();
905
+ toast('Execution logs cleared', 'info');
906
+ await loadFunctionLogs();
907
+ } catch (err) {
908
+ if (btn) {
909
+ btn.disabled = false;
910
+ btn.textContent = 'Clear All Logs';
911
+ }
912
+ toast(err.message || 'Failed to clear logs', 'error');
913
+ }
914
+ }
915
+
916
+ function clearAllFunctionLogs() {
917
+ openClearLogsModal();
918
+ }
919
+
920
+ function formatTimestamp(iso) {
921
+ if (!iso) return '-';
922
+ try {
923
+ const d = new Date(iso);
924
+ if (isNaN(d.getTime())) return iso;
925
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) + ' ' + d.toLocaleDateString();
926
+ } catch {
927
+ return iso;
928
+ }
929
+ }
930
+
931
+ // Forwarders for workbench functions
932
+ function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
933
+ if (typeof window.openFunctionEditor === 'function' && window.openFunctionEditor !== openFunctionEditor) {
934
+ return window.openFunctionEditor(idOrName, pushState, initialTab);
935
+ }
936
+ }
937
+
938
+ function openCreateFunctionPage() {
939
+ if (typeof window.openCreateFunctionPage === 'function' && window.openCreateFunctionPage !== openCreateFunctionPage) {
940
+ return window.openCreateFunctionPage();
941
+ }
942
+ }
943
+
944
+ // ==========================================
945
+ // 4. Global Exports & Startup Hook
946
+ // ==========================================
947
+
948
+ if (typeof window !== 'undefined') {
949
+ window.functionsState = functionsState;
950
+ window.STARTER_RECIPES = STARTER_RECIPES;
951
+ window.renderFunctionsView = renderFunctionsView;
952
+ window.switchFunctionsTab = switchFunctionsTab;
953
+ window.refreshFunctionsView = refreshFunctionsView;
954
+ window.loadFunctionStats = loadFunctionStats;
955
+ window.loadFunctionsList = loadFunctionsList;
956
+ window.renderFunctionsTable = renderFunctionsTable;
957
+ window.toggleFunctionEnabled = toggleFunctionEnabled;
958
+ window.deleteFunctionPrompt = deleteFunctionPrompt;
959
+ window.openDeleteFunctionModal = openDeleteFunctionModal;
960
+ window.closeDeleteFunctionModal = closeDeleteFunctionModal;
961
+ window.confirmDeleteFunction = confirmDeleteFunction;
962
+ window.renderConflictModalState = renderConflictModalState;
963
+ window.openClearLogsModal = openClearLogsModal;
964
+ window.closeClearLogsModal = closeClearLogsModal;
965
+ window.confirmClearAllLogs = confirmClearAllLogs;
966
+ window.copyFunctionEndpoint = copyFunctionEndpoint;
967
+ window.openFunctionEditor = window.openFunctionEditor || openFunctionEditor;
968
+ window.openCreateFunctionPage = window.openCreateFunctionPage || openCreateFunctionPage;
969
+ window.loadFunctionLogs = loadFunctionLogs;
970
+ window.renderFunctionLogsTable = renderFunctionLogsTable;
971
+ window.filterFunctionLogs = filterFunctionLogs;
972
+ window.viewFunctionLogs = viewFunctionLogs;
973
+ window.viewLogPayload = viewLogPayload;
974
+ window.clearAllFunctionLogs = clearAllFunctionLogs;
975
+ window.formatTimestamp = formatTimestamp;
976
+ }
977
+
978
+ if (typeof state !== 'undefined' && state.token && typeof loadFunctionStats === 'function') {
979
+ loadFunctionStats();
980
+ }