@nodestackapp/server 0.0.0-stage → 2.0.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 (361) hide show
  1. package/LICENSE +36 -0
  2. package/README.md +182 -3
  3. package/bin/nodebase.js +4 -0
  4. package/bin/nodestack.js +21 -0
  5. package/dist/NodeBase.d.ts +2 -0
  6. package/dist/NodeBase.d.ts.map +1 -0
  7. package/dist/NodeBase.js +8 -0
  8. package/dist/NodeBase.js.map +1 -0
  9. package/dist/NodeStack.d.ts +111 -0
  10. package/dist/NodeStack.d.ts.map +1 -0
  11. package/dist/NodeStack.js +316 -0
  12. package/dist/NodeStack.js.map +1 -0
  13. package/dist/admin/AdminUIBundler.d.ts +8 -0
  14. package/dist/admin/AdminUIBundler.d.ts.map +1 -0
  15. package/dist/admin/AdminUIBundler.js +104 -0
  16. package/dist/admin/AdminUIBundler.js.map +1 -0
  17. package/dist/admin/AdminUIService.d.ts +30 -0
  18. package/dist/admin/AdminUIService.d.ts.map +1 -0
  19. package/dist/admin/AdminUIService.js +210 -0
  20. package/dist/admin/AdminUIService.js.map +1 -0
  21. package/dist/admin/DocsService.d.ts +29 -0
  22. package/dist/admin/DocsService.d.ts.map +1 -0
  23. package/dist/admin/DocsService.js +564 -0
  24. package/dist/admin/DocsService.js.map +1 -0
  25. package/dist/admin/ui/css/analytics.css +382 -0
  26. package/dist/admin/ui/css/main.css +2189 -0
  27. package/dist/admin/ui/css/rules.css +292 -0
  28. package/dist/admin/ui/css/webhooks.css +360 -0
  29. package/dist/admin/ui/favicon.svg +17 -0
  30. package/dist/admin/ui/icon.svg +17 -0
  31. package/dist/admin/ui/index.html +15168 -0
  32. package/dist/admin/ui/js/analytics.js +673 -0
  33. package/dist/admin/ui/js/api.js +369 -0
  34. package/dist/admin/ui/js/app.js +254 -0
  35. package/dist/admin/ui/js/apps.js +454 -0
  36. package/dist/admin/ui/js/collections.js +435 -0
  37. package/dist/admin/ui/js/command-palette.js +631 -0
  38. package/dist/admin/ui/js/demo.js +661 -0
  39. package/dist/admin/ui/js/modals.js +2379 -0
  40. package/dist/admin/ui/js/plugin-tester.js +559 -0
  41. package/dist/admin/ui/js/plugins.js +778 -0
  42. package/dist/admin/ui/js/records.js +1270 -0
  43. package/dist/admin/ui/js/rules.js +775 -0
  44. package/dist/admin/ui/js/schema.js +290 -0
  45. package/dist/admin/ui/js/state.js +140 -0
  46. package/dist/admin/ui/js/theme.js +120 -0
  47. package/dist/admin/ui/js/views.js +632 -0
  48. package/dist/admin/ui/js/webhooks.js +1104 -0
  49. package/dist/analytics/AnalyticsService.d.ts +62 -0
  50. package/dist/analytics/AnalyticsService.d.ts.map +1 -0
  51. package/dist/analytics/AnalyticsService.js +196 -0
  52. package/dist/analytics/AnalyticsService.js.map +1 -0
  53. package/dist/apps/AppManager.d.ts +28 -0
  54. package/dist/apps/AppManager.d.ts.map +1 -0
  55. package/dist/apps/AppManager.js +211 -0
  56. package/dist/apps/AppManager.js.map +1 -0
  57. package/dist/apps/AppRegistry.d.ts +27 -0
  58. package/dist/apps/AppRegistry.d.ts.map +1 -0
  59. package/dist/apps/AppRegistry.js +220 -0
  60. package/dist/apps/AppRegistry.js.map +1 -0
  61. package/dist/apps/AppScope.d.ts +57 -0
  62. package/dist/apps/AppScope.d.ts.map +1 -0
  63. package/dist/apps/AppScope.js +299 -0
  64. package/dist/apps/AppScope.js.map +1 -0
  65. package/dist/apps/index.d.ts +5 -0
  66. package/dist/apps/index.d.ts.map +1 -0
  67. package/dist/apps/index.js +21 -0
  68. package/dist/apps/index.js.map +1 -0
  69. package/dist/apps/models/App.d.ts +29 -0
  70. package/dist/apps/models/App.d.ts.map +1 -0
  71. package/dist/apps/models/App.js +3 -0
  72. package/dist/apps/models/App.js.map +1 -0
  73. package/dist/audit/AuditLogService.d.ts +68 -0
  74. package/dist/audit/AuditLogService.d.ts.map +1 -0
  75. package/dist/audit/AuditLogService.js +243 -0
  76. package/dist/audit/AuditLogService.js.map +1 -0
  77. package/dist/auth/AuthService.d.ts +35 -0
  78. package/dist/auth/AuthService.d.ts.map +1 -0
  79. package/dist/auth/AuthService.js +303 -0
  80. package/dist/auth/AuthService.js.map +1 -0
  81. package/dist/cli/cli.d.ts +3 -0
  82. package/dist/cli/cli.d.ts.map +1 -0
  83. package/dist/cli/cli.js +541 -0
  84. package/dist/cli/cli.js.map +1 -0
  85. package/dist/core/config/ConfigService.d.ts +42 -0
  86. package/dist/core/config/ConfigService.d.ts.map +1 -0
  87. package/dist/core/config/ConfigService.js +142 -0
  88. package/dist/core/config/ConfigService.js.map +1 -0
  89. package/dist/core/config/EnvLoader.d.ts +7 -0
  90. package/dist/core/config/EnvLoader.d.ts.map +1 -0
  91. package/dist/core/config/EnvLoader.js +84 -0
  92. package/dist/core/config/EnvLoader.js.map +1 -0
  93. package/dist/core/container/Container.d.ts +34 -0
  94. package/dist/core/container/Container.d.ts.map +1 -0
  95. package/dist/core/container/Container.js +98 -0
  96. package/dist/core/container/Container.js.map +1 -0
  97. package/dist/core/container/Tokens.d.ts +42 -0
  98. package/dist/core/container/Tokens.d.ts.map +1 -0
  99. package/dist/core/container/Tokens.js +42 -0
  100. package/dist/core/container/Tokens.js.map +1 -0
  101. package/dist/core/errors/AppError.d.ts +24 -0
  102. package/dist/core/errors/AppError.d.ts.map +1 -0
  103. package/dist/core/errors/AppError.js +52 -0
  104. package/dist/core/errors/AppError.js.map +1 -0
  105. package/dist/core/events/EventBus.d.ts +45 -0
  106. package/dist/core/events/EventBus.d.ts.map +1 -0
  107. package/dist/core/events/EventBus.js +360 -0
  108. package/dist/core/events/EventBus.js.map +1 -0
  109. package/dist/core/events/types.d.ts +35 -0
  110. package/dist/core/events/types.d.ts.map +1 -0
  111. package/dist/core/events/types.js +3 -0
  112. package/dist/core/events/types.js.map +1 -0
  113. package/dist/core/maintenance/MaintenanceGate.d.ts +65 -0
  114. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -0
  115. package/dist/core/maintenance/MaintenanceGate.js +162 -0
  116. package/dist/core/maintenance/MaintenanceGate.js.map +1 -0
  117. package/dist/core/plugins/PluginManager.d.ts +150 -0
  118. package/dist/core/plugins/PluginManager.d.ts.map +1 -0
  119. package/dist/core/plugins/PluginManager.js +1592 -0
  120. package/dist/core/plugins/PluginManager.js.map +1 -0
  121. package/dist/core/plugins/types.d.ts +170 -0
  122. package/dist/core/plugins/types.d.ts.map +1 -0
  123. package/dist/core/plugins/types.js +3 -0
  124. package/dist/core/plugins/types.js.map +1 -0
  125. package/dist/database/DatabaseService.d.ts +27 -0
  126. package/dist/database/DatabaseService.d.ts.map +1 -0
  127. package/dist/database/DatabaseService.js +97 -0
  128. package/dist/database/DatabaseService.js.map +1 -0
  129. package/dist/database/drivers/IDatabaseDriver.d.ts +17 -0
  130. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -0
  131. package/dist/database/drivers/IDatabaseDriver.js +3 -0
  132. package/dist/database/drivers/IDatabaseDriver.js.map +1 -0
  133. package/dist/database/drivers/NodeSqliteDriver.d.ts +16 -0
  134. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -0
  135. package/dist/database/drivers/NodeSqliteDriver.js +115 -0
  136. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -0
  137. package/dist/database/migrations/SystemMigrations.d.ts +5 -0
  138. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -0
  139. package/dist/database/migrations/SystemMigrations.js +164 -0
  140. package/dist/database/migrations/SystemMigrations.js.map +1 -0
  141. package/dist/demo/DemoService.d.ts +27 -0
  142. package/dist/demo/DemoService.d.ts.map +1 -0
  143. package/dist/demo/DemoService.js +22 -0
  144. package/dist/demo/DemoService.js.map +1 -0
  145. package/dist/files/FileStorageService.d.ts +35 -0
  146. package/dist/files/FileStorageService.d.ts.map +1 -0
  147. package/dist/files/FileStorageService.js +126 -0
  148. package/dist/files/FileStorageService.js.map +1 -0
  149. package/dist/http/HttpServer.d.ts +63 -0
  150. package/dist/http/HttpServer.d.ts.map +1 -0
  151. package/dist/http/HttpServer.js +513 -0
  152. package/dist/http/HttpServer.js.map +1 -0
  153. package/dist/http/controllers/AnalyticsController.d.ts +9 -0
  154. package/dist/http/controllers/AnalyticsController.d.ts.map +1 -0
  155. package/dist/http/controllers/AnalyticsController.js +18 -0
  156. package/dist/http/controllers/AnalyticsController.js.map +1 -0
  157. package/dist/http/controllers/AppController.d.ts +29 -0
  158. package/dist/http/controllers/AppController.d.ts.map +1 -0
  159. package/dist/http/controllers/AppController.js +36 -0
  160. package/dist/http/controllers/AppController.js.map +1 -0
  161. package/dist/http/controllers/AuditLogController.d.ts +26 -0
  162. package/dist/http/controllers/AuditLogController.d.ts.map +1 -0
  163. package/dist/http/controllers/AuditLogController.js +32 -0
  164. package/dist/http/controllers/AuditLogController.js.map +1 -0
  165. package/dist/http/controllers/AuthController.d.ts +18 -0
  166. package/dist/http/controllers/AuthController.d.ts.map +1 -0
  167. package/dist/http/controllers/AuthController.js +84 -0
  168. package/dist/http/controllers/AuthController.js.map +1 -0
  169. package/dist/http/controllers/BaseController.d.ts +7 -0
  170. package/dist/http/controllers/BaseController.d.ts.map +1 -0
  171. package/dist/http/controllers/BaseController.js +20 -0
  172. package/dist/http/controllers/BaseController.js.map +1 -0
  173. package/dist/http/controllers/CollectionController.d.ts +44 -0
  174. package/dist/http/controllers/CollectionController.d.ts.map +1 -0
  175. package/dist/http/controllers/CollectionController.js +89 -0
  176. package/dist/http/controllers/CollectionController.js.map +1 -0
  177. package/dist/http/controllers/DemoController.d.ts +34 -0
  178. package/dist/http/controllers/DemoController.d.ts.map +1 -0
  179. package/dist/http/controllers/DemoController.js +56 -0
  180. package/dist/http/controllers/DemoController.js.map +1 -0
  181. package/dist/http/controllers/FileController.d.ts +29 -0
  182. package/dist/http/controllers/FileController.d.ts.map +1 -0
  183. package/dist/http/controllers/FileController.js +172 -0
  184. package/dist/http/controllers/FileController.js.map +1 -0
  185. package/dist/http/controllers/HealthController.d.ts +10 -0
  186. package/dist/http/controllers/HealthController.d.ts.map +1 -0
  187. package/dist/http/controllers/HealthController.js +28 -0
  188. package/dist/http/controllers/HealthController.js.map +1 -0
  189. package/dist/http/controllers/LogController.d.ts +15 -0
  190. package/dist/http/controllers/LogController.d.ts.map +1 -0
  191. package/dist/http/controllers/LogController.js +25 -0
  192. package/dist/http/controllers/LogController.js.map +1 -0
  193. package/dist/http/controllers/RealtimeController.d.ts +13 -0
  194. package/dist/http/controllers/RealtimeController.d.ts.map +1 -0
  195. package/dist/http/controllers/RealtimeController.js +54 -0
  196. package/dist/http/controllers/RealtimeController.js.map +1 -0
  197. package/dist/http/controllers/RecordController.d.ts +74 -0
  198. package/dist/http/controllers/RecordController.d.ts.map +1 -0
  199. package/dist/http/controllers/RecordController.js +202 -0
  200. package/dist/http/controllers/RecordController.js.map +1 -0
  201. package/dist/http/controllers/SnapshotController.d.ts +58 -0
  202. package/dist/http/controllers/SnapshotController.d.ts.map +1 -0
  203. package/dist/http/controllers/SnapshotController.js +79 -0
  204. package/dist/http/controllers/SnapshotController.js.map +1 -0
  205. package/dist/http/controllers/TemplateController.d.ts +29 -0
  206. package/dist/http/controllers/TemplateController.d.ts.map +1 -0
  207. package/dist/http/controllers/TemplateController.js +63 -0
  208. package/dist/http/controllers/TemplateController.js.map +1 -0
  209. package/dist/http/controllers/WebhookController.d.ts +78 -0
  210. package/dist/http/controllers/WebhookController.d.ts.map +1 -0
  211. package/dist/http/controllers/WebhookController.js +113 -0
  212. package/dist/http/controllers/WebhookController.js.map +1 -0
  213. package/dist/http/middleware/AppResolutionMiddleware.d.ts +8 -0
  214. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -0
  215. package/dist/http/middleware/AppResolutionMiddleware.js +98 -0
  216. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -0
  217. package/dist/http/middleware/AuthMiddleware.d.ts +17 -0
  218. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -0
  219. package/dist/http/middleware/AuthMiddleware.js +97 -0
  220. package/dist/http/middleware/AuthMiddleware.js.map +1 -0
  221. package/dist/http/middleware/ChaosMiddleware.d.ts +130 -0
  222. package/dist/http/middleware/ChaosMiddleware.d.ts.map +1 -0
  223. package/dist/http/middleware/ChaosMiddleware.js +434 -0
  224. package/dist/http/middleware/ChaosMiddleware.js.map +1 -0
  225. package/dist/index.d.ts +55 -0
  226. package/dist/index.d.ts.map +1 -0
  227. package/dist/index.js +147 -0
  228. package/dist/index.js.map +1 -0
  229. package/dist/logger/LogService.d.ts +31 -0
  230. package/dist/logger/LogService.d.ts.map +1 -0
  231. package/dist/logger/LogService.js +104 -0
  232. package/dist/logger/LogService.js.map +1 -0
  233. package/dist/plugins/algolia.d.ts +76 -0
  234. package/dist/plugins/algolia.d.ts.map +1 -0
  235. package/dist/plugins/algolia.js +532 -0
  236. package/dist/plugins/algolia.js.map +1 -0
  237. package/dist/plugins/index.d.ts +6 -0
  238. package/dist/plugins/index.d.ts.map +1 -0
  239. package/dist/plugins/index.js +22 -0
  240. package/dist/plugins/index.js.map +1 -0
  241. package/dist/plugins/resend.d.ts +42 -0
  242. package/dist/plugins/resend.d.ts.map +1 -0
  243. package/dist/plugins/resend.js +335 -0
  244. package/dist/plugins/resend.js.map +1 -0
  245. package/dist/plugins/s3.d.ts +35 -0
  246. package/dist/plugins/s3.d.ts.map +1 -0
  247. package/dist/plugins/s3.js +425 -0
  248. package/dist/plugins/s3.js.map +1 -0
  249. package/dist/plugins/stripe.d.ts +45 -0
  250. package/dist/plugins/stripe.d.ts.map +1 -0
  251. package/dist/plugins/stripe.js +470 -0
  252. package/dist/plugins/stripe.js.map +1 -0
  253. package/dist/plugins/webhooks.d.ts +35 -0
  254. package/dist/plugins/webhooks.d.ts.map +1 -0
  255. package/dist/plugins/webhooks.js +415 -0
  256. package/dist/plugins/webhooks.js.map +1 -0
  257. package/dist/realtime/RealtimeService.d.ts +26 -0
  258. package/dist/realtime/RealtimeService.d.ts.map +1 -0
  259. package/dist/realtime/RealtimeService.js +165 -0
  260. package/dist/realtime/RealtimeService.js.map +1 -0
  261. package/dist/records/CsvHelper.d.ts +27 -0
  262. package/dist/records/CsvHelper.d.ts.map +1 -0
  263. package/dist/records/CsvHelper.js +195 -0
  264. package/dist/records/CsvHelper.js.map +1 -0
  265. package/dist/records/FakerEngine.d.ts +73 -0
  266. package/dist/records/FakerEngine.d.ts.map +1 -0
  267. package/dist/records/FakerEngine.js +644 -0
  268. package/dist/records/FakerEngine.js.map +1 -0
  269. package/dist/records/FilterCodec.d.ts +22 -0
  270. package/dist/records/FilterCodec.d.ts.map +1 -0
  271. package/dist/records/FilterCodec.js +57 -0
  272. package/dist/records/FilterCodec.js.map +1 -0
  273. package/dist/records/FtsService.d.ts +63 -0
  274. package/dist/records/FtsService.d.ts.map +1 -0
  275. package/dist/records/FtsService.js +310 -0
  276. package/dist/records/FtsService.js.map +1 -0
  277. package/dist/records/MockDataService.d.ts +31 -0
  278. package/dist/records/MockDataService.d.ts.map +1 -0
  279. package/dist/records/MockDataService.js +222 -0
  280. package/dist/records/MockDataService.js.map +1 -0
  281. package/dist/records/QueryFilterParser.d.ts +35 -0
  282. package/dist/records/QueryFilterParser.d.ts.map +1 -0
  283. package/dist/records/QueryFilterParser.js +263 -0
  284. package/dist/records/QueryFilterParser.js.map +1 -0
  285. package/dist/records/RecordService.d.ts +77 -0
  286. package/dist/records/RecordService.d.ts.map +1 -0
  287. package/dist/records/RecordService.js +704 -0
  288. package/dist/records/RecordService.js.map +1 -0
  289. package/dist/rules/RuleBuilder.d.ts +72 -0
  290. package/dist/rules/RuleBuilder.d.ts.map +1 -0
  291. package/dist/rules/RuleBuilder.js +383 -0
  292. package/dist/rules/RuleBuilder.js.map +1 -0
  293. package/dist/rules/RuleEngine.d.ts +42 -0
  294. package/dist/rules/RuleEngine.d.ts.map +1 -0
  295. package/dist/rules/RuleEngine.js +347 -0
  296. package/dist/rules/RuleEngine.js.map +1 -0
  297. package/dist/schema/OpenApiGenerator.d.ts +32 -0
  298. package/dist/schema/OpenApiGenerator.d.ts.map +1 -0
  299. package/dist/schema/OpenApiGenerator.js +1836 -0
  300. package/dist/schema/OpenApiGenerator.js.map +1 -0
  301. package/dist/schema/SchemaInferenceService.d.ts +82 -0
  302. package/dist/schema/SchemaInferenceService.d.ts.map +1 -0
  303. package/dist/schema/SchemaInferenceService.js +622 -0
  304. package/dist/schema/SchemaInferenceService.js.map +1 -0
  305. package/dist/schema/SchemaService.d.ts +33 -0
  306. package/dist/schema/SchemaService.d.ts.map +1 -0
  307. package/dist/schema/SchemaService.js +338 -0
  308. package/dist/schema/SchemaService.js.map +1 -0
  309. package/dist/schema/TypeGenerator.d.ts +19 -0
  310. package/dist/schema/TypeGenerator.d.ts.map +1 -0
  311. package/dist/schema/TypeGenerator.js +173 -0
  312. package/dist/schema/TypeGenerator.js.map +1 -0
  313. package/dist/schema/models/Collection.d.ts +44 -0
  314. package/dist/schema/models/Collection.d.ts.map +1 -0
  315. package/dist/schema/models/Collection.js +3 -0
  316. package/dist/schema/models/Collection.js.map +1 -0
  317. package/dist/schema/models/Field.d.ts +25 -0
  318. package/dist/schema/models/Field.d.ts.map +1 -0
  319. package/dist/schema/models/Field.js +3 -0
  320. package/dist/schema/models/Field.js.map +1 -0
  321. package/dist/snapshots/SnapshotService.d.ts +75 -0
  322. package/dist/snapshots/SnapshotService.d.ts.map +1 -0
  323. package/dist/snapshots/SnapshotService.js +775 -0
  324. package/dist/snapshots/SnapshotService.js.map +1 -0
  325. package/dist/snapshots/types.d.ts +63 -0
  326. package/dist/snapshots/types.d.ts.map +1 -0
  327. package/dist/snapshots/types.js +5 -0
  328. package/dist/snapshots/types.js.map +1 -0
  329. package/dist/templates/TemplateImageGenerator.d.ts +43 -0
  330. package/dist/templates/TemplateImageGenerator.d.ts.map +1 -0
  331. package/dist/templates/TemplateImageGenerator.js +350 -0
  332. package/dist/templates/TemplateImageGenerator.js.map +1 -0
  333. package/dist/templates/TemplateService.d.ts +31 -0
  334. package/dist/templates/TemplateService.d.ts.map +1 -0
  335. package/dist/templates/TemplateService.js +209 -0
  336. package/dist/templates/TemplateService.js.map +1 -0
  337. package/dist/templates/definitions/blog.d.ts +3 -0
  338. package/dist/templates/definitions/blog.d.ts.map +1 -0
  339. package/dist/templates/definitions/blog.js +386 -0
  340. package/dist/templates/definitions/blog.js.map +1 -0
  341. package/dist/templates/definitions/crm.d.ts +3 -0
  342. package/dist/templates/definitions/crm.d.ts.map +1 -0
  343. package/dist/templates/definitions/crm.js +456 -0
  344. package/dist/templates/definitions/crm.js.map +1 -0
  345. package/dist/templates/definitions/ecommerce.d.ts +3 -0
  346. package/dist/templates/definitions/ecommerce.d.ts.map +1 -0
  347. package/dist/templates/definitions/ecommerce.js +781 -0
  348. package/dist/templates/definitions/ecommerce.js.map +1 -0
  349. package/dist/templates/definitions/index.d.ts +7 -0
  350. package/dist/templates/definitions/index.d.ts.map +1 -0
  351. package/dist/templates/definitions/index.js +15 -0
  352. package/dist/templates/definitions/index.js.map +1 -0
  353. package/dist/templates/types.d.ts +65 -0
  354. package/dist/templates/types.d.ts.map +1 -0
  355. package/dist/templates/types.js +3 -0
  356. package/dist/templates/types.js.map +1 -0
  357. package/dist/webhooks/WebhookService.d.ts +149 -0
  358. package/dist/webhooks/WebhookService.d.ts.map +1 -0
  359. package/dist/webhooks/WebhookService.js +781 -0
  360. package/dist/webhooks/WebhookService.js.map +1 -0
  361. package/package.json +88 -6
@@ -0,0 +1,2379 @@
1
+ // Modals & Data Import Wizard
2
+ function closeModal() {
3
+ const modalRoot = document.getElementById('modal-root');
4
+ if (modalRoot) {
5
+ modalRoot.innerHTML = '';
6
+ }
7
+ }
8
+
9
+ // ==========================================
10
+ // Form & Modal Micro-Interactions Helpers
11
+ // ==========================================
12
+
13
+ // Interactive Toggle Switch Helper (iOS/macOS Style)
14
+ function handleToggleChange(inputEl, labelId) {
15
+ if (!inputEl) return;
16
+ const isChecked = Boolean(inputEl.checked);
17
+ inputEl.setAttribute('aria-checked', isChecked ? 'true' : 'false');
18
+ inputEl.value = isChecked ? 'true' : 'false';
19
+ if (labelId) {
20
+ const lbl = document.getElementById(labelId);
21
+ if (lbl) {
22
+ lbl.textContent = isChecked ? 'True' : 'False';
23
+ }
24
+ }
25
+ }
26
+
27
+ // JSON Editing: Real-time Syntax Validation
28
+ function validateJsonField(el) {
29
+ if (typeof el === 'string') el = document.getElementById(el);
30
+ if (!el) return true;
31
+
32
+ const errorId = el.id ? `${el.id}-error` : null;
33
+ let errorEl = errorId ? document.getElementById(errorId) : null;
34
+ const raw = el.value.trim();
35
+
36
+ if (!raw) {
37
+ el.classList.remove('input-invalid');
38
+ el.classList.remove('input-valid');
39
+ el.style.borderColor = '';
40
+ el.style.boxShadow = '';
41
+ if (errorEl) {
42
+ errorEl.textContent = '';
43
+ errorEl.style.display = 'none';
44
+ }
45
+ return true;
46
+ }
47
+
48
+ try {
49
+ JSON.parse(raw);
50
+ el.classList.remove('input-invalid');
51
+ el.classList.add('input-valid');
52
+ el.style.borderColor = 'var(--accent-success, #10b981)';
53
+ el.style.boxShadow = '';
54
+ if (errorEl) {
55
+ errorEl.textContent = '';
56
+ errorEl.style.display = 'none';
57
+ }
58
+ return true;
59
+ } catch (err) {
60
+ el.classList.remove('input-valid');
61
+ el.classList.add('input-invalid');
62
+ el.style.borderColor = 'var(--accent-danger, #ef4444)';
63
+ el.style.boxShadow = '0 0 0 1px var(--accent-danger, #ef4444)';
64
+ if (errorEl) {
65
+ errorEl.textContent = 'Invalid JSON: ' + err.message;
66
+ errorEl.style.display = 'block';
67
+ }
68
+ return false;
69
+ }
70
+ }
71
+
72
+ // JSON Editing: Format / Prettify
73
+ function formatJsonField(fieldId) {
74
+ const el = typeof fieldId === 'string' ? document.getElementById(fieldId) : fieldId;
75
+ if (!el) return;
76
+ const raw = el.value.trim();
77
+ if (!raw) return;
78
+
79
+ try {
80
+ const parsed = JSON.parse(raw);
81
+ el.value = JSON.stringify(parsed, null, 2);
82
+ validateJsonField(el);
83
+ if (typeof toast === 'function') {
84
+ toast('JSON formatted successfully', 'success');
85
+ }
86
+ } catch (err) {
87
+ validateJsonField(el);
88
+ if (typeof toast === 'function') {
89
+ toast('Invalid JSON: ' + err.message, 'error');
90
+ }
91
+ }
92
+ }
93
+
94
+ // Format ISO / Timestamp values for <input type="datetime-local">
95
+ function formatForDatetimeLocal(val) {
96
+ if (!val) return '';
97
+ try {
98
+ const d = new Date(val);
99
+ if (isNaN(d.getTime())) {
100
+ if (typeof val === 'string') return val.replace(' ', 'T').slice(0, 16);
101
+ return '';
102
+ }
103
+ const pad = (n) => String(n).padStart(2, '0');
104
+ const yyyy = d.getFullYear();
105
+ const mm = pad(d.getMonth() + 1);
106
+ const dd = pad(d.getDate());
107
+ const hh = pad(d.getHours());
108
+ const min = pad(d.getMinutes());
109
+ return `${yyyy}-${mm}-${dd}T${hh}:${min}`;
110
+ } catch {
111
+ return '';
112
+ }
113
+ }
114
+
115
+ // Keyboard Ergonomics: Autofocus first editable field
116
+ function focusFirstModalField(container) {
117
+ const root = container || document.getElementById('modal-root');
118
+ if (!root) return;
119
+
120
+ const findAndFocus = () => {
121
+ const candidates = root.querySelectorAll(
122
+ 'input:not([type="hidden"]):not([disabled]):not([readonly]), ' +
123
+ 'textarea:not([disabled]):not([readonly]), ' +
124
+ 'select:not([disabled]):not([readonly])'
125
+ );
126
+
127
+ for (const el of candidates) {
128
+ const style = typeof window !== 'undefined' && window.getComputedStyle ? window.getComputedStyle(el) : null;
129
+ if (style && (style.display === 'none' || style.visibility === 'hidden')) {
130
+ continue;
131
+ }
132
+ if (typeof el.focus === 'function') {
133
+ el.focus();
134
+ return el;
135
+ }
136
+ }
137
+
138
+ if (candidates.length > 0 && typeof candidates[0].focus === 'function') {
139
+ candidates[0].focus();
140
+ return candidates[0];
141
+ }
142
+ };
143
+
144
+ findAndFocus();
145
+ if (typeof requestAnimationFrame !== 'undefined') {
146
+ requestAnimationFrame(findAndFocus);
147
+ } else if (typeof setTimeout !== 'undefined') {
148
+ setTimeout(findAndFocus, 20);
149
+ }
150
+ }
151
+
152
+ // Keyboard Ergonomics: Submit active modal form
153
+ function submitActiveModal() {
154
+ const modalRoot = document.getElementById('modal-root');
155
+ if (!modalRoot || modalRoot.children.length === 0 || !modalRoot.innerHTML.trim()) return;
156
+
157
+ // Real-time pre-submission check: if active modal has JSON fields, validate syntax
158
+ const jsonFields = modalRoot.querySelectorAll('.json-textarea, textarea[id^="field-"]');
159
+ for (const jf of jsonFields) {
160
+ if (!validateJsonField(jf)) {
161
+ jf.focus();
162
+ if (typeof toast === 'function') {
163
+ toast('Please fix invalid JSON syntax before submitting', 'error');
164
+ }
165
+ return;
166
+ }
167
+ }
168
+
169
+ // Restrict submission to explicit submit controls or footer action buttons
170
+ // to prevent ambiguous modals (e.g. templates gallery) from triggering arbitrary body buttons
171
+ const submitBtn = modalRoot.querySelector(
172
+ '.modal-footer button[type="submit"]:not([disabled]), ' +
173
+ '.modal-footer .btn-primary:not([disabled]), ' +
174
+ '.modal-footer .btn-danger:not([disabled]), ' +
175
+ 'form button[type="submit"]:not([disabled]), ' +
176
+ 'form input[type="submit"]:not([disabled])'
177
+ );
178
+
179
+ if (submitBtn) {
180
+ submitBtn.click();
181
+ return;
182
+ }
183
+
184
+ const form = modalRoot.querySelector('form');
185
+ if (form) {
186
+ if (typeof form.requestSubmit === 'function') {
187
+ form.requestSubmit();
188
+ } else {
189
+ form.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
190
+ }
191
+ }
192
+ }
193
+
194
+ // Keyboard Ergonomics: Global Escape & Ctrl+Enter / Cmd+Enter keydown handler
195
+ function handleModalKeyDown(e) {
196
+ const modalRoot = document.getElementById('modal-root');
197
+ const hasModal = modalRoot && modalRoot.children.length > 0 && modalRoot.innerHTML.trim().length > 0;
198
+ if (!hasModal) return;
199
+
200
+ if (e.key === 'Escape') {
201
+ e.preventDefault();
202
+ e.stopPropagation();
203
+ closeModal();
204
+ return;
205
+ }
206
+
207
+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
208
+ e.preventDefault();
209
+ e.stopPropagation();
210
+ submitActiveModal();
211
+ return;
212
+ }
213
+
214
+ if (e.key === 'Enter') {
215
+ const target = e.target;
216
+ if (target && target.tagName === 'INPUT' && target.type !== 'checkbox' && target.type !== 'radio' && target.type !== 'button' && target.type !== 'submit') {
217
+ e.preventDefault();
218
+ submitActiveModal();
219
+ return;
220
+ }
221
+ }
222
+ }
223
+
224
+ if (typeof window !== 'undefined') {
225
+ window.removeEventListener('keydown', handleModalKeyDown);
226
+ window.addEventListener('keydown', handleModalKeyDown);
227
+ }
228
+
229
+ // Export Handler
230
+
231
+ function openNewRecordModal() {
232
+ if (typeof closeRecordDrawer === 'function') closeRecordDrawer();
233
+ const col = state.activeCollection;
234
+ const modal = document.getElementById('modal-root');
235
+ modal.innerHTML = `
236
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
237
+ <div class="modal">
238
+ <div class="modal-header">
239
+ <h2 class="modal-title">Create Record — ${col.name}</h2>
240
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
241
+ </div>
242
+ <div class="modal-body">
243
+ ${col.type === 'auth' ? `
244
+ <div class="form-group">
245
+ <label class="form-label">Email *</label>
246
+ <input type="email" class="form-input" id="field-email" required>
247
+ </div>
248
+ <div class="form-group">
249
+ <label class="form-label">Password * (min 8 chars)</label>
250
+ <input type="password" class="form-input" id="field-password" required>
251
+ </div>
252
+ ` : ''}
253
+ ${col.schema.map(f => `
254
+ <div class="form-group">
255
+ ${f.type === 'json' ? `
256
+ <div class="json-field-container">
257
+ <div class="json-field-header">
258
+ <label class="form-label" style="margin:0;">${f.name} (${f.type}) ${f.required ? '*' : ''}</label>
259
+ <button type="button" class="btn btn-secondary btn-sm btn-format-json" style="font-size:11px; padding:2px 8px; line-height:1.4;" onclick="formatJsonField('field-${f.name}')" title="Format / Prettify JSON syntax">Format / Prettify</button>
260
+ </div>
261
+ <textarea class="form-textarea json-textarea" id="field-${f.name}" placeholder="{}" oninput="validateJsonField(this)" onblur="validateJsonField(this)"></textarea>
262
+ <div id="field-${f.name}-error" class="json-syntax-error" style="display:none;"></div>
263
+ </div>
264
+ ` : `
265
+ <label class="form-label">${f.name} (${f.type}) ${f.required ? '*' : ''}</label>
266
+ ${f.type === 'file' ? `
267
+ <input type="file" class="form-input" id="field-${f.name}" ${f.required ? 'required' : ''}>
268
+ ` : f.type === 'bool' ? `
269
+ <div class="toggle-control-wrapper">
270
+ <label class="toggle-switch" for="field-${f.name}">
271
+ <input type="checkbox" class="toggle-checkbox" id="field-${f.name}" role="switch" aria-checked="false" value="false" onchange="handleToggleChange(this, 'field-${f.name}-label')">
272
+ <span class="toggle-slider"></span>
273
+ <span class="toggle-state-label" id="field-${f.name}-label">False</span>
274
+ </label>
275
+ </div>
276
+ ` : f.type === 'date' ? `
277
+ <input type="datetime-local" class="form-input" id="field-${f.name}" ${f.required ? 'required' : ''}>
278
+ ` : f.type === 'number' ? `
279
+ <input type="number" class="form-input" id="field-${f.name}">
280
+ ` : `
281
+ <input type="text" class="form-input" id="field-${f.name}">
282
+ `}
283
+ `}
284
+ </div>
285
+ `).join('')}
286
+ </div>
287
+ <div class="modal-footer">
288
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
289
+ <button class="btn btn-primary" onclick="submitNewRecord()">Create Record</button>
290
+ </div>
291
+ </div>
292
+ </div>
293
+ `;
294
+ focusFirstModalField(modal);
295
+ }
296
+
297
+ async function submitNewRecord() {
298
+ const col = state.activeCollection;
299
+
300
+ // Real-time pre-submission check: validate JSON fields before submitting
301
+ for (const f of col.schema) {
302
+ if (f.type === 'json') {
303
+ const el = document.getElementById(`field-${f.name}`);
304
+ if (el && !validateJsonField(el)) {
305
+ el.focus();
306
+ toast(`Invalid JSON in field '${f.name}'. Please correct syntax before submitting.`, 'error');
307
+ return;
308
+ }
309
+ }
310
+ }
311
+
312
+ const hasFileInput = col.schema.some(f => f.type === 'file');
313
+
314
+ let body;
315
+ if (hasFileInput) {
316
+ const formData = new FormData();
317
+ if (col.type === 'auth') {
318
+ formData.append('email', document.getElementById('field-email').value);
319
+ formData.append('password', document.getElementById('field-password').value);
320
+ }
321
+
322
+ for (const f of col.schema) {
323
+ const el = document.getElementById(`field-${f.name}`);
324
+ if (!el) continue;
325
+ if (f.type === 'file') {
326
+ if (el.files && el.files[0]) {
327
+ formData.append(f.name, el.files[0]);
328
+ }
329
+ } else if (f.type === 'bool') {
330
+ const isChecked = el.type === 'checkbox' ? el.checked : el.value === 'true';
331
+ formData.append(f.name, isChecked ? 'true' : 'false');
332
+ } else if (f.type === 'date') {
333
+ if (el.value) {
334
+ const parsedDate = new Date(el.value);
335
+ formData.append(f.name, !isNaN(parsedDate.getTime()) ? parsedDate.toISOString() : el.value);
336
+ } else {
337
+ formData.append(f.name, '');
338
+ }
339
+ } else if (f.type === 'number') {
340
+ formData.append(f.name, el.value);
341
+ } else if (f.type === 'json') {
342
+ formData.append(f.name, el.value.trim());
343
+ } else {
344
+ formData.append(f.name, el.value);
345
+ }
346
+ }
347
+ body = formData;
348
+ } else {
349
+ const data = {};
350
+ if (col.type === 'auth') {
351
+ data.email = document.getElementById('field-email').value;
352
+ data.password = document.getElementById('field-password').value;
353
+ }
354
+
355
+ for (const f of col.schema) {
356
+ const el = document.getElementById(`field-${f.name}`);
357
+ if (!el) continue;
358
+ if (f.type === 'bool') {
359
+ const isChecked = el.type === 'checkbox' ? el.checked : el.value === 'true';
360
+ data[f.name] = isChecked;
361
+ } else if (f.type === 'date') {
362
+ if (el.value) {
363
+ const parsedDate = new Date(el.value);
364
+ data[f.name] = !isNaN(parsedDate.getTime()) ? parsedDate.toISOString() : el.value;
365
+ } else {
366
+ data[f.name] = null;
367
+ }
368
+ } else if (f.type === 'number') {
369
+ data[f.name] = el.value !== '' ? Number(el.value) : null;
370
+ } else if (f.type === 'json') {
371
+ if (el.value.trim() !== '') {
372
+ try {
373
+ data[f.name] = JSON.parse(el.value.trim());
374
+ } catch {
375
+ data[f.name] = el.value.trim();
376
+ }
377
+ } else {
378
+ data[f.name] = null;
379
+ }
380
+ } else {
381
+ data[f.name] = el.value;
382
+ }
383
+ }
384
+ body = JSON.stringify(data);
385
+ }
386
+
387
+ try {
388
+ await api(`/api/collections/${col.name}/records`, {
389
+ method: 'POST',
390
+ body,
391
+ });
392
+ toast('Record created successfully!', 'success');
393
+ closeModal();
394
+ loadRecords();
395
+ } catch (e) {
396
+ toast(e.message, 'error');
397
+ }
398
+ }
399
+
400
+ // Edit Record
401
+ function editRecord(id) {
402
+ if (typeof closeRecordDrawer === 'function') closeRecordDrawer();
403
+ const rec = state.records.find(r => r.id === id);
404
+ if (!rec) return;
405
+
406
+ const col = state.activeCollection;
407
+ const modal = document.getElementById('modal-root');
408
+ modal.innerHTML = `
409
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
410
+ <div class="modal">
411
+ <div class="modal-header">
412
+ <h2 class="modal-title">Edit Record — ${id}</h2>
413
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
414
+ </div>
415
+ <div class="modal-body">
416
+ ${col.schema.map(f => `
417
+ <div class="form-group">
418
+ ${f.type === 'json' ? `
419
+ <div class="json-field-container">
420
+ <div class="json-field-header">
421
+ <label class="form-label" style="margin:0;">${f.name} (${f.type})</label>
422
+ <button type="button" class="btn btn-secondary btn-sm btn-format-json" style="font-size:11px; padding:2px 8px; line-height:1.4;" onclick="formatJsonField('field-edit-${f.name}')" title="Format / Prettify JSON syntax">Format / Prettify</button>
423
+ </div>
424
+ <textarea class="form-textarea json-textarea" id="field-edit-${f.name}" oninput="validateJsonField(this)" onblur="validateJsonField(this)">${typeof rec[f.name] === 'object' && rec[f.name] !== null ? JSON.stringify(rec[f.name], null, 2) : rec[f.name] || ''}</textarea>
425
+ <div id="field-edit-${f.name}-error" class="json-syntax-error" style="display:none;"></div>
426
+ </div>
427
+ ` : `
428
+ <label class="form-label">${f.name} (${f.type})</label>
429
+ ${f.type === 'file' ? `
430
+ ${rec[f.name] ? `
431
+ <div style="margin-bottom:6px; display:flex; align-items:center; gap:8px;">
432
+ <span style="font-size:12px; color:var(--text-muted);">Current:</span>
433
+ <a href="${escapeHtml(getRecordFileUrl(col.name, rec.id, rec[f.name]))}" target="_blank" style="color:#60a5fa; font-family:var(--font-mono); font-size:12px; text-decoration:underline;">
434
+ ${escapeHtml(rec[f.name])}
435
+ </a>
436
+ </div>
437
+ ` : ''}
438
+ <input type="file" class="form-input" id="field-edit-${f.name}">
439
+ <small style="color:var(--text-muted); font-size:11px;">Select a file to replace the existing one</small>
440
+ ` : f.type === 'bool' ? `
441
+ <div class="toggle-control-wrapper">
442
+ <label class="toggle-switch" for="field-edit-${f.name}">
443
+ <input type="checkbox" class="toggle-checkbox" id="field-edit-${f.name}" role="switch" aria-checked="${rec[f.name] ? 'true' : 'false'}" value="${rec[f.name] ? 'true' : 'false'}" ${rec[f.name] ? 'checked' : ''} onchange="handleToggleChange(this, 'field-edit-${f.name}-label')">
444
+ <span class="toggle-slider"></span>
445
+ <span class="toggle-state-label" id="field-edit-${f.name}-label">${rec[f.name] ? 'True' : 'False'}</span>
446
+ </label>
447
+ </div>
448
+ ` : f.type === 'date' ? `
449
+ <input type="datetime-local" class="form-input" id="field-edit-${f.name}" value="${formatForDatetimeLocal(rec[f.name])}">
450
+ ` : f.type === 'number' ? `
451
+ <input type="number" class="form-input" id="field-edit-${f.name}" value="${rec[f.name] ?? ''}">
452
+ ` : `
453
+ <input type="text" class="form-input" id="field-edit-${f.name}" value="${rec[f.name] ?? ''}">
454
+ `}
455
+ `}
456
+ </div>
457
+ `).join('')}
458
+ </div>
459
+ <div class="modal-footer">
460
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
461
+ <button class="btn btn-primary" onclick="submitEditRecord('${id}')">Save Changes</button>
462
+ </div>
463
+ </div>
464
+ </div>
465
+ `;
466
+ focusFirstModalField(modal);
467
+ }
468
+
469
+ async function submitEditRecord(id) {
470
+ const col = state.activeCollection;
471
+
472
+ // Real-time pre-submission check: validate JSON fields before submitting
473
+ for (const f of col.schema) {
474
+ if (f.type === 'json') {
475
+ const el = document.getElementById(`field-edit-${f.name}`);
476
+ if (el && !validateJsonField(el)) {
477
+ el.focus();
478
+ toast(`Invalid JSON in field '${f.name}'. Please correct syntax before submitting.`, 'error');
479
+ return;
480
+ }
481
+ }
482
+ }
483
+
484
+ let hasNewFile = false;
485
+ for (const f of col.schema) {
486
+ if (f.type === 'file') {
487
+ const el = document.getElementById(`field-edit-${f.name}`);
488
+ if (el && el.files && el.files[0]) {
489
+ hasNewFile = true;
490
+ break;
491
+ }
492
+ }
493
+ }
494
+
495
+ let body;
496
+ if (hasNewFile) {
497
+ const formData = new FormData();
498
+ for (const f of col.schema) {
499
+ const el = document.getElementById(`field-edit-${f.name}`);
500
+ if (!el) continue;
501
+ if (f.type === 'file') {
502
+ if (el.files && el.files[0]) {
503
+ formData.append(f.name, el.files[0]);
504
+ }
505
+ } else if (f.type === 'bool') {
506
+ const isChecked = el.type === 'checkbox' ? el.checked : el.value === 'true';
507
+ formData.append(f.name, isChecked ? 'true' : 'false');
508
+ } else if (f.type === 'date') {
509
+ if (el.value) {
510
+ const parsedDate = new Date(el.value);
511
+ formData.append(f.name, !isNaN(parsedDate.getTime()) ? parsedDate.toISOString() : el.value);
512
+ } else {
513
+ formData.append(f.name, '');
514
+ }
515
+ } else if (f.type === 'number') {
516
+ formData.append(f.name, el.value);
517
+ } else if (f.type === 'json') {
518
+ formData.append(f.name, el.value.trim());
519
+ } else {
520
+ formData.append(f.name, el.value);
521
+ }
522
+ }
523
+ body = formData;
524
+ } else {
525
+ const data = {};
526
+ for (const f of col.schema) {
527
+ const el = document.getElementById(`field-edit-${f.name}`);
528
+ if (!el) continue;
529
+ if (f.type === 'file') {
530
+ // Keep existing file
531
+ continue;
532
+ }
533
+ if (f.type === 'bool') {
534
+ const isChecked = el.type === 'checkbox' ? el.checked : el.value === 'true';
535
+ data[f.name] = isChecked;
536
+ } else if (f.type === 'date') {
537
+ if (el.value) {
538
+ const parsedDate = new Date(el.value);
539
+ data[f.name] = !isNaN(parsedDate.getTime()) ? parsedDate.toISOString() : el.value;
540
+ } else {
541
+ data[f.name] = null;
542
+ }
543
+ } else if (f.type === 'number') {
544
+ data[f.name] = el.value !== '' ? Number(el.value) : null;
545
+ } else if (f.type === 'json') {
546
+ if (el.value.trim() !== '') {
547
+ try {
548
+ data[f.name] = JSON.parse(el.value.trim());
549
+ } catch {
550
+ data[f.name] = el.value.trim();
551
+ }
552
+ } else {
553
+ data[f.name] = null;
554
+ }
555
+ } else {
556
+ data[f.name] = el.value;
557
+ }
558
+ }
559
+ body = JSON.stringify(data);
560
+ }
561
+
562
+ try {
563
+ await api(`/api/collections/${col.name}/records/${id}`, {
564
+ method: 'PATCH',
565
+ body,
566
+ });
567
+ toast('Record updated successfully!', 'success');
568
+ closeModal();
569
+ loadRecords();
570
+ } catch (e) {
571
+ toast(e.message, 'error');
572
+ }
573
+ }
574
+
575
+ async function deleteRecord(id) {
576
+ if (!confirm(`Are you sure you want to delete record '${id}'?`)) return;
577
+ try {
578
+ await api(`/api/collections/${state.activeCollection.name}/records/${id}`, {
579
+ method: 'DELETE',
580
+ });
581
+ toast('Record deleted!', 'success');
582
+ if (typeof closeRecordDrawer === 'function' && state.selectedRecordId === id) {
583
+ closeRecordDrawer();
584
+ }
585
+ loadRecords();
586
+ } catch (e) {
587
+ toast(e.message, 'error');
588
+ }
589
+ }
590
+
591
+ // New Collection Modal
592
+ function openNewCollectionModal() {
593
+ const modal = document.getElementById('modal-root');
594
+ modal.innerHTML = `
595
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
596
+ <div class="modal">
597
+ <div class="modal-header">
598
+ <h2 class="modal-title">Create Collection</h2>
599
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
600
+ </div>
601
+ <div class="modal-body">
602
+ <div style="background: rgba(59, 130, 246, 0.08); border: 1px solid rgba(59, 130, 246, 0.25); border-radius: 8px; padding: 0.75rem 0.9rem; margin-bottom: 1.25rem;">
603
+ <div style="font-weight: 600; font-size: 11px; color: var(--accent-primary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem;">Or Start Fast With:</div>
604
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
605
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openTemplatesModal()" style="display: flex; align-items: center; justify-content: flex-start; gap: 8px; padding: 7px 10px; border-color: rgba(147, 197, 253, 0.25); text-align: left;">
606
+ <span style="font-size: 16px;">✨</span>
607
+ <div>
608
+ <div style="font-weight: 600; font-size: 12px; color: var(--text-heading);">Starter Templates</div>
609
+ <div style="font-size: 10px; color: var(--text-muted);">E-Commerce, Blog, CRM</div>
610
+ </div>
611
+ </button>
612
+ <button type="button" class="btn btn-secondary btn-sm" onclick="openImportJsonModal()" style="display: flex; align-items: center; justify-content: flex-start; gap: 8px; padding: 7px 10px; border-color: rgba(147, 197, 253, 0.25); text-align: left;">
613
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:#60a5fa;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
614
+ <div>
615
+ <div style="font-weight: 600; font-size: 12px; color: var(--text-heading);">Paste JSON → Instant API</div>
616
+ <div style="font-size: 10px; color: var(--text-muted);">Auto-infer schema in 1 second</div>
617
+ </div>
618
+ </button>
619
+ </div>
620
+ </div>
621
+ <div class="form-group">
622
+ <label class="form-label">Collection Name *</label>
623
+ <input type="text" class="form-input" id="new-col-name" placeholder="e.g. posts, products" required>
624
+ </div>
625
+ <div class="form-group">
626
+ <label class="form-label">Type</label>
627
+ <select class="form-select" id="new-col-type">
628
+ <option value="base">Base Collection</option>
629
+ <option value="auth">Auth Collection (Users, Members)</option>
630
+ </select>
631
+ </div>
632
+ </div>
633
+ <div class="modal-footer">
634
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
635
+ <button class="btn btn-primary" onclick="submitNewCollection()">Create</button>
636
+ </div>
637
+ </div>
638
+ </div>
639
+ `;
640
+ focusFirstModalField(modal);
641
+ }
642
+
643
+ // ==========================================
644
+ // Paste JSON → Instant API (Schema Auto-Inference)
645
+ // ==========================================
646
+
647
+ let importJsonState = {
648
+ parsedRecords: [],
649
+ inferredFields: [],
650
+ suggestedName: '',
651
+ error: null,
652
+ };
653
+
654
+ function isClientDateString(val) {
655
+ if (typeof val !== 'string') return false;
656
+ const str = val.trim();
657
+ if (str.length < 8 || str.length > 35) return false;
658
+ if (/^\d+(\.\d+)?$/.test(str)) return false;
659
+ const dateRegex = /^\d{4}[-/]\d{1,2}[-/]\d{1,2}(?:[T\s]\d{1,2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?)?$/i;
660
+ if (!dateRegex.test(str)) return false;
661
+ return !isNaN(Date.parse(str));
662
+ }
663
+
664
+ function inferFieldTypeClient(values) {
665
+ const nonNull = values.filter((v) => v !== undefined && v !== null && v !== '');
666
+ if (nonNull.length === 0) return 'text';
667
+
668
+ if (nonNull.some((v) => typeof v === 'object')) return 'json';
669
+ if (nonNull.every((v) => typeof v === 'boolean' || v === 'true' || v === 'false')) return 'bool';
670
+ if (
671
+ nonNull.every(
672
+ (v) =>
673
+ typeof v === 'number' ||
674
+ (typeof v === 'string' && /^-?\d+(\.\d+)?$/.test(v.trim()) && !/^0\d+/.test(v.trim()))
675
+ )
676
+ )
677
+ return 'number';
678
+ if (nonNull.every((v) => isClientDateString(v))) return 'date';
679
+ return 'text';
680
+ }
681
+
682
+ function sanitizeFieldNameClient(rawKey) {
683
+ let clean = rawKey
684
+ .trim()
685
+ .replace(/[^a-zA-Z0-9_]/g, '_')
686
+ .replace(/^_+/, '')
687
+ .replace(/_+$/, '');
688
+ if (!clean) clean = 'field';
689
+ if (/^[0-9]/.test(clean)) clean = `f_${clean}`;
690
+ return clean;
691
+ }
692
+
693
+ function openImportJsonModal() {
694
+ const modal = document.getElementById('modal-root');
695
+ modal.innerHTML = `
696
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
697
+ <div class="modal modal-lg" style="max-width: 780px;">
698
+ <div class="modal-header">
699
+ <div style="display:flex; align-items:center; gap:0.6rem;">
700
+ <div style="width:32px; height:32px; border-radius:8px; background:rgba(59,130,246,0.15); display:flex; align-items:center; justify-content:center; color:#60a5fa;"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg></div>
701
+ <div>
702
+ <h2 class="modal-title" style="display:flex; align-items:center; gap:8px;">
703
+ Import from JSON
704
+ <span class="badge badge-get" style="font-size:10px; font-weight:700;">INSTANT API</span>
705
+ </h2>
706
+ <div style="font-size:12px; color:var(--text-muted); margin-top:2px;">
707
+ Paste any raw JSON object or array. Field types & SQLite columns are auto-inferred in 1 second.
708
+ </div>
709
+ </div>
710
+ </div>
711
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
712
+ </div>
713
+
714
+ <div class="modal-body" style="gap:1rem; max-height:75vh; overflow-y:auto;">
715
+ <!-- Collection Name Input -->
716
+ <div class="form-group" style="margin-bottom:0.25rem;">
717
+ <label class="form-label" style="display:flex; justify-content:space-between; align-items:center;">
718
+ <span>Collection Name *</span>
719
+ <span id="name-feedback" style="font-size:11px; color:var(--text-muted);">Will create SQLite table and REST API</span>
720
+ </label>
721
+ <div style="position:relative;">
722
+ <span style="position:absolute; left:12px; top:50%; transform:translateY(-50%); font-size:13px; color:var(--text-muted); font-family:monospace;">/api/collections/</span>
723
+ <input type="text" class="form-input" id="import-json-name" placeholder="products" style="padding-left:145px; font-family:monospace; font-weight:600;" oninput="updateImportJsonPreview()">
724
+ </div>
725
+ </div>
726
+
727
+ <!-- Raw JSON Textarea -->
728
+ <div class="form-group" style="margin-bottom:0.25rem;">
729
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.4rem;">
730
+ <label class="form-label" style="margin:0;">Raw JSON Payload (Object or Array) *</label>
731
+ <div style="display:flex; gap:6px;">
732
+ <button type="button" class="btn btn-secondary btn-sm" style="font-size:11px; padding:2px 8px;" onclick="formatJsonField('import-json-input')" title="Format / Prettify JSON">Format / Prettify</button>
733
+ <button class="btn btn-secondary btn-sm" style="font-size:11px; padding:2px 8px;" onclick="loadSampleJson()" title="Load realistic mock JSON">✨ Load Sample JSON</button>
734
+ <button class="btn btn-secondary btn-sm" style="font-size:11px; padding:2px 8px;" onclick="pasteFromClipboard()" title="Paste from clipboard">📋 Paste</button>
735
+ <button class="btn btn-secondary btn-sm" style="font-size:11px; padding:2px 8px;" onclick="clearJsonInput()">Clear</button>
736
+ </div>
737
+ </div>
738
+ <textarea class="form-textarea" id="import-json-input" placeholder='Paste mock JSON from ChatGPT, Postman, or an API spec:&#10;[&#10; {&#10; "name": "Wireless Headphones",&#10; "price": 149.99,&#10; "inStock": true,&#10; "releasedAt": "2026-03-15T09:30:00Z",&#10; "features": { "bluetooth": 5.3, "anc": true }&#10; }&#10;]' style="min-height:160px; font-family:\x27JetBrains Mono\x27, monospace; font-size:12px; line-height:1.45; tab-size:2;" oninput="onJsonInputChanged()"></textarea>
739
+ </div>
740
+
741
+ <!-- Live Auto-Inference Schema Preview -->
742
+ <div id="import-json-preview-container" style="background:var(--bg-input); border:1px solid var(--border-subtle); border-radius:8px; padding:0.85rem 1rem;">
743
+ <div id="import-json-preview-content">
744
+ <div style="font-size:12px; color:var(--text-muted); display:flex; align-items:center; gap:8px;">
745
+ <span>ℹ</span>
746
+ <span>Paste raw JSON above to preview auto-inferred columns (text, number, bool, date, json).</span>
747
+ </div>
748
+ </div>
749
+ </div>
750
+ </div>
751
+
752
+ <div class="modal-footer" style="display:flex; justify-content:space-between; align-items:center;">
753
+ <div style="font-size:11px; color:var(--text-muted); display:flex; align-items:center; gap:4px;">
754
+ <span class="live-dot" style="width:6px; height:6px;"></span>
755
+ <span>Creates collection, SQLite columns & populates records in 1s</span>
756
+ </div>
757
+ <div style="display:flex; gap:0.5rem;">
758
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
759
+ <button class="btn btn-primary" id="btn-submit-import-json" onclick="submitImportJson()">Create Collection & Import Records</button>
760
+ </div>
761
+ </div>
762
+ </div>
763
+ </div>
764
+ `;
765
+
766
+ // If user had selected text or already typed something, re-trigger
767
+ importJsonState = { parsedRecords: [], inferredFields: [], suggestedName: '', error: null };
768
+ focusFirstModalField(modal);
769
+ }
770
+
771
+ function loadSampleJson() {
772
+ const sample = [
773
+ {
774
+ name: 'Sony WH-1000XM5',
775
+ category: 'Audio',
776
+ price: 348.0,
777
+ inStock: true,
778
+ rating: 4.8,
779
+ releasedAt: '2026-01-20T10:00:00Z',
780
+ specs: { driver: '30mm', batteryHours: 30, anc: true },
781
+ },
782
+ {
783
+ name: 'Apple AirPods Max',
784
+ category: 'Audio',
785
+ price: 549.0,
786
+ inStock: true,
787
+ rating: 4.6,
788
+ releasedAt: '2025-11-15T08:00:00Z',
789
+ specs: { driver: '40mm', batteryHours: 20, anc: true },
790
+ },
791
+ {
792
+ name: 'Bose QuietComfort Ultra',
793
+ category: 'Audio',
794
+ price: 429.0,
795
+ inStock: false,
796
+ rating: 4.7,
797
+ releasedAt: '2026-02-10T12:00:00Z',
798
+ specs: { driver: '35mm', batteryHours: 24, spatialAudio: true },
799
+ },
800
+ ];
801
+
802
+ const nameInput = document.getElementById('import-json-name');
803
+ if (nameInput && !nameInput.value.trim()) {
804
+ nameInput.value = 'products';
805
+ }
806
+ const jsonInput = document.getElementById('import-json-input');
807
+ if (jsonInput) {
808
+ jsonInput.value = JSON.stringify(sample, null, 2);
809
+ onJsonInputChanged();
810
+ }
811
+ }
812
+
813
+ async function pasteFromClipboard() {
814
+ try {
815
+ const text = await navigator.clipboard.readText();
816
+ const jsonInput = document.getElementById('import-json-input');
817
+ if (jsonInput && text) {
818
+ jsonInput.value = text;
819
+ onJsonInputChanged();
820
+ }
821
+ } catch {
822
+ toast('Please paste using Ctrl+V or Cmd+V directly in the textarea', 'info');
823
+ }
824
+ }
825
+
826
+ function clearJsonInput() {
827
+ const jsonInput = document.getElementById('import-json-input');
828
+ if (jsonInput) {
829
+ jsonInput.value = '';
830
+ onJsonInputChanged();
831
+ }
832
+ }
833
+
834
+ function onJsonInputChanged() {
835
+ const jsonInput = document.getElementById('import-json-input');
836
+ const text = jsonInput?.value.trim();
837
+ const previewContainer = document.getElementById('import-json-preview-content');
838
+ const nameInput = document.getElementById('import-json-name');
839
+
840
+ if (!text) {
841
+ if (jsonInput) {
842
+ jsonInput.classList.remove('input-invalid');
843
+ jsonInput.style.borderColor = '';
844
+ jsonInput.style.boxShadow = '';
845
+ }
846
+ importJsonState = { parsedRecords: [], inferredFields: [], suggestedName: '', error: null };
847
+ if (previewContainer) {
848
+ previewContainer.innerHTML = `
849
+ <div style="font-size:12px; color:var(--text-muted); display:flex; align-items:center; gap:8px;">
850
+ <span>ℹ</span>
851
+ <span>Paste raw JSON above to preview auto-inferred columns (text, number, bool, date, json).</span>
852
+ </div>
853
+ `;
854
+ }
855
+ return;
856
+ }
857
+
858
+ try {
859
+ const parsed = JSON.parse(text);
860
+ if (jsonInput) {
861
+ jsonInput.classList.remove('input-invalid');
862
+ jsonInput.style.borderColor = '';
863
+ jsonInput.style.boxShadow = '';
864
+ }
865
+ let records = [];
866
+ let suggestedName = '';
867
+
868
+ if (Array.isArray(parsed)) {
869
+ if (parsed.length === 0) throw new Error('Array must contain at least one item');
870
+ if (typeof parsed[0] !== 'object' || parsed[0] === null || Array.isArray(parsed[0])) {
871
+ throw new Error('Array items must be JSON objects, not primitives');
872
+ }
873
+ records = parsed;
874
+ } else if (typeof parsed === 'object' && parsed !== null) {
875
+ const wrapperCandidates = ['data', 'items', 'records', 'results', 'rows', 'list'];
876
+ for (const cand of wrapperCandidates) {
877
+ if (Array.isArray(parsed[cand]) && parsed[cand].length > 0 && typeof parsed[cand][0] === 'object') {
878
+ records = parsed[cand];
879
+ suggestedName = parsed.collection || parsed.name || '';
880
+ break;
881
+ }
882
+ }
883
+
884
+ if (records.length === 0) {
885
+ const arrayKeys = Object.keys(parsed).filter(
886
+ (k) => Array.isArray(parsed[k]) && parsed[k].length > 0 && typeof parsed[k][0] === 'object'
887
+ );
888
+ if (arrayKeys.length === 1) {
889
+ records = parsed[arrayKeys[0]];
890
+ suggestedName = arrayKeys[0].toLowerCase();
891
+ } else {
892
+ records = [parsed];
893
+ }
894
+ }
895
+ } else {
896
+ throw new Error('JSON payload must be an object or an array of objects');
897
+ }
898
+
899
+ if (suggestedName && nameInput && !nameInput.value.trim()) {
900
+ nameInput.value = suggestedName.replace(/[^a-zA-Z0-9_]/g, '_');
901
+ }
902
+
903
+ const rawKeys = [];
904
+ const seenKeys = new Set();
905
+ for (const rec of records) {
906
+ for (const k of Object.keys(rec)) {
907
+ if (!seenKeys.has(k)) {
908
+ seenKeys.add(k);
909
+ rawKeys.push(k);
910
+ }
911
+ }
912
+ }
913
+
914
+ const inferredFields = [];
915
+ const existingFieldNames = new Set(['id', 'created', 'updated']);
916
+
917
+ for (const k of rawKeys) {
918
+ const lower = k.toLowerCase().trim();
919
+ if (lower === 'id' || lower === 'created' || lower === 'updated') continue;
920
+
921
+ const clean = sanitizeFieldNameClient(k);
922
+ let finalName = clean;
923
+ let counter = 1;
924
+ while (existingFieldNames.has(finalName.toLowerCase())) {
925
+ counter++;
926
+ finalName = `${clean}_${counter}`;
927
+ }
928
+ existingFieldNames.add(finalName.toLowerCase());
929
+
930
+ const vals = [];
931
+ for (const rec of records) {
932
+ if (rec[k] !== undefined) vals.push(rec[k]);
933
+ }
934
+
935
+ const type = inferFieldTypeClient(vals);
936
+ const sampleVal = vals.length > 0 ? vals[0] : null;
937
+
938
+ inferredFields.push({
939
+ name: finalName,
940
+ originalKey: k,
941
+ type: type,
942
+ sample: sampleVal,
943
+ });
944
+ }
945
+
946
+ importJsonState = {
947
+ parsedRecords: records,
948
+ inferredFields: inferredFields,
949
+ suggestedName: suggestedName,
950
+ error: null,
951
+ };
952
+
953
+ renderInferredFieldsPreview();
954
+ } catch (e) {
955
+ if (jsonInput) {
956
+ jsonInput.classList.add('input-invalid');
957
+ jsonInput.style.borderColor = 'var(--accent-danger)';
958
+ jsonInput.style.boxShadow = '0 0 0 1px var(--accent-danger)';
959
+ }
960
+ importJsonState = { parsedRecords: [], inferredFields: [], suggestedName: '', error: e.message };
961
+ if (previewContainer) {
962
+ previewContainer.innerHTML = `
963
+ <div style="font-size:12px; color:var(--accent-danger); display:flex; align-items:center; gap:8px;">
964
+ <span>⚠</span>
965
+ <span>Invalid JSON: ${e.message}</span>
966
+ </div>
967
+ `;
968
+ }
969
+ }
970
+ }
971
+
972
+ function renderInferredFieldsPreview() {
973
+ const previewContainer = document.getElementById('import-json-preview-content');
974
+ if (!previewContainer) return;
975
+
976
+ const { parsedRecords, inferredFields } = importJsonState;
977
+ const colName = document.getElementById('import-json-name')?.value.trim() || 'my_collection';
978
+
979
+ const typeBadges = {
980
+ text: 'background:rgba(59,130,246,0.15); color:#60a5fa; border:1px solid rgba(59,130,246,0.3);',
981
+ number: 'background:rgba(168,85,247,0.15); color:#c084fc; border:1px solid rgba(168,85,247,0.3);',
982
+ bool: 'background:rgba(245,158,11,0.15); color:#fbbf24; border:1px solid rgba(245,158,11,0.3);',
983
+ date: 'background:rgba(16,185,129,0.15); color:#34d399; border:1px solid rgba(16,185,129,0.3);',
984
+ json: 'background:rgba(236,72,153,0.15); color:#f472b6; border:1px solid rgba(236,72,153,0.3);',
985
+ email: 'background:rgba(20,184,166,0.15); color:#2dd4bf; border:1px solid rgba(20,184,166,0.3);',
986
+ url: 'background:rgba(99,102,241,0.15); color:#818cf8; border:1px solid rgba(99,102,241,0.3);',
987
+ };
988
+
989
+ previewContainer.innerHTML = `
990
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem; border-bottom:1px solid var(--border-subtle); padding-bottom:0.5rem;">
991
+ <div style="display:flex; align-items:center; gap:8px;">
992
+ <span style="font-weight:700; font-size:13px; color: var(--text-heading);">✓ ${parsedRecords.length} record${parsedRecords.length === 1 ? '' : 's'} detected</span>
993
+ <span class="badge badge-get" style="font-size:11px;">${inferredFields.length} columns inferred</span>
994
+ </div>
995
+ <span style="font-size:11px; color:var(--text-muted);">Instant SQLite columns</span>
996
+ </div>
997
+
998
+ <div style="display:flex; flex-direction:column; gap:6px; max-height:180px; overflow-y:auto; margin-bottom:0.75rem; padding-right:4px;">
999
+ ${inferredFields.map((f, idx) => `
1000
+ <div style="display:flex; align-items:center; justify-content:space-between; background:var(--bg-card); padding:6px 10px; border-radius:6px; border:1px solid var(--border-subtle); font-size:12px;">
1001
+ <div style="display:flex; align-items:center; gap:8px; min-width:140px;">
1002
+ <span style="font-family:monospace; font-weight:600; color: var(--text-heading);">${f.name}</span>
1003
+ ${f.originalKey !== f.name ? `<span style="font-size:10px; color:var(--text-muted); font-family:monospace;">(from "${f.originalKey}")</span>` : ''}
1004
+ </div>
1005
+ <div style="display:flex; align-items:center; gap:8px;">
1006
+ <select class="form-select" id="field-type-override-${idx}" style="font-size:11px; padding:2px 6px; height:24px; border-radius:4px; font-family:monospace; ${typeBadges[f.type] || ''}" onchange="onFieldTypeOverrideChanged(${idx}, this.value)">
1007
+ <option value="text" ${f.type === 'text' ? 'selected' : ''}>text</option>
1008
+ <option value="number" ${f.type === 'number' ? 'selected' : ''}>number</option>
1009
+ <option value="bool" ${f.type === 'bool' ? 'selected' : ''}>bool</option>
1010
+ <option value="date" ${f.type === 'date' ? 'selected' : ''}>date</option>
1011
+ <option value="json" ${f.type === 'json' ? 'selected' : ''}>json</option>
1012
+ <option value="email" ${f.type === 'email' ? 'selected' : ''}>email</option>
1013
+ <option value="url" ${f.type === 'url' ? 'selected' : ''}>url</option>
1014
+ </select>
1015
+ <span style="color:var(--text-muted); font-size:11px; max-width:180px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-family:monospace;" title='${JSON.stringify(f.sample)}'>
1016
+ ${f.sample !== null && f.sample !== undefined ? (typeof f.sample === 'object' ? JSON.stringify(f.sample) : String(f.sample)) : '<null>'}
1017
+ </span>
1018
+ </div>
1019
+ </div>
1020
+ `).join('')}
1021
+ </div>
1022
+
1023
+ <div style="background:rgba(0,0,0,0.25); border:1px solid rgba(59,130,246,0.2); border-radius:6px; padding:6px 10px; font-size:11px; color:var(--text-muted); display:flex; justify-content:space-between; align-items:center;">
1024
+ <div>
1025
+ <span style="color:#60a5fa; font-weight:600;">REST API ready:</span>
1026
+ <code style="margin-left:6px; color: var(--text-heading);">GET /api/collections/${colName}/records</code>
1027
+ </div>
1028
+ <span style="font-size:10px; color:#34d399;">● Full CRUD + Realtime + Docs</span>
1029
+ </div>
1030
+ `;
1031
+ }
1032
+
1033
+ function onFieldTypeOverrideChanged(idx, newType) {
1034
+ if (importJsonState.inferredFields[idx]) {
1035
+ importJsonState.inferredFields[idx].type = newType;
1036
+ renderInferredFieldsPreview();
1037
+ }
1038
+ }
1039
+
1040
+ function updateImportJsonPreview() {
1041
+ if (importJsonState.parsedRecords.length > 0) {
1042
+ renderInferredFieldsPreview();
1043
+ }
1044
+ }
1045
+
1046
+ async function submitImportJson() {
1047
+ const nameInput = document.getElementById('import-json-name');
1048
+ const jsonInput = document.getElementById('import-json-input');
1049
+ const submitBtn = document.getElementById('btn-submit-import-json');
1050
+
1051
+ const name = nameInput ? nameInput.value.trim() : '';
1052
+ if (!name) {
1053
+ toast('Please enter a collection name', 'error');
1054
+ nameInput?.focus();
1055
+ return;
1056
+ }
1057
+
1058
+ if (!/^[a-zA-Z0-9_]+$/.test(name)) {
1059
+ toast('Collection name must only contain alphanumeric characters and underscores', 'error');
1060
+ nameInput?.focus();
1061
+ return;
1062
+ }
1063
+
1064
+ const text = jsonInput ? jsonInput.value.trim() : '';
1065
+ if (!text) {
1066
+ toast('Please paste raw JSON payload', 'error');
1067
+ jsonInput?.focus();
1068
+ return;
1069
+ }
1070
+
1071
+ if (submitBtn) {
1072
+ submitBtn.disabled = true;
1073
+ submitBtn.textContent = 'Creating API...';
1074
+ }
1075
+
1076
+ try {
1077
+ const schemaOverrides = (importJsonState.inferredFields || []).map((f) => ({
1078
+ name: f.name,
1079
+ type: f.type,
1080
+ }));
1081
+
1082
+ const res = await api('/api/collections/import-json', {
1083
+ method: 'POST',
1084
+ body: JSON.stringify({
1085
+ name,
1086
+ data: text,
1087
+ schemaOverrides,
1088
+ }),
1089
+ });
1090
+
1091
+ toast(
1092
+ `Collection '${res.collection.name}' created with ${res.recordCount} records in ${res.durationMs}ms!`,
1093
+ 'success'
1094
+ );
1095
+ closeModal();
1096
+ await loadCollections();
1097
+ selectCollection(res.collection.name);
1098
+ } catch (e) {
1099
+ toast(e.message, 'error');
1100
+ if (submitBtn) {
1101
+ submitBtn.disabled = false;
1102
+ submitBtn.textContent = 'Create Collection & Import Records';
1103
+ }
1104
+ }
1105
+ }
1106
+
1107
+ async function submitNewCollection() {
1108
+ const name = document.getElementById('new-col-name').value.trim();
1109
+ const type = document.getElementById('new-col-type').value;
1110
+ if (!name) return;
1111
+
1112
+ try {
1113
+ const col = await api('/api/collections', {
1114
+ method: 'POST',
1115
+ body: JSON.stringify({
1116
+ name,
1117
+ type,
1118
+ schema: [
1119
+ { id: 'f_title', name: 'title', type: 'text', required: true },
1120
+ ],
1121
+ }),
1122
+ });
1123
+
1124
+ toast(`Collection '${col.name}' created!`, 'success');
1125
+ closeModal();
1126
+ await loadCollections();
1127
+ selectCollection(col.name);
1128
+ } catch (e) {
1129
+ toast(e.message, 'error');
1130
+ }
1131
+ }
1132
+
1133
+
1134
+ function parseCsvClient(csvText) {
1135
+ const text = csvText.replace(/^\uFEFF/, '').trim();
1136
+ if (!text) return { headers: [], rows: [] };
1137
+
1138
+ // Detect delimiter from first line
1139
+ const firstLine = text.split(/\r?\n/)[0] || '';
1140
+ let inQ = false, commas = 0, semis = 0, tabs = 0;
1141
+ for (let i = 0; i < firstLine.length; i++) {
1142
+ const c = firstLine[i];
1143
+ if (c === '"') inQ = !inQ;
1144
+ else if (!inQ) {
1145
+ if (c === ',') commas++;
1146
+ else if (c === ';') semis++;
1147
+ else if (c === '\t') tabs++;
1148
+ }
1149
+ }
1150
+ const delimiter = (tabs > commas && tabs > semis) ? '\t' : (semis > commas && semis > tabs) ? ';' : ',';
1151
+
1152
+ const rows = [];
1153
+ let currentRow = [];
1154
+ let currentCell = '';
1155
+ let inQuotes = false;
1156
+ let i = 0;
1157
+ const len = text.length;
1158
+
1159
+ while (i < len) {
1160
+ const char = text[i];
1161
+ if (inQuotes) {
1162
+ if (char === '"') {
1163
+ if (i + 1 < len && text[i + 1] === '"') {
1164
+ currentCell += '"';
1165
+ i += 2;
1166
+ continue;
1167
+ } else {
1168
+ inQuotes = false;
1169
+ i++;
1170
+ continue;
1171
+ }
1172
+ } else {
1173
+ currentCell += char;
1174
+ i++;
1175
+ continue;
1176
+ }
1177
+ } else {
1178
+ if (char === '"') {
1179
+ inQuotes = true;
1180
+ i++;
1181
+ continue;
1182
+ } else if (char === delimiter) {
1183
+ currentRow.push(currentCell);
1184
+ currentCell = '';
1185
+ i++;
1186
+ continue;
1187
+ } else if (char === '\r') {
1188
+ if (i + 1 < len && text[i + 1] === '\n') {
1189
+ i++;
1190
+ }
1191
+ currentRow.push(currentCell);
1192
+ currentCell = '';
1193
+ rows.push(currentRow);
1194
+ currentRow = [];
1195
+ i++;
1196
+ continue;
1197
+ } else if (char === '\n') {
1198
+ currentRow.push(currentCell);
1199
+ currentCell = '';
1200
+ rows.push(currentRow);
1201
+ currentRow = [];
1202
+ i++;
1203
+ continue;
1204
+ } else {
1205
+ currentCell += char;
1206
+ i++;
1207
+ continue;
1208
+ }
1209
+ }
1210
+ }
1211
+ currentRow.push(currentCell);
1212
+ rows.push(currentRow);
1213
+
1214
+ if (rows.length > 0 && rows[rows.length - 1].length === 1 && rows[rows.length - 1][0] === '') {
1215
+ rows.pop();
1216
+ }
1217
+
1218
+ if (rows.length === 0) return { headers: [], rows: [] };
1219
+ const headers = rows[0].map(h => h.trim());
1220
+ const dataRows = [];
1221
+ for (let r = 1; r < rows.length; r++) {
1222
+ const vals = rows[r];
1223
+ if (vals.length === 1 && vals[0].trim() === '') continue;
1224
+ const rowObj = {};
1225
+ for (let c = 0; c < headers.length; c++) {
1226
+ rowObj[headers[c]] = vals[c] !== undefined ? vals[c] : '';
1227
+ }
1228
+ dataRows.push(rowObj);
1229
+ }
1230
+
1231
+ return { headers, rows: dataRows };
1232
+ }
1233
+
1234
+ function findBestFieldMatch(headerName, col) {
1235
+ const clean = headerName.toLowerCase().replace(/[\s\-_]/g, '');
1236
+ if (!clean) return '';
1237
+
1238
+ if (col.type === 'auth') {
1239
+ if (clean === 'email' || clean === 'mail') return 'email';
1240
+ if (clean === 'password' || clean === 'pass') return 'password';
1241
+ }
1242
+
1243
+ // Exact or normalized match
1244
+ for (const f of col.schema) {
1245
+ const fClean = f.name.toLowerCase().replace(/[\s\-_]/g, '');
1246
+ if (fClean === clean) return f.name;
1247
+ }
1248
+
1249
+ // Common aliases
1250
+ if (clean === 'id') return 'id';
1251
+ if (clean === 'created' || clean === 'createdat') return 'created';
1252
+ if (clean === 'updated' || clean === 'updatedat') return 'updated';
1253
+
1254
+ // Substring match
1255
+ for (const f of col.schema) {
1256
+ const fClean = f.name.toLowerCase().replace(/[\s\-_]/g, '');
1257
+ if (clean.includes(fClean) || fClean.includes(clean)) {
1258
+ return f.name;
1259
+ }
1260
+ }
1261
+
1262
+ return '';
1263
+ }
1264
+
1265
+ function downloadSampleCsv() {
1266
+ const col = state.activeCollection;
1267
+ if (!col) return;
1268
+ const headers = [];
1269
+ const sampleRow1 = [];
1270
+ const sampleRow2 = [];
1271
+
1272
+ if (col.type === 'auth') {
1273
+ headers.push('email', 'password');
1274
+ sampleRow1.push('user1@example.com', 'password123');
1275
+ sampleRow2.push('user2@example.com', 'password456');
1276
+ }
1277
+
1278
+ for (const f of col.schema) {
1279
+ headers.push(f.name);
1280
+ if (f.type === 'number') {
1281
+ sampleRow1.push('10');
1282
+ sampleRow2.push('25');
1283
+ } else if (f.type === 'bool') {
1284
+ sampleRow1.push('true');
1285
+ sampleRow2.push('false');
1286
+ } else if (f.type === 'email') {
1287
+ sampleRow1.push('contact1@example.com');
1288
+ sampleRow2.push('contact2@example.com');
1289
+ } else if (f.type === 'date') {
1290
+ sampleRow1.push('2026-01-15');
1291
+ sampleRow2.push('2026-02-20');
1292
+ } else if (f.type === 'select' && f.options?.values?.length) {
1293
+ sampleRow1.push(f.options.values[0]);
1294
+ sampleRow2.push(f.options.values[1] || f.options.values[0]);
1295
+ } else if (f.type === 'json') {
1296
+ sampleRow1.push('{"tag": "demo"}');
1297
+ sampleRow2.push('{"tag": "test"}');
1298
+ } else {
1299
+ sampleRow1.push(`Sample ${f.name} 1`);
1300
+ sampleRow2.push(`Sample ${f.name} 2`);
1301
+ }
1302
+ }
1303
+
1304
+ const csv = [
1305
+ headers.join(','),
1306
+ sampleRow1.map(v => v.includes(',') || v.includes('"') ? `"${v.replace(/"/g, '""')}"` : v).join(','),
1307
+ sampleRow2.map(v => v.includes(',') || v.includes('"') ? `"${v.replace(/"/g, '""')}"` : v).join(',')
1308
+ ].join('\r\n');
1309
+
1310
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
1311
+ const url = URL.createObjectURL(blob);
1312
+ const a = document.createElement('a');
1313
+ a.href = url;
1314
+ a.download = `${col.name}_sample_template.csv`;
1315
+ document.body.appendChild(a);
1316
+ a.click();
1317
+ document.body.removeChild(a);
1318
+ URL.revokeObjectURL(url);
1319
+ }
1320
+
1321
+ function openImportModal() {
1322
+ const col = state.activeCollection;
1323
+ if (!col) return;
1324
+
1325
+ currentImport = {
1326
+ fileName: '',
1327
+ headers: [],
1328
+ rows: [],
1329
+ mapping: {},
1330
+ continueOnError: true,
1331
+ };
1332
+
1333
+ renderImportModalStep1();
1334
+ }
1335
+
1336
+ function renderImportModalStep1() {
1337
+ const col = state.activeCollection;
1338
+ const modal = document.getElementById('modal-root');
1339
+ modal.innerHTML = `
1340
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
1341
+ <div class="modal modal-lg">
1342
+ <div class="modal-header">
1343
+ <div>
1344
+ <h2 class="modal-title">Import CSV — ${col.name}</h2>
1345
+ <div style="font-size:12px; color:var(--text-muted); margin-top:2px;">Step 1: Upload or drag & drop CSV file</div>
1346
+ </div>
1347
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
1348
+ </div>
1349
+ <div class="modal-body" style="gap:1.25rem;">
1350
+ <div class="dropzone" id="csv-dropzone"
1351
+ ondragover="handleDragOver(event)"
1352
+ ondragleave="handleDragLeave(event)"
1353
+ ondrop="handleFileDrop(event)"
1354
+ onclick="document.getElementById('csv-file-picker').click()">
1355
+ <div style="width:48px; height:48px; border-radius:50%; background:rgba(59,130,246,0.1); color:#60a5fa; display:flex; align-items:center; justify-content:center; font-size:24px;">
1356
+ 📁
1357
+ </div>
1358
+ <div style="font-weight:600; font-size:14px;">Drag & drop your CSV file here, or click to browse</div>
1359
+ <div style="font-size:12px; color:var(--text-muted);">Supports .csv files, RFC 4180 format, and auto-detects delimiters (, ; \\t)</div>
1360
+ <input type="file" id="csv-file-picker" accept=".csv,text/csv" style="display:none;" onchange="handleFileSelect(event)">
1361
+ </div>
1362
+
1363
+ <div style="display:flex; justify-content:space-between; align-items:center; padding:0.75rem 1rem; background:var(--bg-input); border-radius:6px; border:1px solid var(--border-subtle); font-size:12px;">
1364
+ <span style="color:var(--text-muted);">Need a sample CSV with all collection headers?</span>
1365
+ <button class="btn btn-secondary btn-sm" onclick="downloadSampleCsv()">📥 Download Sample CSV</button>
1366
+ </div>
1367
+
1368
+ <div>
1369
+ <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:0.5rem;">
1370
+ <label class="form-label" style="margin:0; cursor:pointer;" onclick="togglePasteArea()">
1371
+ <span id="paste-toggle-icon">▶</span> Or paste raw CSV text
1372
+ </label>
1373
+ </div>
1374
+ <div id="paste-csv-container" style="display:none;">
1375
+ <textarea class="form-textarea" id="paste-csv-input" placeholder="id,title,views&#10;1,My First Post,100" style="min-height:90px;"></textarea>
1376
+ <div style="display:flex; justify-content:flex-end; margin-top:0.5rem;">
1377
+ <button class="btn btn-secondary btn-sm" onclick="processPastedCsv()">Parse Pasted CSV</button>
1378
+ </div>
1379
+ </div>
1380
+ </div>
1381
+ </div>
1382
+ <div class="modal-footer">
1383
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
1384
+ </div>
1385
+ </div>
1386
+ </div>
1387
+ `;
1388
+ focusFirstModalField(modal);
1389
+ }
1390
+
1391
+ function togglePasteArea() {
1392
+ const c = document.getElementById('paste-csv-container');
1393
+ const icon = document.getElementById('paste-toggle-icon');
1394
+ if (c.style.display === 'none') {
1395
+ c.style.display = 'block';
1396
+ icon.textContent = '▼';
1397
+ } else {
1398
+ c.style.display = 'none';
1399
+ icon.textContent = '▶';
1400
+ }
1401
+ }
1402
+
1403
+ function handleDragOver(e) {
1404
+ e.preventDefault();
1405
+ const dz = document.getElementById('csv-dropzone');
1406
+ if (dz) dz.classList.add('dragover');
1407
+ }
1408
+
1409
+ function handleDragLeave(e) {
1410
+ e.preventDefault();
1411
+ const dz = document.getElementById('csv-dropzone');
1412
+ if (dz) dz.classList.remove('dragover');
1413
+ }
1414
+
1415
+ function handleFileDrop(e) {
1416
+ e.preventDefault();
1417
+ const dz = document.getElementById('csv-dropzone');
1418
+ if (dz) dz.classList.remove('dragover');
1419
+
1420
+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]) {
1421
+ readAndProcessFile(e.dataTransfer.files[0]);
1422
+ }
1423
+ }
1424
+
1425
+ function handleFileSelect(e) {
1426
+ if (e.target && e.target.files && e.target.files[0]) {
1427
+ readAndProcessFile(e.target.files[0]);
1428
+ }
1429
+ }
1430
+
1431
+ function processPastedCsv() {
1432
+ const val = document.getElementById('paste-csv-input').value;
1433
+ if (!val.trim()) {
1434
+ toast('Please paste some CSV text first', 'error');
1435
+ return;
1436
+ }
1437
+ readAndProcessText(val, 'pasted_data.csv');
1438
+ }
1439
+
1440
+ function readAndProcessFile(file) {
1441
+ const reader = new FileReader();
1442
+ reader.onload = (e) => {
1443
+ const text = e.target.result;
1444
+ readAndProcessText(text, file.name);
1445
+ };
1446
+ reader.onerror = () => {
1447
+ toast('Failed to read file', 'error');
1448
+ };
1449
+ reader.readAsText(file);
1450
+ }
1451
+
1452
+ function readAndProcessText(text, fileName) {
1453
+ const parsed = parseCsvClient(text);
1454
+ if (parsed.headers.length === 0 || parsed.rows.length === 0) {
1455
+ toast('CSV file is empty or could not be parsed', 'error');
1456
+ return;
1457
+ }
1458
+
1459
+ const col = state.activeCollection;
1460
+ currentImport.fileName = fileName;
1461
+ currentImport.headers = parsed.headers;
1462
+ currentImport.rows = parsed.rows;
1463
+ currentImport.mapping = {};
1464
+
1465
+ // Auto-map columns
1466
+ for (const h of parsed.headers) {
1467
+ currentImport.mapping[h] = findBestFieldMatch(h, col);
1468
+ }
1469
+
1470
+ renderImportModalStep2();
1471
+ }
1472
+
1473
+ function renderImportModalStep2() {
1474
+ const col = state.activeCollection;
1475
+ const modal = document.getElementById('modal-root');
1476
+
1477
+ // Options for schema field dropdown
1478
+ const fieldOptions = [
1479
+ { value: '', label: '-- Skip Field (Do not import) --' }
1480
+ ];
1481
+
1482
+ if (col.type === 'auth') {
1483
+ fieldOptions.push(
1484
+ { value: 'email', label: 'email (email) *' },
1485
+ { value: 'password', label: 'password (text)' }
1486
+ );
1487
+ }
1488
+
1489
+ for (const f of col.schema) {
1490
+ fieldOptions.push({
1491
+ value: f.name,
1492
+ label: `${f.name} (${f.type})${f.required ? ' *' : ''}`
1493
+ });
1494
+ }
1495
+
1496
+ fieldOptions.push(
1497
+ { value: 'id', label: 'id (system ID)' },
1498
+ { value: 'created', label: 'created (system timestamp)' },
1499
+ { value: 'updated', label: 'updated (system timestamp)' }
1500
+ );
1501
+
1502
+ modal.innerHTML = `
1503
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
1504
+ <div class="modal modal-lg">
1505
+ <div class="modal-header">
1506
+ <div>
1507
+ <h2 class="modal-title">Visual Column Mapping — ${col.name}</h2>
1508
+ <div style="font-size:12px; color:var(--text-muted); margin-top:2px;">
1509
+ Step 2: Map CSV columns to collection fields (File: <span class="code-badge">${currentImport.fileName}</span> — <strong>${currentImport.rows.length}</strong> rows detected)
1510
+ </div>
1511
+ </div>
1512
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
1513
+ </div>
1514
+ <div class="modal-body" style="gap:1.25rem;">
1515
+ <div class="mapping-table-container">
1516
+ <table class="mapping-table">
1517
+ <thead>
1518
+ <tr>
1519
+ <th style="width:28%;">CSV Column Header</th>
1520
+ <th style="width:32%;">Sample Values</th>
1521
+ <th style="width:5%; text-align:center;"></th>
1522
+ <th style="width:35%;">Collection Destination Field</th>
1523
+ </tr>
1524
+ </thead>
1525
+ <tbody>
1526
+ ${currentImport.headers.map((h, idx) => {
1527
+ const sampleVals = currentImport.rows.slice(0, 2).map(r => r[h]).filter(v => v !== undefined && v !== '');
1528
+ const sampleStr = sampleVals.length > 0 ? sampleVals.join(' | ') : '<em style="color:#6b7280;">(empty)</em>';
1529
+ const selected = currentImport.mapping[h] || '';
1530
+
1531
+ return `
1532
+ <tr>
1533
+ <td>
1534
+ <span style="font-weight:600; font-size:13px;">${h}</span>
1535
+ </td>
1536
+ <td>
1537
+ <span class="code-badge" title="${String(sampleStr).replace(/"/g, '&quot;')}">${sampleStr}</span>
1538
+ </td>
1539
+ <td style="text-align:center; color:var(--text-muted); font-size:14px;">
1540
+ ➔
1541
+ </td>
1542
+ <td>
1543
+ <select class="form-select" style="padding:0.4rem 0.6rem; font-size:12px; width:100%;" onchange="updateColumnMapping('${h.replace(/'/g, "\\'")}', this.value)">
1544
+ ${fieldOptions.map(opt => `
1545
+ <option value="${opt.value}" ${opt.value === selected ? 'selected' : ''}>${opt.label}</option>
1546
+ `).join('')}
1547
+ </select>
1548
+ </td>
1549
+ </tr>
1550
+ `;
1551
+ }).join('')}
1552
+ </tbody>
1553
+ </table>
1554
+ </div>
1555
+
1556
+ <!-- Live Mapped Preview -->
1557
+ <div>
1558
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.5rem;">
1559
+ <h4 style="font-size:13px; font-weight:700;">Live Mapped Preview (First 3 Rows)</h4>
1560
+ <span style="font-size:11px; color:var(--text-muted);">Updates in real time as mappings change</span>
1561
+ </div>
1562
+ <div class="mapping-table-container" style="max-height:160px; overflow:auto;">
1563
+ <table class="mapping-table" id="live-preview-table">
1564
+ <!-- Injected dynamically -->
1565
+ </table>
1566
+ </div>
1567
+ </div>
1568
+
1569
+ <!-- Import Options -->
1570
+ <div style="display:flex; align-items:center; justify-content:space-between; padding:0.75rem 1rem; background:var(--bg-input); border-radius:6px; border:1px solid var(--border-subtle); font-size:12px;">
1571
+ <label style="display:flex; align-items:center; gap:8px; cursor:pointer;">
1572
+ <input type="checkbox" id="import-continue-on-error" ${currentImport.continueOnError ? 'checked' : ''} onchange="currentImport.continueOnError = this.checked">
1573
+ <span>Skip records with validation errors and continue importing</span>
1574
+ </label>
1575
+ <span style="color:var(--text-muted);">Ready to import: <strong>${currentImport.rows.length}</strong> records</span>
1576
+ </div>
1577
+ </div>
1578
+ <div class="modal-footer">
1579
+ <button class="btn btn-secondary" onclick="renderImportModalStep1()">← Change File</button>
1580
+ <button class="btn btn-primary" id="btn-do-import" onclick="executeImport()">
1581
+ <span>Import ${currentImport.rows.length} Records</span>
1582
+ </button>
1583
+ </div>
1584
+ </div>
1585
+ </div>
1586
+ `;
1587
+
1588
+ renderLivePreview();
1589
+ focusFirstModalField(modal);
1590
+ }
1591
+
1592
+ function updateColumnMapping(csvHeader, targetField) {
1593
+ currentImport.mapping[csvHeader] = targetField;
1594
+ renderLivePreview();
1595
+ }
1596
+
1597
+ function renderLivePreview() {
1598
+ const table = document.getElementById('live-preview-table');
1599
+ if (!table) return;
1600
+
1601
+ const activeMappings = Object.entries(currentImport.mapping).filter(([_, target]) => Boolean(target));
1602
+ if (activeMappings.length === 0) {
1603
+ table.innerHTML = `<tbody><tr><td colspan="5" style="text-align:center; padding:1.5rem; color:var(--text-muted);">No fields mapped yet. Map at least one column above to preview data.</td></tr></tbody>`;
1604
+ return;
1605
+ }
1606
+
1607
+ const mappedHeaders = activeMappings.map(([_, target]) => target);
1608
+ const previewRows = currentImport.rows.slice(0, 3);
1609
+
1610
+ table.innerHTML = `
1611
+ <thead>
1612
+ <tr>
1613
+ ${mappedHeaders.map(h => `<th>${h}</th>`).join('')}
1614
+ </tr>
1615
+ </thead>
1616
+ <tbody>
1617
+ ${previewRows.map(row => `
1618
+ <tr>
1619
+ ${activeMappings.map(([csvH, _]) => {
1620
+ const val = row[csvH];
1621
+ if (val === undefined || val === '') return '<td style="color:#6b7280;">NULL</td>';
1622
+ return `<td>${String(val).slice(0, 40)}</td>`;
1623
+ }).join('')}
1624
+ </tr>
1625
+ `).join('')}
1626
+ </tbody>
1627
+ `;
1628
+ }
1629
+
1630
+ async function executeImport() {
1631
+ const col = state.activeCollection;
1632
+ if (!col) return;
1633
+
1634
+ const activeMappings = Object.entries(currentImport.mapping).filter(([_, target]) => Boolean(target));
1635
+ if (activeMappings.length === 0) {
1636
+ toast('Please map at least one CSV column to a collection field', 'error');
1637
+ return;
1638
+ }
1639
+
1640
+ const btn = document.getElementById('btn-do-import');
1641
+ if (btn) {
1642
+ btn.disabled = true;
1643
+ btn.innerHTML = '<span>Importing...</span>';
1644
+ }
1645
+
1646
+ try {
1647
+ // Transform all rows using mapped columns
1648
+ const recordsToImport = [];
1649
+ for (const row of currentImport.rows) {
1650
+ const rec = {};
1651
+ let hasAnyVal = false;
1652
+ for (const [csvH, targetF] of activeMappings) {
1653
+ const rawVal = row[csvH];
1654
+ if (rawVal !== undefined && rawVal !== '') {
1655
+ hasAnyVal = true;
1656
+ rec[targetF] = rawVal;
1657
+ }
1658
+ }
1659
+ if (hasAnyVal) {
1660
+ recordsToImport.push(rec);
1661
+ }
1662
+ }
1663
+
1664
+ if (recordsToImport.length === 0) {
1665
+ throw new Error('No non-empty records found to import with current mappings');
1666
+ }
1667
+
1668
+ const res = await api(`/api/collections/${col.name}/import`, {
1669
+ method: 'POST',
1670
+ body: JSON.stringify({
1671
+ records: recordsToImport,
1672
+ options: {
1673
+ continueOnError: currentImport.continueOnError,
1674
+ },
1675
+ }),
1676
+ });
1677
+
1678
+ renderImportResults(res);
1679
+ await loadRecords();
1680
+ } catch (e) {
1681
+ toast(e.message, 'error');
1682
+ if (btn) {
1683
+ btn.disabled = false;
1684
+ btn.innerHTML = `<span>Import ${currentImport.rows.length} Records</span>`;
1685
+ }
1686
+ }
1687
+ }
1688
+
1689
+ function renderImportResults(res) {
1690
+ const col = state.activeCollection;
1691
+ const modal = document.getElementById('modal-root');
1692
+
1693
+ const hasErrors = res.errors && res.errors.length > 0;
1694
+
1695
+ modal.innerHTML = `
1696
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
1697
+ <div class="modal modal-lg">
1698
+ <div class="modal-header">
1699
+ <h2 class="modal-title">Import Finished — ${col.name}</h2>
1700
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
1701
+ </div>
1702
+ <div class="modal-body" style="gap:1.25rem;">
1703
+ <div style="background:${hasErrors && res.imported === 0 ? 'rgba(239,68,68,0.1)' : 'rgba(16,185,129,0.1)'}; border:1px solid ${hasErrors && res.imported === 0 ? 'rgba(239,68,68,0.3)' : 'rgba(16,185,129,0.3)'}; border-radius:8px; padding:1.25rem; display:flex; align-items:center; gap:1rem;">
1704
+ <div style="font-size:28px;">
1705
+ ${res.imported > 0 ? '🎉' : '⚠️'}
1706
+ </div>
1707
+ <div>
1708
+ <div style="font-weight:700; font-size:15px; color:${res.imported > 0 ? '#34d399' : '#f87171'};">
1709
+ ${res.imported} of ${res.total} records imported successfully
1710
+ </div>
1711
+ <div style="font-size:12px; color:var(--text-muted); margin-top:2px;">
1712
+ ${hasErrors ? `${res.failed} records had issues and were skipped.` : 'All records were validated and inserted into the database.'}
1713
+ </div>
1714
+ </div>
1715
+ </div>
1716
+
1717
+ ${hasErrors ? `
1718
+ <div>
1719
+ <h4 style="font-size:13px; font-weight:700; color:#f87171; margin-bottom:0.5rem;">Errors & Skipped Rows (${res.errors.length})</h4>
1720
+ <div class="mapping-table-container" style="max-height:220px; overflow-y:auto;">
1721
+ <table class="mapping-table">
1722
+ <thead>
1723
+ <tr>
1724
+ <th style="width:15%;">Row</th>
1725
+ <th style="width:85%;">Error Message</th>
1726
+ </tr>
1727
+ </thead>
1728
+ <tbody>
1729
+ ${res.errors.map(err => `
1730
+ <tr>
1731
+ <td><span class="code-badge">Row ${err.row}</span></td>
1732
+ <td style="color:#f87171; font-family:var(--font-mono); font-size:12px;">${err.error}</td>
1733
+ </tr>
1734
+ `).join('')}
1735
+ </tbody>
1736
+ </table>
1737
+ </div>
1738
+ </div>
1739
+ ` : ''}
1740
+ </div>
1741
+ <div class="modal-footer">
1742
+ <button class="btn btn-primary" onclick="closeModal()">Done</button>
1743
+ </div>
1744
+ </div>
1745
+ </div>
1746
+ `;
1747
+
1748
+ toast(`Import finished: ${res.imported} records added to ${col.name}`, res.imported > 0 ? 'success' : 'error');
1749
+ }
1750
+
1751
+ // ==========================================
1752
+ // 1-Click Generate Mock Data Modal (Faker Engine)
1753
+ // ==========================================
1754
+
1755
+ let selectedMockCount = 50;
1756
+
1757
+ function getFieldMockDescription(f, col) {
1758
+ const clean = f.name.toLowerCase().replace(/[^a-z0-9]/g, '');
1759
+ if (f.type === 'email' || clean.includes('email') || clean.includes('mail')) {
1760
+ return 'Realistic unique emails (e.g. sarah.jenkins@example.com)';
1761
+ }
1762
+ if (f.type === 'file') {
1763
+ if (clean.includes('avatar') || clean.includes('photo') || clean.includes('profile')) {
1764
+ return 'DiceBear / Unsplash avatar images (with SVG badge fallback)';
1765
+ }
1766
+ return 'Placeholder cover/product images with SVG metadata';
1767
+ }
1768
+ if (f.type === 'select') {
1769
+ const vals = f.options?.values || ['draft', 'published', 'archived'];
1770
+ return `Random distribution across options: [${vals.slice(0, 3).join(', ')}${vals.length > 3 ? '...' : ''}]`;
1771
+ }
1772
+ if (f.type === 'relation') {
1773
+ const targetId = f.options?.collectionId || 'collection';
1774
+ const targetCol = state.collections.find(c => c.id === targetId || c.name === targetId);
1775
+ const colTitle = targetCol ? targetCol.name : targetId;
1776
+ return `Auto-links to existing '${colTitle}' records (auto-seeds if empty)`;
1777
+ }
1778
+ if (f.type === 'number') {
1779
+ if (clean.includes('price') || clean.includes('cost') || clean.includes('amount') || clean.includes('salary')) {
1780
+ return 'Realistic currency figures (e.g. $19.99, $49.00, $129.50)';
1781
+ }
1782
+ if (clean === 'age') return 'Realistic human ages (18-70)';
1783
+ if (clean.includes('rating') || clean.includes('score')) return 'Star ratings (3.5 - 5.0)';
1784
+ return 'Random realistic numeric values';
1785
+ }
1786
+ if (f.type === 'bool') {
1787
+ return 'Distributed booleans (true/false weighted for active/published)';
1788
+ }
1789
+ if (f.type === 'date') {
1790
+ return 'Realistic ISO timestamps in recent past';
1791
+ }
1792
+ if (f.type === 'json') {
1793
+ return 'Structured mock JSON (tags, settings, address)';
1794
+ }
1795
+ if (clean === 'name' || clean === 'fullname' || clean === 'author' || clean === 'customer') {
1796
+ return 'Real human full names (e.g. Sarah Jenkins, Marcus Vance)';
1797
+ }
1798
+ if (clean === 'firstname') return 'First names (e.g. Sarah, Marcus)';
1799
+ if (clean === 'lastname') return 'Last names (e.g. Jenkins, Vance)';
1800
+ if (clean.includes('company') || clean.includes('org')) return 'Company names (e.g. Acme Corp, Nexus Digital)';
1801
+ if (clean.includes('title') || clean.includes('headline')) return 'Article/Product titles';
1802
+ if (clean.includes('bio') || clean.includes('desc') || clean.includes('about')) return 'Natural sentences and bios';
1803
+ if (clean.includes('city')) return 'World cities (e.g. San Francisco, Tokyo)';
1804
+ if (clean.includes('country')) return 'Country names (e.g. United States, Japan)';
1805
+ if (clean.includes('street') || clean.includes('address')) return 'Realistic street addresses';
1806
+ if (clean.includes('phone') || clean.includes('tel')) return 'International phone numbers';
1807
+ return `Realistic synthetic ${f.name} values`;
1808
+ }
1809
+
1810
+ function selectMockCount(count) {
1811
+ selectedMockCount = count;
1812
+ document.querySelectorAll('.count-pill').forEach(btn => {
1813
+ if (parseInt(btn.getAttribute('data-count')) === count) {
1814
+ btn.classList.add('active');
1815
+ } else {
1816
+ btn.classList.remove('active');
1817
+ }
1818
+ });
1819
+ const input = document.getElementById('mock-custom-count');
1820
+ if (input) input.value = count;
1821
+ const submitBtn = document.getElementById('btn-submit-mock');
1822
+ if (submitBtn) {
1823
+ submitBtn.innerHTML = `<span>✨ Generate ${count} Records</span>`;
1824
+ }
1825
+ }
1826
+
1827
+ function onMockCustomCountChange(val) {
1828
+ const parsed = Math.max(1, Math.min(500, parseInt(val) || 25));
1829
+ selectedMockCount = parsed;
1830
+ document.querySelectorAll('.count-pill').forEach(btn => {
1831
+ if (parseInt(btn.getAttribute('data-count')) === parsed) {
1832
+ btn.classList.add('active');
1833
+ } else {
1834
+ btn.classList.remove('active');
1835
+ }
1836
+ });
1837
+ const submitBtn = document.getElementById('btn-submit-mock');
1838
+ if (submitBtn) {
1839
+ submitBtn.innerHTML = `<span>✨ Generate ${parsed} Records</span>`;
1840
+ }
1841
+ }
1842
+
1843
+ function openMockDataModal() {
1844
+ const col = state.activeCollection;
1845
+ if (!col) return;
1846
+
1847
+ selectedMockCount = 50;
1848
+ const modal = document.getElementById('modal-root');
1849
+ modal.innerHTML = `
1850
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
1851
+ <div class="modal modal-lg">
1852
+ <div class="modal-header">
1853
+ <div style="display:flex; align-items:center; gap:0.75rem;">
1854
+ <div style="width:36px; height:36px; border-radius:8px; background:rgba(59,130,246,0.15); color:#60a5fa; display:flex; align-items:center; justify-content:center; font-size:18px;">
1855
+ ✨
1856
+ </div>
1857
+ <div>
1858
+ <h2 class="modal-title" style="margin:0;">Generate Mock Data — ${col.name}</h2>
1859
+ <div style="font-size:12px; color:var(--text-muted); margin-top:2px;">Built-in Faker Engine with intelligent schema type inspection</div>
1860
+ </div>
1861
+ </div>
1862
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
1863
+ </div>
1864
+
1865
+ <div class="modal-body" style="gap:1.25rem;">
1866
+ <!-- Record Count Picker -->
1867
+ <div>
1868
+ <label class="form-label" style="margin-bottom:0.5rem; font-weight:600;">How many records would you like to generate?</label>
1869
+ <div style="display:flex; align-items:center; gap:0.5rem; flex-wrap:wrap;">
1870
+ <button type="button" class="count-pill" data-count="10" onclick="selectMockCount(10)">10 records</button>
1871
+ <button type="button" class="count-pill" data-count="25" onclick="selectMockCount(25)">25 records</button>
1872
+ <button type="button" class="count-pill active" data-count="50" onclick="selectMockCount(50)">50 records</button>
1873
+ <button type="button" class="count-pill" data-count="100" onclick="selectMockCount(100)">100 records</button>
1874
+
1875
+ <div style="display:flex; align-items:center; gap:6px; margin-left:auto;">
1876
+ <span style="font-size:12px; color:var(--text-muted);">Custom:</span>
1877
+ <input type="number" id="mock-custom-count" min="1" max="500" value="50" class="form-input" style="width:80px; padding:0.35rem 0.5rem; text-align:center;" oninput="onMockCustomCountChange(this.value)">
1878
+ </div>
1879
+ </div>
1880
+ </div>
1881
+
1882
+ <!-- Schema Field Inspection Preview -->
1883
+ <div>
1884
+ <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:0.5rem;">
1885
+ <label class="form-label" style="margin:0; font-weight:600;">Schema Field Inspection</label>
1886
+ <span style="font-size:11px; color:var(--text-muted);">${col.schema.length + (col.type === 'auth' ? 2 : 0)} fields detected</span>
1887
+ </div>
1888
+ <div class="mapping-table-container" style="max-height:220px; overflow-y:auto; border:1px solid var(--border-subtle); border-radius:6px;">
1889
+ <table class="mapping-table" style="width:100%; border-collapse:collapse; font-size:12px;">
1890
+ <thead>
1891
+ <tr style="background:var(--bg-input); text-align:left; border-bottom:1px solid var(--border-subtle);">
1892
+ <th style="padding:8px 12px; width:25%;">Field</th>
1893
+ <th style="padding:8px 12px; width:15%;">Type</th>
1894
+ <th style="padding:8px 12px; width:60%;">Simulated Content</th>
1895
+ </tr>
1896
+ </thead>
1897
+ <tbody>
1898
+ ${col.type === 'auth' ? `
1899
+ <tr style="border-bottom:1px solid var(--border-subtle);">
1900
+ <td style="padding:8px 12px; font-weight:600;">email</td>
1901
+ <td style="padding:8px 12px;"><span class="badge">auth</span></td>
1902
+ <td style="padding:8px 12px; color:var(--text-muted);">Unique realistic emails (e.g. sarah.jenkins@example.com)</td>
1903
+ </tr>
1904
+ <tr style="border-bottom:1px solid var(--border-subtle);">
1905
+ <td style="padding:8px 12px; font-weight:600;">password</td>
1906
+ <td style="padding:8px 12px;"><span class="badge">auth</span></td>
1907
+ <td style="padding:8px 12px; color:var(--text-muted);">Secure bcrypt-hashed credentials ("NodeStack2026!")</td>
1908
+ </tr>
1909
+ ` : ''}
1910
+ ${col.schema.map(f => `
1911
+ <tr style="border-bottom:1px solid var(--border-subtle);">
1912
+ <td style="padding:8px 12px; font-weight:600;">
1913
+ ${f.name} ${f.required ? '<span style="color:#f87171;">*</span>' : ''}
1914
+ </td>
1915
+ <td style="padding:8px 12px;">
1916
+ <span class="badge badge-${f.type}">${f.type}</span>
1917
+ </td>
1918
+ <td style="padding:8px 12px; color:var(--text-muted);">
1919
+ ${getFieldMockDescription(f, col)}
1920
+ </td>
1921
+ </tr>
1922
+ `).join('')}
1923
+ </tbody>
1924
+ </table>
1925
+ </div>
1926
+ </div>
1927
+
1928
+ <!-- Options -->
1929
+ <div style="background:var(--bg-input); padding:0.85rem 1rem; border-radius:6px; border:1px solid var(--border-subtle); display:flex; flex-direction:column; gap:0.6rem;">
1930
+ <label style="display:flex; align-items:center; gap:8px; font-size:13px; cursor:pointer;">
1931
+ <input type="checkbox" id="mock-download-files" checked style="cursor:pointer;">
1932
+ <span>Auto-download realistic avatar / placeholder images (DiceBear / Unsplash)</span>
1933
+ </label>
1934
+ <label style="display:flex; align-items:center; gap:8px; font-size:13px; cursor:pointer;">
1935
+ <input type="checkbox" id="mock-auto-seed-relations" checked style="cursor:pointer;">
1936
+ <span>Automatically seed empty referenced collections to satisfy relations</span>
1937
+ </label>
1938
+ </div>
1939
+ </div>
1940
+
1941
+ <div class="modal-footer">
1942
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
1943
+ <button class="btn btn-primary" id="btn-submit-mock" onclick="submitGenerateMockData()">
1944
+ <span>✨ Generate ${selectedMockCount} Records</span>
1945
+ </button>
1946
+ </div>
1947
+ </div>
1948
+ </div>
1949
+ `;
1950
+ focusFirstModalField(modal);
1951
+ }
1952
+
1953
+ async function submitGenerateMockData() {
1954
+ const col = state.activeCollection;
1955
+ if (!col) return;
1956
+
1957
+ const submitBtn = document.getElementById('btn-submit-mock');
1958
+ const downloadFiles = document.getElementById('mock-download-files')?.checked ?? true;
1959
+ const autoSeedRelations = document.getElementById('mock-auto-seed-relations')?.checked ?? true;
1960
+
1961
+ const count = selectedMockCount || 50;
1962
+
1963
+ if (submitBtn) {
1964
+ submitBtn.disabled = true;
1965
+ submitBtn.innerHTML = `
1966
+ <div style="width:14px; height:14px; border:2px solid #ffffff; border-top-color:transparent; border-radius:50%; animation:spin 0.6s linear infinite;"></div>
1967
+ <span>Generating ${count} Records...</span>
1968
+ `;
1969
+ }
1970
+
1971
+ try {
1972
+ const res = await api(`/api/collections/${col.name}/generate-mock`, {
1973
+ method: 'POST',
1974
+ body: JSON.stringify({
1975
+ count,
1976
+ options: {
1977
+ downloadFiles,
1978
+ autoSeedRelations,
1979
+ },
1980
+ }),
1981
+ });
1982
+
1983
+ toast(`✨ Successfully generated ${res.count || count} realistic records!`, 'success');
1984
+ closeModal();
1985
+ await loadRecords();
1986
+ } catch (err) {
1987
+ toast(`Mock Generation Failed: ${err.message || String(err)}`, 'error');
1988
+ if (submitBtn) {
1989
+ submitBtn.disabled = false;
1990
+ submitBtn.innerHTML = `<span>✨ Generate ${count} Records</span>`;
1991
+ }
1992
+ }
1993
+ }
1994
+
1995
+ // Starter Templates & Recipes Modal
1996
+ function openTemplatesModal() {
1997
+ const modal = document.getElementById('modal-root');
1998
+ const templates = [
1999
+ {
2000
+ id: 'ecommerce',
2001
+ name: 'E-Commerce',
2002
+ icon: '🛒',
2003
+ badge: '20 Items & Images',
2004
+ accent: '#3b82f6',
2005
+ description: 'Pre-seeded with 20 items & high-res SVG product images, categories, orders, and verified customer reviews.',
2006
+ collections: ['products', 'categories', 'orders', 'reviews'],
2007
+ stats: '4 collections • 48 records • 25 images'
2008
+ },
2009
+ {
2010
+ id: 'blog',
2011
+ name: 'Blog / Content',
2012
+ icon: '📝',
2013
+ badge: 'Editorial Engine',
2014
+ accent: '#10b981',
2015
+ description: 'Pre-seeded with technical markdown articles, author avatars, category tags, cover images, and discussions.',
2016
+ collections: ['posts', 'authors', 'tags', 'comments'],
2017
+ stats: '4 collections • 28 records • 12 images'
2018
+ },
2019
+ {
2020
+ id: 'crm',
2021
+ name: 'SaaS / CRM',
2022
+ icon: '👥',
2023
+ badge: 'Pipeline & Deals',
2024
+ accent: '#8b5cf6',
2025
+ description: 'Pre-seeded with B2B companies with logo marks, leads with scoring, pipeline deal stages, and activity logs.',
2026
+ collections: ['companies', 'leads', 'deals', 'activities'],
2027
+ stats: '4 collections • 26 records • 6 images'
2028
+ }
2029
+ ];
2030
+
2031
+ modal.innerHTML = `
2032
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
2033
+ <div class="modal" style="max-width:820px; max-height:90vh; display:flex; flex-direction:column;">
2034
+ <div class="modal-header" style="align-items:flex-start;">
2035
+ <div>
2036
+ <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
2037
+ <h2 class="modal-title" style="font-size:20px;">Starter Templates & Recipes</h2>
2038
+ <span class="badge badge-get" style="font-size:11px;">1-Click Setup</span>
2039
+ </div>
2040
+ <p style="font-size:13px; color:var(--text-muted); margin:0;">
2041
+ Never start from an empty database. Choose a battle-tested template pre-seeded with schemas, relations, and realistic data with images.
2042
+ </p>
2043
+ </div>
2044
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
2045
+ </div>
2046
+
2047
+ <div class="modal-body" style="overflow-y:auto; padding:1.25rem; display:flex; flex-direction:column; gap:1.25rem;">
2048
+ <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(230px, 1fr)); gap:1rem;">
2049
+ ${templates.map(t => `
2050
+ <div style="background:var(--bg-input); border:1px solid var(--border-subtle); border-radius:10px; padding:1.25rem; display:flex; flex-direction:column; justify-content:space-between; gap:1rem; position:relative; overflow:hidden; transition:all 0.2s ease;">
2051
+ <div style="position:absolute; top:0; left:0; right:0; height:4px; background:${t.accent};"></div>
2052
+ <div>
2053
+ <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:0.6rem;">
2054
+ <span style="font-size:24px;">${t.icon}</span>
2055
+ <span class="badge" style="background:var(--bg-hover-subtle); border-color:rgba(255,255,255,0.15); font-size:11px; color: var(--text-heading);">${t.badge}</span>
2056
+ </div>
2057
+ <h3 style="font-size:16px; font-weight:700; margin-bottom:0.3rem; color: var(--text-heading);">${t.name}</h3>
2058
+ <p style="font-size:12px; color:var(--text-muted); line-height:1.4; margin-bottom:0.75rem;">${t.description}</p>
2059
+
2060
+ <div style="background:var(--bg-card); border:1px solid var(--border-subtle); border-radius:6px; padding:0.6rem; margin-bottom:0.5rem;">
2061
+ <div style="font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.04em; margin-bottom:0.4rem;">Collections included:</div>
2062
+ <div style="display:flex; flex-wrap:wrap; gap:4px;">
2063
+ ${t.collections.map(c => `
2064
+ <span style="background:rgba(255,255,255,0.06); padding:2px 6px; border-radius:4px; font-family:var(--font-mono); font-size:11px; color:#cbd5e1;">${c}</span>
2065
+ `).join('')}
2066
+ </div>
2067
+ </div>
2068
+ <div style="font-size:11px; color:var(--text-muted);">${t.stats}</div>
2069
+ </div>
2070
+
2071
+ <button class="btn btn-primary" id="btn-apply-${t.id}" style="width:100%; display:flex; align-items:center; justify-content:center; gap:6px;" onclick="openApplyTemplateConfirmModal('${t.id}')">
2072
+ <span>🚀 Launch ${t.name}</span>
2073
+ </button>
2074
+ </div>
2075
+ `).join('')}
2076
+ </div>
2077
+
2078
+ <div style="background:rgba(255,255,255,0.03); border:1px solid var(--border-subtle); border-radius:8px; padding:0.75rem 1rem; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:0.5rem;">
2079
+ <span style="font-size:12px; color:var(--text-muted);">
2080
+ Click any template above to review schema preview & overwrite settings before launching.
2081
+ </span>
2082
+ <span style="font-size:12px; font-family:var(--font-mono); color:var(--text-muted);">
2083
+ CLI: <code style="color:#60a5fa;">npx nodestack start --template ecommerce</code>
2084
+ </span>
2085
+ </div>
2086
+ </div>
2087
+ </div>
2088
+ </div>
2089
+ `;
2090
+ focusFirstModalField(modal);
2091
+ }
2092
+
2093
+ function openApplyTemplateConfirmModal(templateId) {
2094
+ const templateMeta = {
2095
+ ecommerce: {
2096
+ name: 'E-Commerce Recipe',
2097
+ icon: '🛒',
2098
+ badge: '20 Items & SVG Images',
2099
+ accent: '#3b82f6',
2100
+ description: 'Complete online storefront architecture with products catalog, categories, customer orders, and verified customer reviews.',
2101
+ collections: [
2102
+ { name: 'products', type: 'base', count: 20, desc: 'name, slug, price, description, inStock, rating, category, images (custom SVGs)' },
2103
+ { name: 'categories', type: 'base', count: 4, desc: 'title, slug, icon, active' },
2104
+ { name: 'orders', type: 'base', count: 8, desc: 'customerName, customerEmail, totalAmount, status, items' },
2105
+ { name: 'reviews', type: 'base', count: 15, desc: 'author, rating, comment, verifiedPurchase, product' },
2106
+ ],
2107
+ stats: '4 collections • 47 pre-seeded sample records • 20 vector SVG product images',
2108
+ },
2109
+ blog: {
2110
+ name: 'Blog / Content Engine',
2111
+ icon: '📝',
2112
+ badge: 'Editorial Platform',
2113
+ accent: '#10b981',
2114
+ description: 'Modern publishing engine featuring rich markdown posts, author profiles with avatars, categorization tags, and reader comments.',
2115
+ collections: [
2116
+ { name: 'posts', type: 'base', count: 8, desc: 'title, slug, content (Markdown), published, author, tags, cover' },
2117
+ { name: 'authors', type: 'auth', count: 4, desc: 'name, bio, role, avatar (custom SVG)' },
2118
+ { name: 'tags', type: 'base', count: 6, desc: 'name, slug, color' },
2119
+ { name: 'comments', type: 'base', count: 12, desc: 'authorName, content, post, approved' },
2120
+ ],
2121
+ stats: '4 collections • 30 pre-seeded sample records • 4 author profile SVG avatars',
2122
+ },
2123
+ crm: {
2124
+ name: 'SaaS / CRM Pipeline',
2125
+ icon: '👥',
2126
+ badge: 'B2B Sales Pipeline',
2127
+ accent: '#8b5cf6',
2128
+ description: 'B2B customer relationship management pipeline with target companies, inbound leads, deal revenue stages, and sales team activities.',
2129
+ collections: [
2130
+ { name: 'companies', type: 'base', count: 6, desc: 'name, domain, size, industry, logo (custom SVG)' },
2131
+ { name: 'leads', type: 'base', count: 10, desc: 'firstName, lastName, email, company, status, score' },
2132
+ { name: 'deals', type: 'base', count: 8, desc: 'title, value, stage, company, probability' },
2133
+ { name: 'activities', type: 'base', count: 14, desc: 'type, subject, notes, deal, dueDate, completed' },
2134
+ ],
2135
+ stats: '4 collections • 38 pre-seeded sample records • 6 company vector SVG logos',
2136
+ },
2137
+ };
2138
+
2139
+ const t = templateMeta[templateId] || templateMeta.ecommerce;
2140
+ const existingMatches = state.collections.filter(c => t.collections.some(tc => tc.name === c.name));
2141
+
2142
+ const modal = document.getElementById('modal-root');
2143
+ modal.innerHTML = `
2144
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
2145
+ <div class="modal" style="max-width: 580px;">
2146
+ <div class="modal-header" style="border-bottom: 1px solid var(--border-subtle); padding: 1.25rem 1.5rem;">
2147
+ <div style="display: flex; align-items: center; gap: 0.75rem;">
2148
+ <div style="width: 38px; height: 38px; border-radius: 8px; background: rgba(255,255,255,0.06); display: flex; align-items: center; justify-content: center; font-size: 20px;">
2149
+ ${t.icon}
2150
+ </div>
2151
+ <div>
2152
+ <h2 class="modal-title" style="font-size: 16px; margin: 0; color: var(--text-heading);">Confirm Template Launch: ${t.name}</h2>
2153
+ <span style="font-size: 11px; color: var(--text-muted);">${t.badge}</span>
2154
+ </div>
2155
+ </div>
2156
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
2157
+ </div>
2158
+
2159
+ <div class="modal-body" style="padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1rem;">
2160
+ <p style="font-size: 13px; color: var(--text-muted); line-height: 1.5; margin: 0;">
2161
+ ${t.description}
2162
+ </p>
2163
+
2164
+ <div style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 0.85rem 1rem;">
2165
+ <div style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.04em; margin-bottom: 0.6rem;">
2166
+ Collections to be created & pre-seeded:
2167
+ </div>
2168
+ <div style="display: flex; flex-direction: column; gap: 0.45rem;">
2169
+ ${t.collections.map(c => `
2170
+ <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 0.5rem; font-size: 12px; border-bottom: 1px solid rgba(255,255,255,0.04); padding-bottom: 0.35rem;">
2171
+ <div>
2172
+ <strong style="color: var(--text-heading); font-family: var(--font-mono);">${c.name}</strong>
2173
+ <span style="color: var(--text-muted); font-size: 11px; margin-left: 6px;">(${c.desc})</span>
2174
+ </div>
2175
+ <span class="badge badge-get" style="font-size: 10px; flex-shrink: 0;">${c.count} records</span>
2176
+ </div>
2177
+ `).join('')}
2178
+ </div>
2179
+ <div style="margin-top: 0.6rem; font-size: 11px; color: var(--accent-primary);">
2180
+ ✨ ${t.stats}
2181
+ </div>
2182
+ </div>
2183
+
2184
+ ${existingMatches.length > 0 ? `
2185
+ <div style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.35); border-radius: 8px; padding: 0.75rem 1rem;">
2186
+ <div style="font-size: 12px; font-weight: 700; color: #f59e0b; margin-bottom: 0.25rem;">
2187
+ ⚠️ Existing Collections Detected
2188
+ </div>
2189
+ <div style="font-size: 12px; color: #cbd5e1; line-height: 1.4;">
2190
+ The following collection(s) already exist: <strong style="color: var(--text-heading);">${existingMatches.map(m => m.name).join(', ')}</strong>.
2191
+ </div>
2192
+ </div>
2193
+ ` : ''}
2194
+
2195
+ <div style="background: rgba(255, 255, 255, 0.03); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 0.75rem 1rem;">
2196
+ <label style="display: flex; align-items: flex-start; gap: 0.6rem; font-size: 12px; color: var(--text-main); cursor: pointer;">
2197
+ <input type="checkbox" id="confirm-template-overwrite" style="margin-top: 2px;">
2198
+ <div>
2199
+ <strong style="color: var(--text-heading);">Overwrite existing collections if they match</strong>
2200
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 2px;">
2201
+ If checked, matching tables and their records will be overwritten with the template data.
2202
+ </div>
2203
+ </div>
2204
+ </label>
2205
+ </div>
2206
+ </div>
2207
+
2208
+ <div class="modal-footer" style="padding: 1rem 1.5rem; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end; gap: 0.75rem;">
2209
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
2210
+ <button class="btn btn-primary" id="btn-confirm-apply-${templateId}" onclick="submitApplyTemplateConfirmed('${templateId}')" style="display: flex; align-items: center; gap: 6px;">
2211
+ <span>Confirm & Launch 🚀</span>
2212
+ </button>
2213
+ </div>
2214
+ </div>
2215
+ </div>
2216
+ `;
2217
+ focusFirstModalField(modal);
2218
+ }
2219
+
2220
+ async function submitApplyTemplateConfirmed(templateId) {
2221
+ const btn = document.getElementById(`btn-confirm-apply-${templateId}`);
2222
+ const overwrite = document.getElementById('confirm-template-overwrite')?.checked ?? false;
2223
+
2224
+ if (btn) {
2225
+ btn.disabled = true;
2226
+ btn.innerHTML = `
2227
+ <div style="width:13px; height:13px; border:2px solid #ffffff; border-top-color:transparent; border-radius:50%; animation:spin 0.6s linear infinite; display:inline-block; margin-right:4px;"></div>
2228
+ <span>Seeding Template...</span>
2229
+ `;
2230
+ }
2231
+
2232
+ try {
2233
+ const res = await api('/api/templates/apply', {
2234
+ method: 'POST',
2235
+ body: JSON.stringify({
2236
+ template: templateId,
2237
+ overwrite: Boolean(overwrite),
2238
+ }),
2239
+ });
2240
+
2241
+ if (res.skipped) {
2242
+ toast(res.message || `Template '${templateId}' is already applied.`, 'info');
2243
+ } else {
2244
+ toast(`✨ ${res.templateName} recipe installed! ${res.collections.length} collections, ${res.totalRecords} records seeded.`, 'success');
2245
+ }
2246
+
2247
+ closeModal();
2248
+ await loadCollections();
2249
+
2250
+ // Select the primary collection of the template
2251
+ const primaryColMap = {
2252
+ ecommerce: 'products',
2253
+ blog: 'posts',
2254
+ crm: 'deals',
2255
+ };
2256
+ const targetCol = primaryColMap[templateId] || res.collections[0];
2257
+ if (targetCol && state.collections.some(c => c.name === targetCol)) {
2258
+ selectCollection(targetCol);
2259
+ } else {
2260
+ selectNav('home');
2261
+ }
2262
+ } catch (err) {
2263
+ toast(`Failed to apply template: ${err.message || String(err)}`, 'error');
2264
+ if (btn) {
2265
+ btn.disabled = false;
2266
+ btn.innerHTML = `<span>Confirm & Launch 🚀</span>`;
2267
+ }
2268
+ }
2269
+ }
2270
+
2271
+ function applyTemplateFromUi(templateId) {
2272
+ openApplyTemplateConfirmModal(templateId);
2273
+ }
2274
+
2275
+ // Delete Collection Modal
2276
+ function openDeleteCollectionModal(colName) {
2277
+ const col = state.collections.find(c => c.name === colName) || { name: colName };
2278
+ const modal = document.getElementById('modal-root');
2279
+ modal.innerHTML = `
2280
+ <div class="modal-backdrop" onclick="if(event.target===this)closeModal()">
2281
+ <div class="modal" style="max-width:440px;">
2282
+ <div class="modal-header" style="border-bottom-color:rgba(239, 68, 68, 0.2);">
2283
+ <div style="display:flex; align-items:center; gap:0.5rem;">
2284
+ <span style="font-size:18px;">⚠️</span>
2285
+ <h2 class="modal-title" style="color:#ef4444; font-size:16px;">Delete Collection</h2>
2286
+ </div>
2287
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
2288
+ </div>
2289
+ <div class="modal-body" style="padding:1.25rem; display:flex; flex-direction:column; gap:1rem;">
2290
+ <p style="font-size:13px; color:#cbd5e1; line-height:1.5; margin:0;">
2291
+ Are you sure you want to permanently delete the collection <strong style="color: var(--text-heading); font-family:var(--font-mono);">${col.name}</strong>?
2292
+ </p>
2293
+ <div style="background:rgba(239, 68, 68, 0.08); border:1px solid rgba(239, 68, 68, 0.25); border-radius:6px; padding:0.75rem; font-size:12px; color:#fca5a5; line-height:1.4;">
2294
+ This will drop the SQLite table <strong style="font-family:var(--font-mono);">${col.name}</strong>, remove all schema definitions, and permanently erase all stored records and file assets.
2295
+ </div>
2296
+ <div class="form-group" style="margin:0;">
2297
+ <label class="form-label" style="font-size:12px;">Type <strong>${col.name}</strong> to confirm:</label>
2298
+ <input type="text" class="form-input" id="confirm-delete-col-input" placeholder="${col.name}" oninput="
2299
+ const btn = document.getElementById('btn-confirm-delete-col');
2300
+ if (btn) btn.disabled = (this.value.trim() !== '${col.name}');
2301
+ " onkeydown="
2302
+ if (event.key === 'Enter' && this.value.trim() === '${col.name}') {
2303
+ submitDeleteCollection('${col.name}');
2304
+ }
2305
+ " autofocus>
2306
+ </div>
2307
+ </div>
2308
+ <div class="modal-footer" style="padding:0.75rem 1.25rem;">
2309
+ <button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
2310
+ <button class="btn btn-danger" id="btn-confirm-delete-col" disabled onclick="submitDeleteCollection('${col.name}')">
2311
+ Delete Permanently
2312
+ </button>
2313
+ </div>
2314
+ </div>
2315
+ </div>
2316
+ `;
2317
+ focusFirstModalField(modal);
2318
+ }
2319
+
2320
+ async function submitDeleteCollection(colName) {
2321
+ const btn = document.getElementById('btn-confirm-delete-col');
2322
+ if (btn) {
2323
+ btn.disabled = true;
2324
+ btn.innerHTML = `
2325
+ <div style="width:12px; height:12px; border:2px solid #ffffff; border-top-color:transparent; border-radius:50%; animation:spin 0.6s linear infinite; display:inline-block; margin-right:4px;"></div>
2326
+ <span>Deleting...</span>
2327
+ `;
2328
+ }
2329
+
2330
+ try {
2331
+ await api('/api/collections/' + encodeURIComponent(colName), {
2332
+ method: 'DELETE',
2333
+ });
2334
+
2335
+ toast(`Collection '${colName}' deleted successfully`, 'success');
2336
+ closeModal();
2337
+
2338
+ if (state.activeCollection?.name === colName) {
2339
+ state.activeCollection = null;
2340
+ }
2341
+
2342
+ await loadCollections();
2343
+ selectNav('home');
2344
+ } catch (err) {
2345
+ toast(`Failed to delete collection: ${err.message || String(err)}`, 'error');
2346
+ if (btn) {
2347
+ btn.disabled = false;
2348
+ btn.innerHTML = 'Delete Permanently';
2349
+ }
2350
+ }
2351
+ }
2352
+
2353
+ // Expose helpers on window for browser event handlers & tests
2354
+ if (typeof window !== 'undefined') {
2355
+ window.closeModal = closeModal;
2356
+ window.openNewRecordModal = openNewRecordModal;
2357
+ window.submitNewRecord = submitNewRecord;
2358
+ window.editRecord = editRecord;
2359
+ window.submitEditRecord = submitEditRecord;
2360
+ window.deleteRecord = deleteRecord;
2361
+ window.openNewCollectionModal = openNewCollectionModal;
2362
+ window.openImportJsonModal = openImportJsonModal;
2363
+ window.submitNewCollection = submitNewCollection;
2364
+ window.openImportModal = openImportModal;
2365
+ window.openMockDataModal = openMockDataModal;
2366
+ window.openTemplatesModal = openTemplatesModal;
2367
+ window.openApplyTemplateConfirmModal = openApplyTemplateConfirmModal;
2368
+ window.openDeleteCollectionModal = openDeleteCollectionModal;
2369
+ window.submitDeleteCollection = submitDeleteCollection;
2370
+ window.handleToggleChange = handleToggleChange;
2371
+ window.validateJsonField = validateJsonField;
2372
+ window.formatJsonField = formatJsonField;
2373
+ window.formatForDatetimeLocal = formatForDatetimeLocal;
2374
+ window.focusFirstModalField = focusFirstModalField;
2375
+ window.submitActiveModal = submitActiveModal;
2376
+ window.handleModalKeyDown = handleModalKeyDown;
2377
+ }
2378
+
2379
+