@nodestackapp/server 2.5.0 → 2.7.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 (269) hide show
  1. package/README.md +42 -28
  2. package/dist/NodeStack.d.ts +5 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +117 -18
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +2 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +40 -3
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +21479 -17251
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/api.js +8 -0
  14. package/dist/admin/ui/js/app.js +698 -641
  15. package/dist/admin/ui/js/apps.js +514 -489
  16. package/dist/admin/ui/js/collections.js +486 -484
  17. package/dist/admin/ui/js/command-palette.js +693 -673
  18. package/dist/admin/ui/js/cron.js +1706 -0
  19. package/dist/admin/ui/js/database.js +10 -0
  20. package/dist/admin/ui/js/flows-designer.js +1219 -1076
  21. package/dist/admin/ui/js/flows.js +947 -890
  22. package/dist/admin/ui/js/functions-tester.js +1 -1
  23. package/dist/admin/ui/js/functions-workbench.js +1162 -1101
  24. package/dist/admin/ui/js/functions.js +983 -979
  25. package/dist/admin/ui/js/rules.js +1080 -775
  26. package/dist/admin/ui/js/schema.js +346 -304
  27. package/dist/admin/ui/js/snapshots.js +338 -0
  28. package/dist/admin/ui/js/views.js +1 -1
  29. package/dist/apps/AppManager.d.ts +1 -1
  30. package/dist/apps/AppManager.d.ts.map +1 -1
  31. package/dist/apps/AppManager.js +11 -21
  32. package/dist/apps/AppManager.js.map +1 -1
  33. package/dist/apps/AppRegistry.d.ts +1 -0
  34. package/dist/apps/AppRegistry.d.ts.map +1 -1
  35. package/dist/apps/AppRegistry.js +78 -23
  36. package/dist/apps/AppRegistry.js.map +1 -1
  37. package/dist/apps/AppScope.d.ts +2 -1
  38. package/dist/apps/AppScope.d.ts.map +1 -1
  39. package/dist/apps/AppScope.js +27 -17
  40. package/dist/apps/AppScope.js.map +1 -1
  41. package/dist/auth/ApiKeyService.d.ts +63 -2
  42. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  43. package/dist/auth/ApiKeyService.js +518 -8
  44. package/dist/auth/ApiKeyService.js.map +1 -1
  45. package/dist/auth/AuthService.d.ts +30 -1
  46. package/dist/auth/AuthService.d.ts.map +1 -1
  47. package/dist/auth/AuthService.js +468 -65
  48. package/dist/auth/AuthService.js.map +1 -1
  49. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  50. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/AppleProvider.js +40 -3
  52. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  53. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  54. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  55. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  56. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  57. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  58. package/dist/auth/oauth/DiscordProvider.js +4 -1
  59. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  60. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  61. package/dist/auth/oauth/GitHubProvider.js +4 -1
  62. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  63. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  64. package/dist/auth/oauth/GoogleProvider.js +4 -1
  65. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  66. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  67. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  68. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  69. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  70. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  71. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  72. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  73. package/dist/auth/oauth/types.d.ts +4 -2
  74. package/dist/auth/oauth/types.d.ts.map +1 -1
  75. package/dist/cli/cli.d.ts.map +1 -1
  76. package/dist/cli/cli.js +228 -12
  77. package/dist/cli/cli.js.map +1 -1
  78. package/dist/core/config/ConfigService.d.ts.map +1 -1
  79. package/dist/core/config/ConfigService.js +5 -3
  80. package/dist/core/config/ConfigService.js.map +1 -1
  81. package/dist/core/config/EnvLoader.d.ts +14 -0
  82. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  83. package/dist/core/config/EnvLoader.js +44 -0
  84. package/dist/core/config/EnvLoader.js.map +1 -1
  85. package/dist/core/container/Container.d.ts +14 -0
  86. package/dist/core/container/Container.d.ts.map +1 -1
  87. package/dist/core/container/Container.js +32 -0
  88. package/dist/core/container/Container.js.map +1 -1
  89. package/dist/core/container/Tokens.d.ts +2 -0
  90. package/dist/core/container/Tokens.d.ts.map +1 -1
  91. package/dist/core/container/Tokens.js +2 -0
  92. package/dist/core/container/Tokens.js.map +1 -1
  93. package/dist/core/errors/AppError.d.ts +7 -7
  94. package/dist/core/errors/AppError.d.ts.map +1 -1
  95. package/dist/core/errors/AppError.js +18 -14
  96. package/dist/core/errors/AppError.js.map +1 -1
  97. package/dist/core/events/EventBus.d.ts.map +1 -1
  98. package/dist/core/events/EventBus.js +36 -6
  99. package/dist/core/events/EventBus.js.map +1 -1
  100. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  101. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  102. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  103. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  104. package/dist/core/plugins/PluginManager.d.ts +20 -1
  105. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  106. package/dist/core/plugins/PluginManager.js +231 -146
  107. package/dist/core/plugins/PluginManager.js.map +1 -1
  108. package/dist/core/plugins/types.d.ts +48 -31
  109. package/dist/core/plugins/types.d.ts.map +1 -1
  110. package/dist/cron/CronParser.d.ts +83 -0
  111. package/dist/cron/CronParser.d.ts.map +1 -0
  112. package/dist/cron/CronParser.js +538 -0
  113. package/dist/cron/CronParser.js.map +1 -0
  114. package/dist/cron/CronService.d.ts +74 -0
  115. package/dist/cron/CronService.d.ts.map +1 -0
  116. package/dist/cron/CronService.js +1254 -0
  117. package/dist/cron/CronService.js.map +1 -0
  118. package/dist/cron/types.d.ts +98 -0
  119. package/dist/cron/types.d.ts.map +1 -0
  120. package/dist/cron/types.js +3 -0
  121. package/dist/cron/types.js.map +1 -0
  122. package/dist/database/DatabaseService.d.ts +4 -1
  123. package/dist/database/DatabaseService.d.ts.map +1 -1
  124. package/dist/database/DatabaseService.js +34 -9
  125. package/dist/database/DatabaseService.js.map +1 -1
  126. package/dist/database/config/DatabaseConfigService.d.ts +1 -0
  127. package/dist/database/config/DatabaseConfigService.d.ts.map +1 -1
  128. package/dist/database/config/DatabaseConfigService.js +4 -2
  129. package/dist/database/config/DatabaseConfigService.js.map +1 -1
  130. package/dist/database/drivers/DriverPackageLoader.d.ts +11 -0
  131. package/dist/database/drivers/DriverPackageLoader.d.ts.map +1 -0
  132. package/dist/database/drivers/DriverPackageLoader.js +112 -0
  133. package/dist/database/drivers/DriverPackageLoader.js.map +1 -0
  134. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  135. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  136. package/dist/database/drivers/DriverRegistry.js +29 -0
  137. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  138. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  139. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  140. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  141. package/dist/database/drivers/MssqlDriver.js +10 -5
  142. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  143. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  144. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  145. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  146. package/dist/database/drivers/PostgresDriver.d.ts.map +1 -1
  147. package/dist/database/drivers/PostgresDriver.js +4 -5
  148. package/dist/database/drivers/PostgresDriver.js.map +1 -1
  149. package/dist/database/migration/DatabaseMigrationService.d.ts +1 -0
  150. package/dist/database/migration/DatabaseMigrationService.d.ts.map +1 -1
  151. package/dist/database/migration/DatabaseMigrationService.js +51 -0
  152. package/dist/database/migration/DatabaseMigrationService.js.map +1 -1
  153. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  154. package/dist/database/migrations/SystemMigrations.js +200 -5
  155. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  156. package/dist/flows/FlowEngine.js.map +1 -1
  157. package/dist/flows/FlowService.d.ts +10 -1
  158. package/dist/flows/FlowService.d.ts.map +1 -1
  159. package/dist/flows/FlowService.js +227 -14
  160. package/dist/flows/FlowService.js.map +1 -1
  161. package/dist/flows/FlowValidator.d.ts +2 -1
  162. package/dist/flows/FlowValidator.d.ts.map +1 -1
  163. package/dist/flows/FlowValidator.js +89 -4
  164. package/dist/flows/FlowValidator.js.map +1 -1
  165. package/dist/flows/types.d.ts +20 -3
  166. package/dist/flows/types.d.ts.map +1 -1
  167. package/dist/functions/FunctionService.d.ts +10 -2
  168. package/dist/functions/FunctionService.d.ts.map +1 -1
  169. package/dist/functions/FunctionService.js +271 -37
  170. package/dist/functions/FunctionService.js.map +1 -1
  171. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  172. package/dist/functions/runtime/QuickJsWasmRuntime.js +189 -177
  173. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  174. package/dist/functions/types.d.ts +31 -2
  175. package/dist/functions/types.d.ts.map +1 -1
  176. package/dist/http/HttpServer.d.ts +7 -1
  177. package/dist/http/HttpServer.d.ts.map +1 -1
  178. package/dist/http/HttpServer.js +187 -8
  179. package/dist/http/HttpServer.js.map +1 -1
  180. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  181. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  182. package/dist/http/controllers/ApiKeyController.js +47 -1
  183. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  184. package/dist/http/controllers/AuthController.d.ts +12 -0
  185. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  186. package/dist/http/controllers/AuthController.js +40 -2
  187. package/dist/http/controllers/AuthController.js.map +1 -1
  188. package/dist/http/controllers/CronController.d.ts +63 -0
  189. package/dist/http/controllers/CronController.d.ts.map +1 -0
  190. package/dist/http/controllers/CronController.js +92 -0
  191. package/dist/http/controllers/CronController.js.map +1 -0
  192. package/dist/http/controllers/DatabaseController.d.ts.map +1 -1
  193. package/dist/http/controllers/DatabaseController.js +53 -0
  194. package/dist/http/controllers/DatabaseController.js.map +1 -1
  195. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  196. package/dist/http/controllers/FlowController.js +45 -4
  197. package/dist/http/controllers/FlowController.js.map +1 -1
  198. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  199. package/dist/http/controllers/FunctionController.js +16 -2
  200. package/dist/http/controllers/FunctionController.js.map +1 -1
  201. package/dist/http/controllers/HealthController.js +2 -2
  202. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  203. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  204. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  205. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  206. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  207. package/dist/http/middleware/AuthMiddleware.js +6 -3
  208. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  209. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  210. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  211. package/dist/index.d.ts +2 -2
  212. package/dist/index.d.ts.map +1 -1
  213. package/dist/index.js +6 -2
  214. package/dist/index.js.map +1 -1
  215. package/dist/queue/QueueService.d.ts +9 -0
  216. package/dist/queue/QueueService.d.ts.map +1 -1
  217. package/dist/queue/QueueService.js +143 -60
  218. package/dist/queue/QueueService.js.map +1 -1
  219. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  220. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  221. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  222. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  223. package/dist/records/FtsService.d.ts +7 -3
  224. package/dist/records/FtsService.d.ts.map +1 -1
  225. package/dist/records/FtsService.js +69 -5
  226. package/dist/records/FtsService.js.map +1 -1
  227. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  228. package/dist/records/QueryFilterParser.js +58 -20
  229. package/dist/records/QueryFilterParser.js.map +1 -1
  230. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  231. package/dist/records/RecordSanitizer.js +32 -4
  232. package/dist/records/RecordSanitizer.js.map +1 -1
  233. package/dist/records/RecordService.d.ts +6 -0
  234. package/dist/records/RecordService.d.ts.map +1 -1
  235. package/dist/records/RecordService.js +95 -14
  236. package/dist/records/RecordService.js.map +1 -1
  237. package/dist/records/RecordValidator.d.ts +10 -0
  238. package/dist/records/RecordValidator.d.ts.map +1 -1
  239. package/dist/records/RecordValidator.js +110 -2
  240. package/dist/records/RecordValidator.js.map +1 -1
  241. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  242. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  243. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  244. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  245. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  246. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  247. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  248. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  249. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  250. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  251. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  252. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  253. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  254. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  255. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  256. package/dist/schema/OpenApiGenerator.js +103 -3
  257. package/dist/schema/OpenApiGenerator.js.map +1 -1
  258. package/dist/schema/models/Field.d.ts +1 -0
  259. package/dist/schema/models/Field.d.ts.map +1 -1
  260. package/dist/snapshots/SnapshotService.d.ts.map +1 -1
  261. package/dist/snapshots/SnapshotService.js +21 -9
  262. package/dist/snapshots/SnapshotService.js.map +1 -1
  263. package/dist/snapshots/drivers/LogicalSnapshotDriver.d.ts.map +1 -1
  264. package/dist/snapshots/drivers/LogicalSnapshotDriver.js +2 -0
  265. package/dist/snapshots/drivers/LogicalSnapshotDriver.js.map +1 -1
  266. package/dist/templates/definitions/ecommerce.js +6 -6
  267. package/dist/templates/definitions/ecommerce.js.map +1 -1
  268. package/dist/webhooks/WebhookService.js +1 -1
  269. package/package.json +5 -3
@@ -1,1101 +1,1162 @@
1
- // Serverless Functions Dedicated Workbench & Code Editor Module
2
- // Companion module for NodeStack Admin UI Functions
3
-
4
- // ==========================================
5
- // 1. Context API (ctx) Documentation & Snippets
6
- // ==========================================
7
-
8
- const CTX_DOCS = [
9
- // HTTP Request (context.request)
10
- {
11
- name: 'context.request.body',
12
- type: 'any',
13
- cat: 'request',
14
- desc: 'Parsed JSON payload sent in HTTP POST/PATCH invocation',
15
- snippet: 'const body = context.request?.body || {};\n'
16
- },
17
- {
18
- name: 'context.request.query',
19
- type: 'Record<string, any>',
20
- cat: 'request',
21
- desc: 'URL query string parameters (e.g. ?limit=10&status=active)',
22
- snippet: 'const { limit, status } = context.request?.query || {};\n'
23
- },
24
- {
25
- name: 'context.request.auth',
26
- type: '{ id, role, email } | null',
27
- cat: 'request',
28
- desc: 'Authenticated caller identity, or null if public invocation',
29
- snippet: 'if (!context.request?.auth) return { status: 401, body: { error: "Unauthorized" } };\n'
30
- },
31
- {
32
- name: 'context.request.headers',
33
- type: 'Record<string, string>',
34
- cat: 'request',
35
- desc: 'HTTP request headers map (lowercase header keys)',
36
- snippet: 'const authHeader = context.request?.headers["authorization"];\n'
37
- },
38
- {
39
- name: 'context.request.method',
40
- type: "'GET' | 'POST' | 'PATCH' | 'DELETE'",
41
- cat: 'request',
42
- desc: 'HTTP method used to invoke this function',
43
- snippet: 'const method = context.request?.method;\n'
44
- },
45
-
46
- // DB Lifecycle Event (context.event)
47
- {
48
- name: 'context.event.record',
49
- type: 'Record<string, any>',
50
- cat: 'event',
51
- desc: 'Target database record being mutated during collection lifecycle hook',
52
- snippet: 'const record = context.event?.record;\n'
53
- },
54
- {
55
- name: 'context.event.collection',
56
- type: 'string',
57
- cat: 'event',
58
- desc: 'Target collection name triggering this lifecycle event',
59
- snippet: 'const collection = context.event?.collection;\n'
60
- },
61
- {
62
- name: 'context.event.action',
63
- type: "'create' | 'update' | 'delete'",
64
- cat: 'event',
65
- desc: 'Collection mutation action triggering this hook',
66
- snippet: 'const action = context.event?.action;\n'
67
- },
68
- {
69
- name: 'context.event.isBefore',
70
- type: 'boolean',
71
- cat: 'event',
72
- desc: 'true for before-write hooks (can validate or cancel write), false for after-write',
73
- snippet: 'if (context.event?.isBefore && !isValid) return { status: 400, body: { cancel: true, reason: "Validation failed" } };\n'
74
- },
75
-
76
- // Database CRUD (core.sdk.collection)
77
- {
78
- name: 'core.sdk.collection(col).get(id)',
79
- type: 'Promise<Record>',
80
- cat: 'records',
81
- desc: 'Fetch a single record by collection name and record ID',
82
- snippet: 'const item = await core.sdk.collection("products").get(id);\n'
83
- },
84
- {
85
- name: 'core.sdk.collection(col).list(opts)',
86
- type: 'Promise<{ items, totalItems }>',
87
- cat: 'records',
88
- desc: 'Query records with filter, sort, page, and perPage options',
89
- snippet: 'const { items, totalItems } = await core.sdk.collection("orders").list({ filter: "status = \'paid\'", perPage: 20 });\n'
90
- },
91
- {
92
- name: 'core.sdk.collection(col).create(data)',
93
- type: 'Promise<Record>',
94
- cat: 'records',
95
- desc: 'Create and insert a new record into target collection',
96
- snippet: 'const newRec = await core.sdk.collection("audit_events").create({ event: "checkout", timestamp: new Date().toISOString() });\n'
97
- },
98
- {
99
- name: 'core.sdk.collection(col).update(id, data)',
100
- type: 'Promise<Record>',
101
- cat: 'records',
102
- desc: 'Update fields on an existing database record',
103
- snippet: 'await core.sdk.collection("products").update(productId, { inStock: false });\n'
104
- },
105
- {
106
- name: 'core.sdk.collection(col).delete(id)',
107
- type: 'Promise<boolean>',
108
- cat: 'records',
109
- desc: 'Delete a record from database by collection name and ID',
110
- snippet: 'await core.sdk.collection("temp_tokens").delete(tokenId);\n'
111
- },
112
-
113
- // Queues (core.sdk.queue)
114
- {
115
- name: 'core.sdk.queue(name).send(payload, opts)',
116
- type: 'Promise<QueueMessage>',
117
- cat: 'queue',
118
- desc: 'Enqueue a message into a generic queue',
119
- snippet: 'await core.sdk.queue("notifications").send({ to: "user@example.com", text: "Welcome!" });\n'
120
- },
121
- {
122
- name: 'core.sdk.queue(name).claim(opts)',
123
- type: 'Promise<QueueMessage[]>',
124
- cat: 'queue',
125
- desc: 'Claim one or more pending messages from a queue with lease lock',
126
- snippet: 'const messages = await core.sdk.queue("notifications").claim({ limit: 1, visibilityTimeoutSeconds: 30 });\n'
127
- },
128
- {
129
- name: 'core.sdk.queue(name).complete(messageId, result, claimToken)',
130
- type: 'Promise<boolean>',
131
- cat: 'queue',
132
- desc: 'Acknowledge and mark a claimed message as completed with optional claim token',
133
- snippet: 'await core.sdk.queue("notifications").complete(message.id, { sent: true }, message.claimToken);\n'
134
- },
135
- {
136
- name: 'core.sdk.queue(name).fail(messageId, error, opts)',
137
- type: 'Promise<MessageFailResult>',
138
- cat: 'queue',
139
- desc: 'Reject a message with error details and trigger retry/backoff, returning { retried, deadLettered, attempts }',
140
- snippet: 'await core.sdk.queue("notifications").fail(message.id, "SMTP timeout", { backoffDelayMs: 5000, claimToken: message.claimToken });\n'
141
- },
142
- {
143
- name: 'core.sdk.queue(name).touch(messageId, extensionSeconds, claimToken)',
144
- type: 'Promise<boolean>',
145
- cat: 'queue',
146
- desc: 'Extend visibility timeout lease on an in-progress message',
147
- snippet: 'await core.sdk.queue("notifications").touch(message.id, 60, message.claimToken);\n'
148
- },
149
- {
150
- name: 'ctx.queue(name).send(payload, opts) / ctx.queue.send(...)',
151
- type: 'Promise<QueueMessage>',
152
- cat: 'queue',
153
- desc: 'Convenience alias on context.queue for enqueuing messages',
154
- snippet: 'await ctx.queue.send("notifications", { to: "user@example.com" });\n'
155
- },
156
-
157
- // Outbound Network, Observability & Environment
158
- {
159
- name: 'core.network.http.fetch(url, options)',
160
- type: 'Promise<{ ok, status, json(), text() }>',
161
- cat: 'utils',
162
- desc: 'SSRF-guarded outbound HTTP request (also available as global fetch)',
163
- snippet: 'const res = await core.network.http.fetch("https://api.example.com/data", { method: "POST" });\nconst data = await res.json();\n'
164
- },
165
- {
166
- name: 'core.observability.log(...args)',
167
- type: '(...args: any[]) => void',
168
- cat: 'utils',
169
- desc: 'Structured execution logging captured in Execution Logs (also console.log)',
170
- snippet: 'core.observability.log("Processing execution step", { step: 1, time: Date.now() });\n'
171
- },
172
- {
173
- name: 'context.env',
174
- type: 'Record<string, string>',
175
- cat: 'utils',
176
- desc: 'Environment variables and secrets defined in the JSON configuration below',
177
- snippet: 'const secretKey = context.env.MY_API_KEY;\n'
178
- },
179
- {
180
- name: 'context.app',
181
- type: '{ id, slug, name }',
182
- cat: 'utils',
183
- desc: 'Current tenant application identification and slug',
184
- snippet: 'const { id, slug } = context.app;\n'
185
- }
186
- ];
187
-
188
- function renderCtxItemsHtml(activeCategory = 'all') {
189
- return CTX_DOCS.map(item => {
190
- const isVisible = activeCategory === 'all' || item.cat === activeCategory;
191
- const jsSnippetArg = JSON.stringify(item.snippet).replace(/"/g, '&quot;');
192
- return `
193
- <div class="ctx-item" data-cat="${item.cat}" style="display: ${isVisible ? 'flex' : 'none'}; flex-direction: column; gap: 4px; padding: 7px 10px; border-radius: 6px; background: var(--bg-card); border: 1px solid var(--border-subtle); font-size: 11.5px;">
194
- <div style="display: flex; align-items: center; justify-content: space-between; gap: 6px;">
195
- <div style="display: flex; align-items: center; gap: 6px; overflow: hidden;">
196
- <code style="color: var(--accent-primary); font-weight: 600; font-size: 12px; white-space: nowrap;">${escapeHtml(item.name)}</code>
197
- <span style="font-size: 10px; color: var(--text-muted); padding: 1px 5px; background: var(--bg-input); border-radius: 3px; border: 1px solid var(--border-subtle); white-space: nowrap;">${escapeHtml(item.type)}</span>
198
- </div>
199
- <button type="button" class="btn btn-secondary btn-sm" onclick="insertFunctionSnippet(${jsSnippetArg})" style="font-size: 10px; padding: 2px 7px; flex-shrink: 0;" title="Click to insert snippet into code editor">
200
- + Insert
201
- </button>
202
- </div>
203
- <div style="color: var(--text-muted); font-size: 11px; line-height: 1.35;">
204
- ${escapeHtml(item.desc)}
205
- </div>
206
- </div>
207
- `;
208
- }).join('');
209
- }
210
-
211
- function insertFunctionSnippet(snippet) {
212
- if (functionsState.cmEditor) {
213
- functionsState.cmEditor.replaceSelection(snippet);
214
- functionsState.cmEditor.save();
215
- functionsState.cmEditor.focus();
216
- return;
217
- }
218
- const textarea = document.getElementById('fn-editor-code');
219
- if (!textarea) return;
220
-
221
- const start = textarea.selectionStart;
222
- const end = textarea.selectionEnd;
223
- const val = textarea.value;
224
-
225
- if (start !== undefined && end !== undefined && start >= 0) {
226
- textarea.value = val.substring(0, start) + snippet + val.substring(end);
227
- textarea.selectionStart = textarea.selectionEnd = start + snippet.length;
228
- } else {
229
- textarea.value += '\n' + snippet;
230
- }
231
- textarea.focus();
232
- }
233
-
234
- function filterCtxCategory(category) {
235
- const buttons = document.querySelectorAll('.ctx-cat-btn');
236
- buttons.forEach(btn => {
237
- const isTarget = btn.getAttribute('data-cat') === category;
238
- if (isTarget) {
239
- btn.classList.add('active');
240
- btn.style.background = 'var(--accent-primary)';
241
- btn.style.color = '#fff';
242
- } else {
243
- btn.classList.remove('active');
244
- btn.style.background = 'var(--bg-card)';
245
- btn.style.color = 'var(--text-muted)';
246
- }
247
- });
248
-
249
- const items = document.querySelectorAll('.ctx-item');
250
- items.forEach(item => {
251
- const cat = item.getAttribute('data-cat');
252
- item.style.display = (category === 'all' || cat === category) ? 'flex' : 'none';
253
- });
254
- }
255
-
256
- function filterCtxSearch(query) {
257
- const q = (query || '').toLowerCase().trim();
258
- const items = document.querySelectorAll('.ctx-item');
259
- items.forEach(item => {
260
- const text = item.textContent.toLowerCase();
261
- item.style.display = (!q || text.includes(q)) ? 'flex' : 'none';
262
- });
263
- }
264
-
265
- function applyStarterRecipe(key) {
266
- if (!key || !STARTER_RECIPES[key]) return;
267
- if (functionsState.cmEditor) {
268
- functionsState.cmEditor.setValue(STARTER_RECIPES[key]);
269
- functionsState.cmEditor.save();
270
- functionsState.cmEditor.focus();
271
- return;
272
- }
273
- const area = document.getElementById('fn-editor-code');
274
- if (area) {
275
- area.value = STARTER_RECIPES[key];
276
- area.focus();
277
- }
278
- }
279
-
280
- function toggleWorkbenchCtxRef(forceState) {
281
- if (typeof forceState === 'boolean') {
282
- functionsState.isCtxRefExpanded = forceState;
283
- } else {
284
- functionsState.isCtxRefExpanded = !functionsState.isCtxRefExpanded;
285
- }
286
-
287
- const header = document.getElementById('workbench-ctx-header');
288
- const content = document.getElementById('workbench-ctx-content');
289
- const btn = document.getElementById('btn-toggle-workbench-ctx');
290
- const toolbarBtn = document.getElementById('btn-toolbar-toggle-ctx');
291
-
292
- if (header) {
293
- header.style.borderBottom = functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none';
294
- }
295
- if (content) {
296
- content.style.display = functionsState.isCtxRefExpanded ? 'flex' : 'none';
297
- }
298
- if (btn) {
299
- btn.textContent = functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾';
300
- }
301
- if (toolbarBtn) {
302
- toolbarBtn.style.background = functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)';
303
- toolbarBtn.style.color = functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)';
304
- }
305
- }
306
-
307
- // ==========================================
308
- // 2. CodeMirror Integration & Themes
309
- // ==========================================
310
-
311
- function getCodeMirrorTheme() {
312
- if (typeof ThemeManager !== 'undefined' && typeof ThemeManager.getEffectiveTheme === 'function') {
313
- return ThemeManager.getEffectiveTheme() === 'light' ? 'eclipse' : 'dracula';
314
- }
315
- if (typeof document !== 'undefined' && document.documentElement) {
316
- return document.documentElement.classList.contains('light') ? 'eclipse' : 'dracula';
317
- }
318
- return 'dracula';
319
- }
320
-
321
- function initFunctionCodeMirror() {
322
- if (typeof CodeMirror === 'undefined') return;
323
- const codeArea = document.getElementById('fn-editor-code');
324
- if (!codeArea) return;
325
-
326
- if (functionsState.cmEditor) {
327
- try {
328
- functionsState.cmEditor.toTextArea();
329
- } catch (_) {}
330
- functionsState.cmEditor = null;
331
- }
332
-
333
- try {
334
- functionsState.cmEditor = CodeMirror.fromTextArea(codeArea, {
335
- mode: { name: 'javascript', typescript: true },
336
- theme: getCodeMirrorTheme(),
337
- lineNumbers: true,
338
- matchBrackets: true,
339
- autoCloseBrackets: true,
340
- tabSize: 2,
341
- indentWithTabs: false,
342
- lineWrapping: true,
343
- extraKeys: {
344
- 'Tab': function(cm) {
345
- cm.replaceSelection(' ');
346
- },
347
- 'Ctrl-S': function() {
348
- saveFunctionEditor();
349
- },
350
- 'Cmd-S': function() {
351
- saveFunctionEditor();
352
- }
353
- }
354
- });
355
-
356
- functionsState.cmEditor.on('change', () => {
357
- functionsState.cmEditor.save();
358
- });
359
-
360
- setTimeout(() => {
361
- functionsState.cmEditor?.refresh();
362
- }, 50);
363
- } catch (err) {
364
- console.warn('CodeMirror initialization skipped or failed:', err);
365
- }
366
- }
367
-
368
- if (typeof window !== 'undefined') {
369
- window.addEventListener('nodestack-theme-changed', (e) => {
370
- if (functionsState.cmEditor) {
371
- const isLight = (e.detail && e.detail.effective === 'light') || getCodeMirrorTheme() === 'eclipse';
372
- functionsState.cmEditor.setOption('theme', isLight ? 'eclipse' : 'dracula');
373
- }
374
- });
375
- }
376
-
377
- // ==========================================
378
- // 3. Workbench Routing & Navigation
379
- // ==========================================
380
-
381
- function openCreateFunctionPage() {
382
- openFunctionEditor('new', true, 'code');
383
- }
384
-
385
- async function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
386
- let fn;
387
-
388
- if (idOrName === 'new' || !idOrName) {
389
- fn = {
390
- isNew: true,
391
- id: '',
392
- name: '',
393
- description: '',
394
- code: STARTER_RECIPES.starter,
395
- enabled: true,
396
- authPolicy: 'public',
397
- methods: ['GET', 'POST'],
398
- eventTrigger: '',
399
- timeoutMs: 1000,
400
- memoryLimitMb: 32,
401
- allowedDomains: [],
402
- elevated: false,
403
- env: {},
404
- };
405
- } else {
406
- fn = (functionsState.functions || []).find(f => f.id === idOrName || f.name === idOrName);
407
-
408
- if (!fn) {
409
- try {
410
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
411
- const endpoint = slug && slug !== 'default'
412
- ? `/api/apps/${slug}/functions/${encodeURIComponent(idOrName)}`
413
- : `/api/functions/${encodeURIComponent(idOrName)}`;
414
- fn = await api(endpoint);
415
- } catch (_) {}
416
- }
417
-
418
- if (!fn) {
419
- toast(`Function '${idOrName}' not found`, 'error');
420
- if (typeof selectNav === 'function') selectNav('functions', false);
421
- return;
422
- }
423
- }
424
-
425
- functionsState.currentView = 'editor';
426
- functionsState.activeFunctionForEdit = fn;
427
- functionsState.editorTab = initialTab || 'code';
428
-
429
- if (pushState && typeof updateUrl === 'function') {
430
- updateUrl(fn.isNew ? '/_/functions/new' : '/_/functions/' + encodeURIComponent(fn.name || fn.id));
431
- }
432
-
433
- if (typeof updateBreadcrumbs === 'function') {
434
- updateBreadcrumbs();
435
- }
436
-
437
- renderFunctionEditorView(fn);
438
- }
439
-
440
- function closeFunctionEditor(pushState = true) {
441
- if (functionsState.cmEditor) {
442
- try {
443
- functionsState.cmEditor.toTextArea();
444
- } catch (_) {}
445
- functionsState.cmEditor = null;
446
- }
447
- functionsState.currentView = 'list';
448
- functionsState.activeFunctionForEdit = null;
449
-
450
- if (pushState && typeof updateUrl === 'function') {
451
- updateUrl('/_/functions');
452
- }
453
-
454
- if (typeof updateBreadcrumbs === 'function') {
455
- updateBreadcrumbs();
456
- }
457
-
458
- if (typeof renderFunctionsView === 'function') {
459
- renderFunctionsView();
460
- }
461
- }
462
-
463
- function switchFunctionEditorTab(tab) {
464
- functionsState.editorTab = tab;
465
- ['code', 'test', 'config', 'logs'].forEach(t => {
466
- const btn = document.getElementById('editor-tab-btn-' + t);
467
- const pane = document.getElementById('fn-editor-pane-' + t);
468
- if (btn) btn.classList.toggle('active', t === tab);
469
- if (pane) {
470
- if (t === 'code') {
471
- pane.style.display = (t === tab) ? 'flex' : 'none';
472
- if (t === tab && functionsState.cmEditor) {
473
- setTimeout(() => { functionsState.cmEditor?.refresh(); }, 20);
474
- }
475
- } else if (t === 'test' || t === 'config') {
476
- pane.style.display = (t === tab) ? 'grid' : 'none';
477
- } else if (t === 'logs') {
478
- pane.style.display = (t === tab) ? 'flex' : 'none';
479
- }
480
- }
481
- });
482
-
483
- if (tab === 'logs' && typeof loadFunctionEditorLogs === 'function') {
484
- loadFunctionEditorLogs();
485
- }
486
- }
487
-
488
- function syncEditorFunctionName(val) {
489
- const clean = (val || '').toLowerCase().replace(/[^a-z0-9_-]/g, '');
490
- const headerInput = document.getElementById('fn-editor-name-header');
491
- const configInput = document.getElementById('fn-editor-name');
492
- if (headerInput && headerInput.value !== clean) headerInput.value = clean;
493
- if (configInput && configInput.value !== clean) configInput.value = clean;
494
- if (functionsState.activeFunctionForEdit) {
495
- functionsState.activeFunctionForEdit.name = clean;
496
- }
497
- const preview = document.getElementById('fn-editor-endpoint-preview');
498
- if (preview) {
499
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
500
- const prefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
501
- preview.textContent = `ANY ${prefix}/${clean || '{name}'}/invoke`;
502
- }
503
- }
504
-
505
- function copyFunctionEndpoint(path) {
506
- const fullUrl = window.location.origin + path;
507
- if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
508
- navigator.clipboard.writeText(fullUrl).then(() => {
509
- toast('Copied function endpoint URL to clipboard', 'info');
510
- }).catch(() => {
511
- prompt('Copy function endpoint URL:', fullUrl);
512
- });
513
- } else {
514
- prompt('Copy function endpoint URL:', fullUrl);
515
- }
516
- }
517
-
518
- function updateEditorHeaderBadges(fn) {
519
- const container = document.getElementById('editor-header-badges');
520
- if (!container) return;
521
- container.innerHTML = `
522
- <span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
523
- ${fn.enabled !== false ? '● Active' : '○ Disabled'}
524
- </span>
525
- <span class="badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
526
- ${escapeHtml((fn.authPolicy || 'public').toUpperCase())}
527
- </span>
528
- ${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
529
- `;
530
- }
531
-
532
- // ==========================================
533
- // 4. Workbench Sub-Renderers & Main Assembler
534
- // ==========================================
535
-
536
- function renderWorkbenchHeader(fn, isNew, invokePath) {
537
- return `
538
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; border-bottom: 1px solid var(--border-subtle); padding-bottom: 1rem;">
539
- <div style="display: flex; align-items: center; gap: 14px;">
540
- <button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Back to functions list" style="display: flex; align-items: center; gap: 6px;">
541
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
542
- <span>Functions</span>
543
- </button>
544
- <div>
545
- ${isNew ? `
546
- <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
547
- <input type="text" id="fn-editor-name-header" class="input" placeholder="function-name" value="${escapeHtml(fn.name || '')}" oninput="syncEditorFunctionName(this.value)" style="font-family: monospace; font-size: 1.15rem; font-weight: 700; width: 250px; padding: 4px 10px;" title="Function Name (Slug)">
548
- <span class="badge" style="background: rgba(99, 102, 241, 0.15); color: #6366f1; font-weight: 600;">✨ New Function</span>
549
- </div>
550
- <div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
551
- <span>Endpoint: <code id="fn-editor-endpoint-preview" style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
552
- <span>Default limits: 1000ms / 32MB</span>
553
- </div>
554
- ` : `
555
- <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
556
- <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0; font-family: monospace; display: flex; align-items: center; gap: 8px;">
557
- ${escapeHtml(fn.name)}
558
- </h2>
559
- <div id="editor-header-badges" style="display: inline-flex; align-items: center; gap: 6px;">
560
- <span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
561
- ${fn.enabled !== false ? '● Active' : '○ Disabled'}
562
- </span>
563
- <span class="badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
564
- ${escapeHtml((fn.authPolicy || 'public').toUpperCase())}
565
- </span>
566
- ${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
567
- </div>
568
- </div>
569
- <div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
570
- <span>Endpoint: <code style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
571
- <button type="button" class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="font-size: 10px; padding: 1px 6px;" title="Copy full invoke endpoint">
572
- 📋 Copy URL
573
- </button>
574
- ${fn.eventTrigger ? `<span style="color: var(--accent-primary);">⚡ Hook: <code>${escapeHtml(fn.eventTrigger)}</code></span>` : ''}
575
- <span>Limits: ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB</span>
576
- </div>
577
- `}
578
- </div>
579
- </div>
580
-
581
- <div style="display: flex; align-items: center; gap: 8px;">
582
- ${!isNew ? `
583
- <button class="btn btn-secondary btn-sm" onclick="switchFunctionEditorTab('test')" style="display: flex; align-items: center; gap: 6px;">
584
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
585
- <span>Run Test</span>
586
- </button>
587
- <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">
588
- Delete
589
- </button>
590
- ` : `
591
- <button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Cancel and return to list">
592
- Cancel
593
- </button>
594
- `}
595
- <button class="btn btn-primary btn-sm" id="btn-editor-save" onclick="saveFunctionEditor()" style="display: flex; align-items: center; gap: 6px; font-weight: 600;">
596
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
597
- <span>${isNew ? 'Create Function' : 'Save Changes'}</span>
598
- </button>
599
- </div>
600
- </div>
601
- `;
602
- }
603
-
604
- function renderWorkbenchTabs(activeTab) {
605
- return `
606
- <div style="display: flex; align-items: center; gap: 8px; border-bottom: 1px solid var(--border-subtle); padding-bottom: 8px;">
607
- <button class="webhook-tab-btn ${activeTab === 'code' ? 'active' : ''}" id="editor-tab-btn-code" onclick="switchFunctionEditorTab('code')">
608
- <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>
609
- Code & Context Reference
610
- </button>
611
- <button class="webhook-tab-btn ${activeTab === 'test' ? 'active' : ''}" id="editor-tab-btn-test" onclick="switchFunctionEditorTab('test')">
612
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
613
- Live Test Runner
614
- </button>
615
- <button class="webhook-tab-btn ${activeTab === 'config' ? 'active' : ''}" id="editor-tab-btn-config" onclick="switchFunctionEditorTab('config')">
616
- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
617
- Configuration & Triggers
618
- </button>
619
- <button class="webhook-tab-btn ${activeTab === 'logs' ? 'active' : ''}" id="editor-tab-btn-logs" onclick="switchFunctionEditorTab('logs')">
620
- <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>
621
- Function Logs & History
622
- </button>
623
- </div>
624
- `;
625
- }
626
-
627
- function renderWorkbenchCodePane(fn) {
628
- return `
629
- <div id="fn-editor-pane-code" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'code' ? 'flex' : 'none'}; flex-direction: column; gap: 1rem; width: 100%;">
630
- <div class="card" style="padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem;">
631
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
632
- <div style="display: flex; align-items: center; gap: 8px;">
633
- <span style="font-weight: 600; font-size: 13px; color: var(--text-heading);">Function Handler Source</span>
634
- <span style="font-size: 11px; color: var(--text-muted); font-family: monospace;">export default async function(core, context) { ... }</span>
635
- </div>
636
- <div style="display: flex; align-items: center; gap: 8px;">
637
- <button type="button" class="btn btn-secondary btn-sm" id="btn-toolbar-toggle-ctx" onclick="toggleWorkbenchCtxRef()" style="font-size: 11px; display: flex; align-items: center; gap: 6px; padding: 3px 9px; background: ${functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)'}; color: ${functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)'};" title="Toggle Context Reference Panel">
638
- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
639
- <span>API Reference (core, context)</span>
640
- </button>
641
- <span style="font-size: 11px; color: var(--text-muted);">Templates:</span>
642
- <select class="input" style="font-size: 11px; padding: 2px 8px;" onchange="applyStarterRecipe(this.value)">
643
- <option value="">Apply Recipe...</option>
644
- <option value="starter">Basic Hello World</option>
645
- <option value="discount">Cart Discount Calculation</option>
646
- <option value="hook">Validation & Mutation Hook</option>
647
- <option value="fetch">External API Fetch</option>
648
- </select>
649
- <span style="font-size: 10px; color: var(--text-muted); background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px;">Ctrl+S to save</span>
650
- </div>
651
- </div>
652
-
653
- <textarea id="fn-editor-code" style="width: 100%; min-height: 520px; height: calc(100vh - 290px); font-family: 'JetBrains Mono', Consolas, Monaco, monospace; font-size: 13px; line-height: 1.5; padding: 14px; border-radius: 8px; border: 1px solid var(--border-subtle); background: #0f172a; color: #f8fafc; resize: vertical;" spellcheck="false">${escapeHtml(fn.code)}</textarea>
654
-
655
- <!-- Vertical Collapsible Context API Reference (Collapsed by default) -->
656
- <div class="ctx-reference-panel" style="border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--bg-input); overflow: hidden; margin-top: 4px;">
657
- <div id="workbench-ctx-header" onclick="toggleWorkbenchCtxRef()" style="display: flex; align-items: center; justify-content: space-between; padding: 9px 14px; background: var(--bg-card); cursor: pointer; user-select: none; border-bottom: ${functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none'}; font-size: 12px;">
658
- <div style="display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text-heading);">
659
- <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--accent-primary);"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
660
- <span>Platform Reference (<code>core, context</code>)</span>
661
- <span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">— 1-click snippet insert for SDK, queue, request, events & network</span>
662
- </div>
663
- <div style="display: flex; align-items: center; gap: 8px;">
664
- <span class="badge" style="background: var(--bg-card-hover); color: var(--text-muted); font-size: 10px;">22 items</span>
665
- <button type="button" class="btn btn-secondary btn-sm" id="btn-toggle-workbench-ctx" onclick="event.stopPropagation(); toggleWorkbenchCtxRef();" style="font-size: 11px; padding: 2px 9px;">
666
- ${functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾'}
667
- </button>
668
- </div>
669
- </div>
670
-
671
- <div id="workbench-ctx-content" style="display: ${functionsState.isCtxRefExpanded ? 'flex' : 'none'}; flex-direction: column; gap: 10px; padding: 12px 14px; background: var(--bg-card);">
672
- <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
673
- <div style="display: flex; align-items: center; gap: 5px; flex-wrap: wrap;">
674
- <button type="button" class="ctx-cat-btn active" data-cat="all" onclick="filterCtxCategory('all')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--accent-primary); color: #fff; cursor: pointer; font-weight: 500;">All (22)</button>
675
- <button type="button" class="ctx-cat-btn" data-cat="request" onclick="filterCtxCategory('request')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">HTTP (context.request)</button>
676
- <button type="button" class="ctx-cat-btn" data-cat="event" onclick="filterCtxCategory('event')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">DB Events (context.event)</button>
677
- <button type="button" class="ctx-cat-btn" data-cat="records" onclick="filterCtxCategory('records')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Collections (core.sdk)</button>
678
- <button type="button" class="ctx-cat-btn" data-cat="queue" onclick="filterCtxCategory('queue')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Queues (core.sdk)</button>
679
- <button type="button" class="ctx-cat-btn" data-cat="utils" onclick="filterCtxCategory('utils')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Network & Obs</button>
680
- </div>
681
- <div style="flex: 1; max-width: 260px; min-width: 180px;">
682
- <input type="text" id="ctx-search-input" class="input" placeholder="Search core & context APIs..." oninput="filterCtxSearch(this.value)" style="width: 100%; font-size: 11px; padding: 4px 8px;">
683
- </div>
684
- </div>
685
-
686
- <div id="ctx-items-container" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 8px; max-height: 240px; overflow-y: auto; padding-right: 4px;">
687
- ${renderCtxItemsHtml()}
688
- </div>
689
- </div>
690
- </div>
691
- </div>
692
- </div>
693
- `;
694
- }
695
-
696
- function renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString) {
697
- return `
698
- <div id="fn-editor-pane-config" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'config' ? 'grid' : 'none'}; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: start;">
699
- <!-- Column 1: General & Triggers -->
700
- <div style="display: flex; flex-direction: column; gap: 1rem;">
701
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
702
- <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
703
- General Settings
704
- </div>
705
- <div>
706
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Function Identifier (Name)</label>
707
- <input type="text" id="fn-editor-name" class="input" value="${escapeHtml(fn.name || '')}" ${isNew ? 'placeholder="e.g. calculate-discount" oninput="syncEditorFunctionName(this.value)"' : 'readonly'} style="width: 100%; font-family: monospace; ${!isNew ? 'background: var(--bg-input); opacity: 0.85;' : ''}">
708
- <span style="font-size: 11px; color: var(--text-muted); margin-top: 2px; display: block;">Immutable endpoint slug for API invocation routes. Alphanumeric characters, underscores, and dashes only.</span>
709
- </div>
710
- <div>
711
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Description</label>
712
- <input type="text" id="fn-editor-desc" class="input" value="${escapeHtml(fn.description || '')}" placeholder="What does this function do?" style="width: 100%;">
713
- </div>
714
- <div style="display: flex; align-items: center; gap: 10px; padding: 10px; background: var(--bg-card-hover); border-radius: 6px;">
715
- <input type="checkbox" id="fn-editor-enabled" ${fn.enabled !== false ? 'checked' : ''} style="cursor: pointer;">
716
- <div>
717
- <label for="fn-editor-enabled" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--text-main);">Function Enabled</label>
718
- <div style="font-size: 11px; color: var(--text-muted);">When disabled, API calls return 503 Service Unavailable and lifecycle hooks skip execution.</div>
719
- </div>
720
- </div>
721
- </div>
722
-
723
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
724
- <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
725
- Triggers & Invocation
726
- </div>
727
- <div>
728
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Allowed HTTP Methods</label>
729
- <div style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;" id="fn-editor-methods-group">
730
- ${['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map(m => `
731
- <label style="display: flex; align-items: center; gap: 4px; font-size: 12px; cursor: pointer;">
732
- <input type="checkbox" class="fn-editor-method-cb" value="${m}" ${(fn.methods || ['GET', 'POST']).includes(m) ? 'checked' : ''} style="cursor: pointer;">
733
- <span>${m}</span>
734
- </label>
735
- `).join('')}
736
- </div>
737
- <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">Allowed HTTP methods for external API invocation routes.</span>
738
- </div>
739
- <div>
740
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Database Lifecycle Hook Trigger</label>
741
- <input type="text" id="fn-editor-hook" class="input" value="${escapeHtml(fn.eventTrigger || '')}" placeholder="e.g. orders:beforeCreate or articles:afterUpdate" style="width: 100%; font-size: 12px; font-family: monospace;">
742
- <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
743
- Format: <code>&lt;collection&gt;:&lt;phase&gt;&lt;Action&gt;</code>. Available phases: <code>beforeCreate</code>, <code>afterCreate</code>, <code>beforeUpdate</code>, <code>afterUpdate</code>, <code>beforeDelete</code>, <code>afterDelete</code>.
744
- </span>
745
- </div>
746
- </div>
747
- </div>
748
-
749
- <!-- Column 2: Runtime Limits, Auth & Secrets -->
750
- <div style="display: flex; flex-direction: column; gap: 1rem;">
751
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
752
- <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
753
- Security & Guardrails
754
- </div>
755
- <div>
756
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Authorization Policy</label>
757
- <select id="fn-editor-auth" class="input" style="width: 100%;">
758
- <option value="public" ${fn.authPolicy === 'public' ? 'selected' : ''}>Public (No Token Required)</option>
759
- <option value="auth" ${fn.authPolicy === 'auth' ? 'selected' : ''}>User Token (Requires Bearer JWT)</option>
760
- <option value="admin" ${fn.authPolicy === 'admin' ? 'selected' : ''}>Admin Only (Requires Admin Token)</option>
761
- <option value="apiKey" ${fn.authPolicy === 'apiKey' ? 'selected' : ''}>API Key (Requires nsk_live_...)</option>
762
- </select>
763
- </div>
764
-
765
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
766
- <div>
767
- <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Timeout (ms)</label>
768
- <input type="number" id="fn-editor-timeout" class="input" value="${fn.timeoutMs || 1000}" min="100" max="15000" style="width: 100%; font-size: 12px;">
769
- </div>
770
- <div>
771
- <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Memory Cap (MB)</label>
772
- <input type="number" id="fn-editor-memory" class="input" value="${fn.memoryLimitMb || 32}" min="4" max="128" style="width: 100%; font-size: 12px;">
773
- </div>
774
- </div>
775
-
776
- <div>
777
- <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Outbound Egress Whitelist (SSRF Protection)</label>
778
- <input type="text" id="fn-editor-domains" class="input" value="${escapeHtml(allowedDomainsString)}" placeholder="e.g. api.stripe.com, *.resend.com (Leave blank for all public domains)" style="width: 100%; font-size: 12px;">
779
- </div>
780
-
781
- <div style="display: flex; align-items: center; gap: 8px; padding: 10px; background: rgba(239, 68, 68, 0.08); border-radius: 6px; border: 1px solid rgba(239, 68, 68, 0.2);">
782
- <input type="checkbox" id="fn-editor-elevated" ${fn.elevated ? 'checked' : ''} style="cursor: pointer;">
783
- <div>
784
- <label for="fn-editor-elevated" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--accent-danger);">
785
- Elevated Service Role
786
- </label>
787
- <div style="font-size: 11px; color: var(--text-muted);">Bypasses collection RuleEngine access rules. Allows reading and mutating records as superuser.</div>
788
- </div>
789
- </div>
790
- </div>
791
-
792
- <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 0.75rem;">
793
- <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px; display: flex; align-items: center; justify-content: space-between;">
794
- <span>Environment Secrets (<code>context.env</code>)</span>
795
- <span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">JSON Object</span>
796
- </div>
797
- <textarea id="fn-editor-env" style="width: 100%; height: 95px; font-family: monospace; font-size: 12px; padding: 8px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-card-hover); color: var(--text-main);" placeholder='{ "STRIPE_SECRET": "sk_test_..." }'>${escapeHtml(envString)}</textarea>
798
- <span style="font-size: 11px; color: var(--text-muted);">Encrypted in database and injected at runtime into <code>context.env</code>. Isolated from system <code>process.env</code>.</span>
799
- </div>
800
- </div>
801
- </div>
802
- `;
803
- }
804
-
805
- function renderFunctionEditorView(fn) {
806
- const container = document.getElementById('page-view-functions') || document.getElementById('main-body');
807
- if (!container) return;
808
-
809
- const isNew = !!fn.isNew;
810
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
811
- const invokePrefix = slug && slug !== 'default'
812
- ? `/api/apps/${slug}/functions`
813
- : `/api/functions`;
814
- const invokePath = `${invokePrefix}/${fn.name || '{name}'}/invoke`;
815
-
816
- const envString = fn.env && Object.keys(fn.env).length > 0
817
- ? JSON.stringify(fn.env, null, 2)
818
- : '{}';
819
-
820
- const allowedDomainsString = (fn.allowedDomains || []).join(', ');
821
-
822
- const testPaneHtml = typeof renderWorkbenchTestPane === 'function'
823
- ? renderWorkbenchTestPane(fn, isNew)
824
- : '';
825
-
826
- const logsPaneHtml = typeof renderWorkbenchLogsPane === 'function'
827
- ? renderWorkbenchLogsPane(fn, isNew)
828
- : '';
829
-
830
- container.innerHTML = `
831
- <div class="function-editor-page" style="max-width: 1440px; margin: 0 auto; padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1rem;">
832
- ${renderWorkbenchHeader(fn, isNew, invokePath)}
833
- ${renderWorkbenchTabs(functionsState.editorTab)}
834
- ${renderWorkbenchCodePane(fn)}
835
- ${testPaneHtml}
836
- ${renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString)}
837
- ${logsPaneHtml}
838
- </div>
839
- `;
840
-
841
- // Attach keyboard shortcut for saving and tab indentation
842
- const codeArea = document.getElementById('fn-editor-code');
843
- if (codeArea) {
844
- codeArea.addEventListener('keydown', (e) => {
845
- if (e.key === 'Tab') {
846
- e.preventDefault();
847
- const start = codeArea.selectionStart;
848
- const end = codeArea.selectionEnd;
849
- codeArea.value = codeArea.value.substring(0, start) + ' ' + codeArea.value.substring(end);
850
- codeArea.selectionStart = codeArea.selectionEnd = start + 2;
851
- }
852
- if ((e.ctrlKey || e.metaKey) && e.key === 's') {
853
- e.preventDefault();
854
- saveFunctionEditor();
855
- }
856
- });
857
- }
858
-
859
- // Global Ctrl+S handler while on workbench view
860
- window.onkeydown = (e) => {
861
- if ((e.ctrlKey || e.metaKey) && e.key === 's' && functionsState.currentView === 'editor') {
862
- e.preventDefault();
863
- saveFunctionEditor();
864
- }
865
- };
866
-
867
- // Initialize CodeMirror editor
868
- initFunctionCodeMirror();
869
-
870
- // If logs tab is active on existing function, load logs
871
- if (functionsState.editorTab === 'logs' && !isNew && typeof loadFunctionEditorLogs === 'function') {
872
- loadFunctionEditorLogs();
873
- }
874
- }
875
-
876
- // ==========================================
877
- // 5. Persistence Handlers
878
- // ==========================================
879
-
880
- async function saveFunctionEditor() {
881
- const btn = document.getElementById('btn-editor-save');
882
- const fn = functionsState.activeFunctionForEdit;
883
- if (!fn) return;
884
-
885
- const isNew = !!fn.isNew;
886
-
887
- if (btn) {
888
- btn.disabled = true;
889
- btn.textContent = isNew ? 'Creating...' : 'Saving...';
890
- }
891
-
892
- try {
893
- if (functionsState.cmEditor) {
894
- functionsState.cmEditor.save();
895
- }
896
- const codeEl = document.getElementById('fn-editor-code');
897
- const descEl = document.getElementById('fn-editor-desc');
898
- const authEl = document.getElementById('fn-editor-auth');
899
- const hookEl = document.getElementById('fn-editor-hook');
900
- const timeoutEl = document.getElementById('fn-editor-timeout');
901
- const memoryEl = document.getElementById('fn-editor-memory');
902
- const domainsEl = document.getElementById('fn-editor-domains');
903
- const elevatedEl = document.getElementById('fn-editor-elevated');
904
- const enabledEl = document.getElementById('fn-editor-enabled');
905
- const envEl = document.getElementById('fn-editor-env');
906
-
907
- const nameHeaderEl = document.getElementById('fn-editor-name-header');
908
- const nameConfigEl = document.getElementById('fn-editor-name');
909
- let name = (nameHeaderEl ? nameHeaderEl.value.trim() : (nameConfigEl ? nameConfigEl.value.trim() : (fn.name || ''))).toLowerCase();
910
-
911
- if (isNew) {
912
- if (!name) {
913
- throw new Error('Please enter a function identifier (name)');
914
- }
915
- if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
916
- throw new Error('Function name must contain only alphanumeric characters, underscores, and dashes');
917
- }
918
- }
919
-
920
- const code = codeEl ? codeEl.value : fn.code;
921
- const description = descEl ? descEl.value.trim() : (fn.description || '');
922
- const authPolicy = authEl ? authEl.value : (fn.authPolicy || 'public');
923
- const eventTrigger = hookEl ? hookEl.value.trim() : (fn.eventTrigger || '');
924
- const timeoutMs = timeoutEl ? (parseInt(timeoutEl.value, 10) || 1000) : fn.timeoutMs;
925
- const memoryLimitMb = memoryEl ? (parseInt(memoryEl.value, 10) || 32) : fn.memoryLimitMb;
926
- const domainsRaw = domainsEl ? domainsEl.value.trim() : '';
927
- const allowedDomains = domainsRaw ? domainsRaw.split(',').map(s => s.trim()).filter(Boolean) : (fn.allowedDomains || []);
928
- const elevated = elevatedEl ? elevatedEl.checked : !!fn.elevated;
929
- const enabled = enabledEl ? enabledEl.checked : (fn.enabled !== false);
930
-
931
- let env = fn.env || {};
932
- if (envEl && envEl.value.trim()) {
933
- try {
934
- env = JSON.parse(envEl.value.trim());
935
- } catch {
936
- throw new Error('Environment secrets must be valid JSON');
937
- }
938
- }
939
-
940
- const methodCbs = document.querySelectorAll('.fn-editor-method-cb:checked');
941
- const methods = methodCbs.length > 0
942
- ? Array.from(methodCbs).map(cb => cb.value)
943
- : (fn.methods || ['GET', 'POST']);
944
-
945
- const payload = {
946
- description,
947
- authPolicy,
948
- methods,
949
- eventTrigger: eventTrigger || null,
950
- timeoutMs,
951
- memoryLimitMb,
952
- allowedDomains,
953
- elevated,
954
- enabled,
955
- code,
956
- env,
957
- };
958
-
959
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
960
- const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
961
-
962
- if (isNew) {
963
- const createPayload = {
964
- name,
965
- methods: fn.methods || ['GET', 'POST'],
966
- ...payload,
967
- };
968
-
969
- const created = await api(baseUrl, {
970
- method: 'POST',
971
- headers: { 'Content-Type': 'application/json' },
972
- body: JSON.stringify(createPayload),
973
- });
974
-
975
- functionsState.activeFunctionForEdit = created;
976
- if (!Array.isArray(functionsState.functions)) {
977
- functionsState.functions = [];
978
- }
979
- const existingIdx = functionsState.functions.findIndex(f => f.id === created.id);
980
- if (existingIdx !== -1) {
981
- functionsState.functions[existingIdx] = created;
982
- } else {
983
- functionsState.functions.unshift(created);
984
- }
985
-
986
- toast(`Function '${created.name}' created successfully`, 'success');
987
- if (typeof updateUrl === 'function') {
988
- updateUrl('/_/functions/' + encodeURIComponent(created.name));
989
- }
990
- if (typeof updateBreadcrumbs === 'function') {
991
- updateBreadcrumbs();
992
- }
993
- renderFunctionEditorView(created);
994
- if (typeof loadFunctionStats === 'function') {
995
- await loadFunctionStats();
996
- }
997
- } else {
998
- const updated = await api(`${baseUrl}/${fn.id}`, {
999
- method: 'PATCH',
1000
- headers: { 'Content-Type': 'application/json' },
1001
- body: JSON.stringify(payload),
1002
- });
1003
-
1004
- functionsState.activeFunctionForEdit = updated;
1005
- const idx = (functionsState.functions || []).findIndex(f => f.id === fn.id);
1006
- if (idx !== -1) {
1007
- functionsState.functions[idx] = updated;
1008
- }
1009
-
1010
- updateEditorHeaderBadges(updated);
1011
- toast(`Function '${updated.name}' saved successfully`, 'success');
1012
- if (typeof loadFunctionStats === 'function') {
1013
- await loadFunctionStats();
1014
- }
1015
- }
1016
- } catch (err) {
1017
- toast(err.message || 'Failed to save function', 'error');
1018
- } finally {
1019
- if (btn) {
1020
- btn.disabled = false;
1021
- const active = functionsState.activeFunctionForEdit;
1022
- const stillNew = active && active.isNew;
1023
- btn.innerHTML = stillNew
1024
- ? `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Create Function</span>`
1025
- : `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Save Changes</span>`;
1026
- }
1027
- }
1028
- }
1029
-
1030
- // ==========================================
1031
- // 6. Backward Compatibility Shims
1032
- // ==========================================
1033
-
1034
- function openCreateFunctionModal() {
1035
- openCreateFunctionPage();
1036
- }
1037
-
1038
- function openEditFunctionModal(id) {
1039
- openFunctionEditor(id);
1040
- }
1041
-
1042
- function openTestFunctionModal(id) {
1043
- openFunctionEditor(id, true, 'test');
1044
- }
1045
-
1046
- function renderFunctionModal(fnData) {
1047
- openFunctionEditor(fnData?.isNew ? 'new' : (fnData?.id || fnData?.name || 'new'));
1048
- }
1049
-
1050
- function closeFunctionModal() {
1051
- const modalRoot = document.getElementById('modal-root');
1052
- if (modalRoot) modalRoot.innerHTML = '';
1053
- }
1054
-
1055
- async function saveFunctionModal() {
1056
- return saveFunctionEditor();
1057
- }
1058
-
1059
- async function executeFunctionLiveTest() {
1060
- if (typeof executeFunctionEditorTest === 'function') {
1061
- return executeFunctionEditorTest();
1062
- }
1063
- }
1064
-
1065
- function toggleCtxReference() {
1066
- toggleWorkbenchCtxRef();
1067
- }
1068
-
1069
- // Global Exports
1070
- if (typeof window !== 'undefined') {
1071
- window.CTX_DOCS = CTX_DOCS;
1072
- window.renderCtxItemsHtml = renderCtxItemsHtml;
1073
- window.insertFunctionSnippet = insertFunctionSnippet;
1074
- window.filterCtxCategory = filterCtxCategory;
1075
- window.filterCtxSearch = filterCtxSearch;
1076
- window.applyStarterRecipe = applyStarterRecipe;
1077
- window.toggleWorkbenchCtxRef = toggleWorkbenchCtxRef;
1078
- window.toggleCtxReference = toggleCtxReference;
1079
- window.getCodeMirrorTheme = getCodeMirrorTheme;
1080
- window.initFunctionCodeMirror = initFunctionCodeMirror;
1081
- window.openCreateFunctionPage = openCreateFunctionPage;
1082
- window.openFunctionEditor = openFunctionEditor;
1083
- window.closeFunctionEditor = closeFunctionEditor;
1084
- window.switchFunctionEditorTab = switchFunctionEditorTab;
1085
- window.syncEditorFunctionName = syncEditorFunctionName;
1086
- window.copyFunctionEndpoint = copyFunctionEndpoint;
1087
- window.updateEditorHeaderBadges = updateEditorHeaderBadges;
1088
- window.renderWorkbenchHeader = renderWorkbenchHeader;
1089
- window.renderWorkbenchTabs = renderWorkbenchTabs;
1090
- window.renderWorkbenchCodePane = renderWorkbenchCodePane;
1091
- window.renderWorkbenchConfigPane = renderWorkbenchConfigPane;
1092
- window.renderFunctionEditorView = renderFunctionEditorView;
1093
- window.saveFunctionEditor = saveFunctionEditor;
1094
- window.openCreateFunctionModal = openCreateFunctionModal;
1095
- window.openEditFunctionModal = openEditFunctionModal;
1096
- window.openTestFunctionModal = openTestFunctionModal;
1097
- window.renderFunctionModal = renderFunctionModal;
1098
- window.closeFunctionModal = closeFunctionModal;
1099
- window.saveFunctionModal = saveFunctionModal;
1100
- window.executeFunctionLiveTest = executeFunctionLiveTest;
1101
- }
1
+ // Serverless Functions Dedicated Workbench & Code Editor Module
2
+ // Companion module for NodeStack Admin UI Functions
3
+
4
+ // ==========================================
5
+ // 1. Context API (ctx) Documentation & Snippets
6
+ // ==========================================
7
+
8
+ const CTX_DOCS = [
9
+ // HTTP Request (context.request)
10
+ {
11
+ name: 'context.request.body',
12
+ type: 'any',
13
+ cat: 'request',
14
+ desc: 'Parsed JSON payload sent in HTTP POST/PATCH invocation',
15
+ snippet: 'const body = context.request?.body || {};\n'
16
+ },
17
+ {
18
+ name: 'context.request.query',
19
+ type: 'Record<string, any>',
20
+ cat: 'request',
21
+ desc: 'URL query string parameters (e.g. ?limit=10&status=active)',
22
+ snippet: 'const { limit, status } = context.request?.query || {};\n'
23
+ },
24
+ {
25
+ name: 'context.request.auth',
26
+ type: '{ id, role, email } | null',
27
+ cat: 'request',
28
+ desc: 'Authenticated caller identity, or null if public invocation',
29
+ snippet: 'if (!context.request?.auth) return { status: 401, body: { error: "Unauthorized" } };\n'
30
+ },
31
+ {
32
+ name: 'context.request.headers',
33
+ type: 'Record<string, string>',
34
+ cat: 'request',
35
+ desc: 'HTTP request headers map (lowercase header keys)',
36
+ snippet: 'const authHeader = context.request?.headers["authorization"];\n'
37
+ },
38
+ {
39
+ name: 'context.request.method',
40
+ type: "'GET' | 'POST' | 'PATCH' | 'DELETE'",
41
+ cat: 'request',
42
+ desc: 'HTTP method used to invoke this function',
43
+ snippet: 'const method = context.request?.method;\n'
44
+ },
45
+
46
+ // DB Lifecycle Event (context.event)
47
+ {
48
+ name: 'context.event.record',
49
+ type: 'Record<string, any>',
50
+ cat: 'event',
51
+ desc: 'Target database record being mutated during collection lifecycle hook',
52
+ snippet: 'const record = context.event?.record;\n'
53
+ },
54
+ {
55
+ name: 'context.event.collection',
56
+ type: 'string',
57
+ cat: 'event',
58
+ desc: 'Target collection name triggering this lifecycle event',
59
+ snippet: 'const collection = context.event?.collection;\n'
60
+ },
61
+ {
62
+ name: 'context.event.action',
63
+ type: "'create' | 'update' | 'delete'",
64
+ cat: 'event',
65
+ desc: 'Collection mutation action triggering this hook',
66
+ snippet: 'const action = context.event?.action;\n'
67
+ },
68
+ {
69
+ name: 'context.event.isBefore',
70
+ type: 'boolean',
71
+ cat: 'event',
72
+ desc: 'true for before-write hooks (can validate or cancel write), false for after-write',
73
+ snippet: 'if (context.event?.isBefore && !isValid) return { status: 400, body: { cancel: true, reason: "Validation failed" } };\n'
74
+ },
75
+
76
+ // Database CRUD (core.sdk.collection)
77
+ {
78
+ name: 'core.sdk.collection(col).get(id)',
79
+ type: 'Promise<Record>',
80
+ cat: 'records',
81
+ desc: 'Fetch a single record by collection name and record ID',
82
+ snippet: 'const item = await core.sdk.collection("products").get(id);\n'
83
+ },
84
+ {
85
+ name: 'core.sdk.collection(col).list(opts)',
86
+ type: 'Promise<{ items, totalItems }>',
87
+ cat: 'records',
88
+ desc: 'Query records with filter, sort, page, and perPage options',
89
+ snippet: 'const { items, totalItems } = await core.sdk.collection("orders").list({ filter: "status = \'paid\'", perPage: 20 });\n'
90
+ },
91
+ {
92
+ name: 'core.sdk.collection(col).create(data)',
93
+ type: 'Promise<Record>',
94
+ cat: 'records',
95
+ desc: 'Create and insert a new record into target collection',
96
+ snippet: 'const newRec = await core.sdk.collection("audit_events").create({ event: "checkout", timestamp: new Date().toISOString() });\n'
97
+ },
98
+ {
99
+ name: 'core.sdk.collection(col).update(id, data)',
100
+ type: 'Promise<Record>',
101
+ cat: 'records',
102
+ desc: 'Update fields on an existing database record',
103
+ snippet: 'await core.sdk.collection("products").update(productId, { inStock: false });\n'
104
+ },
105
+ {
106
+ name: 'core.sdk.collection(col).delete(id)',
107
+ type: 'Promise<boolean>',
108
+ cat: 'records',
109
+ desc: 'Delete a record from database by collection name and ID',
110
+ snippet: 'await core.sdk.collection("temp_tokens").delete(tokenId);\n'
111
+ },
112
+
113
+ // Queues (core.sdk.queue)
114
+ {
115
+ name: 'core.sdk.queue(name).send(payload, opts)',
116
+ type: 'Promise<QueueMessage>',
117
+ cat: 'queue',
118
+ desc: 'Enqueue a message into a generic queue',
119
+ snippet: 'await core.sdk.queue("notifications").send({ to: "user@example.com", text: "Welcome!" });\n'
120
+ },
121
+ {
122
+ name: 'core.sdk.queue(name).claim(opts)',
123
+ type: 'Promise<QueueMessage[]>',
124
+ cat: 'queue',
125
+ desc: 'Claim one or more pending messages from a queue with lease lock',
126
+ snippet: 'const messages = await core.sdk.queue("notifications").claim({ limit: 1, visibilityTimeoutSeconds: 30 });\n'
127
+ },
128
+ {
129
+ name: 'core.sdk.queue(name).complete(messageId, result, claimToken)',
130
+ type: 'Promise<boolean>',
131
+ cat: 'queue',
132
+ desc: 'Acknowledge and mark a claimed message as completed with optional claim token',
133
+ snippet: 'await core.sdk.queue("notifications").complete(message.id, { sent: true }, message.claimToken);\n'
134
+ },
135
+ {
136
+ name: 'core.sdk.queue(name).fail(messageId, error, opts)',
137
+ type: 'Promise<MessageFailResult>',
138
+ cat: 'queue',
139
+ desc: 'Reject a message with error details and trigger retry/backoff, returning { retried, deadLettered, attempts }',
140
+ snippet: 'await core.sdk.queue("notifications").fail(message.id, "SMTP timeout", { backoffDelayMs: 5000, claimToken: message.claimToken });\n'
141
+ },
142
+ {
143
+ name: 'core.sdk.queue(name).touch(messageId, extensionSeconds, claimToken)',
144
+ type: 'Promise<boolean>',
145
+ cat: 'queue',
146
+ desc: 'Extend visibility timeout lease on an in-progress message',
147
+ snippet: 'await core.sdk.queue("notifications").touch(message.id, 60, message.claimToken);\n'
148
+ },
149
+ {
150
+ name: 'ctx.queue(name).send(payload, opts) / ctx.queue.send(...)',
151
+ type: 'Promise<QueueMessage>',
152
+ cat: 'queue',
153
+ desc: 'Convenience alias on context.queue for enqueuing messages',
154
+ snippet: 'await ctx.queue.send("notifications", { to: "user@example.com" });\n'
155
+ },
156
+
157
+ // Outbound Network, Observability & Environment
158
+ {
159
+ name: 'core.network.http.fetch(url, options)',
160
+ type: 'Promise<{ ok, status, json(), text() }>',
161
+ cat: 'utils',
162
+ desc: 'SSRF-guarded outbound HTTP request (also available as global fetch)',
163
+ snippet: 'const res = await core.network.http.fetch("https://api.example.com/data", { method: "POST" });\nconst data = await res.json();\n'
164
+ },
165
+ {
166
+ name: 'core.observability.logger.log/warn/error(...args)',
167
+ type: '(...args: any[]) => void',
168
+ cat: 'utils',
169
+ desc: 'Structured execution logging captured in Execution Logs (also console.log)',
170
+ snippet: 'const logger = core.observability.logger;\nlogger.log("Processing execution step", { step: 1, time: Date.now() });\n'
171
+ },
172
+ {
173
+ name: 'core.observability.metric(name, value, tags)',
174
+ type: '(name: string, value: number, tags?: Record<string, string>) => void',
175
+ cat: 'utils',
176
+ desc: 'Publish telemetry metric with dimensional tags',
177
+ snippet: 'core.observability.metric("checkout_completed", 1, { status: "success" });\n'
178
+ },
179
+ {
180
+ name: 'context.env',
181
+ type: 'Record<string, string>',
182
+ cat: 'utils',
183
+ desc: 'Environment variables and secrets defined in the JSON configuration below',
184
+ snippet: 'const secretKey = context.env.MY_API_KEY;\n'
185
+ },
186
+ {
187
+ name: 'context.app',
188
+ type: '{ id, slug, name }',
189
+ cat: 'utils',
190
+ desc: 'Current tenant application identification and slug',
191
+ snippet: 'const { id, slug } = context.app;\n'
192
+ }
193
+ ];
194
+
195
+ function renderCtxItemsHtml(activeCategory = 'all') {
196
+ return CTX_DOCS.map(item => {
197
+ const isVisible = activeCategory === 'all' || item.cat === activeCategory;
198
+ const jsSnippetArg = JSON.stringify(item.snippet).replace(/"/g, '&quot;');
199
+ return `
200
+ <div class="ctx-item" data-cat="${item.cat}" style="display: ${isVisible ? 'flex' : 'none'}; flex-direction: column; gap: 4px; padding: 7px 10px; border-radius: 6px; background: var(--bg-card); border: 1px solid var(--border-subtle); font-size: 11.5px;">
201
+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 6px;">
202
+ <div style="display: flex; align-items: center; gap: 6px; overflow: hidden;">
203
+ <code style="color: var(--accent-primary); font-weight: 600; font-size: 12px; white-space: nowrap;">${escapeHtml(item.name)}</code>
204
+ <span style="font-size: 10px; color: var(--text-muted); padding: 1px 5px; background: var(--bg-input); border-radius: 3px; border: 1px solid var(--border-subtle); white-space: nowrap;">${escapeHtml(item.type)}</span>
205
+ </div>
206
+ <button type="button" class="btn btn-secondary btn-sm" onclick="insertFunctionSnippet(${jsSnippetArg})" style="font-size: 10px; padding: 2px 7px; flex-shrink: 0;" title="Click to insert snippet into code editor">
207
+ + Insert
208
+ </button>
209
+ </div>
210
+ <div style="color: var(--text-muted); font-size: 11px; line-height: 1.35;">
211
+ ${escapeHtml(item.desc)}
212
+ </div>
213
+ </div>
214
+ `;
215
+ }).join('');
216
+ }
217
+
218
+ function insertFunctionSnippet(snippet) {
219
+ if (functionsState.cmEditor) {
220
+ functionsState.cmEditor.replaceSelection(snippet);
221
+ functionsState.cmEditor.save();
222
+ functionsState.cmEditor.focus();
223
+ return;
224
+ }
225
+ const textarea = document.getElementById('fn-editor-code');
226
+ if (!textarea) return;
227
+
228
+ const start = textarea.selectionStart;
229
+ const end = textarea.selectionEnd;
230
+ const val = textarea.value;
231
+
232
+ if (start !== undefined && end !== undefined && start >= 0) {
233
+ textarea.value = val.substring(0, start) + snippet + val.substring(end);
234
+ textarea.selectionStart = textarea.selectionEnd = start + snippet.length;
235
+ } else {
236
+ textarea.value += '\n' + snippet;
237
+ }
238
+ textarea.focus();
239
+ }
240
+
241
+ function filterCtxCategory(category) {
242
+ const buttons = document.querySelectorAll('.ctx-cat-btn');
243
+ buttons.forEach(btn => {
244
+ const isTarget = btn.getAttribute('data-cat') === category;
245
+ if (isTarget) {
246
+ btn.classList.add('active');
247
+ btn.style.background = 'var(--accent-primary)';
248
+ btn.style.color = '#fff';
249
+ } else {
250
+ btn.classList.remove('active');
251
+ btn.style.background = 'var(--bg-card)';
252
+ btn.style.color = 'var(--text-muted)';
253
+ }
254
+ });
255
+
256
+ const items = document.querySelectorAll('.ctx-item');
257
+ items.forEach(item => {
258
+ const cat = item.getAttribute('data-cat');
259
+ item.style.display = (category === 'all' || cat === category) ? 'flex' : 'none';
260
+ });
261
+ }
262
+
263
+ function filterCtxSearch(query) {
264
+ const q = (query || '').toLowerCase().trim();
265
+ const items = document.querySelectorAll('.ctx-item');
266
+ items.forEach(item => {
267
+ const text = item.textContent.toLowerCase();
268
+ item.style.display = (!q || text.includes(q)) ? 'flex' : 'none';
269
+ });
270
+ }
271
+
272
+ function applyStarterRecipe(key) {
273
+ if (!key || !STARTER_RECIPES[key]) return;
274
+ if (functionsState.cmEditor) {
275
+ functionsState.cmEditor.setValue(STARTER_RECIPES[key]);
276
+ functionsState.cmEditor.save();
277
+ functionsState.cmEditor.focus();
278
+ return;
279
+ }
280
+ const area = document.getElementById('fn-editor-code');
281
+ if (area) {
282
+ area.value = STARTER_RECIPES[key];
283
+ area.focus();
284
+ }
285
+ }
286
+
287
+ function toggleWorkbenchCtxRef(forceState) {
288
+ if (typeof forceState === 'boolean') {
289
+ functionsState.isCtxRefExpanded = forceState;
290
+ } else {
291
+ functionsState.isCtxRefExpanded = !functionsState.isCtxRefExpanded;
292
+ }
293
+
294
+ const header = document.getElementById('workbench-ctx-header');
295
+ const content = document.getElementById('workbench-ctx-content');
296
+ const btn = document.getElementById('btn-toggle-workbench-ctx');
297
+ const toolbarBtn = document.getElementById('btn-toolbar-toggle-ctx');
298
+
299
+ if (header) {
300
+ header.style.borderBottom = functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none';
301
+ }
302
+ if (content) {
303
+ content.style.display = functionsState.isCtxRefExpanded ? 'flex' : 'none';
304
+ }
305
+ if (btn) {
306
+ btn.textContent = functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾';
307
+ }
308
+ if (toolbarBtn) {
309
+ toolbarBtn.style.background = functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)';
310
+ toolbarBtn.style.color = functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)';
311
+ }
312
+ }
313
+
314
+ // ==========================================
315
+ // 2. CodeMirror Integration & Themes
316
+ // ==========================================
317
+
318
+ function getCodeMirrorTheme() {
319
+ if (typeof ThemeManager !== 'undefined' && typeof ThemeManager.getEffectiveTheme === 'function') {
320
+ return ThemeManager.getEffectiveTheme() === 'light' ? 'eclipse' : 'dracula';
321
+ }
322
+ if (typeof document !== 'undefined' && document.documentElement) {
323
+ return document.documentElement.classList.contains('light') ? 'eclipse' : 'dracula';
324
+ }
325
+ return 'dracula';
326
+ }
327
+
328
+ function initFunctionCodeMirror() {
329
+ if (typeof CodeMirror === 'undefined') return;
330
+ const codeArea = document.getElementById('fn-editor-code');
331
+ if (!codeArea) return;
332
+
333
+ if (functionsState.cmEditor) {
334
+ try {
335
+ functionsState.cmEditor.toTextArea();
336
+ } catch (_) {}
337
+ functionsState.cmEditor = null;
338
+ }
339
+
340
+ try {
341
+ functionsState.cmEditor = CodeMirror.fromTextArea(codeArea, {
342
+ mode: { name: 'javascript', typescript: true },
343
+ theme: getCodeMirrorTheme(),
344
+ lineNumbers: true,
345
+ matchBrackets: true,
346
+ autoCloseBrackets: true,
347
+ tabSize: 2,
348
+ indentWithTabs: false,
349
+ lineWrapping: true,
350
+ extraKeys: {
351
+ 'Tab': function(cm) {
352
+ cm.replaceSelection(' ');
353
+ },
354
+ 'Ctrl-S': function() {
355
+ saveFunctionEditor();
356
+ },
357
+ 'Cmd-S': function() {
358
+ saveFunctionEditor();
359
+ }
360
+ }
361
+ });
362
+
363
+ functionsState.cmEditor.on('change', () => {
364
+ functionsState.cmEditor.save();
365
+ });
366
+
367
+ setTimeout(() => {
368
+ functionsState.cmEditor?.refresh();
369
+ }, 50);
370
+ } catch (err) {
371
+ console.warn('CodeMirror initialization skipped or failed:', err);
372
+ }
373
+ }
374
+
375
+ if (typeof window !== 'undefined') {
376
+ window.addEventListener('nodestack-theme-changed', (e) => {
377
+ if (functionsState.cmEditor) {
378
+ const isLight = (e.detail && e.detail.effective === 'light') || getCodeMirrorTheme() === 'eclipse';
379
+ functionsState.cmEditor.setOption('theme', isLight ? 'eclipse' : 'dracula');
380
+ }
381
+ });
382
+ }
383
+
384
+ // ==========================================
385
+ // 3. Workbench Routing & Navigation
386
+ // ==========================================
387
+
388
+ function openCreateFunctionPage() {
389
+ openFunctionEditor('new', true, 'code');
390
+ }
391
+
392
+ async function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
393
+ let fn;
394
+
395
+ if (idOrName === 'new' || !idOrName) {
396
+ fn = {
397
+ isNew: true,
398
+ id: '',
399
+ name: '',
400
+ description: '',
401
+ code: STARTER_RECIPES.starter,
402
+ enabled: true,
403
+ authPolicy: 'admin',
404
+ invokeRule: null,
405
+ methods: ['GET', 'POST'],
406
+ eventTrigger: '',
407
+ timeoutMs: 1000,
408
+ memoryLimitMb: 32,
409
+ allowedDomains: [],
410
+ elevated: false,
411
+ env: {},
412
+ };
413
+ } else {
414
+ fn = (functionsState.functions || []).find(f => f.id === idOrName || f.name === idOrName);
415
+
416
+ if (!fn) {
417
+ try {
418
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
419
+ const endpoint = slug && slug !== 'default'
420
+ ? `/api/apps/${slug}/functions/${encodeURIComponent(idOrName)}`
421
+ : `/api/functions/${encodeURIComponent(idOrName)}`;
422
+ fn = await api(endpoint);
423
+ } catch (_) {}
424
+ }
425
+
426
+ if (!fn) {
427
+ toast(`Function '${idOrName}' not found`, 'error');
428
+ if (typeof selectNav === 'function') selectNav('functions', false);
429
+ return;
430
+ }
431
+ }
432
+
433
+ functionsState.currentView = 'editor';
434
+ functionsState.activeFunctionForEdit = fn;
435
+ functionsState.editorTab = initialTab || 'code';
436
+
437
+ if (pushState && typeof updateUrl === 'function') {
438
+ updateUrl(fn.isNew ? '/_/functions/new' : '/_/functions/' + encodeURIComponent(fn.name || fn.id));
439
+ }
440
+
441
+ if (typeof updateBreadcrumbs === 'function') {
442
+ updateBreadcrumbs();
443
+ }
444
+
445
+ renderFunctionEditorView(fn);
446
+ }
447
+
448
+ function closeFunctionEditor(pushState = true) {
449
+ if (functionsState.cmEditor) {
450
+ try {
451
+ functionsState.cmEditor.toTextArea();
452
+ } catch (_) {}
453
+ functionsState.cmEditor = null;
454
+ }
455
+ functionsState.currentView = 'list';
456
+ functionsState.activeFunctionForEdit = null;
457
+
458
+ if (pushState && typeof updateUrl === 'function') {
459
+ updateUrl('/_/functions');
460
+ }
461
+
462
+ if (typeof updateBreadcrumbs === 'function') {
463
+ updateBreadcrumbs();
464
+ }
465
+
466
+ if (typeof renderFunctionsView === 'function') {
467
+ renderFunctionsView();
468
+ }
469
+ }
470
+
471
+ function switchFunctionEditorTab(tab) {
472
+ functionsState.editorTab = tab;
473
+ ['code', 'test', 'config', 'logs'].forEach(t => {
474
+ const btn = document.getElementById('editor-tab-btn-' + t);
475
+ const pane = document.getElementById('fn-editor-pane-' + t);
476
+ if (btn) btn.classList.toggle('active', t === tab);
477
+ if (pane) {
478
+ if (t === 'code') {
479
+ pane.style.display = (t === tab) ? 'flex' : 'none';
480
+ if (t === tab && functionsState.cmEditor) {
481
+ setTimeout(() => { functionsState.cmEditor?.refresh(); }, 20);
482
+ }
483
+ } else if (t === 'test' || t === 'config') {
484
+ pane.style.display = (t === tab) ? 'grid' : 'none';
485
+ } else if (t === 'logs') {
486
+ pane.style.display = (t === tab) ? 'flex' : 'none';
487
+ }
488
+ }
489
+ });
490
+
491
+ if (tab === 'logs' && typeof loadFunctionEditorLogs === 'function') {
492
+ loadFunctionEditorLogs();
493
+ }
494
+ }
495
+
496
+ function syncEditorFunctionName(val) {
497
+ const clean = (val || '').toLowerCase().replace(/[^a-z0-9_-]/g, '');
498
+ const headerInput = document.getElementById('fn-editor-name-header');
499
+ const configInput = document.getElementById('fn-editor-name');
500
+ if (headerInput && headerInput.value !== clean) headerInput.value = clean;
501
+ if (configInput && configInput.value !== clean) configInput.value = clean;
502
+ if (functionsState.activeFunctionForEdit) {
503
+ functionsState.activeFunctionForEdit.name = clean;
504
+ }
505
+ const preview = document.getElementById('fn-editor-endpoint-preview');
506
+ if (preview) {
507
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
508
+ const prefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
509
+ preview.textContent = `ANY ${prefix}/${clean || '{name}'}/invoke`;
510
+ }
511
+ }
512
+
513
+ function copyFunctionEndpoint(path) {
514
+ const fullUrl = window.location.origin + path;
515
+ if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
516
+ navigator.clipboard.writeText(fullUrl).then(() => {
517
+ toast('Copied function endpoint URL to clipboard', 'info');
518
+ }).catch(() => {
519
+ prompt('Copy function endpoint URL:', fullUrl);
520
+ });
521
+ } else {
522
+ prompt('Copy function endpoint URL:', fullUrl);
523
+ }
524
+ }
525
+
526
+ function formatAuthPolicyBadge(policy) {
527
+ const p = policy || 'public';
528
+ if (p === 'custom') {
529
+ return '<span class="badge" style="background: rgba(245, 158, 11, 0.15); color: #f59e0b;">CUSTOM RULE</span>';
530
+ }
531
+ if (p === 'admin') {
532
+ return '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;">ADMIN</span>';
533
+ }
534
+ return `<span class="badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">${escapeHtml(p.toUpperCase())}</span>`;
535
+ }
536
+
537
+ function updateEditorHeaderBadges(fn) {
538
+ const container = document.getElementById('editor-header-badges');
539
+ if (!container) return;
540
+ container.innerHTML = `
541
+ <span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
542
+ ${fn.enabled !== false ? '● Active' : '○ Disabled'}
543
+ </span>
544
+ ${formatAuthPolicyBadge(fn.authPolicy)}
545
+ ${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
546
+ `;
547
+ }
548
+
549
+ // ==========================================
550
+ // 4. Workbench Sub-Renderers & Main Assembler
551
+ // ==========================================
552
+
553
+ function renderWorkbenchHeader(fn, isNew, invokePath) {
554
+ return `
555
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; border-bottom: 1px solid var(--border-subtle); padding-bottom: 1rem;">
556
+ <div style="display: flex; align-items: center; gap: 14px;">
557
+ <button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Back to functions list" style="display: flex; align-items: center; gap: 6px;">
558
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
559
+ <span>Functions</span>
560
+ </button>
561
+ <div>
562
+ ${isNew ? `
563
+ <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
564
+ <input type="text" id="fn-editor-name-header" class="input" placeholder="function-name" value="${escapeHtml(fn.name || '')}" oninput="syncEditorFunctionName(this.value)" style="font-family: monospace; font-size: 1.15rem; font-weight: 700; width: 250px; padding: 4px 10px;" title="Function Name (Slug)">
565
+ <span class="badge" style="background: rgba(99, 102, 241, 0.15); color: #6366f1; font-weight: 600;">✨ New Function</span>
566
+ </div>
567
+ <div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
568
+ <span>Endpoint: <code id="fn-editor-endpoint-preview" style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
569
+ <span>Default limits: 1000ms / 32MB</span>
570
+ </div>
571
+ ` : `
572
+ <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
573
+ <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0; font-family: monospace; display: flex; align-items: center; gap: 8px;">
574
+ ${escapeHtml(fn.name)}
575
+ </h2>
576
+ ${fn.id ? `<code style="font-size: 11px; color: var(--text-muted); background: var(--bg-card-hover); border: 1px solid var(--border-subtle); padding: 2px 6px; border-radius: 4px;" title="Unique Function ID">id: ${escapeHtml(fn.id)}</code>` : ''}
577
+ <div id="editor-header-badges" style="display: inline-flex; align-items: center; gap: 6px;">
578
+ <span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
579
+ ${fn.enabled !== false ? '● Active' : '○ Disabled'}
580
+ </span>
581
+ ${formatAuthPolicyBadge(fn.authPolicy)}
582
+ ${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
583
+ </div>
584
+ </div>
585
+ <div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
586
+ <span>Endpoint: <code style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
587
+ <button type="button" class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="font-size: 10px; padding: 1px 6px;" title="Copy full invoke endpoint">
588
+ 📋 Copy URL
589
+ </button>
590
+ ${fn.eventTrigger ? `<span style="color: var(--accent-primary);">⚡ Hook: <code>${escapeHtml(fn.eventTrigger)}</code></span>` : ''}
591
+ ${fn.cronSchedule ? `<span style="color: var(--accent-success);">⏱️ Cron: <code>${escapeHtml(fn.cronSchedule)}</code> (${escapeHtml(fn.cronTimezone || 'UTC')})</span>` : ''}
592
+ <span>Limits: ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB</span>
593
+ </div>
594
+ `}
595
+ </div>
596
+ </div>
597
+
598
+ <div style="display: flex; align-items: center; gap: 8px;">
599
+ ${!isNew ? `
600
+ <button class="btn btn-secondary btn-sm" onclick="switchFunctionEditorTab('test')" style="display: flex; align-items: center; gap: 6px;">
601
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
602
+ <span>Run Test</span>
603
+ </button>
604
+ <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">
605
+ Delete
606
+ </button>
607
+ ` : `
608
+ <button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Cancel and return to list">
609
+ Cancel
610
+ </button>
611
+ `}
612
+ <button class="btn btn-primary btn-sm" id="btn-editor-save" onclick="saveFunctionEditor()" style="display: flex; align-items: center; gap: 6px; font-weight: 600;">
613
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
614
+ <span>${isNew ? 'Create Function' : 'Save Changes'}</span>
615
+ </button>
616
+ </div>
617
+ </div>
618
+ `;
619
+ }
620
+
621
+ function renderWorkbenchTabs(activeTab) {
622
+ return `
623
+ <div style="display: flex; align-items: center; gap: 8px; border-bottom: 1px solid var(--border-subtle); padding-bottom: 8px;">
624
+ <button class="webhook-tab-btn ${activeTab === 'code' ? 'active' : ''}" id="editor-tab-btn-code" onclick="switchFunctionEditorTab('code')">
625
+ <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>
626
+ Code & Context Reference
627
+ </button>
628
+ <button class="webhook-tab-btn ${activeTab === 'test' ? 'active' : ''}" id="editor-tab-btn-test" onclick="switchFunctionEditorTab('test')">
629
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
630
+ Live Test Runner
631
+ </button>
632
+ <button class="webhook-tab-btn ${activeTab === 'config' ? 'active' : ''}" id="editor-tab-btn-config" onclick="switchFunctionEditorTab('config')">
633
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
634
+ Configuration & Triggers
635
+ </button>
636
+ <button class="webhook-tab-btn ${activeTab === 'logs' ? 'active' : ''}" id="editor-tab-btn-logs" onclick="switchFunctionEditorTab('logs')">
637
+ <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>
638
+ Function Logs & History
639
+ </button>
640
+ </div>
641
+ `;
642
+ }
643
+
644
+ function renderWorkbenchCodePane(fn) {
645
+ return `
646
+ <div id="fn-editor-pane-code" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'code' ? 'flex' : 'none'}; flex-direction: column; gap: 1rem; width: 100%;">
647
+ <div class="card" style="padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem;">
648
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
649
+ <div style="display: flex; align-items: center; gap: 8px;">
650
+ <span style="font-weight: 600; font-size: 13px; color: var(--text-heading);">Function Handler Source</span>
651
+ <span style="font-size: 11px; color: var(--text-muted); font-family: monospace;">export default async function(core, context) { ... }</span>
652
+ </div>
653
+ <div style="display: flex; align-items: center; gap: 8px;">
654
+ <button type="button" class="btn btn-secondary btn-sm" id="btn-toolbar-toggle-ctx" onclick="toggleWorkbenchCtxRef()" style="font-size: 11px; display: flex; align-items: center; gap: 6px; padding: 3px 9px; background: ${functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)'}; color: ${functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)'};" title="Toggle Context Reference Panel">
655
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
656
+ <span>API Reference (core, context)</span>
657
+ </button>
658
+ <span style="font-size: 11px; color: var(--text-muted);">Templates:</span>
659
+ <select class="input" style="font-size: 11px; padding: 2px 8px;" onchange="applyStarterRecipe(this.value)">
660
+ <option value="">Apply Recipe...</option>
661
+ <option value="starter">Basic Hello World</option>
662
+ <option value="discount">Cart Discount Calculation</option>
663
+ <option value="hook">Validation & Mutation Hook</option>
664
+ <option value="fetch">External API Fetch</option>
665
+ </select>
666
+ <span style="font-size: 10px; color: var(--text-muted); background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px;">Ctrl+S to save</span>
667
+ </div>
668
+ </div>
669
+
670
+ <textarea id="fn-editor-code" style="width: 100%; min-height: 520px; height: calc(100vh - 290px); font-family: 'JetBrains Mono', Consolas, Monaco, monospace; font-size: 13px; line-height: 1.5; padding: 14px; border-radius: 8px; border: 1px solid var(--border-subtle); background: #0f172a; color: #f8fafc; resize: vertical;" spellcheck="false">${escapeHtml(fn.code)}</textarea>
671
+
672
+ <!-- Vertical Collapsible Context API Reference (Collapsed by default) -->
673
+ <div class="ctx-reference-panel" style="border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--bg-input); overflow: hidden; margin-top: 4px;">
674
+ <div id="workbench-ctx-header" onclick="toggleWorkbenchCtxRef()" style="display: flex; align-items: center; justify-content: space-between; padding: 9px 14px; background: var(--bg-card); cursor: pointer; user-select: none; border-bottom: ${functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none'}; font-size: 12px;">
675
+ <div style="display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text-heading);">
676
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--accent-primary);"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
677
+ <span>Platform Reference (<code>core, context</code>)</span>
678
+ <span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">— 1-click snippet insert for SDK, queue, request, events & network</span>
679
+ </div>
680
+ <div style="display: flex; align-items: center; gap: 8px;">
681
+ <span class="badge" style="background: var(--bg-card-hover); color: var(--text-muted); font-size: 10px;">22 items</span>
682
+ <button type="button" class="btn btn-secondary btn-sm" id="btn-toggle-workbench-ctx" onclick="event.stopPropagation(); toggleWorkbenchCtxRef();" style="font-size: 11px; padding: 2px 9px;">
683
+ ${functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾'}
684
+ </button>
685
+ </div>
686
+ </div>
687
+
688
+ <div id="workbench-ctx-content" style="display: ${functionsState.isCtxRefExpanded ? 'flex' : 'none'}; flex-direction: column; gap: 10px; padding: 12px 14px; background: var(--bg-card);">
689
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
690
+ <div style="display: flex; align-items: center; gap: 5px; flex-wrap: wrap;">
691
+ <button type="button" class="ctx-cat-btn active" data-cat="all" onclick="filterCtxCategory('all')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--accent-primary); color: #fff; cursor: pointer; font-weight: 500;">All (22)</button>
692
+ <button type="button" class="ctx-cat-btn" data-cat="request" onclick="filterCtxCategory('request')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">HTTP (context.request)</button>
693
+ <button type="button" class="ctx-cat-btn" data-cat="event" onclick="filterCtxCategory('event')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">DB Events (context.event)</button>
694
+ <button type="button" class="ctx-cat-btn" data-cat="records" onclick="filterCtxCategory('records')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Collections (core.sdk)</button>
695
+ <button type="button" class="ctx-cat-btn" data-cat="queue" onclick="filterCtxCategory('queue')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Queues (core.sdk)</button>
696
+ <button type="button" class="ctx-cat-btn" data-cat="utils" onclick="filterCtxCategory('utils')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Network & Obs</button>
697
+ </div>
698
+ <div style="flex: 1; max-width: 260px; min-width: 180px;">
699
+ <input type="text" id="ctx-search-input" class="input" placeholder="Search core & context APIs..." oninput="filterCtxSearch(this.value)" style="width: 100%; font-size: 11px; padding: 4px 8px;">
700
+ </div>
701
+ </div>
702
+
703
+ <div id="ctx-items-container" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 8px; max-height: 240px; overflow-y: auto; padding-right: 4px;">
704
+ ${renderCtxItemsHtml()}
705
+ </div>
706
+ </div>
707
+ </div>
708
+ </div>
709
+ </div>
710
+ `;
711
+ }
712
+
713
+ function handleFunctionAuthPolicyChange(policy) {
714
+ if (functionsState.activeFunctionForEdit) {
715
+ functionsState.activeFunctionForEdit.authPolicy = policy;
716
+ }
717
+ const container = document.getElementById('fn-custom-rule-container');
718
+ if (container) {
719
+ container.style.display = policy === 'custom' ? 'block' : 'none';
720
+ if (policy === 'custom' && typeof renderStandaloneRuleEditor === 'function') {
721
+ if (typeof initStandaloneRule === 'function' && (!state.standaloneRules || !state.standaloneRules.fn_invoke)) {
722
+ initStandaloneRule('fn_invoke', functionsState.activeFunctionForEdit?.invokeRule || '@request.auth.id != ""');
723
+ }
724
+ container.innerHTML = renderStandaloneRuleEditor('fn_invoke');
725
+ }
726
+ }
727
+ }
728
+
729
+ function renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString) {
730
+ if (typeof initStandaloneRule === 'function') {
731
+ initStandaloneRule('fn_invoke', fn.invokeRule || '@request.auth.id != ""');
732
+ }
733
+ return `
734
+ <div id="fn-editor-pane-config" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'config' ? 'grid' : 'none'}; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: start;">
735
+ <!-- Column 1: General & Triggers -->
736
+ <div style="display: flex; flex-direction: column; gap: 1rem;">
737
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
738
+ <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
739
+ General Settings
740
+ </div>
741
+ <div>
742
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Function Identifier (Name)</label>
743
+ <input type="text" id="fn-editor-name" class="input" value="${escapeHtml(fn.name || '')}" ${isNew ? 'placeholder="e.g. calculate-discount" oninput="syncEditorFunctionName(this.value)"' : 'readonly'} style="width: 100%; font-family: monospace; ${!isNew ? 'background: var(--bg-input); opacity: 0.85;' : ''}">
744
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 2px; display: block;">Immutable endpoint slug for API invocation routes. Alphanumeric characters, underscores, and dashes only.</span>
745
+ </div>
746
+ <div>
747
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Description</label>
748
+ <input type="text" id="fn-editor-desc" class="input" value="${escapeHtml(fn.description || '')}" placeholder="What does this function do?" style="width: 100%;">
749
+ </div>
750
+ <div style="display: flex; align-items: center; gap: 10px; padding: 10px; background: var(--bg-card-hover); border-radius: 6px;">
751
+ <input type="checkbox" id="fn-editor-enabled" ${fn.enabled !== false ? 'checked' : ''} style="cursor: pointer;">
752
+ <div>
753
+ <label for="fn-editor-enabled" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--text-main);">Function Enabled</label>
754
+ <div style="font-size: 11px; color: var(--text-muted);">When disabled, API calls return 503 Service Unavailable and lifecycle hooks skip execution.</div>
755
+ </div>
756
+ </div>
757
+ </div>
758
+
759
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
760
+ <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
761
+ Triggers & Invocation
762
+ </div>
763
+ <div>
764
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Allowed HTTP Methods</label>
765
+ <div style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;" id="fn-editor-methods-group">
766
+ ${['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].map(m => `
767
+ <label style="display: flex; align-items: center; gap: 4px; font-size: 12px; cursor: pointer;">
768
+ <input type="checkbox" class="fn-editor-method-cb" value="${m}" ${(fn.methods || ['GET', 'POST']).includes(m) ? 'checked' : ''} style="cursor: pointer;">
769
+ <span>${m}</span>
770
+ </label>
771
+ `).join('')}
772
+ </div>
773
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">Allowed HTTP methods for external API invocation routes.</span>
774
+ </div>
775
+ <div>
776
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Database Lifecycle Hook Trigger</label>
777
+ <input type="text" id="fn-editor-hook" class="input" value="${escapeHtml(fn.eventTrigger || '')}" placeholder="e.g. orders:beforeCreate or articles:afterUpdate" style="width: 100%; font-size: 12px; font-family: monospace;">
778
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
779
+ Format: <code>&lt;collection&gt;:&lt;phase&gt;&lt;Action&gt;</code>. Available phases: <code>beforeCreate</code>, <code>afterCreate</code>, <code>beforeUpdate</code>, <code>afterUpdate</code>, <code>beforeDelete</code>, <code>afterDelete</code>.
780
+ </span>
781
+ </div>
782
+ <div>
783
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Scheduled Cron Trigger (Optional)</label>
784
+ <div style="display: flex; gap: 8px;">
785
+ <input type="text" id="fn-editor-cron" class="input" value="${escapeHtml(fn.cronSchedule || '')}" placeholder="e.g. 0 9 * * 1-5 or */15 * * * *" style="flex: 1; font-size: 12px; font-family: monospace;" autocomplete="off">
786
+ <input type="text" id="fn-editor-timezone" class="input" value="${escapeHtml(fn.cronTimezone || 'UTC')}" placeholder="Timezone (UTC)" list="iana-timezones-list" style="width: 140px; font-size: 12px;">
787
+ </div>
788
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
789
+ Standard 5-field cron expression. Automatically scheduled with distributed atomic DB lease locking.
790
+ </span>
791
+ </div>
792
+ </div>
793
+ </div>
794
+
795
+ <!-- Column 2: Runtime Limits, Auth & Secrets -->
796
+ <div style="display: flex; flex-direction: column; gap: 1rem;">
797
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
798
+ <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
799
+ Security & Guardrails
800
+ </div>
801
+ <div>
802
+ <label for="fn-editor-auth" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Authorization Policy</label>
803
+ <select id="fn-editor-auth" class="input" style="width: 100%;" onchange="handleFunctionAuthPolicyChange(this.value)">
804
+ <option value="admin" ${fn.authPolicy === 'admin' ? 'selected' : ''}>Admin Only (Requires Admin Token)</option>
805
+ <option value="auth" ${fn.authPolicy === 'auth' ? 'selected' : ''}>User Token (Bearer JWT or Scoped API Key)</option>
806
+ <option value="apiKey" ${fn.authPolicy === 'apiKey' ? 'selected' : ''}>API Key (Requires nsk_live_... with function scope)</option>
807
+ <option value="custom" ${fn.authPolicy === 'custom' ? 'selected' : ''}>Custom Rule (@request.auth.* or Scoped API Key)</option>
808
+ <option value="public" ${fn.authPolicy === 'public' ? 'selected' : ''}>Public (No Token Required)</option>
809
+ </select>
810
+ <div id="fn-custom-rule-container" style="display: ${fn.authPolicy === 'custom' ? 'block' : 'none'}; margin-top: 8px;">
811
+ ${typeof renderStandaloneRuleEditor === 'function' ? renderStandaloneRuleEditor('fn_invoke') : ''}
812
+ </div>
813
+ </div>
814
+
815
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
816
+ <div>
817
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Timeout (ms)</label>
818
+ <input type="number" id="fn-editor-timeout" class="input" value="${fn.timeoutMs || 1000}" min="100" max="15000" style="width: 100%; font-size: 12px;">
819
+ </div>
820
+ <div>
821
+ <label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Memory Cap (MB)</label>
822
+ <input type="number" id="fn-editor-memory" class="input" value="${fn.memoryLimitMb || 32}" min="4" max="128" style="width: 100%; font-size: 12px;">
823
+ </div>
824
+ </div>
825
+
826
+ <div>
827
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Outbound Egress Whitelist (SSRF Protection)</label>
828
+ <input type="text" id="fn-editor-domains" class="input" value="${escapeHtml(allowedDomainsString)}" placeholder="e.g. api.stripe.com, *.resend.com (Leave blank for all public domains)" style="width: 100%; font-size: 12px;">
829
+ </div>
830
+
831
+ <div style="display: flex; align-items: center; gap: 8px; padding: 10px; background: rgba(239, 68, 68, 0.08); border-radius: 6px; border: 1px solid rgba(239, 68, 68, 0.2);">
832
+ <input type="checkbox" id="fn-editor-elevated" ${fn.elevated ? 'checked' : ''} style="cursor: pointer;">
833
+ <div>
834
+ <label for="fn-editor-elevated" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--accent-danger);">
835
+ Elevated Service Role
836
+ </label>
837
+ <div style="font-size: 11px; color: var(--text-muted);">Bypasses collection RuleEngine access rules. Allows reading and mutating records as superuser.</div>
838
+ </div>
839
+ </div>
840
+ </div>
841
+
842
+ <div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 0.75rem;">
843
+ <div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px; display: flex; align-items: center; justify-content: space-between;">
844
+ <span>Environment Secrets (<code>context.env</code>)</span>
845
+ <span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">JSON Object</span>
846
+ </div>
847
+ <textarea id="fn-editor-env" style="width: 100%; height: 95px; font-family: monospace; font-size: 12px; padding: 8px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-card-hover); color: var(--text-main);" placeholder='{ "STRIPE_SECRET": "sk_test_..." }'>${escapeHtml(envString)}</textarea>
848
+ <span style="font-size: 11px; color: var(--text-muted);">Encrypted in database and injected at runtime into <code>context.env</code>. Isolated from system <code>process.env</code>.</span>
849
+ </div>
850
+ </div>
851
+ </div>
852
+ `;
853
+ }
854
+
855
+ function renderFunctionEditorView(fn) {
856
+ const container = document.getElementById('page-view-functions') || document.getElementById('main-body');
857
+ if (!container) return;
858
+
859
+ const isNew = !!fn.isNew;
860
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
861
+ const invokePrefix = slug && slug !== 'default'
862
+ ? `/api/apps/${slug}/functions`
863
+ : `/api/functions`;
864
+ const invokePath = `${invokePrefix}/${fn.name || '{name}'}/invoke`;
865
+
866
+ const envString = fn.env && Object.keys(fn.env).length > 0
867
+ ? JSON.stringify(fn.env, null, 2)
868
+ : '{}';
869
+
870
+ const allowedDomainsString = (fn.allowedDomains || []).join(', ');
871
+
872
+ const testPaneHtml = typeof renderWorkbenchTestPane === 'function'
873
+ ? renderWorkbenchTestPane(fn, isNew)
874
+ : '';
875
+
876
+ const logsPaneHtml = typeof renderWorkbenchLogsPane === 'function'
877
+ ? renderWorkbenchLogsPane(fn, isNew)
878
+ : '';
879
+
880
+ container.innerHTML = `
881
+ <div class="function-editor-page" style="max-width: 1440px; margin: 0 auto; padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1rem;">
882
+ ${renderWorkbenchHeader(fn, isNew, invokePath)}
883
+ ${renderWorkbenchTabs(functionsState.editorTab)}
884
+ ${renderWorkbenchCodePane(fn)}
885
+ ${testPaneHtml}
886
+ ${renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString)}
887
+ ${logsPaneHtml}
888
+ </div>
889
+ `;
890
+
891
+ // Attach keyboard shortcut for saving and tab indentation
892
+ const codeArea = document.getElementById('fn-editor-code');
893
+ if (codeArea) {
894
+ codeArea.addEventListener('keydown', (e) => {
895
+ if (e.key === 'Tab') {
896
+ e.preventDefault();
897
+ const start = codeArea.selectionStart;
898
+ const end = codeArea.selectionEnd;
899
+ codeArea.value = codeArea.value.substring(0, start) + ' ' + codeArea.value.substring(end);
900
+ codeArea.selectionStart = codeArea.selectionEnd = start + 2;
901
+ }
902
+ if ((e.ctrlKey || e.metaKey) && e.key === 's') {
903
+ e.preventDefault();
904
+ saveFunctionEditor();
905
+ }
906
+ });
907
+ }
908
+
909
+ // Global Ctrl+S handler while on workbench view
910
+ window.onkeydown = (e) => {
911
+ if ((e.ctrlKey || e.metaKey) && e.key === 's' && functionsState.currentView === 'editor') {
912
+ e.preventDefault();
913
+ saveFunctionEditor();
914
+ }
915
+ };
916
+
917
+ // Initialize CodeMirror editor
918
+ initFunctionCodeMirror();
919
+
920
+ // If logs tab is active on existing function, load logs
921
+ if (functionsState.editorTab === 'logs' && !isNew && typeof loadFunctionEditorLogs === 'function') {
922
+ loadFunctionEditorLogs();
923
+ }
924
+ }
925
+
926
+ // ==========================================
927
+ // 5. Persistence Handlers
928
+ // ==========================================
929
+
930
+ async function saveFunctionEditor() {
931
+ const btn = document.getElementById('btn-editor-save');
932
+ const fn = functionsState.activeFunctionForEdit;
933
+ if (!fn) return;
934
+
935
+ const isNew = !!fn.isNew;
936
+
937
+ if (btn) {
938
+ btn.disabled = true;
939
+ btn.textContent = isNew ? 'Creating...' : 'Saving...';
940
+ }
941
+
942
+ try {
943
+ if (functionsState.cmEditor) {
944
+ functionsState.cmEditor.save();
945
+ }
946
+ const codeEl = document.getElementById('fn-editor-code');
947
+ const descEl = document.getElementById('fn-editor-desc');
948
+ const authEl = document.getElementById('fn-editor-auth');
949
+ const hookEl = document.getElementById('fn-editor-hook');
950
+ const timeoutEl = document.getElementById('fn-editor-timeout');
951
+ const memoryEl = document.getElementById('fn-editor-memory');
952
+ const domainsEl = document.getElementById('fn-editor-domains');
953
+ const elevatedEl = document.getElementById('fn-editor-elevated');
954
+ const enabledEl = document.getElementById('fn-editor-enabled');
955
+ const envEl = document.getElementById('fn-editor-env');
956
+ const cronEl = document.getElementById('fn-editor-cron');
957
+ const tzEl = document.getElementById('fn-editor-timezone');
958
+
959
+ const nameHeaderEl = document.getElementById('fn-editor-name-header');
960
+ const nameConfigEl = document.getElementById('fn-editor-name');
961
+ let name = (nameHeaderEl ? nameHeaderEl.value.trim() : (nameConfigEl ? nameConfigEl.value.trim() : (fn.name || ''))).toLowerCase();
962
+
963
+ if (isNew) {
964
+ if (!name) {
965
+ throw new Error('Please enter a function identifier (name)');
966
+ }
967
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
968
+ throw new Error('Function name must contain only alphanumeric characters, underscores, and dashes');
969
+ }
970
+ }
971
+
972
+ const code = codeEl ? codeEl.value : fn.code;
973
+ const description = descEl ? descEl.value.trim() : (fn.description || '');
974
+ const authPolicy = authEl ? authEl.value : (fn.authPolicy || 'admin');
975
+ const invokeRule = authPolicy === 'custom'
976
+ ? (typeof getStandaloneRuleValue === 'function' ? getStandaloneRuleValue('fn_invoke') : (fn.invokeRule || null))
977
+ : null;
978
+ const eventTrigger = hookEl ? hookEl.value.trim() : (fn.eventTrigger || '');
979
+ const timeoutMs = timeoutEl ? (parseInt(timeoutEl.value, 10) || 1000) : fn.timeoutMs;
980
+ const memoryLimitMb = memoryEl ? (parseInt(memoryEl.value, 10) || 32) : fn.memoryLimitMb;
981
+ const domainsRaw = domainsEl ? domainsEl.value.trim() : '';
982
+ const allowedDomains = domainsRaw ? domainsRaw.split(',').map(s => s.trim()).filter(Boolean) : (fn.allowedDomains || []);
983
+ const elevated = elevatedEl ? elevatedEl.checked : !!fn.elevated;
984
+ const enabled = enabledEl ? enabledEl.checked : (fn.enabled !== false);
985
+ const cronSchedule = cronEl ? (cronEl.value.trim() || null) : (fn.cronSchedule || null);
986
+ const cronTimezone = tzEl ? (tzEl.value.trim() || 'UTC') : (fn.cronTimezone || 'UTC');
987
+
988
+ let env = fn.env || {};
989
+ if (envEl && envEl.value.trim()) {
990
+ try {
991
+ env = JSON.parse(envEl.value.trim());
992
+ } catch {
993
+ throw new Error('Environment secrets must be valid JSON');
994
+ }
995
+ }
996
+
997
+ const methodCbs = document.querySelectorAll('.fn-editor-method-cb:checked');
998
+ const methods = methodCbs.length > 0
999
+ ? Array.from(methodCbs).map(cb => cb.value)
1000
+ : (fn.methods || ['GET', 'POST']);
1001
+
1002
+ const payload = {
1003
+ description,
1004
+ authPolicy,
1005
+ invokeRule,
1006
+ methods,
1007
+ eventTrigger: eventTrigger || null,
1008
+ timeoutMs,
1009
+ memoryLimitMb,
1010
+ allowedDomains,
1011
+ elevated,
1012
+ enabled,
1013
+ cronSchedule,
1014
+ cronTimezone,
1015
+ code,
1016
+ env,
1017
+ };
1018
+
1019
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
1020
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
1021
+
1022
+ if (isNew) {
1023
+ const createPayload = {
1024
+ name,
1025
+ methods: fn.methods || ['GET', 'POST'],
1026
+ ...payload,
1027
+ };
1028
+
1029
+ const created = await api(baseUrl, {
1030
+ method: 'POST',
1031
+ headers: { 'Content-Type': 'application/json' },
1032
+ body: JSON.stringify(createPayload),
1033
+ });
1034
+
1035
+ functionsState.activeFunctionForEdit = created;
1036
+ if (!Array.isArray(functionsState.functions)) {
1037
+ functionsState.functions = [];
1038
+ }
1039
+ const existingIdx = functionsState.functions.findIndex(f => f.id === created.id);
1040
+ if (existingIdx !== -1) {
1041
+ functionsState.functions[existingIdx] = created;
1042
+ } else {
1043
+ functionsState.functions.unshift(created);
1044
+ }
1045
+
1046
+ toast(`Function '${created.name}' created successfully`, 'success');
1047
+ if (typeof updateUrl === 'function') {
1048
+ updateUrl('/_/functions/' + encodeURIComponent(created.name));
1049
+ }
1050
+ if (typeof updateBreadcrumbs === 'function') {
1051
+ updateBreadcrumbs();
1052
+ }
1053
+ renderFunctionEditorView(created);
1054
+ if (typeof loadFunctionStats === 'function') {
1055
+ await loadFunctionStats();
1056
+ }
1057
+ } else {
1058
+ const updated = await api(`${baseUrl}/${fn.id}`, {
1059
+ method: 'PATCH',
1060
+ headers: { 'Content-Type': 'application/json' },
1061
+ body: JSON.stringify(payload),
1062
+ });
1063
+
1064
+ functionsState.activeFunctionForEdit = updated;
1065
+ const idx = (functionsState.functions || []).findIndex(f => f.id === fn.id);
1066
+ if (idx !== -1) {
1067
+ functionsState.functions[idx] = updated;
1068
+ }
1069
+
1070
+ updateEditorHeaderBadges(updated);
1071
+ toast(`Function '${updated.name}' saved successfully`, 'success');
1072
+ if (typeof loadFunctionStats === 'function') {
1073
+ await loadFunctionStats();
1074
+ }
1075
+ }
1076
+ } catch (err) {
1077
+ toast(err.message || 'Failed to save function', 'error');
1078
+ } finally {
1079
+ if (btn) {
1080
+ btn.disabled = false;
1081
+ const active = functionsState.activeFunctionForEdit;
1082
+ const stillNew = active && active.isNew;
1083
+ btn.innerHTML = stillNew
1084
+ ? `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Create Function</span>`
1085
+ : `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Save Changes</span>`;
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ // ==========================================
1091
+ // 6. Backward Compatibility Shims
1092
+ // ==========================================
1093
+
1094
+ function openCreateFunctionModal() {
1095
+ openCreateFunctionPage();
1096
+ }
1097
+
1098
+ function openEditFunctionModal(id) {
1099
+ openFunctionEditor(id);
1100
+ }
1101
+
1102
+ function openTestFunctionModal(id) {
1103
+ openFunctionEditor(id, true, 'test');
1104
+ }
1105
+
1106
+ function renderFunctionModal(fnData) {
1107
+ openFunctionEditor(fnData?.isNew ? 'new' : (fnData?.id || fnData?.name || 'new'));
1108
+ }
1109
+
1110
+ function closeFunctionModal() {
1111
+ const modalRoot = document.getElementById('modal-root');
1112
+ if (modalRoot) modalRoot.innerHTML = '';
1113
+ }
1114
+
1115
+ async function saveFunctionModal() {
1116
+ return saveFunctionEditor();
1117
+ }
1118
+
1119
+ async function executeFunctionLiveTest() {
1120
+ if (typeof executeFunctionEditorTest === 'function') {
1121
+ return executeFunctionEditorTest();
1122
+ }
1123
+ }
1124
+
1125
+ function toggleCtxReference() {
1126
+ toggleWorkbenchCtxRef();
1127
+ }
1128
+
1129
+ // Global Exports
1130
+ if (typeof window !== 'undefined') {
1131
+ window.CTX_DOCS = CTX_DOCS;
1132
+ window.renderCtxItemsHtml = renderCtxItemsHtml;
1133
+ window.insertFunctionSnippet = insertFunctionSnippet;
1134
+ window.filterCtxCategory = filterCtxCategory;
1135
+ window.filterCtxSearch = filterCtxSearch;
1136
+ window.applyStarterRecipe = applyStarterRecipe;
1137
+ window.toggleWorkbenchCtxRef = toggleWorkbenchCtxRef;
1138
+ window.toggleCtxReference = toggleCtxReference;
1139
+ window.getCodeMirrorTheme = getCodeMirrorTheme;
1140
+ window.initFunctionCodeMirror = initFunctionCodeMirror;
1141
+ window.openCreateFunctionPage = openCreateFunctionPage;
1142
+ window.openFunctionEditor = openFunctionEditor;
1143
+ window.closeFunctionEditor = closeFunctionEditor;
1144
+ window.switchFunctionEditorTab = switchFunctionEditorTab;
1145
+ window.syncEditorFunctionName = syncEditorFunctionName;
1146
+ window.copyFunctionEndpoint = copyFunctionEndpoint;
1147
+ window.updateEditorHeaderBadges = updateEditorHeaderBadges;
1148
+ window.handleFunctionAuthPolicyChange = handleFunctionAuthPolicyChange;
1149
+ window.renderWorkbenchHeader = renderWorkbenchHeader;
1150
+ window.renderWorkbenchTabs = renderWorkbenchTabs;
1151
+ window.renderWorkbenchCodePane = renderWorkbenchCodePane;
1152
+ window.renderWorkbenchConfigPane = renderWorkbenchConfigPane;
1153
+ window.renderFunctionEditorView = renderFunctionEditorView;
1154
+ window.saveFunctionEditor = saveFunctionEditor;
1155
+ window.openCreateFunctionModal = openCreateFunctionModal;
1156
+ window.openEditFunctionModal = openEditFunctionModal;
1157
+ window.openTestFunctionModal = openTestFunctionModal;
1158
+ window.renderFunctionModal = renderFunctionModal;
1159
+ window.closeFunctionModal = closeFunctionModal;
1160
+ window.saveFunctionModal = saveFunctionModal;
1161
+ window.executeFunctionLiveTest = executeFunctionLiveTest;
1162
+ }