express-file-cluster 0.9.6 → 0.10.2

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 (233) hide show
  1. package/dist/auth/index.cjs +7 -6
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +5 -5
  6. package/dist/chunk-3SWI46YK.js +74 -0
  7. package/dist/chunk-3SWI46YK.js.map +1 -0
  8. package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
  9. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
  10. package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
  11. package/dist/chunk-74BSJXWD.cjs +220 -0
  12. package/dist/chunk-74BSJXWD.cjs.map +1 -0
  13. package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
  14. package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
  15. package/dist/chunk-AGOYTFRO.cjs +42 -0
  16. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  17. package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
  18. package/dist/chunk-B6MB6HEG.js.map +1 -0
  19. package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
  20. package/dist/chunk-BG4A7Z32.js.map +1 -0
  21. package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
  22. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  23. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  24. package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
  25. package/dist/chunk-DN4TCGYB.js.map +1 -0
  26. package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
  27. package/dist/chunk-H2PVWCWC.cjs.map +1 -0
  28. package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
  29. package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
  30. package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
  31. package/dist/chunk-JP36TLL4.cjs.map +1 -0
  32. package/dist/chunk-KLWL7XSC.js +220 -0
  33. package/dist/chunk-KLWL7XSC.js.map +1 -0
  34. package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
  35. package/dist/chunk-M53GODCX.cjs.map +1 -0
  36. package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
  37. package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
  38. package/dist/chunk-R2K7AFIB.cjs.map +1 -0
  39. package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
  40. package/dist/chunk-RETV3GKE.js.map +1 -0
  41. package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
  42. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  43. package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
  44. package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
  45. package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
  46. package/dist/chunk-V73R76I4.js.map +1 -0
  47. package/dist/chunk-XPY5TQDK.js +42 -0
  48. package/dist/chunk-XPY5TQDK.js.map +1 -0
  49. package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
  50. package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
  51. package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
  52. package/dist/chunk-Y75V5FCU.js.map +1 -0
  53. package/dist/cli/db-runner.cjs +2059 -126
  54. package/dist/cli/db-runner.cjs.map +1 -1
  55. package/dist/cli/db-runner.js +2034 -102
  56. package/dist/cli/db-runner.js.map +1 -1
  57. package/dist/cli/index.cjs +50 -29
  58. package/dist/cli/index.cjs.map +1 -1
  59. package/dist/cli/index.js +39 -21
  60. package/dist/cli/index.js.map +1 -1
  61. package/dist/docs/api-reference/auth.md +23 -0
  62. package/dist/docs/api-reference/collection.md +44 -1
  63. package/dist/docs/api-reference/compose.md +1 -1
  64. package/dist/docs/api-reference/db.md +8 -0
  65. package/dist/docs/api-reference/ignite.md +13 -1
  66. package/dist/docs/api-reference/testing.md +26 -0
  67. package/dist/docs/api-reference/types.md +99 -0
  68. package/dist/docs/cli/add.md +2 -2
  69. package/dist/docs/cli/db.md +2 -2
  70. package/dist/docs/core-concepts/background-tasks.md +6 -3
  71. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  72. package/dist/docs/core-concepts/middleware.md +2 -2
  73. package/dist/docs/getting-started/index.md +6 -1
  74. package/dist/docs/guides/authentication.md +33 -0
  75. package/dist/docs/guides/caching.md +34 -1
  76. package/dist/docs/guides/database.md +17 -0
  77. package/dist/docs/guides/environment-variables.md +6 -0
  78. package/dist/docs/guides/feature-matrix.md +58 -0
  79. package/dist/docs/guides/generated-portals.md +3 -1
  80. package/dist/docs/guides/logging.md +17 -0
  81. package/dist/docs/guides/migrations.md +26 -3
  82. package/dist/docs/guides/testing.md +31 -0
  83. package/dist/docs/guides/which-api.md +2 -2
  84. package/dist/docs/index.md +4 -1
  85. package/dist/docs/skills/SKILL.md +5 -1
  86. package/dist/docs/skills/api-surface.md +25 -4
  87. package/dist/docs/skills/auth-internals.md +14 -1
  88. package/dist/docs/skills/pre-flight.md +6 -0
  89. package/dist/docs/skills/routing-rules.md +1 -1
  90. package/dist/docs/skills/tasks-internals.md +4 -3
  91. package/dist/docs/skills/what-not-to-invent.md +13 -4
  92. package/dist/docs/versioning.md +1 -1
  93. package/dist/index.cjs +135 -255
  94. package/dist/index.cjs.map +1 -1
  95. package/dist/index.d.cts +228 -3
  96. package/dist/index.d.ts +228 -3
  97. package/dist/index.js +96 -217
  98. package/dist/index.js.map +1 -1
  99. package/dist/pgboss-backend-4X2YT4RB.js +14 -0
  100. package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
  101. package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
  102. package/dist/registry/index.json +39 -3
  103. package/dist/registry/js-mongo/account-security.json +1 -1
  104. package/dist/registry/js-mongo/admin-users.json +1 -1
  105. package/dist/registry/js-mongo/auth.json +1 -1
  106. package/dist/registry/js-mongo/auth@apple.json +1 -1
  107. package/dist/registry/js-mongo/auth@google.json +1 -1
  108. package/dist/registry/js-mongo/forgot-password.json +1 -1
  109. package/dist/registry/js-mongo/user-profile.json +1 -1
  110. package/dist/registry/js-mongo-collection/_base.json +1 -0
  111. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  112. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  113. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  114. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  115. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  116. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  117. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  118. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  119. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  120. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  121. package/dist/registry/js-mongo-collection/admin.json +1 -0
  122. package/dist/registry/js-mongo-collection/auth.json +1 -0
  123. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  124. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  125. package/dist/registry/js-mongo-collection/billing.json +1 -0
  126. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  127. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  128. package/dist/registry/js-mongo-collection/files.json +1 -0
  129. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  130. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  131. package/dist/registry/js-mongo-collection/support.json +1 -0
  132. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  133. package/dist/registry/js-pg-model/account-security.json +1 -1
  134. package/dist/registry/js-pg-model/admin-users.json +1 -1
  135. package/dist/registry/js-pg-model/auth.json +1 -1
  136. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  137. package/dist/registry/js-pg-model/auth@google.json +1 -1
  138. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  139. package/dist/registry/js-pg-model/user-profile.json +1 -1
  140. package/dist/registry/js-pg-table/account-security.json +1 -1
  141. package/dist/registry/js-pg-table/admin-users.json +1 -1
  142. package/dist/registry/js-pg-table/auth.json +1 -1
  143. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  144. package/dist/registry/js-pg-table/auth@google.json +1 -1
  145. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  146. package/dist/registry/js-pg-table/user-profile.json +1 -1
  147. package/dist/registry/ts-mongo/account-security.json +1 -1
  148. package/dist/registry/ts-mongo/admin-users.json +1 -1
  149. package/dist/registry/ts-mongo/auth.json +1 -1
  150. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  151. package/dist/registry/ts-mongo/auth@google.json +1 -1
  152. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  153. package/dist/registry/ts-mongo/user-profile.json +1 -1
  154. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  155. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  156. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  157. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  158. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  159. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  160. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  161. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  162. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  163. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  164. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  165. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  166. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  167. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  168. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  169. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  170. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  171. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  172. package/dist/registry/ts-mongo-collection/files.json +1 -0
  173. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  174. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  175. package/dist/registry/ts-mongo-collection/support.json +1 -0
  176. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  177. package/dist/registry/ts-pg-model/account-security.json +1 -1
  178. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  179. package/dist/registry/ts-pg-model/auth.json +1 -1
  180. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  181. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  182. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  183. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  184. package/dist/registry/ts-pg-table/account-security.json +1 -1
  185. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  186. package/dist/registry/ts-pg-table/auth.json +1 -1
  187. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  188. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  189. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  190. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  191. package/dist/tasks/index.cjs +5 -2
  192. package/dist/tasks/index.cjs.map +1 -1
  193. package/dist/tasks/index.d.cts +4 -2
  194. package/dist/tasks/index.d.ts +4 -2
  195. package/dist/tasks/index.js +3 -1
  196. package/dist/testing-cjs.cjs +5 -0
  197. package/dist/testing.cjs +59 -0
  198. package/dist/testing.cjs.map +1 -0
  199. package/dist/testing.d.cts +27 -0
  200. package/dist/testing.d.ts +27 -0
  201. package/dist/testing.js +58 -0
  202. package/dist/testing.js.map +1 -0
  203. package/dist/thread-runner.cjs +9 -0
  204. package/dist/thread-runner.cjs.map +1 -0
  205. package/dist/thread-runner.d.cts +3 -0
  206. package/dist/thread-runner.d.ts +3 -0
  207. package/dist/thread-runner.js +8 -0
  208. package/dist/thread-runner.js.map +1 -0
  209. package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
  210. package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
  211. package/package.json +6 -1
  212. package/dist/chunk-2SETEVMO.js.map +0 -1
  213. package/dist/chunk-73XJUT2S.js.map +0 -1
  214. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  215. package/dist/chunk-BBSZLGZW.js.map +0 -1
  216. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  217. package/dist/chunk-HBYSKULC.js.map +0 -1
  218. package/dist/chunk-LJNSJFOL.js +0 -38
  219. package/dist/chunk-LJNSJFOL.js.map +0 -1
  220. package/dist/chunk-OFA7OGN5.js.map +0 -1
  221. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  222. package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
  223. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  224. package/dist/chunk-TYCYYLLM.cjs.map +0 -1
  225. package/dist/chunk-ULWNHN6P.js.map +0 -1
  226. package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
  227. package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
  228. package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
  229. package/dist/pgboss-backend-I6DFUNRM.js +0 -14
  230. /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
  231. /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
  232. /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
  233. /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  connectMongo,
3
+ loadMongoose,
3
4
  setDbClient
4
- } from "../chunk-OFA7OGN5.js";
5
+ } from "../chunk-BG4A7Z32.js";
5
6
  import {
6
7
  camel,
7
8
  lcFirst,
@@ -9,7 +10,7 @@ import {
9
10
  plural,
10
11
  singular,
11
12
  writeModels
12
- } from "../chunk-BBSZLGZW.js";
13
+ } from "../chunk-DN4TCGYB.js";
13
14
  import {
14
15
  registeredModels,
15
16
  setAutoSync,
@@ -17,12 +18,13 @@ import {
17
18
  setSyncSuppressed,
18
19
  snakeCase,
19
20
  tableNameFor
20
- } from "../chunk-ULWNHN6P.js";
21
+ } from "../chunk-RETV3GKE.js";
22
+ import "../chunk-XPY5TQDK.js";
21
23
  import {
22
24
  closePostgres,
23
25
  configureLogger,
24
26
  connectPostgres
25
- } from "../chunk-73XJUT2S.js";
27
+ } from "../chunk-V73R76I4.js";
26
28
 
27
29
  // src/cli/db-runner.ts
28
30
  import pc from "picocolors";
@@ -175,18 +177,1645 @@ async function runSeeds(dir, engine, client, only, onRun) {
175
177
  }
176
178
 
177
179
  // src/db/studio.ts
180
+ import crypto from "crypto";
178
181
  import http from "http";
182
+
183
+ // src/db/studio-page.ts
184
+ var STUDIO_HTML = `<!doctype html>
185
+ <html lang="en">
186
+ <head>
187
+ <meta charset="utf-8">
188
+ <title>EFC Studio</title>
189
+ <meta name="viewport" content="width=device-width,initial-scale=1">
190
+ <meta name="color-scheme" content="dark">
191
+ <style>
192
+ /* Exact client/ tokens */
193
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
194
+ [hidden] { display: none !important; }
195
+
196
+ :root {
197
+ color-scheme: dark;
198
+ --bg: #08090b;
199
+ --bg-card: #0e1014;
200
+ --bg-raised: #14171c;
201
+ --border: #1d2127;
202
+ --border-lit: #2b3038;
203
+ --text: #e8eaed;
204
+ --text-dim: #959ba5;
205
+ --text-muted: #5b616b;
206
+ --accent: #F0A030;
207
+ --accent-2: #f6c37a;
208
+ --accent-dim: rgba(240,160,48,.10);
209
+ --accent-glow:rgba(240,160,48,.22);
210
+ --purple: #b9a8f5;
211
+ --blue: #7cb6f2;
212
+ --orange: #f0a070;
213
+ --green: #8cc49f;
214
+ --red: #f07a72;
215
+ /* Local fonts only: the studio makes no outside requests (and works offline).
216
+ Inter / JetBrains Mono are used when installed, the system's fonts otherwise. */
217
+ --font-mono: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, Consolas, monospace;
218
+ --font-sans: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
219
+ --r: 8px;
220
+ --radius-lg: 12px;
221
+ --ease-out: cubic-bezier(.16,1,.3,1);
222
+ }
223
+
224
+ html, body {
225
+ height: 100%;
226
+ margin: 0;
227
+ overflow: hidden;
228
+ background: var(--bg);
229
+ color: var(--text);
230
+ font-family: var(--font-sans);
231
+ font-size: 16px;
232
+ line-height: 1.5;
233
+ -webkit-font-smoothing: antialiased;
234
+ }
235
+
236
+ body {
237
+ display: flex;
238
+ flex-direction: column;
239
+ }
240
+
241
+ /* Global grid overlay \u2014 exact from client/workspace.css */
242
+ body::before {
243
+ content: '';
244
+ position: fixed;
245
+ inset: 0;
246
+ z-index: 0;
247
+ background-image:
248
+ linear-gradient(var(--border) 1px, transparent 1px),
249
+ linear-gradient(90deg, var(--border) 1px, transparent 1px);
250
+ background-size: 60px 60px;
251
+ opacity: .28;
252
+ pointer-events: none;
253
+ }
254
+
255
+ /* Scrollbars \u2014 exact from client/workspace.css */
256
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
257
+ ::-webkit-scrollbar-track { background: var(--bg); }
258
+ ::-webkit-scrollbar-thumb { background: var(--border-lit); border-radius: 3px; }
259
+ ::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
260
+ * { scrollbar-width: thin; scrollbar-color: var(--border-lit) var(--bg); }
261
+
262
+ ::selection { background: var(--accent); color: #111; }
263
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
264
+
265
+ /* \u2500\u2500\u2500 TOP BAR (exact from client/workspace.html .ws-topbar) \u2500\u2500\u2500 */
266
+ .ws-topbar {
267
+ flex-shrink: 0;
268
+ display: flex;
269
+ align-items: center;
270
+ gap: 16px;
271
+ height: 60px;
272
+ padding: 0 24px;
273
+ border-bottom: 1px solid var(--border);
274
+ background: var(--bg);
275
+ position: relative;
276
+ z-index: 10;
277
+ }
278
+
279
+ .logo {
280
+ font-family: var(--font-mono);
281
+ font-size: 1.25rem;
282
+ font-weight: 500;
283
+ letter-spacing: -.5px;
284
+ display: flex;
285
+ align-items: center;
286
+ gap: 10px;
287
+ color: var(--text);
288
+ user-select: none;
289
+ white-space: nowrap;
290
+ }
291
+ .logo-dot { color: var(--accent); }
292
+ .logo-img { width: 26px; height: 26px; color: var(--accent); flex-shrink: 0; }
293
+
294
+ .ws-topbar-label {
295
+ font-family: var(--font-mono);
296
+ font-size: 14px;
297
+ color: var(--text-muted);
298
+ white-space: nowrap;
299
+ }
300
+
301
+ .badge-group {
302
+ display: flex;
303
+ align-items: center;
304
+ gap: 8px;
305
+ white-space: nowrap;
306
+ }
307
+ .badge-engine, .badge-mode {
308
+ font-family: var(--font-mono);
309
+ font-size: 12.5px;
310
+ font-weight: 500;
311
+ padding: 3px 10px;
312
+ border-radius: 4px;
313
+ line-height: 1.35;
314
+ }
315
+ .badge-engine.pg { color: var(--blue); background: rgba(124,182,242,.12); border: 1px solid rgba(124,182,242,.28); }
316
+ .badge-engine.mongo { color: var(--green); background: rgba(140,196,159,.12); border: 1px solid rgba(140,196,159,.28); }
317
+
318
+ .badge-mode.write { color: var(--green); background: rgba(140,196,159,.12); border: 1px solid rgba(140,196,159,.28); }
319
+ .badge-mode.ro { color: var(--text-muted); background: var(--bg-raised); border: 1px solid var(--border); }
320
+
321
+ .topbar-spacer { flex: 1; }
322
+
323
+ /* \u2500\u2500\u2500 BUTTONS & CONTROLS (exact from client/style.css) \u2500\u2500\u2500 */
324
+ .btn-primary, .btn-ghost, .btn-danger {
325
+ display: inline-flex; align-items: center; justify-content: center; gap: 8px;
326
+ font-family: var(--font-sans);
327
+ font-weight: 500; font-size: 14px; line-height: 1;
328
+ padding: 9px 18px; border-radius: var(--r);
329
+ white-space: nowrap; cursor: pointer;
330
+ transition: background .15s, border-color .15s, color .15s, transform .15s;
331
+ }
332
+
333
+ .btn-primary {
334
+ background: var(--accent); color: #1a1100; border: 1px solid var(--accent);
335
+ }
336
+ .btn-primary:hover:not(:disabled) {
337
+ background: #f3b04f;
338
+ transform: translateY(-1px);
339
+ }
340
+ .btn-primary:disabled {
341
+ opacity: .4; cursor: default; transform: none;
342
+ }
343
+
344
+ .btn-ghost {
345
+ border: 1px solid var(--border-lit); color: var(--text-dim); background: transparent;
346
+ }
347
+ .btn-ghost:hover:not(:disabled) {
348
+ border-color: var(--accent);
349
+ color: var(--accent);
350
+ }
351
+ .btn-ghost:disabled {
352
+ opacity: .35; cursor: default;
353
+ }
354
+
355
+ .btn-icon { padding: 9px 12px; }
356
+
357
+ .btn-group { display: inline-flex; }
358
+ .btn-group .btn-ghost { border-radius: 0; }
359
+ .btn-group .btn-ghost:first-child {
360
+ border-top-left-radius: var(--r);
361
+ border-bottom-left-radius: var(--r);
362
+ }
363
+ .btn-group .btn-ghost:last-child {
364
+ border-top-right-radius: var(--r);
365
+ border-bottom-right-radius: var(--r);
366
+ margin-left: -1px;
367
+ }
368
+
369
+ .btn-danger {
370
+ background: rgba(240, 122, 114, .12);
371
+ border: 1px solid rgba(240, 122, 114, .35);
372
+ color: var(--red);
373
+ }
374
+ .btn-danger:hover:not(:disabled) {
375
+ background: var(--red);
376
+ color: #1a0808;
377
+ border-color: var(--red);
378
+ }
379
+
380
+ /* Tabbar \u2014 exact from client/workspace.css */
381
+ .tabbar {
382
+ display: flex;
383
+ background: var(--bg-card);
384
+ border: 1px solid var(--border);
385
+ border-radius: var(--r);
386
+ overflow: hidden;
387
+ flex-shrink: 0;
388
+ }
389
+ .tab-item {
390
+ display: flex;
391
+ align-items: center;
392
+ gap: 8px;
393
+ padding: 9px 16px;
394
+ font-family: var(--font-mono);
395
+ font-size: 13.5px;
396
+ color: var(--text-dim);
397
+ background: transparent;
398
+ border: 0;
399
+ border-right: 1px solid var(--border);
400
+ cursor: pointer;
401
+ transition: color .15s, background .15s;
402
+ user-select: none;
403
+ }
404
+ .tab-item:last-child { border-right: 0; }
405
+ .tab-item:hover:not(:disabled) { color: var(--text); }
406
+ .tab-item.active {
407
+ background: var(--bg-raised);
408
+ color: var(--text);
409
+ box-shadow: inset 0 -2px 0 var(--accent);
410
+ }
411
+ .tab-item:disabled { opacity: .35; cursor: default; }
412
+
413
+ /* Search Inputs \u2014 exact style.css install input */
414
+ .input-search-wrap {
415
+ display: flex;
416
+ align-items: center;
417
+ background: var(--bg-raised);
418
+ border: 1px solid var(--border-lit);
419
+ border-radius: var(--r);
420
+ padding: 8px 12px;
421
+ gap: 8px;
422
+ transition: border-color .15s, box-shadow .15s;
423
+ }
424
+ .input-search-wrap:focus-within {
425
+ border-color: var(--accent);
426
+ box-shadow: 0 0 0 1px var(--accent-glow);
427
+ }
428
+ .input-search-wrap svg { color: var(--text-dim); flex-shrink: 0; }
429
+ .input-search {
430
+ background: none;
431
+ border: 0;
432
+ color: var(--text);
433
+ font-family: var(--font-mono);
434
+ font-size: 13.5px;
435
+ outline: none;
436
+ width: 100%;
437
+ }
438
+ .input-search::placeholder { color: var(--text-muted); }
439
+ .clear-btn {
440
+ background: none;
441
+ border: 0;
442
+ color: var(--text-dim);
443
+ cursor: pointer;
444
+ font-size: 15px;
445
+ padding: 0 2px;
446
+ }
447
+ .clear-btn:hover { color: var(--text); }
448
+
449
+ /* \u2500\u2500\u2500 APP BODY (Sidebar + Editor Area) \u2500\u2500\u2500 */
450
+ .ws-body {
451
+ flex: 1;
452
+ display: flex;
453
+ min-height: 0;
454
+ position: relative;
455
+ z-index: 1;
456
+ }
457
+
458
+ aside {
459
+ width: 290px;
460
+ min-width: 290px;
461
+ background: var(--bg-card);
462
+ border-right: 1px solid var(--border);
463
+ display: flex;
464
+ flex-direction: column;
465
+ overflow: hidden;
466
+ }
467
+
468
+ .search-box {
469
+ padding: 14px 16px 10px;
470
+ position: relative;
471
+ }
472
+
473
+ .sidebar-header {
474
+ padding: 12px 18px 8px;
475
+ font-family: var(--font-mono);
476
+ font-size: 12px;
477
+ font-weight: 600;
478
+ letter-spacing: 1.2px;
479
+ text-transform: uppercase;
480
+ color: var(--text-muted);
481
+ display: flex;
482
+ justify-content: space-between;
483
+ align-items: center;
484
+ }
485
+
486
+ .table-tree {
487
+ flex: 1;
488
+ overflow-y: auto;
489
+ padding: 4px 10px 18px;
490
+ }
491
+
492
+ .tree-row {
493
+ display: flex;
494
+ align-items: center;
495
+ justify-content: space-between;
496
+ gap: 10px;
497
+ padding: 8px 12px;
498
+ margin-bottom: 3px;
499
+ border-radius: 6px;
500
+ font-size: 13.5px;
501
+ min-height: 38px;
502
+ color: var(--text-dim);
503
+ cursor: pointer;
504
+ white-space: nowrap;
505
+ user-select: none;
506
+ border: 1px solid transparent;
507
+ transition: background .15s, color .15s;
508
+ }
509
+ .tree-row:hover {
510
+ background: var(--bg-raised);
511
+ color: var(--text);
512
+ }
513
+ .tree-row.active {
514
+ background: var(--accent-dim);
515
+ color: var(--text);
516
+ box-shadow: inset 2px 0 0 var(--accent);
517
+ }
518
+ .tree-left {
519
+ display: flex;
520
+ align-items: center;
521
+ gap: 8px;
522
+ overflow: hidden;
523
+ min-width: 0;
524
+ }
525
+ .ico-table {
526
+ color: var(--text-muted);
527
+ flex-shrink: 0;
528
+ }
529
+ .tree-row.active .ico-table {
530
+ color: var(--accent);
531
+ }
532
+ .table-name {
533
+ overflow: hidden;
534
+ text-overflow: ellipsis;
535
+ white-space: nowrap;
536
+ }
537
+ .tree-row.active .table-name {
538
+ color: var(--accent-2);
539
+ font-weight: 600;
540
+ }
541
+
542
+ .count-badge {
543
+ font-family: var(--font-mono);
544
+ font-size: 12px;
545
+ color: var(--text-muted);
546
+ background: var(--bg-raised);
547
+ border: 1px solid var(--border);
548
+ padding: 2px 7px;
549
+ border-radius: 4px;
550
+ flex-shrink: 0;
551
+ }
552
+ .tree-row.active .count-badge {
553
+ background: rgba(240,160,48,.15);
554
+ border-color: rgba(240,160,48,.35);
555
+ color: var(--accent);
556
+ }
557
+
558
+ /* \u2500\u2500\u2500 WORKSPACE CONTENT \u2500\u2500\u2500 */
559
+ main {
560
+ flex: 1;
561
+ display: flex;
562
+ flex-direction: column;
563
+ min-width: 0;
564
+ background: var(--bg);
565
+ overflow: hidden;
566
+ }
567
+
568
+ .workspace-bar {
569
+ height: 50px;
570
+ min-height: 50px;
571
+ padding: 0 24px;
572
+ background: var(--bg-raised);
573
+ border-bottom: 1px solid var(--border);
574
+ display: flex;
575
+ align-items: center;
576
+ gap: 14px;
577
+ flex-shrink: 0;
578
+ }
579
+ .active-title {
580
+ font-family: var(--font-mono);
581
+ font-size: 16px;
582
+ font-weight: 600;
583
+ color: var(--text);
584
+ margin: 0;
585
+ white-space: nowrap;
586
+ }
587
+ .meta-chip {
588
+ font-family: var(--font-mono);
589
+ font-size: 13px;
590
+ color: var(--text-dim);
591
+ background: var(--bg-card);
592
+ border: 1px solid var(--border);
593
+ padding: 3px 10px;
594
+ border-radius: 4px;
595
+ white-space: nowrap;
596
+ }
597
+
598
+ /* \u2500\u2500\u2500 DATA GRID \u2500\u2500\u2500 */
599
+ .wrap {
600
+ overflow: auto;
601
+ flex: 1;
602
+ background: var(--bg);
603
+ position: relative;
604
+ }
605
+
606
+ table.data-table {
607
+ border-collapse: separate;
608
+ border-spacing: 0;
609
+ width: max-content;
610
+ min-width: 100%;
611
+ }
612
+
613
+ th, td {
614
+ border-bottom: 1px solid var(--border);
615
+ border-right: 1px solid var(--border);
616
+ padding: 13px 20px;
617
+ text-align: left;
618
+ vertical-align: middle;
619
+ max-width: 460px;
620
+ overflow: hidden;
621
+ text-overflow: ellipsis;
622
+ white-space: nowrap;
623
+ font-size: 14px;
624
+ line-height: 1.5;
625
+ }
626
+
627
+ th {
628
+ position: sticky;
629
+ top: 0;
630
+ background: var(--bg-card);
631
+ color: var(--text-dim);
632
+ font-family: var(--font-mono);
633
+ font-weight: 600;
634
+ font-size: 12.5px;
635
+ letter-spacing: .06em;
636
+ text-transform: uppercase;
637
+ z-index: 5;
638
+ cursor: pointer;
639
+ user-select: none;
640
+ transition: color .15s, background .15s;
641
+ padding: 12px 20px;
642
+ }
643
+ th:hover {
644
+ color: var(--accent);
645
+ background: var(--bg-raised);
646
+ }
647
+ th .th-content {
648
+ display: flex;
649
+ align-items: center;
650
+ justify-content: space-between;
651
+ gap: 8px;
652
+ }
653
+ th .sort-arrow {
654
+ color: var(--accent);
655
+ font-size: 11px;
656
+ }
657
+
658
+ td {
659
+ font-family: var(--font-mono);
660
+ background: var(--bg);
661
+ color: var(--text);
662
+ }
663
+ tr:hover td {
664
+ background: var(--bg-card);
665
+ }
666
+
667
+ /* Syntax colors from client/style.css */
668
+ td.cell-id { color: var(--purple); font-weight: 500; }
669
+ td.cell-number { color: var(--blue); }
670
+ td.cell-date { color: var(--orange); }
671
+ td.cell-bool-true { color: var(--green); }
672
+ td.cell-bool-false { color: var(--text-muted); }
673
+ td.cell-null { color: var(--text-muted); font-style: italic; }
674
+ td.cell-obj { color: var(--accent); cursor: pointer; }
675
+ td.cell-obj:hover { text-decoration: underline; color: var(--accent-2); }
676
+
677
+ td.num-col, th.num-col {
678
+ width: 52px;
679
+ min-width: 52px;
680
+ max-width: 52px;
681
+ text-align: center;
682
+ position: sticky;
683
+ left: 0;
684
+ z-index: 3;
685
+ border-right: 1px solid var(--border);
686
+ color: var(--text-muted);
687
+ font-family: var(--font-mono);
688
+ font-size: 12px;
689
+ user-select: none;
690
+ }
691
+ th.num-col { z-index: 7; background: var(--bg-card); cursor: default; }
692
+ td.num-col { background: var(--bg-card); }
693
+ tr:hover td.num-col { background: var(--bg-raised); color: var(--accent); }
694
+
695
+ td.act-col, th.act-col {
696
+ width: 100px;
697
+ min-width: 100px;
698
+ max-width: 100px;
699
+ text-align: center;
700
+ position: sticky;
701
+ left: 52px;
702
+ z-index: 2;
703
+ border-right: 2px solid var(--border);
704
+ }
705
+ th.act-col { z-index: 6; background: var(--bg-card); cursor: default; }
706
+ td.act-col { background: var(--bg-card); }
707
+ tr:hover td.act-col { background: var(--bg-raised); }
708
+
709
+ tr.ghost-row td {
710
+ background: transparent !important;
711
+ border-bottom: 1px solid rgba(29, 33, 39, .6);
712
+ border-right: 1px solid rgba(29, 33, 39, .6);
713
+ pointer-events: none;
714
+ user-select: none;
715
+ height: 46px;
716
+ }
717
+ tr.ghost-row td.num-col {
718
+ background: rgba(14, 16, 20, .3) !important;
719
+ }
720
+
721
+ .row-actions {
722
+ display: flex;
723
+ align-items: center;
724
+ justify-content: center;
725
+ gap: 6px;
726
+ }
727
+ .row-act-btn {
728
+ background: none;
729
+ border: 0;
730
+ color: var(--text-dim);
731
+ cursor: pointer;
732
+ padding: 6px;
733
+ border-radius: 4px;
734
+ display: flex;
735
+ align-items: center;
736
+ transition: color .15s, background .15s;
737
+ }
738
+ .row-act-btn svg { width: 15px; height: 15px; }
739
+ .row-act-btn:hover { background: var(--border-lit); color: var(--text); }
740
+ .row-act-btn.edit:hover { color: var(--accent); }
741
+ .row-act-btn.del:hover { color: var(--red); }
742
+
743
+ /* \u2500\u2500\u2500 STRUCTURE CARDS \u2500\u2500\u2500 */
744
+ .structure-wrap {
745
+ padding: 28px;
746
+ max-width: 1100px;
747
+ }
748
+ .window-card {
749
+ background: var(--bg-card);
750
+ border: 1px solid var(--border);
751
+ border-radius: var(--radius-lg);
752
+ overflow: hidden;
753
+ margin-bottom: 24px;
754
+ box-shadow: 0 16px 40px rgba(0,0,0,.45);
755
+ }
756
+ .code-bar {
757
+ display: flex;
758
+ align-items: center;
759
+ gap: 8px;
760
+ padding: 12px 18px;
761
+ border-bottom: 1px solid var(--border);
762
+ background: var(--bg-raised);
763
+ }
764
+ .dot { width: 10px; height: 10px; border-radius: 50%; }
765
+ .dot.r { background: #ff5f57; }
766
+ .dot.y { background: #febc2e; }
767
+ .dot.g { background: #28c840; }
768
+ .code-bar-label {
769
+ font-family: var(--font-mono);
770
+ font-size: 13px;
771
+ font-weight: 500;
772
+ color: var(--text-dim);
773
+ margin-left: 6px;
774
+ }
775
+ .type-tag {
776
+ font-family: var(--font-mono);
777
+ font-size: 12.5px;
778
+ color: var(--blue);
779
+ background: rgba(124,182,242,.12);
780
+ border: 1px solid rgba(124,182,242,.28);
781
+ padding: 3px 8px;
782
+ border-radius: 4px;
783
+ }
784
+ .null-tag {
785
+ font-family: var(--font-mono);
786
+ font-size: 12.5px;
787
+ padding: 3px 8px;
788
+ border-radius: 4px;
789
+ }
790
+ .null-tag.not-null { color: var(--green); background: rgba(140,196,159,.12); border: 1px solid rgba(140,196,159,.28); }
791
+ .null-tag.nullable { color: var(--text-muted); background: var(--bg-raised); border: 1px solid var(--border); }
792
+
793
+ /* Empty state */
794
+ .empty-state {
795
+ display: flex;
796
+ flex-direction: column;
797
+ align-items: center;
798
+ justify-content: center;
799
+ padding: 96px 20px;
800
+ color: var(--text-dim);
801
+ text-align: center;
802
+ }
803
+ .empty-state svg {
804
+ color: var(--accent);
805
+ opacity: .7;
806
+ margin-bottom: 16px;
807
+ }
808
+ .empty-state h3 {
809
+ font-size: 1.25rem;
810
+ font-weight: 600;
811
+ color: var(--text);
812
+ margin-bottom: 8px;
813
+ }
814
+ .empty-state p {
815
+ color: var(--text-dim);
816
+ font-size: 15px;
817
+ }
818
+
819
+ /* \u2500\u2500\u2500 MODALS \u2500\u2500\u2500 */
820
+ .modal-overlay {
821
+ position: fixed;
822
+ inset: 0;
823
+ background: rgba(8, 9, 11, .85);
824
+ backdrop-filter: blur(8px);
825
+ -webkit-backdrop-filter: blur(8px);
826
+ display: none;
827
+ align-items: center;
828
+ justify-content: center;
829
+ z-index: 100;
830
+ }
831
+ .modal-overlay.on { display: flex; }
832
+
833
+ .modal-window {
834
+ background: var(--bg-card);
835
+ border: 1px solid var(--border-lit);
836
+ border-radius: var(--radius-lg);
837
+ width: min(780px, 94vw);
838
+ max-height: 88vh;
839
+ display: flex;
840
+ flex-direction: column;
841
+ box-shadow: 0 24px 80px rgba(0,0,0,.7), 0 0 0 1px var(--border);
842
+ overflow: hidden;
843
+ animation: modalIn .2s var(--ease-out);
844
+ }
845
+ @keyframes modalIn {
846
+ from { opacity: 0; transform: translateY(12px) scale(.98); }
847
+ to { opacity: 1; transform: none; }
848
+ }
849
+
850
+ .modal-header {
851
+ padding: 14px 22px;
852
+ background: var(--bg-raised);
853
+ border-bottom: 1px solid var(--border);
854
+ display: flex;
855
+ align-items: center;
856
+ justify-content: space-between;
857
+ }
858
+ .modal-header h3 {
859
+ font-family: var(--font-mono);
860
+ font-size: 16px;
861
+ font-weight: 600;
862
+ color: var(--text);
863
+ margin: 0;
864
+ }
865
+ .modal-close {
866
+ background: none;
867
+ border: 0;
868
+ color: var(--text-dim);
869
+ font-size: 20px;
870
+ cursor: pointer;
871
+ }
872
+ .modal-close:hover { color: var(--text); }
873
+
874
+ .modal-tabs {
875
+ display: flex;
876
+ background: var(--bg-card);
877
+ border-bottom: 1px solid var(--border);
878
+ padding: 0 16px;
879
+ }
880
+ .modal-tab-btn {
881
+ background: none;
882
+ border: 0;
883
+ border-bottom: 2px solid transparent;
884
+ padding: 11px 20px;
885
+ font-family: var(--font-mono);
886
+ font-size: 14px;
887
+ color: var(--text-dim);
888
+ cursor: pointer;
889
+ transition: color .15s;
890
+ }
891
+ .modal-tab-btn:hover { color: var(--text); }
892
+ .modal-tab-btn.active {
893
+ color: var(--accent);
894
+ border-bottom-color: var(--accent);
895
+ font-weight: 500;
896
+ }
897
+
898
+ .modal-body {
899
+ padding: 24px;
900
+ overflow-y: auto;
901
+ flex: 1;
902
+ }
903
+
904
+ .form-grid {
905
+ display: grid;
906
+ grid-template-columns: 160px 1fr;
907
+ gap: 16px 22px;
908
+ align-items: center;
909
+ }
910
+ .form-label {
911
+ font-family: var(--font-mono);
912
+ font-size: 13.5px;
913
+ color: var(--text-dim);
914
+ word-break: break-all;
915
+ }
916
+ .form-input {
917
+ width: 100%;
918
+ background: var(--bg-raised);
919
+ border: 1px solid var(--border-lit);
920
+ border-radius: var(--r);
921
+ padding: 9px 14px;
922
+ color: var(--text);
923
+ font-family: var(--font-mono);
924
+ font-size: 14px;
925
+ outline: none;
926
+ transition: border-color .15s, box-shadow .15s;
927
+ }
928
+ .form-input:focus {
929
+ border-color: var(--accent);
930
+ box-shadow: 0 0 0 1px var(--accent-glow);
931
+ }
932
+
933
+ .json-textarea {
934
+ width: 100%;
935
+ height: 320px;
936
+ background: var(--bg-raised);
937
+ border: 1px solid var(--border-lit);
938
+ border-radius: var(--r);
939
+ color: var(--text);
940
+ font-family: var(--font-mono);
941
+ font-size: 13.5px;
942
+ line-height: 1.6;
943
+ padding: 16px;
944
+ outline: none;
945
+ resize: vertical;
946
+ }
947
+ .json-textarea:focus {
948
+ border-color: var(--accent);
949
+ box-shadow: 0 0 0 1px var(--accent-glow);
950
+ }
951
+
952
+ .modal-err {
953
+ margin-top: 14px;
954
+ padding: 11px 16px;
955
+ border-radius: var(--r);
956
+ background: rgba(240,122,114,.12);
957
+ border: 1px solid rgba(240,122,114,.35);
958
+ color: var(--red);
959
+ font-family: var(--font-mono);
960
+ font-size: 13px;
961
+ white-space: pre-wrap;
962
+ display: none;
963
+ }
964
+ .modal-err.on { display: block; }
965
+
966
+ .modal-footer {
967
+ padding: 16px 22px;
968
+ border-top: 1px solid var(--border);
969
+ background: var(--bg-raised);
970
+ display: flex;
971
+ align-items: center;
972
+ justify-content: space-between;
973
+ }
974
+ .modal-footer-right {
975
+ display: flex;
976
+ gap: 12px;
977
+ }
978
+
979
+ /* \u2500\u2500\u2500 STATUS BAR \u2500\u2500\u2500 */
980
+ .statusbar {
981
+ flex-shrink: 0;
982
+ height: 30px;
983
+ display: flex;
984
+ align-items: center;
985
+ justify-content: space-between;
986
+ padding: 0 20px;
987
+ background: var(--bg-card);
988
+ border-top: 1px solid var(--border);
989
+ color: var(--text-dim);
990
+ font-family: var(--font-mono);
991
+ font-size: 12.5px;
992
+ position: relative;
993
+ z-index: 10;
994
+ }
995
+ .sb-left, .sb-right, .sb-center {
996
+ display: flex;
997
+ align-items: center;
998
+ gap: 18px;
999
+ }
1000
+ .sb-item {
1001
+ display: flex;
1002
+ align-items: center;
1003
+ gap: 6px;
1004
+ white-space: nowrap;
1005
+ }
1006
+ .sb-dot {
1007
+ width: 7px;
1008
+ height: 7px;
1009
+ border-radius: 50%;
1010
+ background: var(--green);
1011
+ box-shadow: 0 0 6px rgba(140,196,159,.5);
1012
+ }
1013
+ .sb-hint {
1014
+ color: var(--text-muted);
1015
+ font-size: 12px;
1016
+ }
1017
+
1018
+ /* Toast */
1019
+ .toast-wrap {
1020
+ position: fixed;
1021
+ bottom: 38px;
1022
+ right: 24px;
1023
+ display: flex;
1024
+ flex-direction: column;
1025
+ gap: 8px;
1026
+ z-index: 200;
1027
+ pointer-events: none;
1028
+ }
1029
+ .toast {
1030
+ background: var(--bg-card);
1031
+ border: 1px solid var(--border-lit);
1032
+ color: var(--text);
1033
+ padding: 10px 18px;
1034
+ border-radius: var(--r);
1035
+ font-size: 13.5px;
1036
+ box-shadow: 0 8px 24px rgba(0,0,0,.6);
1037
+ display: flex;
1038
+ align-items: center;
1039
+ gap: 8px;
1040
+ animation: toastIn .2s var(--ease-out);
1041
+ }
1042
+ .toast::before {
1043
+ content: '';
1044
+ width: 6px;
1045
+ height: 6px;
1046
+ border-radius: 50%;
1047
+ background: var(--accent);
1048
+ }
1049
+ @keyframes toastIn {
1050
+ from { opacity: 0; transform: translateY(10px); }
1051
+ to { opacity: 1; transform: none; }
1052
+ }
1053
+ </style>
1054
+ </head>
1055
+ <body>
1056
+
1057
+ <!-- TOP BAR (Full width across top so badges never clip) -->
1058
+ <header class="ws-topbar">
1059
+ <div class="logo">
1060
+ <svg class="logo-img" viewBox="0 0 32 32" fill="none" aria-hidden="true">
1061
+ <rect x="6" y="7" width="20" height="3" rx="1.5" fill="currentColor" />
1062
+ <rect x="6" y="14.5" width="14" height="3" rx="1.5" fill="currentColor" opacity="0.85" />
1063
+ <rect x="6" y="22" width="20" height="3" rx="1.5" fill="currentColor" />
1064
+ </svg>
1065
+ <span>efc<span class="logo-dot">.</span>studio</span>
1066
+ </div>
1067
+ <span class="ws-topbar-label">Studio</span>
1068
+ <div class="badge-group">
1069
+ <span class="badge-engine" id="engineBadge">db</span>
1070
+ <span class="badge-mode ro" id="modeBadge">read-only</span>
1071
+ </div>
1072
+
1073
+ <div class="topbar-spacer"></div>
1074
+
1075
+ <div class="header-center" id="rowSearchWrap">
1076
+ <div class="input-search-wrap" style="width: 240px;">
1077
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1078
+ <circle cx="11" cy="11" r="8"></circle>
1079
+ <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
1080
+ </svg>
1081
+ <input type="text" id="rowSearch" class="input-search" placeholder="Filter rows in view..." autocomplete="off" disabled>
1082
+ <button id="rowSearchClear" class="clear-btn" hidden title="Clear filter">&times;</button>
1083
+ </div>
1084
+ </div>
1085
+
1086
+ <div class="tabbar">
1087
+ <button id="btnModeRows" class="tab-item active" title="View data rows">
1088
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1089
+ <line x1="8" y1="6" x2="21" y2="6"></line>
1090
+ <line x1="8" y1="12" x2="21" y2="12"></line>
1091
+ <line x1="8" y1="18" x2="21" y2="18"></line>
1092
+ <line x1="3" y1="6" x2="3.01" y2="6"></line>
1093
+ <line x1="3" y1="12" x2="3.01" y2="12"></line>
1094
+ <line x1="3" y1="18" x2="3.01" y2="18"></line>
1095
+ </svg>
1096
+ Rows
1097
+ </button>
1098
+ <button id="btnModeStructure" class="tab-item" title="View schema structure" disabled>
1099
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1100
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
1101
+ <line x1="3" y1="9" x2="21" y2="9"></line>
1102
+ <line x1="9" y1="21" x2="9" y2="9"></line>
1103
+ </svg>
1104
+ Structure
1105
+ </button>
1106
+ </div>
1107
+
1108
+ <button id="btnRefresh" class="btn-ghost btn-icon" title="Refresh data" disabled>
1109
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1110
+ <path d="M23 4v6h-6"></path>
1111
+ <path d="M1 20v-6h6"></path>
1112
+ <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
1113
+ </svg>
1114
+ </button>
1115
+
1116
+ <div class="btn-group">
1117
+ <button id="prev" class="btn-ghost btn-icon" disabled title="Previous page">
1118
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1119
+ <polyline points="15 18 9 12 15 6"></polyline>
1120
+ </svg>
1121
+ </button>
1122
+ <button id="next" class="btn-ghost btn-icon" disabled title="Next page">
1123
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1124
+ <polyline points="9 18 15 12 9 6"></polyline>
1125
+ </svg>
1126
+ </button>
1127
+ </div>
1128
+
1129
+ <button id="ins" class="btn-primary" hidden>
1130
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1131
+ <line x1="12" y1="5" x2="12" y2="19"></line>
1132
+ <line x1="5" y1="12" x2="19" y2="12"></line>
1133
+ </svg>
1134
+ + Insert
1135
+ </button>
1136
+ </header>
1137
+
1138
+ <div class="ws-body">
1139
+ <aside>
1140
+ <div class="search-box">
1141
+ <div class="input-search-wrap">
1142
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1143
+ <circle cx="11" cy="11" r="8"></circle>
1144
+ <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
1145
+ </svg>
1146
+ <input type="text" id="tableSearch" class="input-search" placeholder="Search tables..." autocomplete="off">
1147
+ <button id="tableSearchClear" class="clear-btn" hidden title="Clear search">&times;</button>
1148
+ </div>
1149
+ </div>
1150
+
1151
+ <div class="sidebar-header">
1152
+ <span>Collections</span>
1153
+ <span id="tableCountBadge"></span>
1154
+ </div>
1155
+
1156
+ <div id="list" class="table-tree"></div>
1157
+ </aside>
1158
+
1159
+ <main>
1160
+ <div class="workspace-bar">
1161
+ <svg class="ico-table" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
1162
+ <rect x="3" y="3" width="18" height="18" rx="2"></rect>
1163
+ <line x1="3" y1="9" x2="21" y2="9"></line>
1164
+ <line x1="9" y1="21" x2="9" y2="9"></line>
1165
+ </svg>
1166
+ <h2 id="title" class="active-title">Select a table</h2>
1167
+ <span id="meta" class="meta-chip">empty</span>
1168
+ </div>
1169
+
1170
+ <div class="wrap" id="grid">
1171
+ <div class="empty-state">
1172
+ <svg width="48" height="48" viewBox="0 0 32 32" fill="none" aria-hidden="true">
1173
+ <rect x="6" y="7" width="20" height="3" rx="1.5" fill="currentColor" />
1174
+ <rect x="6" y="14.5" width="14" height="3" rx="1.5" fill="currentColor" opacity="0.85" />
1175
+ <rect x="6" y="22" width="20" height="3" rx="1.5" fill="currentColor" />
1176
+ </svg>
1177
+ <h3>Select a collection</h3>
1178
+ <p>Choose any table or collection from the left sidebar to inspect and edit records.</p>
1179
+ </div>
1180
+ </div>
1181
+ </main>
1182
+ </div>
1183
+
1184
+ <footer class="statusbar">
1185
+ <div class="sb-left">
1186
+ <div class="sb-item">
1187
+ <span class="sb-dot on"></span>
1188
+ <span id="sbEngine">Database</span>
1189
+ </div>
1190
+ <div class="sb-item">
1191
+ <span id="sbTable">\u2014</span>
1192
+ </div>
1193
+ </div>
1194
+ <div class="sb-center">
1195
+ <span class="sb-hint">Double-click row to inspect/edit \xB7 Filter: / \xB7 Next/Prev: \u2190 / \u2192</span>
1196
+ </div>
1197
+ <div class="sb-right">
1198
+ <div class="sb-item">
1199
+ <span id="sbCount">0 records</span>
1200
+ </div>
1201
+ <div class="sb-item">
1202
+ <span id="sbMode">read-only</span>
1203
+ </div>
1204
+ </div>
1205
+ </footer>
1206
+
1207
+ <!-- Editor Modal -->
1208
+ <div id="ed" class="modal-overlay">
1209
+ <div class="modal-window">
1210
+ <div class="modal-header">
1211
+ <h3 id="edTitle">Edit record</h3>
1212
+ <button id="edClose" class="modal-close" title="Close (Esc)">&times;</button>
1213
+ </div>
1214
+ <div class="modal-tabs">
1215
+ <button id="edTabForm" class="modal-tab-btn active">Form</button>
1216
+ <button id="edTabJson" class="modal-tab-btn">JSON</button>
1217
+ </div>
1218
+ <div class="modal-body">
1219
+ <div id="edFormPanel">
1220
+ <div id="edFormFields" class="form-grid"></div>
1221
+ </div>
1222
+ <div id="edJsonPanel" style="display:none">
1223
+ <textarea id="edText" class="json-textarea" spellcheck="false"></textarea>
1224
+ </div>
1225
+ <div id="edErr" class="modal-err"></div>
1226
+ </div>
1227
+ <div class="modal-footer">
1228
+ <button id="edDel" class="btn-danger">Delete</button>
1229
+ <div class="modal-footer-right">
1230
+ <button id="edCancel" class="btn-ghost">Cancel</button>
1231
+ <button id="edSave" class="btn-primary">Save Changes</button>
1232
+ </div>
1233
+ </div>
1234
+ </div>
1235
+ </div>
1236
+
1237
+ <!-- Value Inspector Modal -->
1238
+ <div id="jsonModal" class="modal-overlay">
1239
+ <div class="modal-window" style="width: min(600px, 94vw);">
1240
+ <div class="modal-header">
1241
+ <h3 id="jsonModalTitle">Inspect Value</h3>
1242
+ <button id="jsonModalClose" class="modal-close">&times;</button>
1243
+ </div>
1244
+ <div class="modal-body">
1245
+ <pre id="jsonModalPre" style="margin:0; font-family:var(--font-mono); font-size:.8rem; line-height:1.6; white-space:pre-wrap; color:var(--text);"></pre>
1246
+ </div>
1247
+ <div class="modal-footer" style="justify-content: flex-end;">
1248
+ <button id="jsonModalCopy" class="btn-ghost">Copy JSON</button>
1249
+ </div>
1250
+ </div>
1251
+ </div>
1252
+
1253
+ <div class="toast-wrap" id="toasts"></div>
1254
+
1255
+ <script>
1256
+ const TOKEN=__EFC_TOKEN__;
1257
+ const LIMIT=50;
1258
+ let cur=null,skip=0,mode='rows',write=false,writable=new Set(),editing=null;
1259
+ let allCollections=[];
1260
+ let currentRows=[];
1261
+ let activeColumns=[];
1262
+ let sortCol=null,sortAsc=true;
1263
+ const SKIP=new Set(['_id','id','__v','createdAt','updatedAt']);
1264
+
1265
+ const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
1266
+
1267
+ function toast(msg){
1268
+ const el=document.createElement('div');
1269
+ el.className='toast';
1270
+ el.textContent=msg;
1271
+ document.getElementById('toasts').appendChild(el);
1272
+ setTimeout(()=>el.remove(),2500);
1273
+ }
1274
+
1275
+ async function api(p){
1276
+ const r=await fetch(p);
1277
+ if(!r.ok){
1278
+ const d=await r.json().catch(()=>({}));
1279
+ throw new Error(d.error||r.statusText);
1280
+ }
1281
+ return r.json();
1282
+ }
1283
+
1284
+ async function send(method,p,body){
1285
+ const r=await fetch(p,{
1286
+ method,
1287
+ headers:{
1288
+ 'Content-Type':'application/json',
1289
+ 'X-EFC-Studio-Token':TOKEN
1290
+ },
1291
+ body:body===undefined?undefined:JSON.stringify(body)
1292
+ });
1293
+ const d=await r.json().catch(()=>({}));
1294
+ if(!r.ok){
1295
+ const e=new Error(d.error||r.statusText);
1296
+ e.issues=d.issues;
1297
+ throw e;
1298
+ }
1299
+ return d;
1300
+ }
1301
+
1302
+ function selectTable(name){
1303
+ cur=name;
1304
+ skip=0;
1305
+ sortCol=null;
1306
+ location.hash='#'+encodeURIComponent(name);
1307
+ document.querySelectorAll('.tree-row').forEach(x=>{
1308
+ const on=x.dataset.name===name;
1309
+ x.classList.toggle('active', on);
1310
+ if(on) x.scrollIntoView({ block: 'nearest' });
1311
+ });
1312
+ document.getElementById('btnModeStructure').disabled=false;
1313
+ document.getElementById('btnRefresh').disabled=false;
1314
+ document.getElementById('rowSearch').disabled=false;
1315
+ show();
1316
+ }
1317
+
1318
+ function renderTableList(filterText=''){
1319
+ const el=document.getElementById('list');
1320
+ el.innerHTML='';
1321
+ const q=filterText.toLowerCase().trim();
1322
+ const filtered=allCollections.filter(c=>!q||c.name.toLowerCase().includes(q));
1323
+ document.getElementById('tableCountBadge').textContent=filtered.length===allCollections.length?String(allCollections.length):filtered.length+' / '+allCollections.length;
1324
+
1325
+ if(!filtered.length){
1326
+ el.innerHTML='<div style="padding:24px 16px; color:var(--text-dim); text-align:center;">No collections match "'+esc(filterText)+'"</div>';
1327
+ return;
1328
+ }
1329
+
1330
+ for(const c of filtered){
1331
+ const b=document.createElement('div');
1332
+ b.className='tree-row'+(cur===c.name?' active':'');
1333
+ b.dataset.name=c.name;
1334
+ b.innerHTML='<div class="tree-left">'+
1335
+ '<svg class="ico-table" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">'+
1336
+ '<rect x="3" y="3" width="18" height="18" rx="2"></rect><line x1="3" y1="9" x2="21" y2="9"></line><line x1="9" y1="21" x2="9" y2="9"></line></svg>'+
1337
+ '<span class="table-name" title="'+esc(c.name)+'">'+esc(c.name)+'</span></div>'+
1338
+ '<span class="count-badge">'+c.count+'</span>';
1339
+ b.onclick=()=>selectTable(c.name);
1340
+ el.appendChild(b);
1341
+ }
1342
+ }
1343
+
1344
+ async function loadList(){
1345
+ const d=await api('/api/collections');
1346
+ write=d.write;
1347
+ writable=new Set(d.collections.filter(c=>c.writable).map(c=>c.name));
1348
+ allCollections=d.collections;
1349
+
1350
+ const eng=document.getElementById('engineBadge');
1351
+ eng.textContent=d.engine;
1352
+ eng.className='badge-engine '+(d.engine==='postgresql'?'pg':'mongo');
1353
+
1354
+ const mb=document.getElementById('modeBadge');
1355
+ mb.textContent=write?'write':'read-only';
1356
+ mb.className='badge-mode '+(write?'write':'ro');
1357
+
1358
+ const sbEng=document.getElementById('sbEngine');
1359
+ if(sbEng) sbEng.textContent=d.engine==='postgresql'?'PostgreSQL':d.engine==='mongo'?'MongoDB':d.engine;
1360
+ const sbMd=document.getElementById('sbMode');
1361
+ if(sbMd) sbMd.textContent=write?'read-write':'read-only';
1362
+
1363
+ renderTableList(document.getElementById('tableSearch').value);
1364
+ if(!allCollections.length){
1365
+ document.getElementById('list').innerHTML='<div style="padding:24px 16px; color:var(--text-dim); text-align:center;">No collections found</div>';
1366
+ return;
1367
+ }
1368
+
1369
+ const hash=decodeURIComponent(location.hash.slice(1));
1370
+ const target=allCollections.find(c=>c.name===hash)||allCollections.find(c=>c.name==='studiobooks')||allCollections[0];
1371
+ if(target&&!cur){
1372
+ selectTable(target.name);
1373
+ }
1374
+ }
1375
+
1376
+ document.getElementById('tableSearch').oninput=(e)=>{
1377
+ const v=e.target.value;
1378
+ document.getElementById('tableSearchClear').hidden=!v;
1379
+ renderTableList(v);
1380
+ };
1381
+ document.getElementById('tableSearchClear').onclick=()=>{
1382
+ document.getElementById('tableSearch').value='';
1383
+ document.getElementById('tableSearchClear').hidden=true;
1384
+ renderTableList();
1385
+ };
1386
+
1387
+ function formatCell(val, key){
1388
+ if(val===null||val===undefined) return '<td class="cell-null">null</td>';
1389
+ if(typeof val==='boolean') return '<td class="'+(val?'cell-bool-true':'cell-bool-false')+'">'+val+'</td>';
1390
+ if(typeof val==='number') return '<td class="cell-number" title="'+val+'">'+val+'</td>';
1391
+ if(typeof val==='object'){
1392
+ const j=JSON.stringify(val);
1393
+ return '<td class="cell-obj" data-json="'+esc(j)+'" title="Click to inspect">'+esc(j)+'</td>';
1394
+ }
1395
+ const s=String(val);
1396
+ const isId=key==='id'||key==='_id'||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
1397
+ const isDate=/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(s);
1398
+ const cls=isId?'cell-id':(isDate?'cell-date':'');
1399
+ return '<td class="'+cls+'" title="'+esc(s)+'">'+esc(s)+'</td>';
1400
+ }
1401
+
1402
+ function renderGrid(rows){
1403
+ const canWrite=writable.has(cur);
1404
+ const g=document.getElementById('grid');
1405
+ if(!rows.length){
1406
+ g.innerHTML='<div class="empty-state">'+
1407
+ '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"></circle><line x1="8" y1="12" x2="16" y2="12"></line></svg>'+
1408
+ '<h3>No records found</h3><p>'+(currentRows.length?'No records match your filter in this view.':'This collection contains no data rows.')+'</p></div>';
1409
+ return;
1410
+ }
1411
+
1412
+ let h='<table class="data-table"><thead><tr>';
1413
+ h+='<th class="num-col">#</th>';
1414
+ if(canWrite) h+='<th class="act-col">Actions</th>';
1415
+ for(const c of activeColumns){
1416
+ const isSorted=sortCol===c;
1417
+ const arrow=isSorted?(sortAsc?'\u25B2':'\u25BC'):'';
1418
+ h+='<th data-col="'+esc(c)+'"><div class="th-content"><span>'+esc(c)+'</span><span class="sort-arrow">'+arrow+'</span></div></th>';
1419
+ }
1420
+ h+='</tr></thead><tbody>';
1421
+
1422
+ rows.forEach((r,i)=>{
1423
+ h+='<tr data-idx="'+i+'">';
1424
+ h+='<td class="num-col">'+(skip+i+1)+'</td>';
1425
+ if(canWrite){
1426
+ h+='<td class="act-col"><div class="row-actions">'+
1427
+ '<button class="row-act-btn edit" data-idx="'+i+'" title="Edit record">'+
1428
+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg>'+
1429
+ '</button>'+
1430
+ '<button class="row-act-btn del" data-idx="'+i+'" title="Delete record">'+
1431
+ '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>'+
1432
+ '</button>'+
1433
+ '</div></td>';
1434
+ }
1435
+ for(const c of activeColumns){
1436
+ h+=formatCell(r[c], c);
1437
+ }
1438
+ h+='</tr>';
1439
+ });
1440
+
1441
+ const ghostCount=Math.max(0, 15 - rows.length);
1442
+ for(let g=0; g<ghostCount; g++){
1443
+ h+='<tr class="ghost-row"><td class="num-col"></td>';
1444
+ if(canWrite) h+='<td class="act-col"></td>';
1445
+ for(let c=0; c<activeColumns.length; c++){
1446
+ h+='<td></td>';
1447
+ }
1448
+ h+='</tr>';
1449
+ }
1450
+
1451
+ h+='</tbody></table>';
1452
+ g.innerHTML=h;
1453
+
1454
+ g.querySelectorAll('th[data-col]').forEach(th=>{
1455
+ th.onclick=()=>{
1456
+ const col=th.dataset.col;
1457
+ if(sortCol===col){
1458
+ if(sortAsc) sortAsc=false;
1459
+ else { sortCol=null; sortAsc=true; }
1460
+ } else {
1461
+ sortCol=col;
1462
+ sortAsc=true;
1463
+ }
1464
+ filterAndSortRows();
1465
+ };
1466
+ });
1467
+
1468
+ g.querySelectorAll('.row-act-btn.edit').forEach(b=>{
1469
+ b.onclick=()=>openEditor(rows[Number(b.dataset.idx)]);
1470
+ });
1471
+
1472
+ g.querySelectorAll('.row-act-btn.del').forEach(b=>{
1473
+ b.onclick=async()=>{
1474
+ const row=rows[Number(b.dataset.idx)];
1475
+ if(!confirm('Delete this record?')) return;
1476
+ try {
1477
+ await send('DELETE', '/api/collections/'+encodeURIComponent(cur)+'/'+encodeURIComponent(row.id??row._id));
1478
+ toast('Record deleted');
1479
+ await loadList();
1480
+ await loadRows();
1481
+ } catch(e) {
1482
+ alert(e.message);
1483
+ }
1484
+ };
1485
+ });
1486
+
1487
+ g.querySelectorAll('td.cell-obj').forEach(td=>{
1488
+ td.onclick=()=>{
1489
+ try {
1490
+ const val=JSON.parse(td.dataset.json);
1491
+ document.getElementById('jsonModalTitle').textContent='Inspect Object Value';
1492
+ document.getElementById('jsonModalPre').textContent=JSON.stringify(val, null, 2);
1493
+ document.getElementById('jsonModal').classList.add('on');
1494
+ } catch(e){}
1495
+ };
1496
+ });
1497
+
1498
+ g.querySelectorAll('td.cell-id').forEach(td=>{
1499
+ td.onclick=()=>{
1500
+ const t=td.getAttribute('title')||td.textContent;
1501
+ navigator.clipboard.writeText(t).then(()=>toast('Copied ID to clipboard')).catch(()=>{});
1502
+ };
1503
+ });
1504
+ }
1505
+
1506
+ function filterAndSortRows(){
1507
+ let rows=[...currentRows];
1508
+ const q=document.getElementById('rowSearch').value.toLowerCase().trim();
1509
+ if(q){
1510
+ rows=rows.filter(r=>Object.values(r).some(v=>v!==null&&v!==undefined&&String(typeof v==='object'?JSON.stringify(v):v).toLowerCase().includes(q)));
1511
+ }
1512
+ if(sortCol){
1513
+ rows.sort((a,b)=>{
1514
+ let va=a[sortCol], vb=b[sortCol];
1515
+ if(va===vb) return 0;
1516
+ if(va===null||va===undefined) return 1;
1517
+ if(vb===null||vb===undefined) return -1;
1518
+ if(typeof va==='string') return sortAsc?va.localeCompare(String(vb)):String(vb).localeCompare(va);
1519
+ return sortAsc?(va>vb?1:-1):(va<vb?1:-1);
1520
+ });
1521
+ }
1522
+ renderGrid(rows);
1523
+ }
1524
+
1525
+ document.getElementById('rowSearch').oninput=(e)=>{
1526
+ document.getElementById('rowSearchClear').hidden=!e.target.value;
1527
+ filterAndSortRows();
1528
+ };
1529
+ document.getElementById('rowSearchClear').onclick=()=>{
1530
+ document.getElementById('rowSearch').value='';
1531
+ document.getElementById('rowSearchClear').hidden=true;
1532
+ filterAndSortRows();
1533
+ };
1534
+
1535
+ async function loadRows(){
1536
+ const d=await api('/api/collections/'+encodeURIComponent(cur)+'?skip='+skip+'&limit='+LIMIT);
1537
+ document.getElementById('title').textContent=cur;
1538
+ document.getElementById('meta').textContent=d.total?(skip+1)+'\u2013'+Math.min(skip+LIMIT,d.total)+' of '+d.total:'empty';
1539
+ document.getElementById('prev').disabled=skip===0;
1540
+ document.getElementById('next').disabled=skip+LIMIT>=d.total;
1541
+
1542
+ const canWrite=writable.has(cur);
1543
+ document.getElementById('ins').hidden=!canWrite;
1544
+ document.getElementById('rowSearchWrap').hidden=false;
1545
+
1546
+ const sbTbl=document.getElementById('sbTable');
1547
+ if(sbTbl) sbTbl.textContent=cur;
1548
+ const sbCnt=document.getElementById('sbCount');
1549
+ if(sbCnt) sbCnt.textContent=d.total?(d.total+' '+(d.total===1?'record':'records')):'0 records';
1550
+ const sbMd=document.getElementById('sbMode');
1551
+ if(sbMd) sbMd.textContent=canWrite?'read-write':'read-only';
1552
+
1553
+ currentRows=d.rows;
1554
+ activeColumns=[...new Set(d.rows.flatMap(r=>Object.keys(r)))];
1555
+ filterAndSortRows();
1556
+ }
1557
+
1558
+ async function loadStructure(){
1559
+ const d=await api('/api/collections/'+encodeURIComponent(cur)+'/structure');
1560
+ document.getElementById('title').textContent=cur;
1561
+ document.getElementById('meta').textContent=d.columns.length+' columns \xB7 '+d.indexes.length+' indexes';
1562
+ document.getElementById('prev').disabled=true;
1563
+ document.getElementById('next').disabled=true;
1564
+ document.getElementById('ins').hidden=true;
1565
+ document.getElementById('rowSearch').value='';
1566
+ document.getElementById('rowSearchWrap').hidden=true;
1567
+
1568
+ const sbTbl=document.getElementById('sbTable');
1569
+ if(sbTbl) sbTbl.textContent=cur+' (schema)';
1570
+ const sbCnt=document.getElementById('sbCount');
1571
+ if(sbCnt) sbCnt.textContent=d.columns.length+' cols \xB7 '+d.indexes.length+' idx';
1572
+
1573
+ let h='<div class="structure-wrap">'+
1574
+ '<div class="window-card">'+
1575
+ '<div class="code-bar">'+
1576
+ '<span class="dot r"></span><span class="dot y"></span><span class="dot g"></span>'+
1577
+ '<span class="code-bar-label">COLUMNS ('+d.columns.length+')</span>'+
1578
+ '</div>'+
1579
+ '<table class="data-table" style="width:100%"><thead><tr><th>Column Name</th><th>Data Type</th><th>Nullable</th></tr></thead><tbody>';
1580
+ for(const c of d.columns){
1581
+ h+='<tr><td style="font-weight:600; color:var(--text)">'+esc(c.name)+'</td>'+
1582
+ '<td><span class="type-tag">'+esc(c.type)+'</span></td>'+
1583
+ '<td><span class="null-tag '+(c.nullable?'nullable':'not-null')+'">'+(c.nullable===undefined?'\u2014':(c.nullable?'NULL':'NOT NULL'))+'</span></td></tr>';
1584
+ }
1585
+ h+='</tbody></table></div>'+
1586
+ '<div class="window-card">'+
1587
+ '<div class="code-bar">'+
1588
+ '<span class="dot r"></span><span class="dot y"></span><span class="dot g"></span>'+
1589
+ '<span class="code-bar-label">INDEXES ('+d.indexes.length+')</span>'+
1590
+ '</div>'+
1591
+ '<table class="data-table" style="width:100%"><thead><tr><th>Index Name</th><th>Definition</th></tr></thead><tbody>';
1592
+ for(const idx of d.indexes){
1593
+ h+='<tr><td style="font-weight:600; color:var(--text)">'+esc(idx.name)+'</td>'+
1594
+ '<td style="color:var(--text-dim); font-family:var(--font-mono)">'+esc(idx.definition)+'</td></tr>';
1595
+ }
1596
+ h+='</tbody></table></div></div>';
1597
+ document.getElementById('grid').innerHTML=h;
1598
+ }
1599
+
1600
+ function show(){
1601
+ document.getElementById('btnModeRows').classList.toggle('active', mode==='rows');
1602
+ document.getElementById('btnModeStructure').classList.toggle('active', mode==='structure');
1603
+ return mode==='rows'?loadRows():loadStructure();
1604
+ }
1605
+
1606
+ document.getElementById('btnModeRows').onclick=()=>{
1607
+ if(mode==='rows') return;
1608
+ mode='rows';
1609
+ show();
1610
+ };
1611
+ document.getElementById('btnModeStructure').onclick=()=>{
1612
+ if(mode==='structure') return;
1613
+ mode='structure';
1614
+ show();
1615
+ };
1616
+ document.getElementById('btnRefresh').onclick=()=>show();
1617
+ document.getElementById('prev').onclick=()=>{skip=Math.max(0,skip-LIMIT);loadRows();};
1618
+ document.getElementById('next').onclick=()=>{skip+=LIMIT;loadRows();};
1619
+ document.getElementById('ins').onclick=()=>openEditor(null);
1620
+
1621
+ function updateEditorForm(vals){
1622
+ const f=document.getElementById('edFormFields');
1623
+ f.innerHTML='';
1624
+ const keys=[...new Set([...Object.keys(vals), ...activeColumns.filter(c=>!SKIP.has(c))])];
1625
+ if(!keys.length){
1626
+ f.innerHTML='<div style="grid-column: span 2; color:var(--text-muted); padding:10px 0;">No editable fields</div>';
1627
+ return;
1628
+ }
1629
+ for(const k of keys){
1630
+ const l=document.createElement('div');
1631
+ l.className='form-label';
1632
+ l.textContent=k;
1633
+ const v=vals[k];
1634
+ const inp=document.createElement('input');
1635
+ inp.className='form-input';
1636
+ inp.dataset.key=k;
1637
+ if(typeof v==='number') {
1638
+ inp.type='number';
1639
+ inp.value=v;
1640
+ } else if(typeof v==='boolean') {
1641
+ inp.type='text';
1642
+ inp.value=String(v);
1643
+ inp.placeholder='true / false';
1644
+ } else if(typeof v==='object'&&v!==null) {
1645
+ inp.type='text';
1646
+ inp.value=JSON.stringify(v);
1647
+ } else {
1648
+ inp.type='text';
1649
+ inp.value=v===undefined||v===null?'':String(v);
1650
+ }
1651
+ inp.oninput=syncFormToJson;
1652
+ f.appendChild(l);
1653
+ f.appendChild(inp);
1654
+ }
1655
+ }
1656
+
1657
+ function syncFormToJson(){
1658
+ const f=document.getElementById('edFormFields');
1659
+ const res={};
1660
+ f.querySelectorAll('.form-input').forEach(inp=>{
1661
+ const k=inp.dataset.key;
1662
+ const raw=inp.value.trim();
1663
+ if(raw==='') return;
1664
+ if(raw==='true') res[k]=true;
1665
+ else if(raw==='false') res[k]=false;
1666
+ else if(raw==='null') res[k]=null;
1667
+ else if(!isNaN(Number(raw))&&inp.type==='number') res[k]=Number(raw);
1668
+ else if((raw.startsWith('{')&&raw.endsWith('}'))||(raw.startsWith('[')&&raw.endsWith(']'))){
1669
+ try { res[k]=JSON.parse(raw); } catch { res[k]=raw; }
1670
+ } else {
1671
+ res[k]=raw;
1672
+ }
1673
+ });
1674
+ document.getElementById('edText').value=JSON.stringify(res, null, 2);
1675
+ }
1676
+
1677
+ function syncJsonToForm(){
1678
+ try {
1679
+ const v=JSON.parse(document.getElementById('edText').value);
1680
+ updateEditorForm(v);
1681
+ document.getElementById('edErr').classList.remove('on');
1682
+ } catch(e){
1683
+ document.getElementById('edErr').textContent='Not valid JSON: '+e.message;
1684
+ document.getElementById('edErr').classList.add('on');
1685
+ }
1686
+ }
1687
+
1688
+ function openEditor(row){
1689
+ editing=row;
1690
+ const v={};
1691
+ if(row){
1692
+ for(const [k,x] of Object.entries(row)){
1693
+ if(!SKIP.has(k)) v[k]=x;
1694
+ }
1695
+ }
1696
+ document.getElementById('edTitle').textContent=row?'Edit '+cur+' #'+(row.id??row._id):'New record in '+cur;
1697
+ document.getElementById('edText').value=JSON.stringify(v, null, 2);
1698
+ updateEditorForm(v);
1699
+ document.getElementById('edErr').classList.remove('on');
1700
+ document.getElementById('edDel').hidden=!row;
1701
+ setEditorTab('form');
1702
+ document.getElementById('ed').classList.add('on');
1703
+ }
1704
+
1705
+ function closeEditor(){
1706
+ document.getElementById('ed').classList.remove('on');
1707
+ editing=null;
1708
+ }
1709
+
1710
+ function setEditorTab(tab){
1711
+ document.getElementById('edTabForm').classList.toggle('active', tab==='form');
1712
+ document.getElementById('edTabJson').classList.toggle('active', tab==='json');
1713
+ document.getElementById('edFormPanel').style.display=tab==='form'?'block':'none';
1714
+ document.getElementById('edJsonPanel').style.display=tab==='json'?'block':'none';
1715
+ }
1716
+
1717
+ document.getElementById('edTabForm').onclick=()=>{
1718
+ syncJsonToForm();
1719
+ setEditorTab('form');
1720
+ };
1721
+ document.getElementById('edTabJson').onclick=()=>{
1722
+ syncFormToJson();
1723
+ setEditorTab('json');
1724
+ };
1725
+
1726
+ document.getElementById('edClose').onclick=closeEditor;
1727
+ document.getElementById('edCancel').onclick=closeEditor;
1728
+
1729
+ document.getElementById('edSave').onclick=async()=>{
1730
+ const err=document.getElementById('edErr');
1731
+ let v;
1732
+ try {
1733
+ v=JSON.parse(document.getElementById('edText').value);
1734
+ } catch(e){
1735
+ err.textContent='Not valid JSON: '+e.message;
1736
+ err.classList.add('on');
1737
+ return;
1738
+ }
1739
+
1740
+ const base='/api/collections/'+encodeURIComponent(cur);
1741
+ try {
1742
+ if(editing){
1743
+ const ch={};
1744
+ for(const [k,x] of Object.entries(v)){
1745
+ if(JSON.stringify(x)!==JSON.stringify(editing[k])) ch[k]=x;
1746
+ }
1747
+ if(Object.keys(ch).length){
1748
+ await send('PATCH', base+'/'+encodeURIComponent(editing.id??editing._id), ch);
1749
+ toast('Record updated');
1750
+ }
1751
+ } else {
1752
+ await send('POST', base, v);
1753
+ toast('Record created');
1754
+ }
1755
+ closeEditor();
1756
+ await loadList();
1757
+ await loadRows();
1758
+ } catch(e){
1759
+ err.textContent=e.message+(e.issues?'\\n'+JSON.stringify(e.issues,null,2):'');
1760
+ err.classList.add('on');
1761
+ }
1762
+ };
1763
+
1764
+ document.getElementById('edDel').onclick=async()=>{
1765
+ if(!confirm('Delete this record?')) return;
1766
+ try {
1767
+ await send('DELETE', '/api/collections/'+encodeURIComponent(cur)+'/'+encodeURIComponent(editing.id??editing._id));
1768
+ toast('Record deleted');
1769
+ closeEditor();
1770
+ await loadList();
1771
+ await loadRows();
1772
+ } catch(e){
1773
+ document.getElementById('edErr').textContent=e.message;
1774
+ document.getElementById('edErr').classList.add('on');
1775
+ }
1776
+ };
1777
+
1778
+ document.getElementById('jsonModalClose').onclick=()=>document.getElementById('jsonModal').classList.remove('on');
1779
+ document.getElementById('jsonModalCopy').onclick=()=>{
1780
+ navigator.clipboard.writeText(document.getElementById('jsonModalPre').textContent)
1781
+ .then(()=>toast('Copied JSON to clipboard')).catch(()=>{});
1782
+ };
1783
+
1784
+ window.addEventListener('keydown', e=>{
1785
+ if(e.key==='Escape'){
1786
+ closeEditor();
1787
+ document.getElementById('jsonModal').classList.remove('on');
1788
+ }
1789
+ if((e.ctrlKey||e.metaKey)&&e.key==='Enter'){
1790
+ if(document.getElementById('ed').classList.contains('on')){
1791
+ document.getElementById('edSave').click();
1792
+ }
1793
+ }
1794
+ });
1795
+
1796
+ loadList().catch(e=>{
1797
+ document.getElementById('grid').innerHTML='<div class="empty-state"><h3>Error loading database</h3><p>'+esc(e.message)+'</p></div>';
1798
+ });
1799
+ </script>
1800
+ </body>
1801
+ </html>`;
1802
+
1803
+ // src/db/studio.ts
179
1804
  function mongoSource(conn) {
180
1805
  const db = conn.db;
181
1806
  return {
182
1807
  async collections() {
183
1808
  const cols = (await db.listCollections({}, { nameOnly: true }).toArray()).map((c) => c.name).filter((n) => !n.startsWith("system.")).sort();
184
- return Promise.all(
185
- cols.map(async (name) => ({
186
- name,
187
- count: await db.collection(name).estimatedDocumentCount()
188
- }))
1809
+ const counted = await Promise.all(
1810
+ cols.map(async (name) => {
1811
+ try {
1812
+ return { name, count: await db.collection(name).estimatedDocumentCount() };
1813
+ } catch {
1814
+ return void 0;
1815
+ }
1816
+ })
189
1817
  );
1818
+ return counted.filter((c) => c !== void 0);
190
1819
  },
191
1820
  async rows(name, skip, limit) {
192
1821
  const col = db.collection(name);
@@ -225,12 +1854,19 @@ function pgSource(pool) {
225
1854
  const q = (ident) => `"${ident.replace(/"/g, '""')}"`;
226
1855
  return {
227
1856
  async collections() {
228
- return Promise.all(
229
- (await tables()).map(async (name) => ({
230
- name,
231
- count: (await pool.query(`SELECT count(*)::int AS n FROM ${q(name)}`)).rows[0].n
232
- }))
1857
+ const counted = await Promise.all(
1858
+ (await tables()).map(async (name) => {
1859
+ try {
1860
+ const { rows } = await pool.query(
1861
+ `SELECT count(*)::int AS n FROM ${q(name)}`
1862
+ );
1863
+ return { name, count: rows[0].n };
1864
+ } catch {
1865
+ return void 0;
1866
+ }
1867
+ })
233
1868
  );
1869
+ return counted.filter((c) => c !== void 0);
234
1870
  },
235
1871
  async rows(name, skip, limit) {
236
1872
  if (!(await tables()).includes(name))
@@ -261,96 +1897,127 @@ function pgSource(pool) {
261
1897
  }
262
1898
  };
263
1899
  }
264
- var PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>EFC Studio</title>
265
- <meta name="viewport" content="width=device-width,initial-scale=1">
266
- <style>
267
- :root{--bg:#0f1115;--panel:#161a21;--line:#262c36;--text:#e6e9ef;--dim:#8b93a3;--acc:#5cc8ff}
268
- *{box-sizing:border-box}body{margin:0;font:13px/1.45 ui-sans-serif,system-ui,sans-serif;background:var(--bg);color:var(--text);display:flex;height:100vh}
269
- aside{width:240px;border-right:1px solid var(--line);overflow:auto;background:var(--panel)}
270
- aside h1{font-size:13px;margin:0;padding:14px 16px;border-bottom:1px solid var(--line);letter-spacing:.04em}
271
- aside h1 span{color:var(--dim);font-weight:400}
272
- aside button{display:flex;justify-content:space-between;width:100%;padding:8px 16px;border:0;background:none;color:var(--text);cursor:pointer;text-align:left;font:inherit}
273
- aside button:hover,aside button.on{background:#1f2530}aside button small{color:var(--dim)}
274
- main{flex:1;display:flex;flex-direction:column;min-width:0}
275
- header{display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:1px solid var(--line)}
276
- header b{font-size:14px}header .sp{flex:1}header button{background:#1f2530;color:var(--text);border:1px solid var(--line);border-radius:6px;padding:4px 10px;cursor:pointer}
277
- header button:disabled{opacity:.4;cursor:default}#meta{color:var(--dim)}
278
- .wrap{overflow:auto;flex:1}table{border-collapse:collapse;width:max-content;min-width:100%}
279
- th,td{border-bottom:1px solid var(--line);padding:6px 12px;text-align:left;vertical-align:top;max-width:360px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,monospace;font-size:12px}
280
- th{position:sticky;top:0;background:var(--panel);color:var(--dim);font-weight:500}
281
- td.obj{color:var(--acc);cursor:pointer}td.null{color:var(--dim)}
282
- .empty{padding:40px;color:var(--dim)}pre{white-space:pre-wrap;margin:0}
283
- </style></head><body>
284
- <aside><h1>EFC STUDIO <span id="engine"></span></h1><div id="list"></div></aside>
285
- <main><header><b id="title">Select a table</b><span id="meta"></span><span class="sp"></span>
286
- <button id="view" disabled>Structure</button><button id="prev" disabled>\u2039 Prev</button><button id="next" disabled>Next \u203A</button></header>
287
- <div class="wrap" id="grid"><div class="empty">Read-only view of your database.</div></div></main>
288
- <script>
289
- const LIMIT=50;let cur=null,skip=0,mode='rows';
290
- const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
291
- async function api(p){const r=await fetch(p);if(!r.ok)throw new Error((await r.json()).error);return r.json()}
292
- async function loadList(){const d=await api('/api/collections');document.getElementById('engine').textContent='\xB7 '+d.engine;
293
- const el=document.getElementById('list');el.innerHTML='';
294
- for(const c of d.collections){const b=document.createElement('button');b.innerHTML=esc(c.name)+'<small>'+c.count+'</small>';
295
- b.onclick=()=>{cur=c.name;skip=0;[...el.children].forEach(x=>x.classList.remove('on'));b.classList.add('on');document.getElementById('view').disabled=false;show()};el.appendChild(b)}
296
- if(!d.collections.length)el.innerHTML='<div class="empty">No tables yet.</div>'}
297
- async function loadRows(){const d=await api('/api/collections/'+encodeURIComponent(cur)+'?skip='+skip+'&limit='+LIMIT);
298
- document.getElementById('title').textContent=cur;
299
- document.getElementById('meta').textContent=d.total?(skip+1)+'\u2013'+Math.min(skip+LIMIT,d.total)+' of '+d.total:'empty';
300
- document.getElementById('prev').disabled=skip===0;document.getElementById('next').disabled=skip+LIMIT>=d.total;
301
- const cols=[...new Set(d.rows.flatMap(r=>Object.keys(r)))];const g=document.getElementById('grid');
302
- if(!d.rows.length){g.innerHTML='<div class="empty">No rows.</div>';return}
303
- let h='<table><thead><tr>'+cols.map(c=>'<th>'+esc(c)+'</th>').join('')+'</tr></thead><tbody>';
304
- for(const r of d.rows){h+='<tr>'+cols.map(c=>{const v=r[c];if(v===null||v===undefined)return '<td class="null">null</td>';
305
- if(typeof v==='object'){const j=JSON.stringify(v);return '<td class="obj" title="click to expand" data-j="'+esc(j)+'">'+esc(j)+'</td>'}
306
- return '<td title="'+esc(v)+'">'+esc(v)+'</td>'}).join('')+'</tr>'}
307
- g.innerHTML=h+'</tbody></table>';
308
- g.querySelectorAll('td.obj').forEach(td=>td.onclick=()=>{td.innerHTML='<pre>'+esc(JSON.stringify(JSON.parse(td.dataset.j),null,2))+'</pre>';td.style.whiteSpace='normal';td.onclick=null})}
309
- function show(){document.getElementById('view').textContent=mode==='rows'?'Structure':'Rows';return mode==='rows'?loadRows():loadStructure()}
310
- async function loadStructure(){const d=await api('/api/collections/'+encodeURIComponent(cur)+'/structure');
311
- document.getElementById('title').textContent=cur;document.getElementById('meta').textContent=d.columns.length+' columns \xB7 '+d.indexes.length+' indexes';
312
- document.getElementById('prev').disabled=true;document.getElementById('next').disabled=true;
313
- const row=(cells)=>'<tr>'+cells.map(c=>'<td>'+esc(c)+'</td>').join('')+'</tr>';
314
- document.getElementById('grid').innerHTML='<table><thead><tr><th>column</th><th>type</th><th>nullable</th></tr></thead><tbody>'+
315
- d.columns.map(c=>row([c.name,c.type,c.nullable===undefined?'':String(c.nullable)])).join('')+'</tbody></table>'+
316
- '<table style="margin-top:18px"><thead><tr><th>index</th><th>definition</th></tr></thead><tbody>'+d.indexes.map(i=>row([i.name,i.definition])).join('')+'</tbody></table>'}
317
- document.getElementById('view').onclick=()=>{mode=mode==='rows'?'structure':'rows';skip=0;show()};
318
- document.getElementById('prev').onclick=()=>{skip=Math.max(0,skip-LIMIT);loadRows()};
319
- document.getElementById('next').onclick=()=>{skip+=LIMIT;loadRows()};
320
- loadList().catch(e=>document.getElementById('grid').innerHTML='<div class="empty">'+esc(e.message)+'</div>');
321
- </script></body></html>`;
322
- function startStudio(engine, client, port) {
1900
+ function readJson(req) {
1901
+ return new Promise((resolve, reject) => {
1902
+ let size = 0;
1903
+ const chunks = [];
1904
+ req.on("data", (c) => {
1905
+ size += c.length;
1906
+ if (size > 1048576) {
1907
+ reject(Object.assign(new Error("Body too large"), { status: 413 }));
1908
+ req.destroy();
1909
+ } else chunks.push(c);
1910
+ });
1911
+ req.on("end", () => {
1912
+ try {
1913
+ const v = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
1914
+ if (!v || typeof v !== "object" || Array.isArray(v))
1915
+ throw new Error("Expected a JSON object");
1916
+ resolve(v);
1917
+ } catch (err) {
1918
+ reject(Object.assign(new Error(err.message), { status: 400 }));
1919
+ }
1920
+ });
1921
+ req.on("error", reject);
1922
+ });
1923
+ }
1924
+ var SERVER_FIELDS = ["_id", "id", "__v", "createdAt", "updatedAt"];
1925
+ function startStudio(engine, client, port, options = {}) {
323
1926
  const source = engine === "postgresql" ? pgSource(client) : mongoSource(client);
324
1927
  const json = (res, status, body) => {
325
1928
  res.writeHead(status, { "Content-Type": "application/json" });
326
- res.end(JSON.stringify(body));
1929
+ res.end(JSON.stringify(body, (_k, v) => typeof v === "bigint" ? v.toString() : v));
1930
+ };
1931
+ const token = crypto.randomBytes(32).toString("hex");
1932
+ const page = STUDIO_HTML.replace("__EFC_TOKEN__", JSON.stringify(options.write ? token : ""));
1933
+ let writers;
1934
+ const writerFor = async (name) => {
1935
+ if (!options.write) return void 0;
1936
+ writers ??= (async () => {
1937
+ const map = /* @__PURE__ */ new Map();
1938
+ for (const m of options.models ?? []) {
1939
+ if (!m.studio) continue;
1940
+ try {
1941
+ map.set(await m.studio.storage(), m.studio);
1942
+ } catch {
1943
+ }
1944
+ }
1945
+ return map;
1946
+ })();
1947
+ return (await writers).get(name);
327
1948
  };
328
1949
  const server = http.createServer((req, res) => {
329
1950
  void (async () => {
330
1951
  const url = new URL(req.url ?? "/", "http://localhost");
331
- const host = (req.headers.host ?? "").replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
1952
+ const rawHost = req.headers.host ?? "";
1953
+ const host = rawHost.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
332
1954
  if (!["localhost", "127.0.0.1", "::1"].includes(host)) {
333
1955
  return json(res, 403, { error: "Studio only answers on localhost" });
334
1956
  }
335
- if (req.method !== "GET") return json(res, 405, { error: "Studio is read-only" });
336
- if (url.pathname === "/") {
337
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
338
- return res.end(PAGE);
1957
+ if (req.method !== "GET") {
1958
+ if (!options.write)
1959
+ return json(res, 405, { error: "Studio is read-only (start it with --write)" });
1960
+ const sent = String(req.headers["x-efc-studio-token"] ?? "");
1961
+ const ok = sent.length === token.length && crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(token)) && req.headers.origin === `http://${rawHost}` && String(req.headers["content-type"] ?? "").startsWith("application/json");
1962
+ if (!ok) return json(res, 403, { error: "Missing or invalid studio token" });
339
1963
  }
340
- if (url.pathname === "/api/collections") {
341
- return json(res, 200, { engine, collections: await source.collections() });
1964
+ if (req.method === "GET" && url.pathname === "/") {
1965
+ res.writeHead(200, {
1966
+ "Content-Type": "text/html; charset=utf-8",
1967
+ "Cache-Control": "no-store",
1968
+ "X-Frame-Options": "DENY"
1969
+ });
1970
+ return res.end(page);
1971
+ }
1972
+ if (req.method === "GET" && url.pathname === "/api/collections") {
1973
+ const collections = await source.collections();
1974
+ return json(res, 200, {
1975
+ engine,
1976
+ write: !!options.write,
1977
+ collections: await Promise.all(
1978
+ collections.map(async (c) => ({ ...c, writable: !!await writerFor(c.name) }))
1979
+ )
1980
+ });
342
1981
  }
343
1982
  const st = /^\/api\/collections\/([^/]+)\/structure$/.exec(url.pathname);
344
- if (st) return json(res, 200, await source.structure(decodeURIComponent(st[1])));
1983
+ if (req.method === "GET" && st)
1984
+ return json(res, 200, await source.structure(decodeURIComponent(st[1])));
345
1985
  const m = /^\/api\/collections\/([^/]+)$/.exec(url.pathname);
346
- if (m) {
1986
+ if (req.method === "GET" && m) {
347
1987
  const skip = Math.max(0, Number(url.searchParams.get("skip")) || 0);
348
1988
  const limit = Math.min(500, Math.max(1, Number(url.searchParams.get("limit")) || 50));
349
1989
  return json(res, 200, await source.rows(decodeURIComponent(m[1]), skip, limit));
350
1990
  }
1991
+ const w = /^\/api\/collections\/([^/]+)(?:\/([^/]+))?$/.exec(url.pathname);
1992
+ if (w && req.method !== "GET") {
1993
+ const name = decodeURIComponent(w[1]);
1994
+ const id = w[2] !== void 0 ? decodeURIComponent(w[2]) : void 0;
1995
+ const writer = await writerFor(name);
1996
+ if (!writer) {
1997
+ return json(res, 409, {
1998
+ error: `No model stores in "${name}" \u2014 studio writes go through your models (src/model)`
1999
+ });
2000
+ }
2001
+ const body = req.method === "DELETE" ? {} : await readJson(req);
2002
+ for (const k of SERVER_FIELDS) delete body[k];
2003
+ if (req.method === "POST" && id === void 0)
2004
+ return json(res, 201, { record: await writer.create(body) });
2005
+ if (req.method === "PATCH" && id !== void 0) {
2006
+ const record = await writer.update(id, body);
2007
+ return record ? json(res, 200, { record }) : json(res, 404, { error: "Not found" });
2008
+ }
2009
+ if (req.method === "DELETE" && id !== void 0) {
2010
+ const record = await writer.delete(id);
2011
+ return record ? json(res, 200, { record }) : json(res, 404, { error: "Not found" });
2012
+ }
2013
+ return json(res, 405, { error: "Method not allowed" });
2014
+ }
351
2015
  json(res, 404, { error: "Not found" });
352
2016
  })().catch(
353
- (err) => json(res, err.status ?? 500, { error: err.message })
2017
+ (err) => json(res, err.status ?? err.statusCode ?? 500, {
2018
+ error: err.message,
2019
+ ...err.issues !== void 0 && { issues: err.issues }
2020
+ })
354
2021
  );
355
2022
  });
356
2023
  return new Promise((resolve, reject) => {
@@ -520,7 +2187,7 @@ function scalarType(type) {
520
2187
  if (type === "jsonb" || type === "json") return { def: { type: "json" } };
521
2188
  return { def: { type: "json" }, note: `${type} has no EFC type \u2014 mapped to json` };
522
2189
  }
523
- async function pullPostgres(pool) {
2190
+ async function pullPostgres(pool, names = /* @__PURE__ */ new Map()) {
524
2191
  const q = async (sql) => (await pool.query(sql)).rows;
525
2192
  const tables = (await q(
526
2193
  `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -561,8 +2228,8 @@ async function pullPostgres(pool) {
561
2228
  const fksOf = (t) => fks.filter((f) => f.table === t);
562
2229
  const joinTables = /* @__PURE__ */ new Map();
563
2230
  for (const t of tables) {
564
- const names = colsOf(t).map((c) => c.name).sort().join(",");
565
- if (names !== "owner_id,position,ref_id") continue;
2231
+ const names2 = colsOf(t).map((c) => c.name).sort().join(",");
2232
+ if (names2 !== "owner_id,position,ref_id") continue;
566
2233
  const owner = fksOf(t).find((f) => f.columns[0] === "owner_id")?.target;
567
2234
  const target = fksOf(t).find((f) => f.columns[0] === "ref_id")?.target;
568
2235
  if (owner && target && t.startsWith(`${owner}_`))
@@ -583,7 +2250,7 @@ async function pullPostgres(pool) {
583
2250
  skipped.push(t);
584
2251
  continue;
585
2252
  }
586
- models.set(t, { table: t, name: pascal(singular(t)), idKind });
2253
+ models.set(t, { table: t, name: names.get(t) ?? pascal(singular(t)), idKind });
587
2254
  }
588
2255
  const modelName = (t) => models.get(t)?.name;
589
2256
  const out = [];
@@ -756,7 +2423,7 @@ async function pullPostgres(pool) {
756
2423
  relations.set(target, rels);
757
2424
  }
758
2425
  }
759
- out.push({ name, fields, options, notes });
2426
+ out.push({ name, fields, options, notes, table });
760
2427
  }
761
2428
  for (const model of out) {
762
2429
  const rels = relations.get(model.name);
@@ -769,6 +2436,230 @@ async function pullPostgres(pool) {
769
2436
  return { models: out, skipped };
770
2437
  }
771
2438
 
2439
+ // src/db/pull-mongo.ts
2440
+ var INTERNAL2 = /* @__PURE__ */ new Set(["efc_migrations", "efc_counters"]);
2441
+ var newShape = () => ({ present: 0, kinds: /* @__PURE__ */ new Map() });
2442
+ function bsonKind(v) {
2443
+ if (v === null || v === void 0) return "null";
2444
+ if (typeof v === "string") return "string";
2445
+ if (typeof v === "number") return "number";
2446
+ if (typeof v === "boolean") return "boolean";
2447
+ if (v instanceof Date) return "date";
2448
+ if (Array.isArray(v)) return "array";
2449
+ if (typeof v === "object") {
2450
+ switch (v._bsontype) {
2451
+ case "ObjectId":
2452
+ case "ObjectID":
2453
+ return "objectId";
2454
+ case "Decimal128":
2455
+ return "decimal128";
2456
+ case "Long":
2457
+ return "long";
2458
+ case "Int32":
2459
+ case "Double":
2460
+ return "number";
2461
+ case "Binary":
2462
+ return "binary";
2463
+ case void 0:
2464
+ break;
2465
+ default:
2466
+ return "other";
2467
+ }
2468
+ if (Buffer.isBuffer(v)) return "binary";
2469
+ const o = v;
2470
+ if (o["type"] === "Point" && Array.isArray(o["coordinates"]) && o["coordinates"].length === 2 && o["coordinates"].every((c) => bsonKind(c) === "number")) {
2471
+ return "geoPoint";
2472
+ }
2473
+ return "object";
2474
+ }
2475
+ return "other";
2476
+ }
2477
+ function observe(shape, value) {
2478
+ const kind = bsonKind(value);
2479
+ if (kind === "null") return;
2480
+ shape.present++;
2481
+ shape.kinds.set(kind, (shape.kinds.get(kind) ?? 0) + 1);
2482
+ if (kind === "object") {
2483
+ shape.fields ??= /* @__PURE__ */ new Map();
2484
+ observeObject(shape.fields, value);
2485
+ } else if (kind === "array") {
2486
+ const arr = value;
2487
+ if (arr.length === 0) shape.sawEmptyArray = true;
2488
+ shape.elements ??= newShape();
2489
+ for (const el of arr) observe(shape.elements, el);
2490
+ }
2491
+ }
2492
+ function observeObject(fields, doc) {
2493
+ for (const [k, v] of Object.entries(doc)) {
2494
+ if (k.startsWith("$") || k.includes(".")) continue;
2495
+ let s = fields.get(k);
2496
+ if (!s) fields.set(k, s = newShape());
2497
+ observe(s, v);
2498
+ }
2499
+ }
2500
+ function fieldDef(name, shape, total, path3, ctx) {
2501
+ const kinds = [...shape.kinds.keys()];
2502
+ const required = total > 0 && shape.present === total;
2503
+ if (kinds.length === 0) {
2504
+ ctx.notes.push(`${path3}: always null in the sample \u2014 typed as any (object)`);
2505
+ return { type: "object" };
2506
+ }
2507
+ if (kinds.length > 1) {
2508
+ ctx.notes.push(`${path3}: mixed types (${kinds.sort().join(", ")}) \u2014 typed as any (object)`);
2509
+ return { type: "object", ...required && { required: true } };
2510
+ }
2511
+ const kind = kinds[0];
2512
+ if (kind === "other") {
2513
+ ctx.notes.push(`${path3}: a BSON type EFC doesn't model \u2014 typed as any (object)`);
2514
+ return { type: "object" };
2515
+ }
2516
+ if (kind === "object") {
2517
+ const sub = schemaOf(shape.fields, shape.present, path3, ctx);
2518
+ return required ? { type: "object", required: true, fields: sub } : sub;
2519
+ }
2520
+ if (kind === "array") {
2521
+ const el = shape.elements;
2522
+ const elKinds = [...el.kinds.keys()];
2523
+ if (elKinds.length === 1 && elKinds[0] === "object") {
2524
+ return [schemaOf(el.fields, el.present, `${path3}[]`, ctx)];
2525
+ }
2526
+ if (elKinds.length === 1 && elKinds[0] !== "array" && elKinds[0] !== "other") {
2527
+ const of = elKinds[0];
2528
+ return { type: "array", of, ...of === "objectId" && refFor(name, ctx) };
2529
+ }
2530
+ if (elKinds.length === 0) {
2531
+ ctx.notes.push(`${path3}: only empty arrays in the sample \u2014 element type unknown (object)`);
2532
+ } else {
2533
+ ctx.notes.push(`${path3}: array elements of mixed types \u2014 typed as any (object)`);
2534
+ }
2535
+ return { type: "array", of: "object" };
2536
+ }
2537
+ return {
2538
+ type: kind,
2539
+ ...required && { required: true },
2540
+ ...kind === "objectId" && refFor(name, ctx)
2541
+ };
2542
+ }
2543
+ function refFor(field, ctx) {
2544
+ const base = singular(field.replace(/_?[Ii][Dd]s?$/, "")).toLowerCase();
2545
+ const model = ctx.models.get(base);
2546
+ return model ? { ref: model } : {};
2547
+ }
2548
+ function schemaOf(fields, total, prefix, ctx) {
2549
+ const out = {};
2550
+ for (const [k, shape] of fields) {
2551
+ const def = fieldDef(k, shape, total, prefix ? `${prefix}.${k}` : k, ctx);
2552
+ if (def !== void 0) out[k] = def;
2553
+ }
2554
+ return out;
2555
+ }
2556
+ async function pullMongo(conn, pluralize, opts = {}) {
2557
+ const sampleSize = opts.sample ?? 1e3;
2558
+ const db = conn.db;
2559
+ const collections = (await db.listCollections({ type: "collection" }).toArray()).map((c) => c.name).filter((n) => !n.startsWith("system.") && !INTERNAL2.has(n)).sort();
2560
+ const nameOf2 = new Map(
2561
+ collections.map((c) => [c, opts.names?.get(c) ?? (pascal(singular(c)) || "Model")])
2562
+ );
2563
+ const ctxModels = new Map([...nameOf2.values()].map((m) => [m.toLowerCase(), m]));
2564
+ const models = [];
2565
+ const skipped = [];
2566
+ for (const collection of collections) {
2567
+ const name = nameOf2.get(collection);
2568
+ if (!/^[A-Za-z]/.test(name)) {
2569
+ skipped.push(collection);
2570
+ continue;
2571
+ }
2572
+ const coll = db.collection(collection);
2573
+ const docs = await coll.aggregate([{ $sample: { size: sampleSize } }], { promoteValues: false }).toArray();
2574
+ const ctx = { notes: [], models: ctxModels };
2575
+ const shapes = /* @__PURE__ */ new Map();
2576
+ for (const d of docs) observeObject(shapes, d);
2577
+ const idShape = shapes.get("_id");
2578
+ if (idShape && [...idShape.kinds.keys()].some((k) => k !== "objectId")) {
2579
+ ctx.notes.push(
2580
+ "_id is not an ObjectId here; defineCollection creates ObjectId ids for new documents"
2581
+ );
2582
+ }
2583
+ shapes.delete("_id");
2584
+ shapes.delete("__v");
2585
+ const isDate = (k) => {
2586
+ const s = shapes.get(k);
2587
+ return !!s && s.kinds.size === 1 && s.kinds.has("date");
2588
+ };
2589
+ const options = {};
2590
+ if (isDate("createdAt") && isDate("updatedAt")) {
2591
+ shapes.delete("createdAt");
2592
+ shapes.delete("updatedAt");
2593
+ } else {
2594
+ options["timestamps"] = false;
2595
+ }
2596
+ const fields = Object.entries(schemaOf(shapes, docs.length, "", ctx));
2597
+ for (const [field, def] of fields) {
2598
+ const d = def;
2599
+ const holdsIds = d["type"] === "objectId" || d["type"] === "array" && d["of"] === "objectId";
2600
+ if (!holdsIds || d["ref"] !== void 0) continue;
2601
+ const ids = /* @__PURE__ */ new Map();
2602
+ for (const doc of docs) {
2603
+ for (const v of [doc[field]].flat()) {
2604
+ if (bsonKind(v) === "objectId" && ids.size < 20) ids.set(String(v), v);
2605
+ }
2606
+ }
2607
+ if (ids.size === 0) continue;
2608
+ const holders = [];
2609
+ for (const other of collections) {
2610
+ const found = await db.collection(other).countDocuments({ _id: { $in: [...ids.values()] } });
2611
+ if (found === ids.size) holders.push(other);
2612
+ }
2613
+ if (holders.length === 1) d["ref"] = nameOf2.get(holders[0]);
2614
+ else
2615
+ ctx.notes.push(
2616
+ `${field}: holds ObjectIds${holders.length ? ` found in ${holders.join(", ")}` : ""} \u2014 add ref: '<Model>' if it points at another collection`
2617
+ );
2618
+ }
2619
+ const indexes = [];
2620
+ for (const ix of await coll.indexes()) {
2621
+ if (ix["name"] === "_id_") continue;
2622
+ const key = ix["key"];
2623
+ const textKeys = ix["weights"] ? Object.keys(ix["weights"]) : [];
2624
+ const spec = textKeys.length ? Object.fromEntries(textKeys.map((k) => [k, "text"])) : key;
2625
+ const keys = Object.keys(spec);
2626
+ const simple = keys.length === 1 && ix["partialFilterExpression"] === void 0 && ix["expireAfterSeconds"] === void 0 && !keys[0].includes(".");
2627
+ const field = simple ? fields.find(([f]) => f === keys[0]) : void 0;
2628
+ if (field && !Array.isArray(field[1]) && typeof field[1]["type"] === "string") {
2629
+ const def = field[1];
2630
+ const dir = spec[keys[0]];
2631
+ if (ix["unique"]) def["unique"] = true;
2632
+ else def["index"] = dir === "2dsphere" || dir === "text" || dir === "hashed" ? dir : true;
2633
+ continue;
2634
+ }
2635
+ indexes.push({
2636
+ fields: spec,
2637
+ ...ix["unique"] === true && { unique: true },
2638
+ ...ix["partialFilterExpression"] !== void 0 && {
2639
+ partialFilterExpression: ix["partialFilterExpression"]
2640
+ },
2641
+ ...ix["expireAfterSeconds"] !== void 0 && {
2642
+ expireAfterSeconds: ix["expireAfterSeconds"]
2643
+ }
2644
+ });
2645
+ }
2646
+ if (indexes.length) options["indexes"] = indexes;
2647
+ if (pluralize(name) !== collection) options["collection"] = collection;
2648
+ ctx.notes.unshift(
2649
+ docs.length ? `Pulled from ${docs.length} sampled document(s) of "${collection}": a field is required only when every sample had a value.` : `"${collection}" is empty \u2014 no fields could be inferred.`
2650
+ );
2651
+ models.push({
2652
+ name,
2653
+ fields,
2654
+ options,
2655
+ notes: ctx.notes,
2656
+ api: "defineCollection",
2657
+ table: collection
2658
+ });
2659
+ }
2660
+ return { models, skipped };
2661
+ }
2662
+
772
2663
  // src/cli/db-runner.ts
773
2664
  async function importModels(root) {
774
2665
  const files = [];
@@ -786,6 +2677,27 @@ async function importModels(root) {
786
2677
  for (const f of files.sort()) await import(pathToFileURL2(f).href);
787
2678
  return registeredModels();
788
2679
  }
2680
+ async function existingModels(dir) {
2681
+ const out = /* @__PURE__ */ new Map();
2682
+ if (!fs2.existsSync(dir)) return out;
2683
+ const files = fs2.readdirSync(dir).filter((f) => /\.(ts|js|mts|mjs)$/.test(f) && !f.endsWith(".d.ts")).sort((a, b) => Number(/^index\./.test(a)) - Number(/^index\./.test(b)) || a.localeCompare(b));
2684
+ const fileOf = /* @__PURE__ */ new Map();
2685
+ for (const f of files) {
2686
+ const file = path2.join(dir, f);
2687
+ try {
2688
+ await import(pathToFileURL2(file).href);
2689
+ } catch (err) {
2690
+ console.log(pc.yellow(` ! ${f} didn't load (${err.message.split("\n")[0]})`));
2691
+ continue;
2692
+ }
2693
+ for (const m of registeredModels()) if (!fileOf.has(m.name)) fileOf.set(m.name, file);
2694
+ }
2695
+ for (const m of registeredModels()) {
2696
+ const storage = await m.studio?.storage().catch(() => void 0);
2697
+ if (storage && !out.has(storage)) out.set(storage, { name: m.name, file: fileOf.get(m.name) });
2698
+ }
2699
+ return out;
2700
+ }
789
2701
  function shadowUrl(url, engine, name) {
790
2702
  if (engine === "mongodb")
791
2703
  return url.replace(/^(mongodb(?:\+srv)?:\/\/[^/?]+)(\/[^?]*)?/, `$1/${name}`);
@@ -979,19 +2891,30 @@ async function main() {
979
2891
  break;
980
2892
  }
981
2893
  case "pull": {
982
- if (engine !== "postgresql")
983
- throw new Error(
984
- "[EFC] efc db pull reads PostgreSQL schemas (MongoDB arrives with defineCollection)"
985
- );
986
- const { models, skipped: notPulled } = await pullPostgres(client);
2894
+ setAutoSync(false);
2895
+ const dir = path2.resolve(process.cwd(), opts.out ?? path2.join("src", "model"));
2896
+ const existing = await existingModels(dir);
2897
+ const names = new Map([...existing].map(([table, m]) => [table, m.name]));
2898
+ const { models, skipped: notPulled } = engine === "postgresql" ? await pullPostgres(client, names) : await pullMongo(
2899
+ client,
2900
+ (await loadMongoose()).pluralize(),
2901
+ {
2902
+ ...opts.sample !== void 0 && { sample: opts.sample },
2903
+ names
2904
+ }
2905
+ );
987
2906
  if (models.length === 0) {
988
- console.log(pc.yellow(" No tables found in the current schema"));
2907
+ console.log(
2908
+ pc.yellow(
2909
+ engine === "postgresql" ? " No tables found in the current schema" : " No collections found in the database"
2910
+ )
2911
+ );
989
2912
  break;
990
2913
  }
991
2914
  const typescript = fs2.existsSync(path2.join(process.cwd(), "tsconfig.json"));
992
- const dir = path2.resolve(process.cwd(), opts.out ?? path2.join("src", "model"));
993
2915
  const { written, skipped } = writeModels(dir, models, {
994
2916
  typescript,
2917
+ existing,
995
2918
  ...opts.force && { force: true }
996
2919
  });
997
2920
  console.log(pc.bold(`
@@ -999,15 +2922,16 @@ async function main() {
999
2922
  `));
1000
2923
  for (const f of written)
1001
2924
  console.log(` ${pc.green("+")} ${path2.relative(process.cwd(), f)}`);
1002
- for (const f of skipped)
2925
+ for (const { file, reason } of skipped)
1003
2926
  console.log(
1004
- ` ${pc.yellow("\u2022")} ${path2.relative(process.cwd(), f)} ${pc.dim("exists \u2014 kept (--force overwrites)")}`
2927
+ ` ${pc.yellow("\u2022")} ${path2.relative(process.cwd(), file)} ${pc.dim(reason)}`
1005
2928
  );
1006
2929
  if (notPulled.length)
1007
2930
  console.log(
1008
2931
  pc.dim(
1009
- `
1010
- Not pulled (no single "id" primary key of type uuid, integer or bigint): ${notPulled.join(", ")}`
2932
+ engine === "postgresql" ? `
2933
+ Not pulled (no single "id" primary key of type uuid, integer or bigint): ${notPulled.join(", ")}` : `
2934
+ Not pulled (no usable model name): ${notPulled.join(", ")}`
1011
2935
  )
1012
2936
  );
1013
2937
  const notes = models.reduce((n, m) => n + m.notes.length, 0);
@@ -1048,12 +2972,20 @@ async function main() {
1048
2972
  break;
1049
2973
  }
1050
2974
  case "studio": {
1051
- const { url: studioUrl } = await startStudio(engine, client, opts.port ?? 4983);
2975
+ const models = opts.write ? await importModels(opts.root) : [];
2976
+ const { url: studioUrl } = await startStudio(engine, client, opts.port ?? 4983, {
2977
+ write: !!opts.write,
2978
+ models
2979
+ });
1052
2980
  console.log(
1053
2981
  `
1054
- ${pc.bold("EFC Studio")} ${pc.dim(`(${engine}, read-only)`)} ${pc.cyan(studioUrl)}
2982
+ ${pc.bold("EFC Studio")} ${pc.dim(`(${engine}, ${opts.write ? `write \u2014 ${models.length} model(s)` : "read-only"})`)} ${pc.cyan(studioUrl)}
1055
2983
  `
1056
2984
  );
2985
+ if (opts.write)
2986
+ console.log(
2987
+ pc.yellow(" Writes change real data. Point DATABASE_URL at a development database.\n")
2988
+ );
1057
2989
  await new Promise((resolve) => {
1058
2990
  process.once("SIGINT", resolve);
1059
2991
  process.once("SIGTERM", resolve);