@supatype/cli 0.3.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (903) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/deno.d.ts +11 -0
  3. package/dist/adopt-columns.d.ts +157 -0
  4. package/dist/adopt-columns.d.ts.map +1 -0
  5. package/dist/adopt-columns.js +789 -0
  6. package/dist/adopt-columns.js.map +1 -0
  7. package/dist/adopt-walkthrough.d.ts +50 -15
  8. package/dist/adopt-walkthrough.d.ts.map +1 -1
  9. package/dist/adopt-walkthrough.js +93 -61
  10. package/dist/adopt-walkthrough.js.map +1 -1
  11. package/dist/api-config-cache.d.ts +3 -3
  12. package/dist/api-config-cache.d.ts.map +1 -1
  13. package/dist/api-config-cache.js +14 -20
  14. package/dist/api-config-cache.js.map +1 -1
  15. package/dist/app/framework.d.ts.map +1 -1
  16. package/dist/app/framework.js +5 -5
  17. package/dist/app/framework.js.map +1 -1
  18. package/dist/app/proxy-dev-app.d.ts.map +1 -1
  19. package/dist/app/proxy-dev-app.js +3 -2
  20. package/dist/app/proxy-dev-app.js.map +1 -1
  21. package/dist/ast-read.d.ts +17 -0
  22. package/dist/ast-read.d.ts.map +1 -0
  23. package/dist/ast-read.js +32 -0
  24. package/dist/ast-read.js.map +1 -0
  25. package/dist/augmentation-generator.d.ts +14 -2
  26. package/dist/augmentation-generator.d.ts.map +1 -1
  27. package/dist/augmentation-generator.js +194 -61
  28. package/dist/augmentation-generator.js.map +1 -1
  29. package/dist/augmentation-relationships.d.ts +32 -0
  30. package/dist/augmentation-relationships.d.ts.map +1 -0
  31. package/dist/augmentation-relationships.js +122 -0
  32. package/dist/augmentation-relationships.js.map +1 -0
  33. package/dist/auth-answer.d.ts +16 -0
  34. package/dist/auth-answer.d.ts.map +1 -0
  35. package/dist/auth-answer.js +21 -0
  36. package/dist/auth-answer.js.map +1 -0
  37. package/dist/auth-providers.d.ts +89 -0
  38. package/dist/auth-providers.d.ts.map +1 -0
  39. package/dist/auth-providers.js +243 -0
  40. package/dist/auth-providers.js.map +1 -0
  41. package/dist/binary-cache.d.ts +9 -6
  42. package/dist/binary-cache.d.ts.map +1 -1
  43. package/dist/binary-cache.js +150 -46
  44. package/dist/binary-cache.js.map +1 -1
  45. package/dist/binary-download-lock.d.ts.map +1 -1
  46. package/dist/binary-download-lock.js +13 -10
  47. package/dist/binary-download-lock.js.map +1 -1
  48. package/dist/byo-preflight.d.ts +26 -0
  49. package/dist/byo-preflight.d.ts.map +1 -0
  50. package/dist/byo-preflight.js +69 -0
  51. package/dist/byo-preflight.js.map +1 -0
  52. package/dist/cache-identity-scope.d.ts +7 -3
  53. package/dist/cache-identity-scope.d.ts.map +1 -1
  54. package/dist/cache-identity-scope.js +20 -10
  55. package/dist/cache-identity-scope.js.map +1 -1
  56. package/dist/cache-provider.d.ts +17 -18
  57. package/dist/cache-provider.d.ts.map +1 -1
  58. package/dist/cache-provider.js +27 -25
  59. package/dist/cache-provider.js.map +1 -1
  60. package/dist/cli-package-version.d.ts.map +1 -1
  61. package/dist/cli-package-version.js +2 -2
  62. package/dist/cli-package-version.js.map +1 -1
  63. package/dist/cli-standalone.d.ts.map +1 -1
  64. package/dist/cli-standalone.js +2 -6
  65. package/dist/cli-standalone.js.map +1 -1
  66. package/dist/cli-version-embedded.js +1 -1
  67. package/dist/cli.d.ts.map +1 -1
  68. package/dist/cli.js +4 -0
  69. package/dist/cli.js.map +1 -1
  70. package/dist/client-generator.d.ts +5 -2
  71. package/dist/client-generator.d.ts.map +1 -1
  72. package/dist/client-generator.js +32 -22
  73. package/dist/client-generator.js.map +1 -1
  74. package/dist/cloud-credentials.d.ts.map +1 -1
  75. package/dist/cloud-credentials.js +32 -26
  76. package/dist/cloud-credentials.js.map +1 -1
  77. package/dist/commands/add.d.ts.map +1 -1
  78. package/dist/commands/add.js +3 -2
  79. package/dist/commands/add.js.map +1 -1
  80. package/dist/commands/admin.d.ts +51 -16
  81. package/dist/commands/admin.d.ts.map +1 -1
  82. package/dist/commands/admin.js +162 -136
  83. package/dist/commands/admin.js.map +1 -1
  84. package/dist/commands/adopt.d.ts +23 -0
  85. package/dist/commands/adopt.d.ts.map +1 -1
  86. package/dist/commands/adopt.js +205 -42
  87. package/dist/commands/adopt.js.map +1 -1
  88. package/dist/commands/app.d.ts.map +1 -1
  89. package/dist/commands/app.js +4 -3
  90. package/dist/commands/app.js.map +1 -1
  91. package/dist/commands/cache.d.ts.map +1 -1
  92. package/dist/commands/cache.js +2 -1
  93. package/dist/commands/cache.js.map +1 -1
  94. package/dist/commands/cloud.d.ts +4 -1
  95. package/dist/commands/cloud.d.ts.map +1 -1
  96. package/dist/commands/cloud.js +47 -23
  97. package/dist/commands/cloud.js.map +1 -1
  98. package/dist/commands/db.d.ts.map +1 -1
  99. package/dist/commands/db.js +9 -7
  100. package/dist/commands/db.js.map +1 -1
  101. package/dist/commands/deploy.d.ts +6 -0
  102. package/dist/commands/deploy.d.ts.map +1 -1
  103. package/dist/commands/deploy.js +65 -17
  104. package/dist/commands/deploy.js.map +1 -1
  105. package/dist/commands/dev.d.ts +8 -2
  106. package/dist/commands/dev.d.ts.map +1 -1
  107. package/dist/commands/dev.js +385 -268
  108. package/dist/commands/dev.js.map +1 -1
  109. package/dist/commands/doctor.d.ts +56 -8
  110. package/dist/commands/doctor.d.ts.map +1 -1
  111. package/dist/commands/doctor.js +180 -61
  112. package/dist/commands/doctor.js.map +1 -1
  113. package/dist/commands/engine.d.ts +1 -1
  114. package/dist/commands/engine.d.ts.map +1 -1
  115. package/dist/commands/engine.js +14 -13
  116. package/dist/commands/engine.js.map +1 -1
  117. package/dist/commands/functions.d.ts.map +1 -1
  118. package/dist/commands/functions.js +85 -96
  119. package/dist/commands/functions.js.map +1 -1
  120. package/dist/commands/generate.d.ts +6 -0
  121. package/dist/commands/generate.d.ts.map +1 -1
  122. package/dist/commands/generate.js +20 -20
  123. package/dist/commands/generate.js.map +1 -1
  124. package/dist/commands/init.d.ts +19 -0
  125. package/dist/commands/init.d.ts.map +1 -1
  126. package/dist/commands/init.js +105 -82
  127. package/dist/commands/init.js.map +1 -1
  128. package/dist/commands/internal.d.ts.map +1 -1
  129. package/dist/commands/internal.js +3 -2
  130. package/dist/commands/internal.js.map +1 -1
  131. package/dist/commands/keys.js.map +1 -1
  132. package/dist/commands/link-helpers.d.ts.map +1 -1
  133. package/dist/commands/link-helpers.js +16 -8
  134. package/dist/commands/link-helpers.js.map +1 -1
  135. package/dist/commands/login.d.ts.map +1 -1
  136. package/dist/commands/login.js +2 -1
  137. package/dist/commands/login.js.map +1 -1
  138. package/dist/commands/migrate.d.ts +43 -0
  139. package/dist/commands/migrate.d.ts.map +1 -1
  140. package/dist/commands/migrate.js +98 -47
  141. package/dist/commands/migrate.js.map +1 -1
  142. package/dist/commands/pg.d.ts.map +1 -1
  143. package/dist/commands/pg.js +24 -23
  144. package/dist/commands/pg.js.map +1 -1
  145. package/dist/commands/plugins.d.ts.map +1 -1
  146. package/dist/commands/plugins.js +36 -27
  147. package/dist/commands/plugins.js.map +1 -1
  148. package/dist/commands/pull.d.ts.map +1 -1
  149. package/dist/commands/pull.js +6 -5
  150. package/dist/commands/pull.js.map +1 -1
  151. package/dist/commands/push.d.ts +23 -0
  152. package/dist/commands/push.d.ts.map +1 -1
  153. package/dist/commands/push.js +249 -84
  154. package/dist/commands/push.js.map +1 -1
  155. package/dist/commands/rename.d.ts +20 -0
  156. package/dist/commands/rename.d.ts.map +1 -0
  157. package/dist/commands/rename.js +74 -0
  158. package/dist/commands/rename.js.map +1 -0
  159. package/dist/commands/seed.d.ts +12 -0
  160. package/dist/commands/seed.d.ts.map +1 -1
  161. package/dist/commands/seed.js +65 -12
  162. package/dist/commands/seed.js.map +1 -1
  163. package/dist/commands/self-host.d.ts.map +1 -1
  164. package/dist/commands/self-host.js +93 -27
  165. package/dist/commands/self-host.js.map +1 -1
  166. package/dist/commands/self-update.d.ts.map +1 -1
  167. package/dist/commands/self-update.js +2 -1
  168. package/dist/commands/self-update.js.map +1 -1
  169. package/dist/commands/status.d.ts.map +1 -1
  170. package/dist/commands/status.js +16 -12
  171. package/dist/commands/status.js.map +1 -1
  172. package/dist/commands/types.d.ts.map +1 -1
  173. package/dist/commands/types.js +9 -7
  174. package/dist/commands/types.js.map +1 -1
  175. package/dist/commands/update.d.ts.map +1 -1
  176. package/dist/commands/update.js +8 -4
  177. package/dist/commands/update.js.map +1 -1
  178. package/dist/compose-db-psql.d.ts +20 -0
  179. package/dist/compose-db-psql.d.ts.map +1 -0
  180. package/dist/compose-db-psql.js +30 -0
  181. package/dist/compose-db-psql.js.map +1 -0
  182. package/dist/compose-db-roles.d.ts +41 -0
  183. package/dist/compose-db-roles.d.ts.map +1 -0
  184. package/dist/compose-db-roles.js +118 -0
  185. package/dist/compose-db-roles.js.map +1 -0
  186. package/dist/compose-engine-run.d.ts +27 -0
  187. package/dist/compose-engine-run.d.ts.map +1 -0
  188. package/dist/compose-engine-run.js +61 -0
  189. package/dist/compose-engine-run.js.map +1 -0
  190. package/dist/compose-kong.d.ts +31 -0
  191. package/dist/compose-kong.d.ts.map +1 -0
  192. package/dist/compose-kong.js +145 -0
  193. package/dist/compose-kong.js.map +1 -0
  194. package/dist/compose-rename.d.ts.map +1 -1
  195. package/dist/compose-rename.js +2 -2
  196. package/dist/compose-rename.js.map +1 -1
  197. package/dist/compose-render-mode.d.ts +41 -0
  198. package/dist/compose-render-mode.d.ts.map +1 -0
  199. package/dist/compose-render-mode.js +70 -0
  200. package/dist/compose-render-mode.js.map +1 -0
  201. package/dist/compose-services.d.ts.map +1 -1
  202. package/dist/compose-services.js +3 -2
  203. package/dist/compose-services.js.map +1 -1
  204. package/dist/config.d.ts +18 -2
  205. package/dist/config.d.ts.map +1 -1
  206. package/dist/config.js +50 -13
  207. package/dist/config.js.map +1 -1
  208. package/dist/db-port.d.ts +57 -13
  209. package/dist/db-port.d.ts.map +1 -1
  210. package/dist/db-port.js +78 -38
  211. package/dist/db-port.js.map +1 -1
  212. package/dist/db-preflight.d.ts +22 -8
  213. package/dist/db-preflight.d.ts.map +1 -1
  214. package/dist/db-preflight.js +86 -46
  215. package/dist/db-preflight.js.map +1 -1
  216. package/dist/db-rows.d.ts +20 -0
  217. package/dist/db-rows.d.ts.map +1 -0
  218. package/dist/db-rows.js +20 -0
  219. package/dist/db-rows.js.map +1 -0
  220. package/dist/destructive-consent.d.ts +88 -0
  221. package/dist/destructive-consent.d.ts.map +1 -0
  222. package/dist/destructive-consent.js +184 -0
  223. package/dist/destructive-consent.js.map +1 -0
  224. package/dist/dev-api-keys.d.ts +26 -0
  225. package/dist/dev-api-keys.d.ts.map +1 -0
  226. package/dist/dev-api-keys.js +52 -0
  227. package/dist/dev-api-keys.js.map +1 -0
  228. package/dist/dev-compose.d.ts +92 -15
  229. package/dist/dev-compose.d.ts.map +1 -1
  230. package/dist/dev-compose.js +676 -465
  231. package/dist/dev-compose.js.map +1 -1
  232. package/dist/dev-db-ready.d.ts +20 -0
  233. package/dist/dev-db-ready.d.ts.map +1 -0
  234. package/dist/dev-db-ready.js +21 -0
  235. package/dist/dev-db-ready.js.map +1 -0
  236. package/dist/dev-functions-watch.d.ts +24 -0
  237. package/dist/dev-functions-watch.d.ts.map +1 -0
  238. package/dist/dev-functions-watch.js +82 -0
  239. package/dist/dev-functions-watch.js.map +1 -0
  240. package/dist/dev-initial-push.d.ts +41 -6
  241. package/dist/dev-initial-push.d.ts.map +1 -1
  242. package/dist/dev-initial-push.js +84 -31
  243. package/dist/dev-initial-push.js.map +1 -1
  244. package/dist/dev-ports.d.ts +58 -6
  245. package/dist/dev-ports.d.ts.map +1 -1
  246. package/dist/dev-ports.js +157 -49
  247. package/dist/dev-ports.js.map +1 -1
  248. package/dist/dev-ready-panel.d.ts +5 -0
  249. package/dist/dev-ready-panel.d.ts.map +1 -1
  250. package/dist/dev-ready-panel.js +13 -0
  251. package/dist/dev-ready-panel.js.map +1 -1
  252. package/dist/dev-schema-watch.d.ts +19 -0
  253. package/dist/dev-schema-watch.d.ts.map +1 -0
  254. package/dist/dev-schema-watch.js +49 -0
  255. package/dist/dev-schema-watch.js.map +1 -0
  256. package/dist/dev-session-lock.d.ts +30 -1
  257. package/dist/dev-session-lock.d.ts.map +1 -1
  258. package/dist/dev-session-lock.js +83 -10
  259. package/dist/dev-session-lock.js.map +1 -1
  260. package/dist/dev-shutdown.d.ts +17 -3
  261. package/dist/dev-shutdown.d.ts.map +1 -1
  262. package/dist/dev-shutdown.js +48 -4
  263. package/dist/dev-shutdown.js.map +1 -1
  264. package/dist/diff-output.d.ts +71 -3
  265. package/dist/diff-output.d.ts.map +1 -1
  266. package/dist/diff-output.js +173 -18
  267. package/dist/diff-output.js.map +1 -1
  268. package/dist/docker-env.d.ts +16 -0
  269. package/dist/docker-env.d.ts.map +1 -0
  270. package/dist/docker-env.js +16 -0
  271. package/dist/docker-env.js.map +1 -0
  272. package/dist/docker-postgres.d.ts.map +1 -1
  273. package/dist/docker-postgres.js +14 -9
  274. package/dist/docker-postgres.js.map +1 -1
  275. package/dist/drift-consent.d.ts +36 -0
  276. package/dist/drift-consent.d.ts.map +1 -0
  277. package/dist/drift-consent.js +78 -0
  278. package/dist/drift-consent.js.map +1 -0
  279. package/dist/engine-answers.d.ts +51 -0
  280. package/dist/engine-answers.d.ts.map +1 -0
  281. package/dist/engine-answers.js +183 -0
  282. package/dist/engine-answers.js.map +1 -0
  283. package/dist/engine-client.d.ts +156 -9
  284. package/dist/engine-client.d.ts.map +1 -1
  285. package/dist/engine-client.js +315 -129
  286. package/dist/engine-client.js.map +1 -1
  287. package/dist/engine-floor.d.ts +10 -0
  288. package/dist/engine-floor.d.ts.map +1 -1
  289. package/dist/engine-floor.js +28 -0
  290. package/dist/engine-floor.js.map +1 -1
  291. package/dist/engine-json-line.d.ts +9 -0
  292. package/dist/engine-json-line.d.ts.map +1 -0
  293. package/dist/engine-json-line.js +23 -0
  294. package/dist/engine-json-line.js.map +1 -0
  295. package/dist/engine-ownership-gate.d.ts +79 -0
  296. package/dist/engine-ownership-gate.d.ts.map +1 -0
  297. package/dist/engine-ownership-gate.js +213 -0
  298. package/dist/engine-ownership-gate.js.map +1 -0
  299. package/dist/engine-push-output.d.ts +23 -2
  300. package/dist/engine-push-output.d.ts.map +1 -1
  301. package/dist/engine-push-output.js +22 -15
  302. package/dist/engine-push-output.js.map +1 -1
  303. package/dist/env-file.d.ts +15 -2
  304. package/dist/env-file.d.ts.map +1 -1
  305. package/dist/env-file.js +61 -22
  306. package/dist/env-file.js.map +1 -1
  307. package/dist/error-message.d.ts +5 -0
  308. package/dist/error-message.d.ts.map +1 -0
  309. package/dist/error-message.js +11 -0
  310. package/dist/error-message.js.map +1 -0
  311. package/dist/field-bounds.d.ts +8 -2
  312. package/dist/field-bounds.d.ts.map +1 -1
  313. package/dist/field-bounds.js +9 -15
  314. package/dist/field-bounds.js.map +1 -1
  315. package/dist/field-masking-tier.d.ts +4 -3
  316. package/dist/field-masking-tier.d.ts.map +1 -1
  317. package/dist/field-masking-tier.js +36 -13
  318. package/dist/field-masking-tier.js.map +1 -1
  319. package/dist/functions-deno-types.d.ts +8 -8
  320. package/dist/functions-deno-types.d.ts.map +1 -1
  321. package/dist/functions-deno-types.js +53 -25
  322. package/dist/functions-deno-types.js.map +1 -1
  323. package/dist/functions-router-gen.d.ts +21 -2
  324. package/dist/functions-router-gen.d.ts.map +1 -1
  325. package/dist/functions-router-gen.js +89 -18
  326. package/dist/functions-router-gen.js.map +1 -1
  327. package/dist/functions-template.d.ts +10 -0
  328. package/dist/functions-template.d.ts.map +1 -0
  329. package/dist/functions-template.js +39 -0
  330. package/dist/functions-template.js.map +1 -0
  331. package/dist/hooks-generator.d.ts.map +1 -1
  332. package/dist/hooks-generator.js +110 -83
  333. package/dist/hooks-generator.js.map +1 -1
  334. package/dist/host-database.d.ts +46 -5
  335. package/dist/host-database.d.ts.map +1 -1
  336. package/dist/host-database.js +72 -15
  337. package/dist/host-database.js.map +1 -1
  338. package/dist/index.d.ts +2 -1
  339. package/dist/index.d.ts.map +1 -1
  340. package/dist/index.js +1 -1
  341. package/dist/index.js.map +1 -1
  342. package/dist/init-dependency-versions.d.ts.map +1 -1
  343. package/dist/init-dependency-versions.js +8 -1
  344. package/dist/init-dependency-versions.js.map +1 -1
  345. package/dist/init-project-detect.d.ts.map +1 -1
  346. package/dist/init-project-detect.js +3 -2
  347. package/dist/init-project-detect.js.map +1 -1
  348. package/dist/json-file.d.ts +15 -0
  349. package/dist/json-file.d.ts.map +1 -0
  350. package/dist/json-file.js +38 -0
  351. package/dist/json-file.js.map +1 -0
  352. package/dist/json-type-text.d.ts +18 -0
  353. package/dist/json-type-text.d.ts.map +1 -0
  354. package/dist/json-type-text.js +112 -0
  355. package/dist/json-type-text.js.map +1 -0
  356. package/dist/jwt-secret-length.d.ts +22 -0
  357. package/dist/jwt-secret-length.d.ts.map +1 -0
  358. package/dist/jwt-secret-length.js +36 -0
  359. package/dist/jwt-secret-length.js.map +1 -0
  360. package/dist/jwt.d.ts +5 -0
  361. package/dist/jwt.d.ts.map +1 -1
  362. package/dist/jwt.js +25 -1
  363. package/dist/jwt.js.map +1 -1
  364. package/dist/link.d.ts +5 -1
  365. package/dist/link.d.ts.map +1 -1
  366. package/dist/link.js +47 -5
  367. package/dist/link.js.map +1 -1
  368. package/dist/local-gateway.d.ts +9 -0
  369. package/dist/local-gateway.d.ts.map +1 -1
  370. package/dist/local-gateway.js +16 -0
  371. package/dist/local-gateway.js.map +1 -1
  372. package/dist/local-secrets.d.ts +84 -2
  373. package/dist/local-secrets.d.ts.map +1 -1
  374. package/dist/local-secrets.js +115 -5
  375. package/dist/local-secrets.js.map +1 -1
  376. package/dist/local-stack.d.ts +30 -0
  377. package/dist/local-stack.d.ts.map +1 -0
  378. package/dist/local-stack.js +81 -0
  379. package/dist/local-stack.js.map +1 -0
  380. package/dist/mailer-autoconfirm.d.ts +37 -0
  381. package/dist/mailer-autoconfirm.d.ts.map +1 -0
  382. package/dist/mailer-autoconfirm.js +69 -0
  383. package/dist/mailer-autoconfirm.js.map +1 -0
  384. package/dist/model-cache.d.ts +6 -2
  385. package/dist/model-cache.d.ts.map +1 -1
  386. package/dist/model-cache.js +33 -27
  387. package/dist/model-cache.js.map +1 -1
  388. package/dist/model-hooks.d.ts +7 -6
  389. package/dist/model-hooks.d.ts.map +1 -1
  390. package/dist/model-hooks.js +83 -138
  391. package/dist/model-hooks.js.map +1 -1
  392. package/dist/model-versioning.d.ts +7 -1
  393. package/dist/model-versioning.d.ts.map +1 -1
  394. package/dist/model-versioning.js +24 -27
  395. package/dist/model-versioning.js.map +1 -1
  396. package/dist/native-dev-env.d.ts +39 -0
  397. package/dist/native-dev-env.d.ts.map +1 -0
  398. package/dist/native-dev-env.js +50 -0
  399. package/dist/native-dev-env.js.map +1 -0
  400. package/dist/native-functions-watch.d.ts +11 -0
  401. package/dist/native-functions-watch.d.ts.map +1 -0
  402. package/dist/native-functions-watch.js +59 -0
  403. package/dist/native-functions-watch.js.map +1 -0
  404. package/dist/native-keyspace.d.ts +23 -0
  405. package/dist/native-keyspace.d.ts.map +1 -0
  406. package/dist/native-keyspace.js +53 -0
  407. package/dist/native-keyspace.js.map +1 -0
  408. package/dist/native-pg-auth.d.ts +46 -0
  409. package/dist/native-pg-auth.d.ts.map +1 -0
  410. package/dist/native-pg-auth.js +107 -0
  411. package/dist/native-pg-auth.js.map +1 -0
  412. package/dist/native-realtime.d.ts +26 -0
  413. package/dist/native-realtime.d.ts.map +1 -0
  414. package/dist/native-realtime.js +43 -0
  415. package/dist/native-realtime.js.map +1 -0
  416. package/dist/native-roles-sql.d.ts +27 -0
  417. package/dist/native-roles-sql.d.ts.map +1 -0
  418. package/dist/native-roles-sql.js +73 -0
  419. package/dist/native-roles-sql.js.map +1 -0
  420. package/dist/owner-default.d.ts +19 -0
  421. package/dist/owner-default.d.ts.map +1 -0
  422. package/dist/owner-default.js +42 -0
  423. package/dist/owner-default.js.map +1 -0
  424. package/dist/package-json.d.ts +20 -0
  425. package/dist/package-json.d.ts.map +1 -0
  426. package/dist/package-json.js +29 -0
  427. package/dist/package-json.js.map +1 -0
  428. package/dist/parent-watch.d.ts +40 -0
  429. package/dist/parent-watch.d.ts.map +1 -0
  430. package/dist/parent-watch.js +75 -0
  431. package/dist/parent-watch.js.map +1 -0
  432. package/dist/postgres-ctl.d.ts +29 -6
  433. package/dist/postgres-ctl.d.ts.map +1 -1
  434. package/dist/postgres-ctl.js +67 -17
  435. package/dist/postgres-ctl.js.map +1 -1
  436. package/dist/postgres-image.d.ts +35 -0
  437. package/dist/postgres-image.d.ts.map +1 -0
  438. package/dist/postgres-image.js +127 -0
  439. package/dist/postgres-image.js.map +1 -0
  440. package/dist/postgrest-release.d.ts +25 -0
  441. package/dist/postgrest-release.d.ts.map +1 -0
  442. package/dist/postgrest-release.js +35 -0
  443. package/dist/postgrest-release.js.map +1 -0
  444. package/dist/project-config.d.ts +145 -17
  445. package/dist/project-config.d.ts.map +1 -1
  446. package/dist/project-config.js +271 -115
  447. package/dist/project-config.js.map +1 -1
  448. package/dist/project-name-override.d.ts +25 -0
  449. package/dist/project-name-override.d.ts.map +1 -0
  450. package/dist/project-name-override.js +52 -0
  451. package/dist/project-name-override.js.map +1 -0
  452. package/dist/pull-utils.d.ts +26 -3
  453. package/dist/pull-utils.d.ts.map +1 -1
  454. package/dist/pull-utils.js +44 -5
  455. package/dist/pull-utils.js.map +1 -1
  456. package/dist/push-audit.d.ts +39 -0
  457. package/dist/push-audit.d.ts.map +1 -0
  458. package/dist/push-audit.js +116 -0
  459. package/dist/push-audit.js.map +1 -0
  460. package/dist/push-refusal.d.ts +94 -0
  461. package/dist/push-refusal.d.ts.map +1 -0
  462. package/dist/push-refusal.js +275 -0
  463. package/dist/push-refusal.js.map +1 -0
  464. package/dist/recorded-field-masking-tier.d.ts +43 -0
  465. package/dist/recorded-field-masking-tier.d.ts.map +1 -0
  466. package/dist/recorded-field-masking-tier.js +88 -0
  467. package/dist/recorded-field-masking-tier.js.map +1 -0
  468. package/dist/rename-journal.d.ts +54 -0
  469. package/dist/rename-journal.d.ts.map +1 -0
  470. package/dist/rename-journal.js +150 -0
  471. package/dist/rename-journal.js.map +1 -0
  472. package/dist/resolve-api-url.d.ts.map +1 -1
  473. package/dist/resolve-api-url.js +4 -3
  474. package/dist/resolve-api-url.js.map +1 -1
  475. package/dist/resolve-target.d.ts +85 -26
  476. package/dist/resolve-target.d.ts.map +1 -1
  477. package/dist/resolve-target.js +214 -62
  478. package/dist/resolve-target.js.map +1 -1
  479. package/dist/rest-cache-admin.d.ts +9 -8
  480. package/dist/rest-cache-admin.d.ts.map +1 -1
  481. package/dist/rest-cache-admin.js +32 -9
  482. package/dist/rest-cache-admin.js.map +1 -1
  483. package/dist/rest-ready.d.ts +28 -0
  484. package/dist/rest-ready.d.ts.map +1 -0
  485. package/dist/rest-ready.js +53 -0
  486. package/dist/rest-ready.js.map +1 -0
  487. package/dist/restore-system-relation-targets.d.ts.map +1 -1
  488. package/dist/restore-system-relation-targets.js +49 -31
  489. package/dist/restore-system-relation-targets.js.map +1 -1
  490. package/dist/route-manifest.d.ts.map +1 -1
  491. package/dist/route-manifest.js +4 -10
  492. package/dist/route-manifest.js.map +1 -1
  493. package/dist/runtime-routes.d.ts.map +1 -1
  494. package/dist/runtime-routes.js +23 -28
  495. package/dist/runtime-routes.js.map +1 -1
  496. package/dist/schema-ast-v2.d.ts +35 -1
  497. package/dist/schema-ast-v2.d.ts.map +1 -1
  498. package/dist/schema-ast-v2.js +22 -7
  499. package/dist/schema-ast-v2.js.map +1 -1
  500. package/dist/schema-push-lock.d.ts.map +1 -1
  501. package/dist/schema-push-lock.js +14 -37
  502. package/dist/schema-push-lock.js.map +1 -1
  503. package/dist/schema-sources.d.ts +7 -1
  504. package/dist/schema-sources.d.ts.map +1 -1
  505. package/dist/schema-sources.js +19 -8
  506. package/dist/schema-sources.js.map +1 -1
  507. package/dist/seed-ir.d.ts.map +1 -1
  508. package/dist/seed-ir.js +30 -9
  509. package/dist/seed-ir.js.map +1 -1
  510. package/dist/seed-runner.d.ts.map +1 -1
  511. package/dist/seed-runner.js +26 -3
  512. package/dist/seed-runner.js.map +1 -1
  513. package/dist/seed.d.ts +31 -4
  514. package/dist/seed.d.ts.map +1 -1
  515. package/dist/seed.js +3 -1
  516. package/dist/seed.js.map +1 -1
  517. package/dist/self-host-compose.d.ts +66 -4
  518. package/dist/self-host-compose.d.ts.map +1 -1
  519. package/dist/self-host-compose.js +326 -102
  520. package/dist/self-host-compose.js.map +1 -1
  521. package/dist/shell-ports.d.ts +26 -0
  522. package/dist/shell-ports.d.ts.map +1 -0
  523. package/dist/shell-ports.js +56 -0
  524. package/dist/shell-ports.js.map +1 -0
  525. package/dist/storage-provision.d.ts +21 -4
  526. package/dist/storage-provision.d.ts.map +1 -1
  527. package/dist/storage-provision.js +12 -0
  528. package/dist/storage-provision.js.map +1 -1
  529. package/dist/studio-admin-roles.d.ts.map +1 -1
  530. package/dist/studio-admin-roles.js +2 -1
  531. package/dist/studio-admin-roles.js.map +1 -1
  532. package/dist/studio-auth-config.d.ts +22 -0
  533. package/dist/studio-auth-config.d.ts.map +1 -0
  534. package/dist/studio-auth-config.js +45 -0
  535. package/dist/studio-auth-config.js.map +1 -0
  536. package/dist/studio-roles.d.ts +13 -0
  537. package/dist/studio-roles.d.ts.map +1 -0
  538. package/dist/studio-roles.js +12 -0
  539. package/dist/studio-roles.js.map +1 -0
  540. package/dist/target-client.d.ts +13 -2
  541. package/dist/target-client.d.ts.map +1 -1
  542. package/dist/target-client.js +56 -40
  543. package/dist/target-client.js.map +1 -1
  544. package/dist/tsx-runner.d.ts +13 -0
  545. package/dist/tsx-runner.d.ts.map +1 -1
  546. package/dist/tsx-runner.js +36 -19
  547. package/dist/tsx-runner.js.map +1 -1
  548. package/dist/type-extractor.d.ts +2 -0
  549. package/dist/type-extractor.d.ts.map +1 -1
  550. package/dist/type-extractor.js +419 -115
  551. package/dist/type-extractor.js.map +1 -1
  552. package/dist/type-generation.d.ts +35 -5
  553. package/dist/type-generation.d.ts.map +1 -1
  554. package/dist/type-generation.js +57 -27
  555. package/dist/type-generation.js.map +1 -1
  556. package/dist/type-resolver.d.ts.map +1 -1
  557. package/dist/type-resolver.js +8 -1
  558. package/dist/type-resolver.js.map +1 -1
  559. package/dist/ui/clack-api.d.ts +3 -0
  560. package/dist/ui/clack-api.d.ts.map +1 -1
  561. package/dist/ui/clack-api.js +14 -7
  562. package/dist/ui/clack-api.js.map +1 -1
  563. package/dist/ui/clack.d.ts.map +1 -1
  564. package/dist/ui/clack.js +9 -7
  565. package/dist/ui/clack.js.map +1 -1
  566. package/dist/ui/components/PromptPanel.d.ts +1 -0
  567. package/dist/ui/components/PromptPanel.d.ts.map +1 -1
  568. package/dist/ui/components/PromptPanel.js +2 -1
  569. package/dist/ui/components/PromptPanel.js.map +1 -1
  570. package/dist/ui/confirm.d.ts +8 -0
  571. package/dist/ui/confirm.d.ts.map +1 -1
  572. package/dist/ui/confirm.js +12 -0
  573. package/dist/ui/confirm.js.map +1 -1
  574. package/dist/ui/dev/DevDashboard.d.ts.map +1 -1
  575. package/dist/ui/dev/DevDashboard.js +19 -4
  576. package/dist/ui/dev/DevDashboard.js.map +1 -1
  577. package/dist/ui/flows/FlowApp.d.ts.map +1 -1
  578. package/dist/ui/flows/FlowApp.js +17 -1
  579. package/dist/ui/flows/FlowApp.js.map +1 -1
  580. package/dist/ui/flows/prompt-fields.d.ts +13 -0
  581. package/dist/ui/flows/prompt-fields.d.ts.map +1 -1
  582. package/dist/ui/flows/prompt-fields.js +17 -4
  583. package/dist/ui/flows/prompt-fields.js.map +1 -1
  584. package/dist/ui/flows/types.d.ts +2 -1
  585. package/dist/ui/flows/types.d.ts.map +1 -1
  586. package/dist/ui/runtime/cancel.d.ts +5 -0
  587. package/dist/ui/runtime/cancel.d.ts.map +1 -1
  588. package/dist/ui/runtime/cancel.js +7 -0
  589. package/dist/ui/runtime/cancel.js.map +1 -1
  590. package/dist/ui/runtime/dev-prompt-queue.d.ts +5 -4
  591. package/dist/ui/runtime/dev-prompt-queue.d.ts.map +1 -1
  592. package/dist/ui/runtime/dev-prompt-queue.js +2 -5
  593. package/dist/ui/runtime/dev-prompt-queue.js.map +1 -1
  594. package/dist/ui/runtime/run-clack-flow.js.map +1 -1
  595. package/dist/unique-file-token.d.ts +10 -0
  596. package/dist/unique-file-token.d.ts.map +1 -0
  597. package/dist/unique-file-token.js +13 -0
  598. package/dist/unique-file-token.js.map +1 -0
  599. package/package.json +14 -4
  600. package/.turbo/turbo-build.log +0 -4
  601. package/.turbo/turbo-test.log +0 -582
  602. package/.turbo/turbo-typecheck.log +0 -4
  603. package/assets/supatype-logo-wordmark.ascii.txt +0 -6
  604. package/bin/dev-entry.ts +0 -3
  605. package/dist/supatype-eval-1781522769253.d.mts +0 -2
  606. package/dist/supatype-eval-1781522769253.d.mts.map +0 -1
  607. package/dist/supatype-eval-1781522769253.mjs +0 -3
  608. package/dist/supatype-eval-1781522769253.mjs.map +0 -1
  609. package/scripts/build-release-artifacts.sh +0 -112
  610. package/scripts/generate-homebrew-formula.mjs +0 -123
  611. package/scripts/mirror-deno-release.sh +0 -76
  612. package/src/TYPE-RESOLUTION.md +0 -294
  613. package/src/adopt-walkthrough.ts +0 -142
  614. package/src/api-config-cache.ts +0 -172
  615. package/src/app/framework.ts +0 -247
  616. package/src/app/proxy-dev-app.ts +0 -175
  617. package/src/app-config.ts +0 -208
  618. package/src/app-vite-env.ts +0 -27
  619. package/src/augmentation-generator.ts +0 -279
  620. package/src/binary-cache.ts +0 -998
  621. package/src/binary-download-lock.ts +0 -124
  622. package/src/cache-clean.ts +0 -81
  623. package/src/cache-identity-scope.ts +0 -92
  624. package/src/cache-pins.ts +0 -243
  625. package/src/cache-provider.ts +0 -61
  626. package/src/cli-artifacts.ts +0 -65
  627. package/src/cli-install-method.ts +0 -98
  628. package/src/cli-package-version.ts +0 -19
  629. package/src/cli-standalone.ts +0 -144
  630. package/src/cli-version-embedded.ts +0 -12
  631. package/src/cli.ts +0 -87
  632. package/src/client-generator.ts +0 -122
  633. package/src/cloud-credentials.ts +0 -183
  634. package/src/commands/add.ts +0 -105
  635. package/src/commands/admin.ts +0 -819
  636. package/src/commands/adopt.ts +0 -81
  637. package/src/commands/app.ts +0 -100
  638. package/src/commands/cache.ts +0 -233
  639. package/src/commands/cloud.ts +0 -299
  640. package/src/commands/db.ts +0 -301
  641. package/src/commands/deploy-types.ts +0 -49
  642. package/src/commands/deploy.ts +0 -464
  643. package/src/commands/dev.ts +0 -1217
  644. package/src/commands/diff.ts +0 -73
  645. package/src/commands/doctor.ts +0 -197
  646. package/src/commands/engine.ts +0 -31
  647. package/src/commands/functions.ts +0 -1010
  648. package/src/commands/generate.ts +0 -45
  649. package/src/commands/hooks.ts +0 -138
  650. package/src/commands/init.ts +0 -1537
  651. package/src/commands/internal.ts +0 -60
  652. package/src/commands/introspect.ts +0 -48
  653. package/src/commands/keys.ts +0 -269
  654. package/src/commands/link-helpers.ts +0 -281
  655. package/src/commands/login.ts +0 -127
  656. package/src/commands/logs.ts +0 -56
  657. package/src/commands/migrate-from-v1.ts +0 -132
  658. package/src/commands/migrate.ts +0 -231
  659. package/src/commands/pg.ts +0 -128
  660. package/src/commands/plugins.ts +0 -517
  661. package/src/commands/pull.ts +0 -46
  662. package/src/commands/push.ts +0 -427
  663. package/src/commands/seed.ts +0 -319
  664. package/src/commands/self-host.ts +0 -404
  665. package/src/commands/self-update.ts +0 -89
  666. package/src/commands/status.ts +0 -117
  667. package/src/commands/types.ts +0 -77
  668. package/src/commands/update.ts +0 -172
  669. package/src/components.ts +0 -6
  670. package/src/compose-local-server-image.ts +0 -85
  671. package/src/compose-rename.ts +0 -73
  672. package/src/compose-services.ts +0 -175
  673. package/src/config.ts +0 -276
  674. package/src/db-port.ts +0 -99
  675. package/src/db-preflight.ts +0 -663
  676. package/src/dev-compose.ts +0 -1650
  677. package/src/dev-db-reset.ts +0 -95
  678. package/src/dev-initial-push.ts +0 -134
  679. package/src/dev-log-bus.ts +0 -121
  680. package/src/dev-log-filter.ts +0 -74
  681. package/src/dev-logo.ts +0 -61
  682. package/src/dev-ports.ts +0 -271
  683. package/src/dev-ready-panel.ts +0 -80
  684. package/src/dev-session-lock.ts +0 -98
  685. package/src/dev-session.ts +0 -210
  686. package/src/dev-shutdown.ts +0 -159
  687. package/src/dev-task-colors.ts +0 -66
  688. package/src/diff-output.ts +0 -90
  689. package/src/docker-postgres.ts +0 -295
  690. package/src/docker-runtime.ts +0 -151
  691. package/src/engine-client.ts +0 -350
  692. package/src/engine-floor.ts +0 -261
  693. package/src/engine-push-output.ts +0 -98
  694. package/src/ensure-binary.ts +0 -68
  695. package/src/ensure-component-binaries.ts +0 -71
  696. package/src/ensure-dev-api-config.ts +0 -18
  697. package/src/env-file.ts +0 -183
  698. package/src/field-bounds.ts +0 -359
  699. package/src/field-masking-tier.ts +0 -107
  700. package/src/functions-context-refresh.ts +0 -25
  701. package/src/functions-deno-types.ts +0 -258
  702. package/src/functions-router-gen.ts +0 -256
  703. package/src/gitignore.ts +0 -76
  704. package/src/hook-upload.ts +0 -107
  705. package/src/hooks-generator.ts +0 -444
  706. package/src/host-database.ts +0 -176
  707. package/src/index.ts +0 -11
  708. package/src/init-dependency-versions.ts +0 -69
  709. package/src/init-package-json.ts +0 -63
  710. package/src/init-project-detect.ts +0 -99
  711. package/src/jwt.ts +0 -14
  712. package/src/kong-config.ts +0 -116
  713. package/src/link.ts +0 -250
  714. package/src/local-gateway.ts +0 -9
  715. package/src/local-secrets.ts +0 -104
  716. package/src/local-storage.ts +0 -14
  717. package/src/main.ts +0 -20
  718. package/src/model-cache.ts +0 -122
  719. package/src/model-hooks.ts +0 -430
  720. package/src/model-versioning.ts +0 -167
  721. package/src/pgbouncer-userlist.ts +0 -15
  722. package/src/postgres-ctl.ts +0 -333
  723. package/src/preview-config-check.ts +0 -52
  724. package/src/process-manager.ts +0 -224
  725. package/src/project-config.ts +0 -939
  726. package/src/prompts.ts +0 -2
  727. package/src/pull-utils.ts +0 -275
  728. package/src/realtime-launch.ts +0 -52
  729. package/src/release-pins.ts +0 -31
  730. package/src/release-public-key.ts +0 -12
  731. package/src/required-host-components.ts +0 -37
  732. package/src/resolve-api-url.ts +0 -44
  733. package/src/resolve-target.ts +0 -480
  734. package/src/rest-cache-admin.ts +0 -141
  735. package/src/restore-system-relation-targets.ts +0 -45
  736. package/src/retired-no-cache.ts +0 -27
  737. package/src/route-manifest.ts +0 -17
  738. package/src/runtime-routes.ts +0 -298
  739. package/src/schema-ast-v2.ts +0 -488
  740. package/src/schema-push-lock.ts +0 -170
  741. package/src/schema-sources.ts +0 -248
  742. package/src/scripts/postinstall.ts +0 -20
  743. package/src/seed-ir.ts +0 -311
  744. package/src/seed-runner.ts +0 -109
  745. package/src/seed.ts +0 -451
  746. package/src/self-host-compose.ts +0 -1246
  747. package/src/service-role-check.ts +0 -111
  748. package/src/storage-provision.ts +0 -90
  749. package/src/strict.ts +0 -40
  750. package/src/studio-admin-roles.ts +0 -30
  751. package/src/studio-dev-server.ts +0 -70
  752. package/src/supatype-eval-1781522769253.mts +0 -1
  753. package/src/systemd.ts +0 -137
  754. package/src/target-client.ts +0 -127
  755. package/src/tsx-runner.ts +0 -128
  756. package/src/type-extractor.ts +0 -3378
  757. package/src/type-generation.ts +0 -169
  758. package/src/type-resolver.ts +0 -457
  759. package/src/ui/README.md +0 -21
  760. package/src/ui/brand.ts +0 -6
  761. package/src/ui/clack-api.ts +0 -123
  762. package/src/ui/clack.ts +0 -153
  763. package/src/ui/components/FlowSpinner.tsx +0 -15
  764. package/src/ui/components/LogoWordmark.tsx +0 -36
  765. package/src/ui/components/PromptPanel.tsx +0 -17
  766. package/src/ui/components/SelectField.tsx +0 -58
  767. package/src/ui/confirm.ts +0 -39
  768. package/src/ui/dev/DevDashboard.tsx +0 -223
  769. package/src/ui/dev/DevReadyPanelView.tsx +0 -134
  770. package/src/ui/fatal.ts +0 -38
  771. package/src/ui/flows/FlowApp.tsx +0 -69
  772. package/src/ui/flows/prompt-fields.tsx +0 -198
  773. package/src/ui/flows/types.ts +0 -50
  774. package/src/ui/index.ts +0 -8
  775. package/src/ui/interactive.ts +0 -4
  776. package/src/ui/messages.ts +0 -85
  777. package/src/ui/next-steps.ts +0 -10
  778. package/src/ui/progress.ts +0 -39
  779. package/src/ui/prompts.ts +0 -48
  780. package/src/ui/runtime/cancel.ts +0 -6
  781. package/src/ui/runtime/command-chrome.ts +0 -147
  782. package/src/ui/runtime/dev-prompt-queue.ts +0 -84
  783. package/src/ui/runtime/flow-session.ts +0 -11
  784. package/src/ui/runtime/run-clack-flow.tsx +0 -65
  785. package/src/ui/runtime/stdin-after-ink.ts +0 -20
  786. package/src/ui/theme.ts +0 -41
  787. package/src/valkey-sidecar.ts +0 -126
  788. package/tests/access-composition.test.ts +0 -790
  789. package/tests/admin-ensure.test.ts +0 -139
  790. package/tests/admin-studio-membership.test.ts +0 -121
  791. package/tests/adopt-result.test.ts +0 -27
  792. package/tests/adopt-walkthrough.test.ts +0 -129
  793. package/tests/api-config-cache-seed.test.ts +0 -180
  794. package/tests/api-schemas.test.ts +0 -83
  795. package/tests/app-command.test.ts +0 -64
  796. package/tests/archive-name-alias.test.ts +0 -42
  797. package/tests/ast-derived-outputs.test.ts +0 -92
  798. package/tests/augmentation-generator.test.ts +0 -393
  799. package/tests/binary-cache-cloud-overrides.test.ts +0 -123
  800. package/tests/binary-download-lock.test.ts +0 -41
  801. package/tests/cache-clean.test.ts +0 -206
  802. package/tests/cache-identity-scope.test.ts +0 -61
  803. package/tests/cache-provider-config.test.ts +0 -132
  804. package/tests/cached-artifact-format.test.ts +0 -84
  805. package/tests/cli-help.test.ts +0 -170
  806. package/tests/cli-install-method.test.ts +0 -66
  807. package/tests/cli-package-version.test.ts +0 -15
  808. package/tests/client-generator.test.ts +0 -103
  809. package/tests/command-chrome-coverage.test.ts +0 -154
  810. package/tests/command-chrome-wrap.test.ts +0 -52
  811. package/tests/compose-parsable-defaults.test.ts +0 -60
  812. package/tests/compose-services.test.ts +0 -144
  813. package/tests/config-load-failure.test.ts +0 -44
  814. package/tests/config.test.ts +0 -301
  815. package/tests/db-port.test.ts +0 -128
  816. package/tests/db-preflight.test.ts +0 -152
  817. package/tests/db-published-and-addressable.test.ts +0 -69
  818. package/tests/dev-db-reset.test.ts +0 -162
  819. package/tests/dev-initial-push.test.ts +0 -142
  820. package/tests/dev-ports-owner.test.ts +0 -40
  821. package/tests/dev-ports.test.ts +0 -41
  822. package/tests/dev-ready-panel.test.ts +0 -37
  823. package/tests/dev-session-lock.test.ts +0 -54
  824. package/tests/dev-ui.test.ts +0 -202
  825. package/tests/docker-postgres.test.ts +0 -39
  826. package/tests/docker-runtime.test.ts +0 -225
  827. package/tests/doctor-render.test.ts +0 -62
  828. package/tests/doctor-service-role.test.ts +0 -55
  829. package/tests/engine-floor.test.ts +0 -238
  830. package/tests/engine-push-output.test.ts +0 -96
  831. package/tests/ensure-binary.test.ts +0 -59
  832. package/tests/ensure-dev-api-config.test.ts +0 -22
  833. package/tests/env-file.test.ts +0 -121
  834. package/tests/external-database-compose.test.ts +0 -262
  835. package/tests/external-database-config.test.ts +0 -154
  836. package/tests/field-bounds-matrix.test.ts +0 -163
  837. package/tests/field-bounds.test.ts +0 -139
  838. package/tests/field-masking-tier.test.ts +0 -184
  839. package/tests/field-validators.test.ts +0 -139
  840. package/tests/fixtures/identity-scope-corpus.json +0 -42
  841. package/tests/fixtures/seed_golden_ir.json +0 -186
  842. package/tests/functions-concurrency.test.ts +0 -71
  843. package/tests/functions-context-refresh.test.ts +0 -86
  844. package/tests/functions-deno-types.test.ts +0 -197
  845. package/tests/gitignore-secrets.test.ts +0 -90
  846. package/tests/homebrew-formula.test.ts +0 -100
  847. package/tests/hook-upload.test.ts +0 -125
  848. package/tests/hooks-generator.test.ts +0 -298
  849. package/tests/host-connection-targets.test.ts +0 -84
  850. package/tests/host-database.test.ts +0 -176
  851. package/tests/init-dependency-versions.test.ts +0 -62
  852. package/tests/init-package-json.test.ts +0 -18
  853. package/tests/init-project-detect.test.ts +0 -53
  854. package/tests/init.test.ts +0 -369
  855. package/tests/keys-write.test.ts +0 -148
  856. package/tests/keys.test.ts +0 -166
  857. package/tests/link.test.ts +0 -148
  858. package/tests/local-secrets.test.ts +0 -92
  859. package/tests/local-server-image-env.test.ts +0 -93
  860. package/tests/migrate-from-v1.test.ts +0 -29
  861. package/tests/minisign.test.ts +0 -102
  862. package/tests/model-cache-declaration.test.ts +0 -229
  863. package/tests/model-cache-manifest.test.ts +0 -99
  864. package/tests/model-constraints.test.ts +0 -293
  865. package/tests/model-hooks.test.ts +0 -433
  866. package/tests/model-versions.test.ts +0 -229
  867. package/tests/native-keyspace.test.ts +0 -130
  868. package/tests/normalize-admin-config.test.ts +0 -48
  869. package/tests/pg-spawn-env.test.ts +0 -18
  870. package/tests/port-in-use.test.ts +0 -58
  871. package/tests/postgres-archive-tag.test.ts +0 -9
  872. package/tests/preview-config-check.test.ts +0 -104
  873. package/tests/proxy-dev-app.test.ts +0 -77
  874. package/tests/pull-utils.test.ts +0 -151
  875. package/tests/readiness-poll.test.ts +0 -84
  876. package/tests/realtime-launch.test.ts +0 -25
  877. package/tests/release-pins.test.ts +0 -28
  878. package/tests/required-host-components.test.ts +0 -53
  879. package/tests/resolve-api-url.test.ts +0 -23
  880. package/tests/rest-cache-admin.test.ts +0 -64
  881. package/tests/retired-no-cache.test.ts +0 -46
  882. package/tests/route-manifest.test.ts +0 -29
  883. package/tests/runtime-contract.test.ts +0 -948
  884. package/tests/schema-sources.test.ts +0 -119
  885. package/tests/seed-discover.test.ts +0 -31
  886. package/tests/seed-ir.test.ts +0 -436
  887. package/tests/self-host-keys.test.ts +0 -92
  888. package/tests/service-role-check.test.ts +0 -109
  889. package/tests/service-role-routes.test.ts +0 -51
  890. package/tests/stdin-after-ink.test.ts +0 -8
  891. package/tests/storage-provision.test.ts +0 -100
  892. package/tests/strict.test.ts +0 -78
  893. package/tests/studio-admin-roles.test.ts +0 -59
  894. package/tests/target-client-refresh.test.ts +0 -94
  895. package/tests/tsconfig.json +0 -15
  896. package/tests/tsx-runner.test.ts +0 -66
  897. package/tests/type-extractor.test.ts +0 -1565
  898. package/tests/type-resolver.test.ts +0 -59
  899. package/tests/ui-confirm.test.ts +0 -45
  900. package/tests/ui-messages.test.ts +0 -52
  901. package/tsconfig.json +0 -11
  902. package/tsconfig.tsbuildinfo +0 -1
  903. package/vitest.config.ts +0 -21
@@ -1,3378 +0,0 @@
1
- import { existsSync, readFileSync, realpathSync } from "node:fs"
2
- import { createHash } from "node:crypto"
3
- import { dirname, isAbsolute, relative, resolve } from "node:path"
4
- import ts from "typescript"
5
- import { isIdentityDependent, type AccessRuleNode } from "./cache-identity-scope.js"
6
- import {
7
- applyImportRename,
8
- createResolveContext,
9
- needsChecker,
10
- resolveTypeNode,
11
- tryResolveTypeReference,
12
- unknownTypeError,
13
- type ResolveContext,
14
- } from "./type-resolver.js"
15
-
16
- import {
17
- emitField,
18
- emitModel,
19
- emitSchema,
20
- defaultPgTypeForKind,
21
- scalar,
22
- type BlockDefinitionAst,
23
- type ExtractedSchemaAstV2,
24
- type ExtractedStorageBucketAst,
25
- type FieldAstV2,
26
- type KernelFieldFacts,
27
- type FieldKind,
28
- type ParsedField,
29
- } from "./schema-ast-v2.js"
30
- import { compileBounds, measureFormFor, type DeclaredBounds } from "./field-bounds.js"
31
-
32
- export type { ExtractedSchemaAstV2 as ExtractedSchemaAst, ExtractedStorageBucketAst } from "./schema-ast-v2.js"
33
-
34
- interface FieldParseContext {
35
- autoLocalize?: boolean
36
- }
37
-
38
- export function extractSchemaAstFromTypes(
39
- schemaPath: string,
40
- cwd: string = process.cwd(),
41
- ): ExtractedSchemaAstV2 | null {
42
- const absPath = resolve(cwd, schemaPath)
43
- if (!existsSync(absPath)) {
44
- throw new Error(`Schema file not found: ${absPath}`)
45
- }
46
-
47
- const sourceFiles = loadSchemaSourceFiles(absPath)
48
- const resolveCtx = createResolveContext(sourceFiles)
49
- const bucketAliases = new Map<string, string>()
50
- const bucketsById = new Map<string, ExtractedStorageBucketAst>()
51
- for (const sourceFile of sourceFiles) {
52
- const bucketContext = collectBucketContext(sourceFile, resolveCtx)
53
- for (const [alias, bucketId] of bucketContext.aliases) {
54
- bucketAliases.set(alias, bucketId)
55
- }
56
- for (const [bucketId, bucket] of bucketContext.bucketsById) {
57
- const existing = bucketsById.get(bucketId)
58
- if (existing !== undefined && !bucketsEqual(existing, bucket)) {
59
- throw new Error(
60
- `Conflicting Bucket<> declarations for id "${bucketId}". Use a single export per bucket id.`,
61
- )
62
- }
63
- bucketsById.set(bucketId, bucket)
64
- }
65
- }
66
-
67
- const blockAliases = new Map<string, BlockDefinitionAst>()
68
- for (const sourceFile of sourceFiles) {
69
- const next = collectBlockAliases(sourceFile, bucketAliases, bucketsById, resolveCtx)
70
- for (const [name, block] of next) {
71
- blockAliases.set(name, block)
72
- }
73
- }
74
-
75
- const models: ExtractedSchemaAstV2["models"] = []
76
-
77
- for (const sourceFile of sourceFiles) {
78
- for (const stmt of sourceFile.statements) {
79
- if (!ts.isTypeAliasDeclaration(stmt)) continue
80
- if (!hasExportModifier(stmt)) continue
81
- if (!ts.isTypeReferenceNode(stmt.type)) continue
82
- const modelTypeName = stmt.type.typeName.getText(sourceFile)
83
- if (modelTypeName !== "Model" && modelTypeName !== "LocalizedModel") continue
84
- const [fieldsArg, metaArg] = stmt.type.typeArguments ?? []
85
- if (!fieldsArg) continue
86
- const fieldsLiteral = unwrapModelFields(fieldsArg, sourceFile, resolveCtx)
87
- if (!fieldsLiteral) continue
88
-
89
- const metaHints = parseMetaLiteral(metaArg, sourceFile)
90
- const fieldContext: FieldParseContext = {
91
- autoLocalize: modelTypeName === "LocalizedModel" || metaHints.autoLocalize === true,
92
- }
93
-
94
- const fields: Record<string, FieldAstV2> = {}
95
- for (const member of fieldsLiteral.members) {
96
- if (!ts.isPropertySignature(member) || !member.type) continue
97
- const name = getPropertyName(member.name)
98
- if (!name) continue
99
- fields[name] = parseFieldType(
100
- name,
101
- member.type,
102
- sourceFile,
103
- blockAliases,
104
- bucketAliases,
105
- bucketsById,
106
- fieldContext,
107
- resolveCtx,
108
- )
109
- }
110
-
111
- const {
112
- tableName,
113
- access,
114
- options,
115
- indexes,
116
- constraints,
117
- hooks,
118
- validators,
119
- searchFields,
120
- cache,
121
- } =
122
- parseModelMeta(
123
- metaArg,
124
- sourceFile,
125
- stmt.name.text,
126
- fieldsArg,
127
- fields,
128
- resolveCtx,
129
- )
130
-
131
- models.push(
132
- emitModel(
133
- stmt.name.text,
134
- fields,
135
- options,
136
- tableName,
137
- access,
138
- indexes,
139
- hooks,
140
- constraints,
141
- validators,
142
- searchFields,
143
- cache,
144
- ),
145
- )
146
- }
147
- }
148
-
149
- if (models.length === 0) return null
150
-
151
- const storageBuckets =
152
- bucketsById.size > 0 ? [...bucketsById.values()].sort((a, b) => a.id.localeCompare(b.id)) : undefined
153
-
154
- let localeConfig: { locales: string[]; defaultLocale: string } | undefined
155
- for (const sourceFile of sourceFiles) {
156
- const found = collectLocaleConfig(sourceFile)
157
- if (!found) continue
158
- if (localeConfig !== undefined) {
159
- throw new Error(
160
- "Conflicting LocaleConfig declarations. Export at most one `localeConfig` type alias.",
161
- )
162
- }
163
- localeConfig = found
164
- }
165
-
166
- return emitSchema(models, {
167
- ...(storageBuckets !== undefined && storageBuckets.length > 0 && { storageBuckets }),
168
- ...(localeConfig !== undefined && {
169
- locales: localeConfig.locales,
170
- defaultLocale: localeConfig.defaultLocale,
171
- }),
172
- })
173
- }
174
-
175
- export interface SchemaSourceFile {
176
- relativePath: string
177
- absolutePath: string
178
- sha256: string
179
- bytes: number
180
- }
181
-
182
- export interface SchemaSourceGraph {
183
- entryPoint: string
184
- files: SchemaSourceFile[]
185
- }
186
-
187
- export function collectSchemaSourcePaths(entryAbsPath: string, projectRoot: string): SchemaSourceGraph {
188
- const root = resolve(projectRoot)
189
- const entryReal = realpathSync(entryAbsPath)
190
- const entryPoint = relative(root, entryReal).replace(/\\/g, "/")
191
- if (entryPoint.startsWith("..")) {
192
- throw new Error(`Schema entry must be under project root: ${entryAbsPath}`)
193
- }
194
-
195
- const absolutePaths = walkSchemaSourceAbsPaths(entryReal)
196
- const files: SchemaSourceFile[] = []
197
-
198
- for (const abs of absolutePaths) {
199
- const real = realpathSync(abs)
200
- const rel = relative(root, real).replace(/\\/g, "/")
201
- if (rel.startsWith("..")) {
202
- throw new Error(`Schema source escapes project root: ${abs}`)
203
- }
204
- const content = readFileSync(real)
205
- files.push({
206
- relativePath: rel,
207
- absolutePath: real,
208
- sha256: createHash("sha256").update(content).digest("hex"),
209
- bytes: content.length,
210
- })
211
- }
212
-
213
- files.sort((a, b) => a.relativePath.localeCompare(b.relativePath))
214
- return { entryPoint, files }
215
- }
216
-
217
- function walkSchemaSourceAbsPaths(entryPath: string): string[] {
218
- const visited = new Set<string>()
219
- const paths: string[] = []
220
- const queue: string[] = [entryPath]
221
-
222
- while (queue.length > 0) {
223
- const currentPath = queue.shift()
224
- if (!currentPath) continue
225
- if (visited.has(currentPath)) continue
226
- visited.add(currentPath)
227
- if (!existsSync(currentPath)) continue
228
- paths.push(currentPath)
229
-
230
- const sourceText = readFileSync(currentPath, "utf8")
231
- const sourceFile = ts.createSourceFile(currentPath, sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
232
- const baseDir = dirname(currentPath)
233
- for (const stmt of sourceFile.statements) {
234
- let specifier: string | undefined
235
- if (ts.isExportDeclaration(stmt)) {
236
- if (!stmt.moduleSpecifier || !ts.isStringLiteral(stmt.moduleSpecifier)) continue
237
- specifier = stmt.moduleSpecifier.text
238
- } else if (ts.isImportDeclaration(stmt)) {
239
- if (!stmt.moduleSpecifier || !ts.isStringLiteral(stmt.moduleSpecifier)) continue
240
- specifier = stmt.moduleSpecifier.text
241
- } else {
242
- continue
243
- }
244
- if (!specifier.startsWith(".")) continue
245
- const nextPath = resolveTypeModulePath(baseDir, specifier)
246
- if (!nextPath) continue
247
- if (!visited.has(nextPath)) queue.push(nextPath)
248
- }
249
- }
250
-
251
- return paths
252
- }
253
-
254
- function loadSchemaSourceFiles(entryPath: string): ts.SourceFile[] {
255
- return walkSchemaSourceAbsPaths(entryPath).map((abs) => {
256
- const sourceText = readFileSync(abs, "utf8")
257
- return ts.createSourceFile(abs, sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
258
- })
259
- }
260
-
261
- function resolveTypeModulePath(fromDir: string, specifier: string): string | null {
262
- const basePath = isAbsolute(specifier) ? specifier : resolve(fromDir, specifier)
263
- const candidates = specifier.endsWith(".js")
264
- ? [
265
- basePath,
266
- basePath.replace(/\.js$/i, ".ts"),
267
- basePath.replace(/\.js$/i, ".tsx"),
268
- basePath.replace(/\.js$/i, ".d.ts"),
269
- ]
270
- : [
271
- basePath,
272
- `${basePath}.ts`,
273
- `${basePath}.tsx`,
274
- `${basePath}.d.ts`,
275
- resolve(basePath, "index.ts"),
276
- resolve(basePath, "index.tsx"),
277
- resolve(basePath, "index.d.ts"),
278
- ]
279
-
280
- for (const candidate of candidates) {
281
- if (existsSync(candidate)) return candidate
282
- }
283
- return null
284
- }
285
-
286
- function hasExportModifier(node: ts.Node): boolean {
287
- if (!ts.canHaveModifiers(node)) return false
288
- return (ts.getModifiers(node)?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) ?? false)
289
- }
290
-
291
- function getPropertyName(name: ts.PropertyName): string | null {
292
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text
293
- return null
294
- }
295
-
296
- /**
297
- * Known @supatype/types intersection mixins and the field source text they contribute.
298
- * Used when a mixin type can't be resolved from the local alias registry
299
- * (it comes from the external @supatype/types package, not a local file).
300
- */
301
- const KNOWN_MIXIN_SOURCES: Record<string, string> = {
302
- Timestamps: "{ created_at: ServerDefault<Date>; updated_at: ServerDefault<Date> }",
303
- SoftDelete: "{ deleted_at: Optional<Date> }",
304
- Publishable: "{ published_at: Optional<Date> }",
305
- }
306
-
307
- function synthesizeTypeLiteralMembers(source: string): ts.TypeElement[] {
308
- const synth = ts.createSourceFile(
309
- "__synth__.ts",
310
- `type __T__ = ${source}`,
311
- ts.ScriptTarget.Latest,
312
- true,
313
- ts.ScriptKind.TS,
314
- )
315
- const decl = synth.statements[0]
316
- if (!decl || !ts.isTypeAliasDeclaration(decl) || !ts.isTypeLiteralNode(decl.type)) return []
317
- return [...decl.type.members]
318
- }
319
-
320
- function mergeIntersectionParts(
321
- parts: readonly ts.TypeNode[],
322
- sourceFile: ts.SourceFile,
323
- resolveCtx: ResolveContext,
324
- depth: number,
325
- ): ts.TypeLiteralNode | null {
326
- const allMembers: ts.TypeElement[] = []
327
- for (const part of parts) {
328
- const resolved = unwrapModelFields(part, sourceFile, resolveCtx, depth + 1)
329
- if (resolved) {
330
- allMembers.push(...resolved.members)
331
- continue
332
- }
333
- // Fall back to known @supatype/types intersection mixins (Timestamps, SoftDelete, Publishable)
334
- if (ts.isTypeReferenceNode(part) && ts.isIdentifier(part.typeName)) {
335
- const typeName = applyImportRename(part.typeName.text, sourceFile, resolveCtx.renameMap)
336
- const mixinSource = KNOWN_MIXIN_SOURCES[typeName]
337
- if (mixinSource) {
338
- allMembers.push(...synthesizeTypeLiteralMembers(mixinSource))
339
- continue
340
- }
341
- }
342
- // Unresolvable parts are skipped, the model still extracts with whatever fields were found
343
- }
344
- if (allMembers.length === 0) return null
345
- return ts.factory.createTypeLiteralNode(allMembers)
346
- }
347
-
348
- function unwrapModelFields(
349
- typeNode: ts.TypeNode,
350
- sourceFile: ts.SourceFile,
351
- resolveCtx: ResolveContext,
352
- depth = 0,
353
- ): ts.TypeLiteralNode | null {
354
- if (depth > 16) return null
355
- if (ts.isTypeLiteralNode(typeNode)) return typeNode
356
-
357
- // Handle intersection types: `{ …fields } & Timestamps`, `{ …fields } & SoftDelete`, etc.
358
- if (ts.isIntersectionTypeNode(typeNode)) {
359
- return mergeIntersectionParts(typeNode.types, sourceFile, resolveCtx, depth)
360
- }
361
-
362
- if (needsChecker(typeNode)) {
363
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
364
- if (ts.isTypeLiteralNode(resolved)) return resolved
365
- return unwrapModelFields(resolved, sourceFile, resolveCtx, depth + 1)
366
- }
367
-
368
- if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null
369
-
370
- const typeName = applyImportRename(typeNode.typeName.text, sourceFile, resolveCtx.renameMap)
371
-
372
- // Composite helpers in @supatype/types wrap the concrete field object.
373
- if (
374
- typeName === "WithTimestamps" ||
375
- typeName === "WithSoftDelete" ||
376
- typeName === "WithPublishable"
377
- ) {
378
- const inner = typeNode.typeArguments?.[0]
379
- if (!inner) return null
380
- return unwrapModelFields(inner, sourceFile, resolveCtx, depth + 1)
381
- }
382
-
383
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
384
- if (expanded) {
385
- if (ts.isTypeLiteralNode(expanded)) return expanded
386
- return unwrapModelFields(expanded, sourceFile, resolveCtx, depth + 1)
387
- }
388
-
389
- return null
390
- }
391
-
392
- /** Parse `Default<T, V>` second type argument into a JSON-serializable literal. */
393
- function parseDefaultLiteral(
394
- node: ts.TypeNode,
395
- sourceFile: ts.SourceFile,
396
- ): string | number | boolean | null | undefined {
397
- if (ts.isLiteralTypeNode(node)) {
398
- const lit = node.literal
399
- if (ts.isStringLiteral(lit) || ts.isNoSubstitutionTemplateLiteral(lit)) return lit.text
400
- if (ts.isNumericLiteral(lit)) return Number(lit.text)
401
- if (lit.kind === ts.SyntaxKind.TrueKeyword) return true
402
- if (lit.kind === ts.SyntaxKind.FalseKeyword) return false
403
- if (lit.kind === ts.SyntaxKind.NullKeyword) return null
404
- }
405
- if (node.kind === ts.SyntaxKind.TrueKeyword) return true
406
- if (node.kind === ts.SyntaxKind.FalseKeyword) return false
407
- if (node.kind === ts.SyntaxKind.NullKeyword) return null
408
- // Negative numeric literals appear as PrefixUnaryExpression in some TS versions.
409
- if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
410
- const inner = parseDefaultLiteral(node.operand as unknown as ts.TypeNode, sourceFile)
411
- if (typeof inner === "number") return -inner
412
- }
413
- return undefined
414
- }
415
-
416
- /** Which {@link DeclaredBounds} key each length/item modifier fills. */
417
- const BOUND_KEY_BY_MODIFIER = {
418
- MaxLength: "maxLength",
419
- MinLength: "minLength",
420
- MaxItems: "maxItems",
421
- MinItems: "minItems",
422
- } as const satisfies Record<string, keyof DeclaredBounds>
423
-
424
- /**
425
- * A `Between` bound: a number for a numeric column, an ISO-8601 string for a temporal one.
426
- *
427
- * Which of the two is legal is decided from the field's kind in `compileBounds`, not here, because
428
- * the kind is not known until the wrappers are off.
429
- */
430
- function parseRangeBound(
431
- node: ts.TypeNode | undefined,
432
- sourceFile: ts.SourceFile,
433
- ): number | string | undefined {
434
- const asNumber = parseNumericTypeArg(node, sourceFile)
435
- if (asNumber !== undefined) return asNumber
436
- return literalStringType(node) ?? undefined
437
- }
438
-
439
- /**
440
- * Whether a `JSON<T>` field holds an array, which is what decides between item bounds and none.
441
- *
442
- * Answered from the declared type argument rather than guessed downstream: the engine sees only
443
- * `JSONB` and cannot tell `JSON<Item[]>` from `JSON<{ a: string }>`, so `jsonb_array_length` would
444
- * be a coin flip that raises at insert time when it loses.
445
- */
446
- function jsonTypeArgIsArray(node: ts.TypeNode, sourceFile: ts.SourceFile): boolean {
447
- if (!ts.isTypeReferenceNode(node)) return false
448
- const arg = node.typeArguments?.[0]
449
- if (!arg) return false
450
- return isArrayLikeTypeNode(arg, sourceFile)
451
- }
452
-
453
- function isArrayLikeTypeNode(node: ts.TypeNode, sourceFile: ts.SourceFile): boolean {
454
- if (ts.isArrayTypeNode(node)) return true
455
- // `readonly Item[]`
456
- if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
457
- return isArrayLikeTypeNode(node.type, sourceFile)
458
- }
459
- if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
460
- return node.typeName.text === "Array" || node.typeName.text === "ReadonlyArray"
461
- }
462
- return false
463
- }
464
-
465
- function parseFieldType(
466
- fieldName: string,
467
- typeNode: ts.TypeNode,
468
- sourceFile: ts.SourceFile,
469
- blockAliases: Map<string, BlockDefinitionAst>,
470
- bucketAliases: Map<string, string>,
471
- bucketsById: Map<string, ExtractedStorageBucketAst>,
472
- context: FieldParseContext = {},
473
- resolveCtx: ResolveContext,
474
- ): FieldAstV2 {
475
- const flags = {
476
- required: true,
477
- unique: false,
478
- index: false,
479
- primaryKey: false,
480
- serverGenerated: false,
481
- autoIncrement: false,
482
- relationCardinality: undefined as "one" | "many" | undefined,
483
- relationTarget: undefined as string | undefined,
484
- editorReadOnly: false,
485
- computedFromSources: undefined as string[] | undefined,
486
- computedFromTemplate: undefined as string | undefined,
487
- fieldDefault: undefined as string | number | boolean | null | undefined,
488
- localized: false,
489
- notLocalized: false,
490
- searchable: false,
491
- bounds: {} as DeclaredBounds,
492
- }
493
-
494
- const resolving = new Set<string>()
495
- let current = typeNode
496
- while (ts.isTypeReferenceNode(current) && ts.isIdentifier(current.typeName)) {
497
- const typeName = applyImportRename(current.typeName.text, sourceFile, resolveCtx.renameMap)
498
- switch (typeName) {
499
- case "Optional":
500
- flags.required = false
501
- current = current.typeArguments?.[0] ?? current
502
- continue
503
- case "Unique":
504
- flags.unique = true
505
- current = current.typeArguments?.[0] ?? current
506
- continue
507
- case "Indexed":
508
- flags.index = true
509
- current = current.typeArguments?.[0] ?? current
510
- continue
511
- case "ServerDefault":
512
- flags.serverGenerated = true
513
- current = current.typeArguments?.[0] ?? current
514
- continue
515
- case "AutoIncrement":
516
- flags.serverGenerated = true
517
- flags.autoIncrement = true
518
- current = current.typeArguments?.[0] ?? current
519
- continue
520
- case "PrimaryKey":
521
- flags.primaryKey = true
522
- flags.required = true
523
- flags.unique = true
524
- current = current.typeArguments?.[0] ?? current
525
- continue
526
- case "Default": {
527
- const valueArg = current.typeArguments?.[1]
528
- if (valueArg !== undefined) {
529
- const literal = parseDefaultLiteral(valueArg, sourceFile)
530
- if (literal !== undefined) {
531
- flags.fieldDefault = literal
532
- }
533
- }
534
- // Unwrap to T so `Default<boolean, true>` resolves as boolean, not text.
535
- current = current.typeArguments?.[0] ?? current
536
- continue
537
- }
538
- case "Searchable":
539
- // Used to unwrap and drop the declaration on the floor, so a schema saying a column was
540
- // searchable compiled, pushed, and produced a Studio list view with no search box: the
541
- // engine was never told, so the admin config carried no `searchFields` for Studio to read.
542
- flags.searchable = true
543
- current = current.typeArguments?.[0] ?? current
544
- continue
545
- case "EditorReadOnly":
546
- flags.editorReadOnly = true
547
- current = current.typeArguments?.[0] ?? current
548
- continue
549
- case "Computed":
550
- flags.editorReadOnly = true
551
- flags.serverGenerated = true
552
- current = current.typeArguments?.[0] ?? current
553
- continue
554
- case "ComputedFrom": {
555
- const valueArg = current.typeArguments?.[0]
556
- const sourcesArg = current.typeArguments?.[1]
557
- const parsed = parseComputedFromSecondArg(sourcesArg, sourceFile)
558
- if (parsed) {
559
- flags.computedFromSources = parsed.sources
560
- flags.computedFromTemplate = parsed.template
561
- } else {
562
- flags.computedFromSources = ["title"]
563
- }
564
- current = valueArg ?? current
565
- continue
566
- }
567
- case "MaxLength":
568
- case "MinLength":
569
- case "MaxItems":
570
- case "MinItems": {
571
- const amount = parseNumericTypeArg(current.typeArguments?.[1], sourceFile)
572
- if (amount !== undefined) {
573
- flags.bounds[BOUND_KEY_BY_MODIFIER[typeName]] = amount
574
- }
575
- current = current.typeArguments?.[0] ?? current
576
- continue
577
- }
578
- case "Between": {
579
- const min = parseRangeBound(current.typeArguments?.[1], sourceFile)
580
- const max = parseRangeBound(current.typeArguments?.[2], sourceFile)
581
- if (min !== undefined) flags.bounds.min = min
582
- if (max !== undefined) flags.bounds.max = max
583
- current = current.typeArguments?.[0] ?? current
584
- continue
585
- }
586
- case "Localized":
587
- flags.localized = true
588
- current = current.typeArguments?.[0] ?? current
589
- continue
590
- case "NotLocalized":
591
- flags.notLocalized = true
592
- current = current.typeArguments?.[0] ?? current
593
- continue
594
- case "RelatedTo": {
595
- flags.relationCardinality = "one"
596
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
597
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
598
- // `target` must match `ModelAst.name` to satisfy validator resolution.
599
- // FK column follows the field name (two relations to the same model need distinct columns).
600
- return emitField({
601
- kind: "relation",
602
- kernel: {
603
- cardinality: "belongsTo",
604
- target: flags.relationTarget!,
605
- ...relationOptionsKernel(relOpts),
606
- },
607
- db: { foreignKey: relationForeignKeyFromField(fieldName) },
608
- platform: flags.editorReadOnly ? { readOnly: true } : {},
609
- })
610
- }
611
- case "HasOne": {
612
- flags.relationCardinality = "one"
613
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
614
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
615
- return emitField({
616
- kind: "relation",
617
- kernel: {
618
- cardinality: "hasOne",
619
- target: flags.relationTarget,
620
- ...relationOptionsKernel(relOpts),
621
- },
622
- db: {},
623
- platform: flags.editorReadOnly ? { readOnly: true } : {},
624
- })
625
- }
626
- case "HasMany": {
627
- flags.relationCardinality = "many"
628
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
629
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
630
- return emitField({
631
- kind: "relation",
632
- kernel: {
633
- cardinality: "hasMany",
634
- target: flags.relationTarget,
635
- ...relationOptionsKernel(relOpts),
636
- },
637
- db: {},
638
- platform: flags.editorReadOnly ? { readOnly: true } : {},
639
- })
640
- }
641
- case "ManyToMany": {
642
- flags.relationCardinality = "many"
643
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
644
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
645
- return emitField({
646
- kind: "relation",
647
- kernel: {
648
- cardinality: "manyToMany",
649
- target: flags.relationTarget,
650
- ...relationOptionsKernel(relOpts),
651
- },
652
- db: {},
653
- platform: flags.editorReadOnly ? { readOnly: true } : {},
654
- })
655
- }
656
- default: {
657
- const resolved = tryResolveTypeReference(current, sourceFile, resolveCtx, { fieldName, resolving })
658
- if (resolved) {
659
- current = resolved
660
- continue
661
- }
662
- break
663
- }
664
- }
665
- break
666
- }
667
-
668
- const scalarBase = parseScalarType(
669
- current,
670
- sourceFile,
671
- blockAliases,
672
- bucketAliases,
673
- bucketsById,
674
- context,
675
- resolveCtx,
676
- fieldName,
677
- resolving,
678
- )
679
-
680
- let parsed: ParsedField = {
681
- kind: scalarBase.kind,
682
- kernel: {
683
- ...scalarBase.kernel,
684
- required: flags.required,
685
- ...(flags.primaryKey && { primaryKey: true }),
686
- },
687
- db: {
688
- ...scalarBase.db,
689
- unique: flags.unique,
690
- index: flags.index,
691
- },
692
- platform: {
693
- ...scalarBase.platform,
694
- ...(flags.editorReadOnly && { readOnly: true }),
695
- ...(flags.searchable && { searchable: true }),
696
- },
697
- }
698
-
699
- if (flags.autoIncrement && parsed.kind === "integer") {
700
- parsed = { ...parsed, kind: "serial", db: { ...parsed.db, pgType: "SERIAL" } }
701
- }
702
-
703
- if (fieldName === "id" && parsed.kind === "uuid" && flags.primaryKey === false) {
704
- parsed = {
705
- ...parsed,
706
- kernel: { ...parsed.kernel, primaryKey: true, required: true },
707
- db: { ...parsed.db, unique: true },
708
- }
709
- }
710
-
711
- if (flags.fieldDefault !== undefined) {
712
- if (parsed.kernel.default !== undefined) {
713
- throw new Error(
714
- `Field "${fieldName}": use either Default<…> or an inline type default (e.g. RichText<"…">), not both.`,
715
- )
716
- }
717
- parsed = {
718
- ...parsed,
719
- kernel: { ...parsed.kernel, default: { kind: "value", value: flags.fieldDefault } },
720
- }
721
- }
722
-
723
- if (parsed.kernel.primaryKey === true && parsed.kind === "uuid" && parsed.kernel.default === undefined) {
724
- parsed = {
725
- ...parsed,
726
- kernel: { ...parsed.kernel, default: { kind: "genRandomUuid" } },
727
- }
728
- } else if (
729
- parsed.kernel.primaryKey === true &&
730
- (parsed.kind === "serial" || parsed.kind === "bigSerial")
731
- ) {
732
- flags.serverGenerated = true
733
- }
734
-
735
- if (flags.serverGenerated === true) {
736
- parsed = { ...parsed, db: { ...parsed.db, serverGenerated: true } }
737
- }
738
-
739
- const auditTs =
740
- fieldName === "created_at" ||
741
- fieldName === "updated_at" ||
742
- fieldName === "createdAt" ||
743
- fieldName === "updatedAt"
744
- if (auditTs) {
745
- parsed = { ...parsed, db: { ...parsed.db, serverGenerated: true } }
746
- if (
747
- (parsed.kind === "datetime" || parsed.kind === "date") &&
748
- parsed.kernel.default === undefined
749
- ) {
750
- parsed = { ...parsed, kernel: { ...parsed.kernel, default: { kind: "now" } } }
751
- }
752
- }
753
-
754
- if (
755
- flags.serverGenerated &&
756
- (parsed.kind === "datetime" || parsed.kind === "date") &&
757
- parsed.kernel.default === undefined
758
- ) {
759
- parsed = { ...parsed, kernel: { ...parsed.kernel, default: { kind: "now" } } }
760
- }
761
-
762
- const hasCfTemplate = flags.computedFromTemplate !== undefined
763
- const hasCfSources = Boolean(flags.computedFromSources && flags.computedFromSources.length > 0)
764
- if (parsed.kind === "text" && (hasCfTemplate || hasCfSources)) {
765
- const kernel: ParsedField["kernel"] = { ...parsed.kernel }
766
- if (hasCfSources && flags.computedFromSources) {
767
- kernel.sources = flags.computedFromSources
768
- }
769
- if (hasCfTemplate && flags.computedFromTemplate !== undefined) {
770
- kernel.template = flags.computedFromTemplate
771
- }
772
- parsed = { ...parsed, kernel }
773
- }
774
-
775
- // Bounds compile here, not in the modifier cases above: `MaxLength<string[], 10>` is only knowably
776
- // an item count once the wrappers are off and the kind is `array`. Compiling early is what made
777
- // every bound `char_length`, which does not exist for an array and fails `CREATE TABLE`.
778
- const jsonIsArray = parsed.kind === "json" && jsonTypeArgIsArray(current, sourceFile)
779
- if (jsonIsArray) {
780
- parsed = { ...parsed, kernel: { ...parsed.kernel, jsonArray: true } }
781
- }
782
-
783
- if (Object.keys(flags.bounds).length > 0) {
784
- const compiled = compileBounds(fieldName, parsed.kind, flags.bounds, { jsonIsArray })
785
- parsed = {
786
- ...parsed,
787
- kernel: {
788
- ...parsed.kernel,
789
- ...(compiled.check !== undefined && {
790
- check: mergeCheckConstraint(parsed.kernel.check, compiled.check),
791
- }),
792
- ...(compiled.validation !== undefined && { validation: compiled.validation }),
793
- },
794
- }
795
- }
796
-
797
- return emitField(finalizeParsedField(parsed, flags, context))
798
- }
799
-
800
- function finalizeParsedField(
801
- parsed: ParsedField,
802
- flags: { localized: boolean; notLocalized: boolean },
803
- context: FieldParseContext,
804
- ): ParsedField {
805
- let localized = flags.localized
806
-
807
- if (
808
- !localized &&
809
- !flags.notLocalized &&
810
- context.autoLocalize &&
811
- shouldAutoLocalizeFieldKind(parsed.kind)
812
- ) {
813
- localized = true
814
- }
815
-
816
- if (parsed.kind === "blocks" && parsed.kernel.blocks && context.autoLocalize && !localized) {
817
- return {
818
- ...parsed,
819
- kernel: {
820
- ...parsed.kernel,
821
- blocks: parsed.kernel.blocks.map((blockDef) => ({
822
- ...blockDef,
823
- fields: Object.fromEntries(
824
- Object.entries(blockDef.fields).map(([name, fieldWire]) => [
825
- name,
826
- localizeFieldWire(fieldWire),
827
- ]),
828
- ),
829
- })),
830
- },
831
- }
832
- }
833
-
834
- if (localized) {
835
- return {
836
- ...parsed,
837
- kernel: { ...parsed.kernel, localized: true },
838
- db: { ...parsed.db, pgType: "JSONB" },
839
- }
840
- }
841
- return parsed
842
- }
843
-
844
- function shouldAutoLocalizeFieldKind(kind: unknown): boolean {
845
- return kind === "text" || kind === "richText"
846
- }
847
-
848
- function localizeFieldWire(field: FieldAstV2): FieldAstV2 {
849
- if (field.localized === true) return field
850
- if (!shouldAutoLocalizeFieldKind(field.kind)) return field
851
- const annotations = (field.annotations ?? {}) as { db?: Record<string, unknown>; platform?: Record<string, unknown> }
852
- return {
853
- ...field,
854
- localized: true,
855
- annotations: {
856
- ...annotations,
857
- db: { ...annotations.db, pgType: "JSONB" },
858
- },
859
- }
860
- }
861
-
862
- function parseScalarType(
863
- typeNode: ts.TypeNode,
864
- sourceFile: ts.SourceFile,
865
- blockAliases: Map<string, BlockDefinitionAst>,
866
- bucketAliases: Map<string, string>,
867
- bucketsById: Map<string, ExtractedStorageBucketAst>,
868
- context: FieldParseContext = {},
869
- resolveCtx: ResolveContext,
870
- fieldName = "?",
871
- resolving: Set<string> = new Set(),
872
- ): ParsedField {
873
- if (ts.isArrayTypeNode(typeNode)) {
874
- const element = parseScalarType(
875
- typeNode.elementType,
876
- sourceFile,
877
- blockAliases,
878
- bucketAliases,
879
- bucketsById,
880
- context,
881
- resolveCtx,
882
- fieldName,
883
- resolving,
884
- )
885
- return scalar("array", {
886
- db: { elementType: defaultPgTypeForKind(element.kind) },
887
- })
888
- }
889
-
890
- if (ts.isUnionTypeNode(typeNode)) {
891
- const literals = typeNode.types.filter(ts.isLiteralTypeNode)
892
- if (literals.length === typeNode.types.length && literals.every((lit) => ts.isStringLiteral(lit.literal))) {
893
- return scalar("enum", {
894
- kernel: {
895
- values: literals.map((lit) => (lit.literal as ts.StringLiteral).text),
896
- },
897
- })
898
- }
899
- const nonNull = typeNode.types.find((t) => t.kind !== ts.SyntaxKind.NullKeyword)
900
- if (nonNull) {
901
- return parseScalarType(
902
- nonNull,
903
- sourceFile,
904
- blockAliases,
905
- bucketAliases,
906
- bucketsById,
907
- context,
908
- resolveCtx,
909
- fieldName,
910
- resolving,
911
- )
912
- }
913
- }
914
-
915
- if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
916
- const resolved = tryResolveTypeReference(typeNode, sourceFile, resolveCtx, { fieldName, resolving })
917
- if (resolved) {
918
- return parseScalarType(
919
- resolved,
920
- sourceFile,
921
- blockAliases,
922
- bucketAliases,
923
- bucketsById,
924
- context,
925
- resolveCtx,
926
- fieldName,
927
- resolving,
928
- )
929
- }
930
- }
931
-
932
- if (ts.isTypeReferenceNode(typeNode)) {
933
- const ref = ts.isIdentifier(typeNode.typeName)
934
- ? applyImportRename(typeNode.typeName.text, sourceFile, resolveCtx.renameMap)
935
- : typeNode.typeName.getText(sourceFile)
936
- switch (ref) {
937
- case "UUID":
938
- case "SupatypeAuthUserId":
939
- return scalar("uuid")
940
- case "RichText": {
941
- const defaultArg = typeNode.typeArguments?.[0]
942
- if (!defaultArg) return scalar("richText")
943
- const literal = parseDefaultLiteral(defaultArg, sourceFile)
944
- if (literal === undefined) {
945
- throw new Error(
946
- `RichText default must be a string literal (plain text or Lexical JSON string), not HTML.`,
947
- )
948
- }
949
- if (typeof literal !== "string") {
950
- throw new Error(
951
- `RichText<…> default must be a string literal (plain text or Lexical JSON string).`,
952
- )
953
- }
954
- return scalar("richText", {
955
- kernel: { default: { kind: "value", value: literal } },
956
- })
957
- }
958
- case "Slug": {
959
- const fromArg = typeNode.typeArguments?.[0]
960
- const fromLiteral = fromArg ? literalStringType(fromArg) : null
961
- return scalar("slug", { kernel: { from: fromLiteral ?? "title" } })
962
- }
963
- case "Email":
964
- return scalar("email")
965
- case "URL":
966
- return scalar("url")
967
- case "Markdown":
968
- case "PhoneNumber":
969
- return scalar("text")
970
- case "Color":
971
- return scalar("color")
972
- case "IPAddress":
973
- return scalar("ip")
974
- case "CIDR":
975
- return scalar("cidr")
976
- case "MacAddress":
977
- return scalar("macaddr")
978
- case "XML":
979
- return scalar("xml")
980
- case "TSQuery":
981
- return scalar("tsQuery")
982
- case "TSVector":
983
- return scalar("tsVector")
984
- case "Money":
985
- return scalar("money")
986
- case "Decimal": {
987
- // `Decimal<10, 2>` names a precision and a scale, and the engine renders `NUMERIC(p, s)`
988
- // from them: but nothing used to read the type arguments, so every Decimal became an
989
- // unbounded NUMERIC. Silently, which is the worst way to lose a constraint on a money column.
990
- const precision = parseNumericTypeArg(typeNode.typeArguments?.[0], sourceFile)
991
- const scale = parseNumericTypeArg(typeNode.typeArguments?.[1], sourceFile)
992
- return scalar("decimal", {
993
- kernel: {
994
- ...(precision !== undefined && { precision }),
995
- ...(scale !== undefined && { scale }),
996
- },
997
- })
998
- }
999
- case "DateOnly":
1000
- return scalar("date")
1001
- case "Date":
1002
- case "DateTime":
1003
- case "Timestamp":
1004
- return scalar("datetime", { db: { pgType: "TIMESTAMP WITH TIME ZONE" } })
1005
- case "Int":
1006
- return scalar("integer")
1007
- case "SmallInt":
1008
- return scalar("smallInt")
1009
- case "BigInt":
1010
- return scalar("bigInt")
1011
- case "Float":
1012
- return scalar("float")
1013
- case "Bytea":
1014
- return scalar("bytes")
1015
- case "JSON":
1016
- return scalar("json")
1017
- case "Button":
1018
- return scalar("button", { db: { pgType: "JSONB" } })
1019
- case "Duration":
1020
- return scalar("json", {
1021
- db: { pgType: "JSONB" },
1022
- platform: { editor: "duration" },
1023
- kernel: { tsType: "{ ms: number }" },
1024
- })
1025
- // `Code` and `Currency` each carry two values, so a scalar column would have to drop one:
1026
- // JSONB keeps `lang` with its `source`, and an amount with the currency it is denominated in.
1027
- // `tsType` is what stops the generated client row from flattening them to an opaque object.
1028
- case "Code": {
1029
- const lang = literalStringType(typeNode.typeArguments?.[0])
1030
- return scalar("json", {
1031
- db: { pgType: "JSONB" },
1032
- // `editor` picks the Studio widget. Without it a code snippet and a money amount both get
1033
- // the raw JSON editor, because the widget is otherwise chosen from the column kind alone
1034
- // and both of these are JSONB.
1035
- platform: { editor: "code" },
1036
- kernel: { tsType: `{ lang: ${lang !== null ? JSON.stringify(lang) : "string"}; source: string }` },
1037
- })
1038
- }
1039
- case "Currency": {
1040
- const currencyCode = literalStringType(typeNode.typeArguments?.[0])
1041
- return scalar("json", {
1042
- db: { pgType: "JSONB" },
1043
- platform: { editor: "currency" },
1044
- kernel: {
1045
- tsType: `{ amount: string; code: ${currencyCode !== null ? JSON.stringify(currencyCode) : "string"} }`,
1046
- },
1047
- })
1048
- }
1049
- case "GeoPoint":
1050
- case "Geo":
1051
- return scalar("geo", { kernel: { geoType: "point", srid: 4326 } })
1052
- case "Asset":
1053
- case "FileAsset": {
1054
- const bucket = resolveBucketName(typeNode.typeArguments?.[0], sourceFile, bucketAliases, "assets")
1055
- const assetOpts = parseAssetFieldOptions(typeNode.typeArguments?.[1], sourceFile)
1056
- return attachStorageFieldMeta(
1057
- scalar("file", {
1058
- // JSONB, not TEXT. The column holds { bucket, path }, this package's own
1059
- // DEFAULT_DB_BY_KIND says JSONB, and the engine honours an explicit annotation, so
1060
- // TEXT here was one code path from a text column with a JSON object written into it.
1061
- db: { pgType: "JSONB" },
1062
- kernel: { bucket, ...(assetOpts.localized && { localized: true }) },
1063
- }),
1064
- bucket,
1065
- bucketsById,
1066
- )
1067
- }
1068
- case "ImageAsset": {
1069
- const bucket = resolveBucketName(typeNode.typeArguments?.[0], sourceFile, bucketAliases, "images")
1070
- const assetOpts = parseAssetFieldOptions(typeNode.typeArguments?.[1], sourceFile)
1071
- return attachStorageFieldMeta(
1072
- scalar("image", {
1073
- // JSONB, not TEXT. The column holds { bucket, path }, this package's own
1074
- // DEFAULT_DB_BY_KIND says JSONB, and the engine honours an explicit annotation, so
1075
- // TEXT here was one code path from a text column with a JSON object written into it.
1076
- db: { pgType: "JSONB" },
1077
- kernel: { bucket, ...(assetOpts.localized && { localized: true }) },
1078
- }),
1079
- bucket,
1080
- bucketsById,
1081
- )
1082
- }
1083
- case "Blocks":
1084
- return scalar("blocks", {
1085
- kernel: {
1086
- index: true,
1087
- blocks: parseBlocksTypeDefinitions(
1088
- typeNode.typeArguments?.[0],
1089
- sourceFile,
1090
- blockAliases,
1091
- bucketAliases,
1092
- bucketsById,
1093
- context,
1094
- resolveCtx,
1095
- ),
1096
- },
1097
- })
1098
- case "Vector": {
1099
- const dimensions = typeNode.typeArguments?.[0]?.getText(sourceFile)
1100
- return scalar("vector", {
1101
- kernel: { dimensions: Number(dimensions ?? "1536") },
1102
- })
1103
- }
1104
- default:
1105
- throw unknownTypeError(ref, fieldName)
1106
- }
1107
- }
1108
-
1109
- switch (typeNode.kind) {
1110
- case ts.SyntaxKind.StringKeyword:
1111
- return scalar("text")
1112
- case ts.SyntaxKind.NumberKeyword:
1113
- return scalar("float")
1114
- case ts.SyntaxKind.BooleanKeyword:
1115
- return scalar("boolean")
1116
- default:
1117
- return scalar("json")
1118
- }
1119
- }
1120
-
1121
- function collectBlockAliases(
1122
- sourceFile: ts.SourceFile,
1123
- bucketAliases: Map<string, string>,
1124
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1125
- resolveCtx: ResolveContext,
1126
- ): Map<string, BlockDefinitionAst> {
1127
- const blocks = new Map<string, BlockDefinitionAst>()
1128
- for (const stmt of sourceFile.statements) {
1129
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1130
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1131
- if (!ts.isIdentifier(stmt.type.typeName) || stmt.type.typeName.text !== "Block") continue
1132
- const block = parseInlineBlockDefinition(
1133
- stmt.type,
1134
- sourceFile,
1135
- new Map(),
1136
- bucketAliases,
1137
- bucketsById,
1138
- {},
1139
- resolveCtx,
1140
- )
1141
- if (!block) continue
1142
- blocks.set(stmt.name.text, block)
1143
- }
1144
- return blocks
1145
- }
1146
-
1147
- function collectLocaleConfig(
1148
- sourceFile: ts.SourceFile,
1149
- ): { locales: string[]; defaultLocale: string } | undefined {
1150
- for (const stmt of sourceFile.statements) {
1151
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1152
- if (!hasExportModifier(stmt)) continue
1153
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1154
- if (stmt.type.typeName.getText(sourceFile) !== "LocaleConfig") continue
1155
- const parsed = parseLocaleConfigTypeRef(stmt.type, sourceFile)
1156
- if (parsed) return parsed
1157
- }
1158
- return undefined
1159
- }
1160
-
1161
- function parseLocaleConfigTypeRef(
1162
- typeRef: ts.TypeReferenceNode,
1163
- sourceFile: ts.SourceFile,
1164
- ): { locales: string[]; defaultLocale: string } | null {
1165
- const [localesArg, defaultArg] = typeRef.typeArguments ?? []
1166
- if (!localesArg || !defaultArg) return null
1167
-
1168
- const locales = parseStringLiteralTuple(localesArg, sourceFile)
1169
- const defaultLocale = literalStringType(defaultArg)
1170
- if (!locales || locales.length === 0 || !defaultLocale) return null
1171
- if (!locales.includes(defaultLocale)) {
1172
- throw new Error(
1173
- `LocaleConfig defaultLocale "${defaultLocale}" must be one of: ${locales.join(", ")}`,
1174
- )
1175
- }
1176
- return { locales, defaultLocale }
1177
- }
1178
-
1179
- function parseStringLiteralTuple(node: ts.TypeNode, sourceFile: ts.SourceFile): string[] | null {
1180
- if (!ts.isTupleTypeNode(node)) return null
1181
- const out: string[] = []
1182
- for (const el of node.elements) {
1183
- const lit = literalStringType(el)
1184
- if (!lit) return null
1185
- out.push(lit)
1186
- }
1187
- return out
1188
- }
1189
-
1190
- function collectBucketContext(
1191
- sourceFile: ts.SourceFile,
1192
- resolveCtx: ResolveContext,
1193
- ): {
1194
- aliases: Map<string, string>
1195
- bucketsById: Map<string, ExtractedStorageBucketAst>
1196
- } {
1197
- const aliases = new Map<string, string>()
1198
- const bucketsById = new Map<string, ExtractedStorageBucketAst>()
1199
-
1200
- for (const stmt of sourceFile.statements) {
1201
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1202
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1203
- if (!ts.isIdentifier(stmt.type.typeName) || stmt.type.typeName.text !== "Bucket") continue
1204
- const [nameArg, configArg] = stmt.type.typeArguments ?? []
1205
- if (!nameArg || !ts.isLiteralTypeNode(nameArg) || !ts.isStringLiteral(nameArg.literal)) continue
1206
- const id = nameArg.literal.text
1207
- aliases.set(stmt.name.text, id)
1208
-
1209
- const parsed =
1210
- configArg && ts.isTypeLiteralNode(configArg)
1211
- ? parseBucketTypeLiteral(configArg, sourceFile, id, resolveCtx)
1212
- : {}
1213
-
1214
- const next = buildExtractedBucketAst(id, parsed)
1215
- const existing = bucketsById.get(id)
1216
- if (existing !== undefined && !bucketsEqual(existing, next)) {
1217
- throw new Error(
1218
- `Conflicting Bucket<> declarations for id "${id}". Use a single export per bucket id.`,
1219
- )
1220
- }
1221
- bucketsById.set(id, next)
1222
- }
1223
-
1224
- return { aliases, bucketsById }
1225
- }
1226
-
1227
- function buildExtractedBucketAst(
1228
- id: string,
1229
- parsed: Partial<ParsedBucketLiteral>,
1230
- ): ExtractedStorageBucketAst {
1231
- const mode = parsed.accessMode ?? "private"
1232
- const pub = mode === "public"
1233
-
1234
- const row: ExtractedStorageBucketAst = {
1235
- id,
1236
- public: pub,
1237
- accessMode: mode,
1238
- ...(parsed.allowedMimeTypes !== undefined && parsed.allowedMimeTypes.length > 0
1239
- ? { allowedMimeTypes: parsed.allowedMimeTypes }
1240
- : {}),
1241
- ...(parsed.fileSizeLimit !== undefined ? { fileSizeLimit: parsed.fileSizeLimit } : {}),
1242
- ...(parsed.access !== undefined &&
1243
- Object.keys(parsed.access).length > 0 && { access: parsed.access }),
1244
- ...(parsed.s3BucketPolicy !== undefined ? { s3BucketPolicy: parsed.s3BucketPolicy } : {}),
1245
- }
1246
- return row
1247
- }
1248
-
1249
- interface ParsedBucketLiteral {
1250
- accessMode?: "public" | "private" | "custom"
1251
- allowedMimeTypes?: string[]
1252
- fileSizeLimit?: number
1253
- access?: Record<string, unknown>
1254
- s3BucketPolicy?: string
1255
- }
1256
-
1257
- function parseBucketTypeLiteral(
1258
- lit: ts.TypeLiteralNode,
1259
- sourceFile: ts.SourceFile,
1260
- bucketId: string,
1261
- resolveCtx: ResolveContext,
1262
- ): Partial<ParsedBucketLiteral> {
1263
- const out: Partial<ParsedBucketLiteral> = {}
1264
- for (const member of lit.members) {
1265
- if (!ts.isPropertySignature(member) || !member.type) continue
1266
- const key = getPropertyName(member.name)
1267
- if (!key) continue
1268
-
1269
- if (key === "accessMode") {
1270
- const mode = parseAccessModeLiteral(member.type, sourceFile)
1271
- if (mode !== undefined) out.accessMode = mode
1272
- continue
1273
- }
1274
- if (key === "maxSize") {
1275
- const s = parseSizeStringLiteral(member.type, sourceFile)
1276
- if (s !== undefined) {
1277
- const bytes = parseDataSizeBytes(s)
1278
- out.fileSizeLimit = bytes
1279
- }
1280
- continue
1281
- }
1282
- if (key === "accept") {
1283
- const types = parseMimeAcceptList(member.type, sourceFile)
1284
- if (types !== undefined) out.allowedMimeTypes = types
1285
- continue
1286
- }
1287
- if (key === "access") {
1288
- const acc = parsePartialBucketAccess(member.type, sourceFile, bucketId, resolveCtx)
1289
- if (acc !== undefined && Object.keys(acc).length > 0) out.access = acc
1290
- continue
1291
- }
1292
- if (key === "s3BucketPolicy") {
1293
- const pol = parseJsonStringLiteral(member.type, sourceFile)
1294
- if (pol !== undefined) out.s3BucketPolicy = pol
1295
- continue
1296
- }
1297
- }
1298
- return out
1299
- }
1300
-
1301
- function parseAccessModeLiteral(
1302
- typeNode: ts.TypeNode,
1303
- sourceFile: ts.SourceFile,
1304
- ): "public" | "private" | "custom" | undefined {
1305
- const text = stripQuotes(typeNode.getText(sourceFile))
1306
- if (text === "public" || text === "private" || text === "custom") return text
1307
- return undefined
1308
- }
1309
-
1310
- function parseSizeStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
1311
- if (ts.isLiteralTypeNode(typeNode) && ts.isStringLiteral(typeNode.literal)) {
1312
- return typeNode.literal.text
1313
- }
1314
- return stripQuotes(typeNode.getText(sourceFile)) || undefined
1315
- }
1316
-
1317
- function parseJsonStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
1318
- return parseSizeStringLiteral(typeNode, sourceFile)
1319
- }
1320
-
1321
- function parseMimeAcceptList(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string[] | undefined {
1322
- if (ts.isTypeOperatorNode(typeNode) && typeNode.operator === ts.SyntaxKind.ReadonlyKeyword) {
1323
- return parseMimeAcceptList(typeNode.type, sourceFile)
1324
- }
1325
- if (ts.isTupleTypeNode(typeNode)) {
1326
- const values: string[] = []
1327
- for (const el of typeNode.elements) {
1328
- const node: ts.TypeNode = ts.isNamedTupleMember(el) ? el.type : el
1329
- const s = literalStringType(node)
1330
- if (!s) return undefined
1331
- values.push(s)
1332
- }
1333
- return values.length > 0 ? values : undefined
1334
- }
1335
- if (ts.isUnionTypeNode(typeNode)) {
1336
- const values: string[] = []
1337
- for (const u of typeNode.types) {
1338
- const s = literalStringType(u)
1339
- if (!s) return undefined
1340
- values.push(s)
1341
- }
1342
- return values.length > 0 ? values : undefined
1343
- }
1344
- return undefined
1345
- }
1346
-
1347
- /** The operations a bucket's `access` may name, the same four a model's may. */
1348
- const BUCKET_RULE_KEYS: ReadonlySet<string> = new Set(["read", "create", "update", "delete"])
1349
-
1350
- function parsePartialBucketAccess(
1351
- typeNode: ts.TypeNode,
1352
- sourceFile: ts.SourceFile,
1353
- bucketId: string,
1354
- resolveCtx: ResolveContext,
1355
- ): Record<string, unknown> | undefined {
1356
- // Same hazard as model access: silently dropping these rules publishes a
1357
- // bucket with no read/write restrictions, so an alias must resolve and an
1358
- // unresolvable annotation must fail rather than degrade to "no rules".
1359
- const literal = resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
1360
- if (!literal) {
1361
- throw new Error(
1362
- `Bucket "${bucketId}": could not resolve its \`access\` rules from ` +
1363
- `\`${typeNode.getText(sourceFile)}\`.\n` +
1364
- ` access must be an object type, or a type alias for one, e.g.\n` +
1365
- ` export type MediaAccess = { read: Public; create: Authenticated }\n` +
1366
- ` Refusing to continue: an unresolved access block would leave this bucket unrestricted.`,
1367
- )
1368
- }
1369
- const access: Record<string, unknown> = {}
1370
- for (const member of literal.members) {
1371
- if (!ts.isPropertySignature(member) || !member.type) continue
1372
- const key = getPropertyName(member.name)
1373
- // Refused rather than skipped. Skipping is how `update` went unenforced: the author wrote an
1374
- // overwrite rule, the bucket got none, and nothing said so.
1375
- if (key === null || !BUCKET_RULE_KEYS.has(key)) {
1376
- const written = key ?? member.name.getText(sourceFile)
1377
- throw new Error(
1378
- `Bucket "${bucketId}": \`${written}\` is not a bucket rule. Use read, create, update or delete.`,
1379
- )
1380
- }
1381
- const bucketRule = parseAccessRule(member.type, sourceFile, resolveCtx)
1382
- assertAccessRuleIsRenderable(bucketRule, bucketId, key)
1383
- access[key] = bucketRule
1384
- }
1385
- return access
1386
- }
1387
-
1388
- /** Parse human-readable size from schema types, e.g. `50MB`. */
1389
- function parseDataSizeBytes(lit: string): number {
1390
- const m = lit.trim().match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$/i)
1391
- if (!m?.[1] || !m[2]) throw new Error(`Invalid maxSize literal: "${lit}". Use forms like "50MB", "100KB".`)
1392
- const n = Number(m[1])
1393
- if (!Number.isFinite(n) || n < 0) throw new Error(`Invalid maxSize number in: "${lit}"`)
1394
- const pow: Record<string, number> = {
1395
- B: 0,
1396
- KB: 10,
1397
- MB: 20,
1398
- GB: 30,
1399
- }
1400
- const unit = m[2].toUpperCase() as keyof typeof pow
1401
- const exp = pow[unit]
1402
- if (exp === undefined) throw new Error(`Unsupported maxSize unit in: "${lit}"`)
1403
- return Math.round(n * Math.pow(2, exp))
1404
- }
1405
-
1406
- function stripQuotes(s: string): string {
1407
- return s.replace(/^['"]|['"]$/g, "")
1408
- }
1409
-
1410
- function bucketsEqual(a: ExtractedStorageBucketAst, b: ExtractedStorageBucketAst): boolean {
1411
- return (
1412
- a.public === b.public &&
1413
- (a.accessMode ?? "private") === (b.accessMode ?? "private") &&
1414
- JSON.stringify(a.access ?? null) === JSON.stringify(b.access ?? null) &&
1415
- JSON.stringify(a.allowedMimeTypes ?? null) === JSON.stringify(b.allowedMimeTypes ?? null) &&
1416
- (a.fileSizeLimit ?? null) === (b.fileSizeLimit ?? null) &&
1417
- (a.s3BucketPolicy ?? null) === (b.s3BucketPolicy ?? null)
1418
- )
1419
- }
1420
-
1421
- function attachStorageFieldMeta(
1422
- field: ParsedField,
1423
- bucketId: string,
1424
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1425
- ): ParsedField {
1426
- const cfg = bucketsById.get(bucketId)
1427
- if (cfg?.accessMode !== undefined) {
1428
- return {
1429
- ...field,
1430
- kernel: { ...field.kernel, accessMode: cfg.accessMode },
1431
- }
1432
- }
1433
- return field
1434
- }
1435
-
1436
- function parseBlocksTypeDefinitions(
1437
- blocksArg: ts.TypeNode | undefined,
1438
- sourceFile: ts.SourceFile,
1439
- blockAliases: Map<string, BlockDefinitionAst>,
1440
- bucketAliases: Map<string, string>,
1441
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1442
- context: FieldParseContext = {},
1443
- resolveCtx: ResolveContext,
1444
- ): BlockDefinitionAst[] {
1445
- if (!blocksArg) return []
1446
- const parts = ts.isUnionTypeNode(blocksArg) ? blocksArg.types : [blocksArg]
1447
- const out: BlockDefinitionAst[] = []
1448
- for (const part of parts) {
1449
- if (ts.isTypeReferenceNode(part) && ts.isIdentifier(part.typeName)) {
1450
- if (part.typeName.text === "Block") {
1451
- const inline = parseInlineBlockDefinition(
1452
- part,
1453
- sourceFile,
1454
- blockAliases,
1455
- bucketAliases,
1456
- bucketsById,
1457
- context,
1458
- resolveCtx,
1459
- )
1460
- if (inline) out.push(inline)
1461
- continue
1462
- }
1463
- const aliased = blockAliases.get(part.typeName.text)
1464
- if (aliased) out.push(aliased)
1465
- }
1466
- }
1467
- return out
1468
- }
1469
-
1470
- function parseInlineBlockDefinition(
1471
- ref: ts.TypeReferenceNode,
1472
- sourceFile: ts.SourceFile,
1473
- blockAliases: Map<string, BlockDefinitionAst>,
1474
- bucketAliases: Map<string, string>,
1475
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1476
- context: FieldParseContext = {},
1477
- resolveCtx: ResolveContext,
1478
- ): BlockDefinitionAst | null {
1479
- const [nameArg, fieldsArg, metaArg] = ref.typeArguments ?? []
1480
- const name = literalStringType(nameArg)
1481
- if (!name || !fieldsArg || !ts.isTypeLiteralNode(fieldsArg)) return null
1482
-
1483
- const fields: Record<string, FieldAstV2> = {}
1484
- for (const member of fieldsArg.members) {
1485
- if (!ts.isPropertySignature(member) || !member.type) continue
1486
- const fieldName = getPropertyName(member.name)
1487
- if (!fieldName) continue
1488
- fields[fieldName] = parseFieldType(
1489
- fieldName,
1490
- member.type,
1491
- sourceFile,
1492
- blockAliases,
1493
- bucketAliases,
1494
- bucketsById,
1495
- context,
1496
- resolveCtx,
1497
- )
1498
- }
1499
-
1500
- let label: string | undefined
1501
- let icon: string | undefined
1502
- if (metaArg && ts.isTypeLiteralNode(metaArg)) {
1503
- for (const m of metaArg.members) {
1504
- if (!ts.isPropertySignature(m) || !m.type) continue
1505
- const key = getPropertyName(m.name)
1506
- if (!key) continue
1507
- const value = literalStringType(m.type)
1508
- if (!value) continue
1509
- if (key === "label") label = value
1510
- if (key === "icon") icon = value
1511
- }
1512
- }
1513
-
1514
- return {
1515
- name,
1516
- ...(label !== undefined && { label }),
1517
- ...(icon !== undefined && { icon }),
1518
- fields,
1519
- }
1520
- }
1521
-
1522
- function literalStringType(typeNode: ts.TypeNode | undefined): string | null {
1523
- if (!typeNode) return null
1524
- if (ts.isLiteralTypeNode(typeNode) && ts.isStringLiteral(typeNode.literal)) return typeNode.literal.text
1525
- return null
1526
- }
1527
-
1528
- /** Field names referenced in `{name}` and `{truncate(name, n)}` (case-sensitive, same as model fields). */
1529
- function fieldNamesInComputedTemplate(template: string): string[] {
1530
- const fields = new Set<string>()
1531
- const reTrunc = /\{truncate\s*\(\s*([a-zA-Z_]\w*)\s*,\s*(\d+)\s*\)\}/gi
1532
- let m: RegExpExecArray | null
1533
- while ((m = reTrunc.exec(template)) !== null) {
1534
- const ref = m[1]
1535
- if (ref) fields.add(ref)
1536
- }
1537
- const reSimple = /\{([a-zA-Z_]\w*)\}/g
1538
- while ((m = reSimple.exec(template)) !== null) {
1539
- const ref = m[1]
1540
- if (ref) fields.add(ref)
1541
- }
1542
- return [...fields]
1543
- }
1544
-
1545
- function looksLikeComputedTemplateLiteral(lit: string): boolean {
1546
- return /\{truncate\s*\(/i.test(lit) || /\{[a-zA-Z_]\w*\}/g.test(lit)
1547
- }
1548
-
1549
- /** Resolves second type arg of `ComputedFrom<Value, Sources>`, tuple concat, single field, or template literal. */
1550
- function parseComputedFromSecondArg(
1551
- sourcesArg: ts.TypeNode | undefined,
1552
- sourceFile: ts.SourceFile,
1553
- ): { sources: string[]; template?: string } | null {
1554
- if (!sourcesArg) return null
1555
- const single = literalStringType(sourcesArg)
1556
- if (single) {
1557
- if (looksLikeComputedTemplateLiteral(single)) {
1558
- return { sources: fieldNamesInComputedTemplate(single), template: single }
1559
- }
1560
- return { sources: [single] }
1561
- }
1562
-
1563
- const elemsFromTupleType = (tuple: ts.TupleTypeNode): ts.TypeNode[] | null => {
1564
- const nodes: ts.TypeNode[] = []
1565
- for (const el of tuple.elements) {
1566
- if (ts.isNamedTupleMember(el)) {
1567
- if (!el.type) return null
1568
- nodes.push(el.type)
1569
- continue
1570
- }
1571
- nodes.push(el as ts.TypeNode)
1572
- }
1573
- return nodes
1574
- }
1575
-
1576
- const tupleElems = (): ts.TypeNode[] | null => {
1577
- if (ts.isTupleTypeNode(sourcesArg)) return elemsFromTupleType(sourcesArg)
1578
- if (ts.isTypeOperatorNode(sourcesArg) && sourcesArg.operator === ts.SyntaxKind.ReadonlyKeyword) {
1579
- const inner = sourcesArg.type
1580
- if (inner && ts.isTupleTypeNode(inner)) return elemsFromTupleType(inner)
1581
- }
1582
- return null
1583
- }
1584
-
1585
- const elems = tupleElems()
1586
- if (!elems || elems.length === 0) return null
1587
- const keys: string[] = []
1588
- for (const node of elems) {
1589
- const k = literalStringType(node)
1590
- if (!k) return null
1591
- keys.push(k)
1592
- }
1593
- return { sources: keys }
1594
- }
1595
-
1596
- function resolveBucketName(
1597
- typeArg: ts.TypeNode | undefined,
1598
- sourceFile: ts.SourceFile,
1599
- bucketAliases: Map<string, string>,
1600
- fallback: string,
1601
- ): string {
1602
- if (!typeArg) return fallback
1603
- if (ts.isTypeReferenceNode(typeArg) && ts.isIdentifier(typeArg.typeName)) {
1604
- return bucketAliases.get(typeArg.typeName.text) ?? typeArg.typeName.text
1605
- }
1606
- if (ts.isLiteralTypeNode(typeArg) && ts.isStringLiteral(typeArg.literal)) {
1607
- return typeArg.literal.text
1608
- }
1609
- return typeArg.getText(sourceFile).replace(/^['"]|['"]$/g, "") || fallback
1610
- }
1611
-
1612
- function isBooleanLiteralType(typeNode: ts.TypeNode, value: boolean): boolean {
1613
- if (value) {
1614
- if (typeNode.kind === ts.SyntaxKind.TrueKeyword) return true
1615
- if (ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === ts.SyntaxKind.TrueKeyword) {
1616
- return true
1617
- }
1618
- return false
1619
- }
1620
- if (typeNode.kind === ts.SyntaxKind.FalseKeyword) return true
1621
- if (ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === ts.SyntaxKind.FalseKeyword) {
1622
- return true
1623
- }
1624
- return false
1625
- }
1626
-
1627
- function parseAssetFieldOptions(
1628
- optionsArg: ts.TypeNode | undefined,
1629
- sourceFile: ts.SourceFile,
1630
- ): { localized: boolean } {
1631
- if (!optionsArg || !ts.isTypeLiteralNode(optionsArg)) return { localized: false }
1632
- for (const member of optionsArg.members) {
1633
- if (!ts.isPropertySignature(member) || !member.type) continue
1634
- const key = getPropertyName(member.name)
1635
- if (key === "localized" && isBooleanLiteralType(member.type, true)) {
1636
- return { localized: true }
1637
- }
1638
- }
1639
- return { localized: false }
1640
- }
1641
-
1642
- /** What `versions` resolved to on a model, or absent when the model declares none. */
1643
- type ParsedVersions = { drafts: boolean; keep: number }
1644
-
1645
- /** Versions kept per record when a model states no retention. Mirrors `model-versioning.ts`. */
1646
- const DEFAULT_VERSIONS_KEPT = 20
1647
-
1648
- /**
1649
- * `versions: true` or `versions: { drafts, keep }`.
1650
- *
1651
- * A malformed member is ignored rather than fatal, matching every other key here: the declaration is
1652
- * a *type*, so TypeScript has already refused anything `ModelVersionsOptions` does not allow, and
1653
- * this parser's job is reading what compiled rather than validating it a second time.
1654
- */
1655
- function parseVersions(typeNode: ts.TypeNode): ParsedVersions | undefined {
1656
- if (isBooleanLiteralType(typeNode, true)) {
1657
- return { drafts: true, keep: DEFAULT_VERSIONS_KEPT }
1658
- }
1659
- if (isBooleanLiteralType(typeNode, false)) return undefined
1660
- if (!ts.isTypeLiteralNode(typeNode)) return undefined
1661
-
1662
- const parsed: ParsedVersions = { drafts: true, keep: DEFAULT_VERSIONS_KEPT }
1663
- for (const member of typeNode.members) {
1664
- if (!ts.isPropertySignature(member) || !member.type) continue
1665
- const key = getPropertyName(member.name)
1666
- if (key === "drafts") {
1667
- if (isBooleanLiteralType(member.type, false)) parsed.drafts = false
1668
- if (isBooleanLiteralType(member.type, true)) parsed.drafts = true
1669
- } else if (
1670
- key === "keep" &&
1671
- ts.isLiteralTypeNode(member.type) &&
1672
- ts.isNumericLiteral(member.type.literal)
1673
- ) {
1674
- const keep = Number(member.type.literal.text)
1675
- // A retention of zero would prune the draft being edited, so it reads as "unstated" rather
1676
- // than as an instruction to keep nothing.
1677
- if (Number.isFinite(keep) && keep >= 1) parsed.keep = Math.floor(keep)
1678
- }
1679
- }
1680
- return parsed
1681
- }
1682
-
1683
- function parseMetaLiteral(
1684
- metaArg: ts.TypeNode | undefined,
1685
- sourceFile: ts.SourceFile,
1686
- ): {
1687
- tableName?: string
1688
- singleton?: boolean
1689
- timestamps?: boolean
1690
- softDelete?: boolean
1691
- autoLocalize?: boolean
1692
- versions?: ParsedVersions
1693
- searchable?: string[]
1694
- } {
1695
- const result: {
1696
- tableName?: string
1697
- singleton?: boolean
1698
- timestamps?: boolean
1699
- softDelete?: boolean
1700
- autoLocalize?: boolean
1701
- versions?: ParsedVersions
1702
- searchable?: string[]
1703
- } = {}
1704
-
1705
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return result
1706
-
1707
- for (const member of metaArg.members) {
1708
- if (!ts.isPropertySignature(member) || !member.type) continue
1709
- const key = getPropertyName(member.name)
1710
- if (!key) continue
1711
-
1712
- if (key === "singleton" && isBooleanLiteralType(member.type, true)) {
1713
- result.singleton = true
1714
- } else if (key === "timestamps") {
1715
- if (isBooleanLiteralType(member.type, true)) result.timestamps = true
1716
- if (isBooleanLiteralType(member.type, false)) result.timestamps = false
1717
- } else if (key === "softDelete") {
1718
- if (isBooleanLiteralType(member.type, true)) result.softDelete = true
1719
- if (isBooleanLiteralType(member.type, false)) result.softDelete = false
1720
- } else if (key === "autoLocalize" && isBooleanLiteralType(member.type, true)) {
1721
- result.autoLocalize = true
1722
- } else if (key === "searchable" && ts.isTupleTypeNode(member.type)) {
1723
- result.searchable = member.type.elements
1724
- .map((el) => (ts.isLiteralTypeNode(el) && ts.isStringLiteral(el.literal) ? el.literal.text : null))
1725
- .filter((name): name is string => name !== null)
1726
- } else if (key === "versions") {
1727
- const versions = parseVersions(member.type)
1728
- if (versions !== undefined) result.versions = versions
1729
- } else if (
1730
- key === "tableName" &&
1731
- ts.isLiteralTypeNode(member.type) &&
1732
- ts.isStringLiteral(member.type.literal)
1733
- ) {
1734
- result.tableName = member.type.literal.text
1735
- }
1736
- }
1737
-
1738
- return result
1739
- }
1740
-
1741
- function hasCompositeWrapper(typeNode: ts.TypeNode, wrapperName: string): boolean {
1742
- if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return false
1743
- if (typeNode.typeName.text === wrapperName) return true
1744
- if (
1745
- typeNode.typeName.text === "WithTimestamps" ||
1746
- typeNode.typeName.text === "WithSoftDelete" ||
1747
- typeNode.typeName.text === "WithPublishable"
1748
- ) {
1749
- const inner = typeNode.typeArguments?.[0]
1750
- if (inner) return hasCompositeWrapper(inner, wrapperName)
1751
- }
1752
- return false
1753
- }
1754
-
1755
- function parseModelMeta(
1756
- metaArg: ts.TypeNode | undefined,
1757
- sourceFile: ts.SourceFile,
1758
- modelName: string,
1759
- fieldsArg: ts.TypeNode,
1760
- fields: Record<string, FieldAstV2>,
1761
- resolveCtx: ResolveContext,
1762
- ): {
1763
- tableName: string
1764
- access: Record<string, unknown>
1765
- options: Record<string, unknown>
1766
- indexes: unknown[]
1767
- constraints: unknown[]
1768
- hooks: Record<string, ParsedModelHook>
1769
- validators: Record<string, ParsedModelHook>
1770
- searchFields: string[]
1771
- cache: ParsedModelCache | undefined
1772
- } {
1773
- const literal = parseMetaLiteral(metaArg, sourceFile)
1774
- const singleton = literal.singleton === true
1775
- const tableName =
1776
- literal.tableName ?? (singleton ? `_global_${toSnakeCase(modelName)}` : toSnakeCase(modelName))
1777
-
1778
- const timestamps =
1779
- literal.timestamps ??
1780
- (hasCompositeWrapper(fieldsArg, "WithTimestamps") ||
1781
- (fields["created_at"] !== undefined && fields["updated_at"] !== undefined))
1782
-
1783
- const softDelete =
1784
- literal.softDelete ??
1785
- (hasCompositeWrapper(fieldsArg, "WithSoftDelete") || fields["deleted_at"] !== undefined)
1786
-
1787
- const options: Record<string, unknown> = {}
1788
- if (singleton) options.singleton = true
1789
- if (timestamps) options.timestamps = true
1790
- if (softDelete) options.softDelete = true
1791
- if (literal.autoLocalize === true) options.autoLocalize = true
1792
- if (literal.versions !== undefined) options.versions = literal.versions
1793
-
1794
- const access = parseModelAccess(metaArg, sourceFile, modelName, fields, resolveCtx)
1795
- if (literal.versions !== undefined) assertVersionsWithoutFieldRules(access, modelName)
1796
-
1797
- const cache = parseModelCache(metaArg, sourceFile)
1798
- if (cache !== undefined) assertCacheIsServable(cache, access, fields, modelName)
1799
-
1800
- return {
1801
- tableName,
1802
- access,
1803
- options,
1804
- searchFields: resolveSearchFields(literal.searchable, fields, modelName),
1805
- indexes: parseModelIndexes(metaArg, sourceFile, fields),
1806
- constraints: parseModelConstraints(metaArg, sourceFile, modelName, fields, resolveCtx),
1807
- hooks: parseModelHooks(metaArg, sourceFile),
1808
- validators: parseModelValidators(metaArg, sourceFile, modelName, fields),
1809
- // Always present, possibly undefined: a conditional spread here infers the key away entirely
1810
- // and the caller cannot destructure it. emitModel is what decides whether it reaches the AST.
1811
- cache,
1812
- }
1813
- }
1814
-
1815
- /**
1816
- * Refuse a cache declaration the runtime cannot honour, naming the model and the reason.
1817
- *
1818
- * Both checks exist because the failure they prevent is silent. A public entry on a caller-varying
1819
- * table serves one user's rows to another and looks like a cache hit. `rows: true` on a table with
1820
- * no primary key is simply never registered, and reads stay exactly as fast as they were with a
1821
- * setting in the schema saying otherwise.
1822
- *
1823
- * Checked here rather than left to the server for the same reason the constraint operands are: the
1824
- * message can name what the author wrote.
1825
- */
1826
- function assertCacheIsServable(
1827
- cache: ParsedModelCache,
1828
- access: Record<string, unknown>,
1829
- fields: Record<string, FieldAstV2>,
1830
- model: string,
1831
- ): void {
1832
- if (cache.public === true) {
1833
- const read = access["read"] as AccessRuleNode | undefined
1834
- if (isIdentityDependent(read)) {
1835
- throw new Error(
1836
- `Model "${model}": \`cache.public\` cannot be used with an \`access.read\` rule that ` +
1837
- `varies by caller. A public cache entry is shared by everyone, so one caller's rows ` +
1838
- `would be served to another. Use \`cache: { enabled: true }\` for per-user entries, or ` +
1839
- `make the read rule row-independent: a rule like \`Lte<"published_at", Now>\` varies by ` +
1840
- `row without varying by caller and is safe to share.`,
1841
- )
1842
- }
1843
- }
1844
-
1845
- if (cache.rows === true) {
1846
- const keyed = Object.keys(fields).filter((f) => fields[f]?.["primaryKey"] === true)
1847
- if (keyed.length === 0) {
1848
- throw new Error(
1849
- `Model "${model}": \`cache.rows\` needs a primary key, because the row cache's key IS the ` +
1850
- `primary key, so there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1851
- `response cache, which has no such requirement.`,
1852
- )
1853
- }
1854
- }
1855
-
1856
- assertTtlIsInRange(cache.maxTtl, model)
1857
- }
1858
-
1859
- /**
1860
- * The columns Studio's list view searches, from either way of saying so.
1861
- *
1862
- * Two spellings, because they answer different questions: `Searchable<string>` on the field says
1863
- * *this column is worth searching*, and `searchable: ["title", "name"]` on the model says *search
1864
- * these, in this order*, which matters because the list view filters on the first one. A model
1865
- * using both gets the explicit order first and any remaining flagged columns after it.
1866
- *
1867
- * A name that matches no field throws rather than being dropped. Silently ignoring it is how this
1868
- * whole feature came to be inert: the declaration compiled and nothing downstream ever saw it.
1869
- */
1870
- function resolveSearchFields(
1871
- declared: string[] | undefined,
1872
- fields: Record<string, FieldAstV2>,
1873
- modelName: string,
1874
- ): string[] {
1875
- const ordered: string[] = []
1876
-
1877
- for (const name of declared ?? []) {
1878
- if (fields[name] === undefined) {
1879
- throw new Error(
1880
- `Model "${modelName}": \`searchable\` names "${name}", which is not a field on this model. ` +
1881
- `Searchable columns are: ${Object.keys(fields).join(", ")}.`,
1882
- )
1883
- }
1884
- if (!ordered.includes(name)) ordered.push(name)
1885
- }
1886
-
1887
- for (const [name, field] of Object.entries(fields)) {
1888
- if (field.annotations?.platform?.searchable !== true) continue
1889
- if (!ordered.includes(name)) ordered.push(name)
1890
- }
1891
-
1892
- return ordered
1893
- }
1894
-
1895
- /**
1896
- * The bounds the admin API already enforces, enforced where the number was written.
1897
- *
1898
- * `cache_max_ttl` is refused outside 0–86400 by `PATCH /admin/v1/config/rest`, and a declared cap
1899
- * is the same quantity. Left to the server, an out-of-range `maxTtl` reaches it as part of a
1900
- * manifest rather than a request (nothing refuses a manifest), and the ceiling it produces is
1901
- * whatever the arithmetic makes of it: a negative cap reads as "no cap declared" and permits more
1902
- * than the author asked for, which is the one direction a ceiling must never move in.
1903
- */
1904
- function assertTtlIsInRange(ttl: number | undefined, model: string): void {
1905
- if (ttl === undefined) return
1906
- if (!Number.isInteger(ttl)) {
1907
- throw new Error(
1908
- `Model "${model}": \`cache.maxTtl\` must be a whole number of seconds, not ${ttl}.`,
1909
- )
1910
- }
1911
- if (ttl < 0 || ttl > MAX_CACHE_TTL_SECONDS) {
1912
- throw new Error(
1913
- `Model "${model}": \`cache.maxTtl\` must be between 0 and ${MAX_CACHE_TTL_SECONDS} seconds ` +
1914
- `(24 hours), not ${ttl}. That is the same bound the admin API enforces on the project-wide ` +
1915
- `cache TTL, and a declaration outside it is not a cap the runtime can apply.`,
1916
- )
1917
- }
1918
- }
1919
-
1920
- /** The admin API's bound on a cache TTL, in seconds. */
1921
- const MAX_CACHE_TTL_SECONDS = 86_400
1922
-
1923
- /**
1924
- * Refuse a model that declares both `versions` and per-column rules.
1925
- *
1926
- * A version snapshot is opaque `jsonb`. `supatype_mask` is driven by security labels on a specific
1927
- * table's column and rewrites references to *that* column; the view tier puts the same expression in
1928
- * a view over the real columns. Neither can see inside a snapshot, so a masked value would sit in
1929
- * plain sight in `<table>_versions` for anyone able to read it, and there is no narrower grant to
1930
- * hide it behind now that drafts are visible to the record's creator.
1931
- *
1932
- * Refused here rather than left to the engine for the same reason the constraint operands are: the
1933
- * message can name the model and the columns the author wrote.
1934
- */
1935
- function assertVersionsWithoutFieldRules(access: Record<string, unknown>, model: string): void {
1936
- const fields = access["fields"]
1937
- if (typeof fields !== "object" || fields === null) return
1938
- const masked = Object.keys(fields)
1939
- if (masked.length === 0) return
1940
-
1941
- throw new Error(
1942
- `Model "${model}": \`versions\` and \`access.fields\` cannot both be declared. ` +
1943
- `A version snapshot is opaque JSONB, so the per-column rules on ` +
1944
- `${masked.map((c) => `\`${c}\``).join(", ")} cannot be enforced inside it and the value would ` +
1945
- `be readable in the versions table. Drop one: keep the field rules, or version a model that ` +
1946
- `does not mask a column.`,
1947
- )
1948
- }
1949
-
1950
- /**
1951
- * Operands a `CHECK` cannot evaluate, and why.
1952
- *
1953
- * All of these are legal in an access rule, which is exactly why they need refusing here rather
1954
- * than left to fail at `CREATE TABLE`: the vocabulary is shared, so the mistake is easy and the
1955
- * error Postgres gives for it names nothing useful.
1956
- */
1957
- const CONSTRAINT_FORBIDDEN_OPERANDS: Record<string, string> = {
1958
- authUid: "a CHECK constraint cannot see who is writing",
1959
- authRole: "a CHECK constraint cannot see who is writing",
1960
- claim: "a CHECK constraint cannot read the caller's JWT",
1961
- role: "a CHECK constraint cannot see the caller's role",
1962
- now: "a row valid on insert would become invalid on update, so a constraint cannot read the clock",
1963
- startOf: "a constraint cannot read the clock",
1964
- ago: "a constraint cannot read the clock",
1965
- fromNow: "a constraint cannot read the clock",
1966
- rows: "a CHECK constraint cannot query another table",
1967
- exists: "a CHECK constraint cannot query another table",
1968
- }
1969
-
1970
- /**
1971
- * Walk a parsed constraint node and refuse anything the database cannot enforce as a `CHECK`.
1972
- *
1973
- * Walks the parsed form rather than the syntax, so a node reached through `Any`, `All` or `Not`
1974
- * is checked the same as a top-level one.
1975
- */
1976
- function assertConstraintIsEnforceable(node: unknown, model: string, index: number): void {
1977
- if (Array.isArray(node)) {
1978
- for (const item of node) assertConstraintIsEnforceable(item, model, index)
1979
- return
1980
- }
1981
- if (typeof node !== "object" || node === null) return
1982
-
1983
- const record = node as Record<string, unknown>
1984
- for (const key of ["type", "kind"]) {
1985
- const value = record[key]
1986
- if (typeof value !== "string") continue
1987
- const why = CONSTRAINT_FORBIDDEN_OPERANDS[value]
1988
- if (why !== undefined) {
1989
- throw new Error(
1990
- `Model "${model}": constraint ${index + 1} uses \`${value}\`, which is not allowed in a ` +
1991
- `constraint because ${why}. Move the rule to \`access\` if it depends on the caller.`,
1992
- )
1993
- }
1994
- }
1995
- for (const value of Object.values(record)) assertConstraintIsEnforceable(value, model, index)
1996
- }
1997
-
1998
- /**
1999
- * Resolve `Length<>` and `ItemCount<>` inside a constraint to the measure their column actually
2000
- * takes, so the engine renders mechanically and never has to know about field kinds.
2001
- *
2002
- * Done here because this is the only layer that has both halves: the field's kind, and the table
2003
- * the bounds modifiers already resolve against. The engine seeing `JSONB` cannot tell an array from
2004
- * an object, and a second kind table in Rust is how `char_length(text[])` would come back in a new
2005
- * file after being fixed once.
2006
- */
2007
- function resolveConstraintMeasures(
2008
- node: unknown,
2009
- fields: Record<string, FieldAstV2>,
2010
- model: string,
2011
- index: number,
2012
- ): void {
2013
- if (Array.isArray(node)) {
2014
- for (const item of node) resolveConstraintMeasures(item, fields, model, index)
2015
- return
2016
- }
2017
- if (typeof node !== "object" || node === null) return
2018
-
2019
- const record = node as Record<string, unknown>
2020
- const kind = record["kind"]
2021
- if (kind === "length" || kind === "itemCount") {
2022
- const column = String(record["column"])
2023
- const field = fields[column]
2024
- if (!field) {
2025
- throw new Error(
2026
- `Model "${model}": constraint ${index + 1} measures \`${column}\`, which is not a field on ` +
2027
- "this model. Measures need a declared field, because the measure depends on its type.",
2028
- )
2029
- }
2030
- const measure = kind === "length" ? "length" : "items"
2031
- const resolved = measureFormFor(field.kind as FieldKind, measure, {
2032
- jsonIsArray: field["jsonArray"] === true,
2033
- })
2034
- if (resolved.form === undefined) {
2035
- throw new Error(
2036
- `Model "${model}": constraint ${index + 1} uses ` +
2037
- `\`${kind === "length" ? "Length" : "ItemCount"}<"${column}">\`, but ` +
2038
- `${resolved.instead}.`,
2039
- )
2040
- }
2041
- record["form"] = resolved.form
2042
- return
2043
- }
2044
-
2045
- for (const value of Object.values(record)) {
2046
- resolveConstraintMeasures(value, fields, model, index)
2047
- }
2048
- }
2049
-
2050
- /**
2051
- * Read `constraints` from a model's meta.
2052
- *
2053
- * Reuses `parseAccessRule`, because a constraint *is* an access rule with a narrower operand set:
2054
- * a second parser for the same node vocabulary would be two grammars to keep aligned, and they
2055
- * would drift the first time either gained a node.
2056
- */
2057
- function parseModelConstraints(
2058
- metaArg: ts.TypeNode | undefined,
2059
- sourceFile: ts.SourceFile,
2060
- modelName: string,
2061
- fields: Record<string, FieldAstV2>,
2062
- resolveCtx: ResolveContext,
2063
- ): unknown[] {
2064
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return []
2065
-
2066
- const prop = metaArg.members.find(
2067
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "constraints",
2068
- )
2069
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return []
2070
-
2071
- if (!ts.isTupleTypeNode(prop.type)) {
2072
- throw new Error(
2073
- `Model "${modelName}": \`constraints\` must be a tuple, as in ` +
2074
- `\`constraints: [Lte<"starts_at", "ends_at">]\`.`,
2075
- )
2076
- }
2077
-
2078
- return prop.type.elements.map((element, index) => {
2079
- const parsed = parseAccessRule(element, sourceFile, resolveCtx)
2080
- if (parsed["type"] === "private") {
2081
- throw new Error(
2082
- `Model "${modelName}": constraint ${index + 1}, ` +
2083
- `\`${ownerText(element, sourceFile)}\`, is not a rule this vocabulary knows.`,
2084
- )
2085
- }
2086
- assertConstraintIsEnforceable(parsed, modelName, index)
2087
- resolveConstraintMeasures(parsed, fields, modelName, index)
2088
- return parsed
2089
- })
2090
- }
2091
-
2092
- /** One lifecycle hook: `"fn-name"` or `{ function: "fn-name", timeout: 5000 }`. */
2093
- interface ParsedModelHook {
2094
- function: string
2095
- timeout?: number
2096
- onUnavailable?: "reject" | "log"
2097
- }
2098
-
2099
- const HOOK_EVENTS = ["beforeChange", "afterChange", "beforeDelete", "afterDelete"] as const
2100
-
2101
- /**
2102
- * Read `hooks` from a model's meta.
2103
- *
2104
- * Deliberately strict: an entry that is neither a string nor an object with a `function` name is
2105
- * **dropped**, and `validateModelHooks` then reports the model whose hook did not survive. A hook
2106
- * silently not firing is the failure this feature cannot have, so an unreadable declaration must
2107
- * fail the push rather than extract to nothing.
2108
- */
2109
- /**
2110
- * Read `validate` from a model's meta: field name to the function that checks it.
2111
- *
2112
- * Strict for the same reason `parseModelHooks` is: a validator that silently never fires is the
2113
- * failure this feature cannot have. An entry that is neither a string nor an object with a
2114
- * `function` name is dropped here and reported by `validateModelHooks`, which fails the push.
2115
- *
2116
- * Keyed by the **field** as written, not the column: the extractor resolves the two, and a validator
2117
- * naming a field the model does not declare is an error worth catching here where the message can
2118
- * list what the model does have.
2119
- */
2120
- function parseModelValidators(
2121
- metaArg: ts.TypeNode | undefined,
2122
- sourceFile: ts.SourceFile,
2123
- modelName: string,
2124
- fields: Record<string, FieldAstV2>,
2125
- ): Record<string, ParsedModelHook> {
2126
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2127
-
2128
- const prop = metaArg.members.find(
2129
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "validate",
2130
- )
2131
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return {}
2132
- if (!ts.isTypeLiteralNode(prop.type)) {
2133
- throw new Error(
2134
- `Model "${modelName}": \`validate\` must be an object mapping a field to a function name, ` +
2135
- 'as in `validate: { setupItems: "validate-setup-items" }`.',
2136
- )
2137
- }
2138
-
2139
- const out: Record<string, ParsedModelHook> = {}
2140
- for (const member of prop.type.members) {
2141
- if (!ts.isPropertySignature(member) || !member.type) continue
2142
- const field = getPropertyName(member.name)
2143
- if (!field) continue
2144
-
2145
- if (!Object.prototype.hasOwnProperty.call(fields, field)) {
2146
- const known = Object.keys(fields).join(", ")
2147
- throw new Error(
2148
- `Model "${modelName}": \`validate\` names "${field}", which is not a field on this model. ` +
2149
- `Fields are: ${known}.`,
2150
- )
2151
- }
2152
-
2153
- const parsed = parseModelHookValue(member.type, sourceFile)
2154
- if (parsed === null) {
2155
- throw new Error(
2156
- `Model "${modelName}": the validator for "${field}" must be a function name, or an object ` +
2157
- 'with a `function` name, as in `{ function: "check-it", timeout: 5000 }`.',
2158
- )
2159
- }
2160
- out[field] = parsed
2161
- }
2162
- return out
2163
- }
2164
-
2165
- function parseModelHooks(
2166
- metaArg: ts.TypeNode | undefined,
2167
- sourceFile: ts.SourceFile,
2168
- ): Record<string, ParsedModelHook> {
2169
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2170
-
2171
- const hooksProp = metaArg.members.find(
2172
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "hooks",
2173
- )
2174
- if (!hooksProp || !ts.isPropertySignature(hooksProp) || !hooksProp.type) return {}
2175
- if (!ts.isTypeLiteralNode(hooksProp.type)) return {}
2176
-
2177
- const hooks: Record<string, ParsedModelHook> = {}
2178
- for (const member of hooksProp.type.members) {
2179
- if (!ts.isPropertySignature(member) || !member.type) continue
2180
- const event = getPropertyName(member.name)
2181
- if (!event || !(HOOK_EVENTS as readonly string[]).includes(event)) continue
2182
-
2183
- const parsed = parseModelHookValue(member.type, sourceFile)
2184
- if (parsed !== null) hooks[event] = parsed
2185
- }
2186
- return hooks
2187
- }
2188
-
2189
- function parseModelHookValue(
2190
- node: ts.TypeNode,
2191
- sourceFile: ts.SourceFile,
2192
- ): ParsedModelHook | null {
2193
- const literal = literalStringType(node)
2194
- if (literal !== null) {
2195
- return literal.trim().length > 0 ? { function: literal } : null
2196
- }
2197
- if (!ts.isTypeLiteralNode(node)) return null
2198
-
2199
- let fn: string | undefined
2200
- let timeout: number | undefined
2201
- let onUnavailable: "reject" | "log" | undefined
2202
-
2203
- for (const member of node.members) {
2204
- if (!ts.isPropertySignature(member) || !member.type) continue
2205
- const key = getPropertyName(member.name)
2206
- if (key === "function") {
2207
- const value = literalStringType(member.type)
2208
- if (value !== null && value.trim().length > 0) fn = value
2209
- } else if (key === "timeout") {
2210
- timeout = parseNumericTypeArg(member.type, sourceFile)
2211
- } else if (key === "onUnavailable") {
2212
- const value = literalStringType(member.type)
2213
- if (value === "reject" || value === "log") onUnavailable = value
2214
- }
2215
- }
2216
-
2217
- if (fn === undefined) return null
2218
- return {
2219
- function: fn,
2220
- ...(timeout !== undefined && { timeout }),
2221
- ...(onUnavailable !== undefined && { onUnavailable }),
2222
- }
2223
- }
2224
-
2225
- function parseModelIndexes(
2226
- metaArg: ts.TypeNode | undefined,
2227
- sourceFile: ts.SourceFile,
2228
- fields: Record<string, FieldAstV2>,
2229
- ): unknown[] {
2230
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return []
2231
-
2232
- const indexesProp = metaArg.members.find(
2233
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "indexes",
2234
- )
2235
- if (
2236
- !indexesProp ||
2237
- !ts.isPropertySignature(indexesProp) ||
2238
- !indexesProp.type ||
2239
- !ts.isTupleTypeNode(indexesProp.type)
2240
- ) {
2241
- return []
2242
- }
2243
-
2244
- const indexes: unknown[] = []
2245
- for (const element of indexesProp.type.elements) {
2246
- if (!ts.isTypeLiteralNode(element)) continue
2247
- const indexDef: Record<string, unknown> = { using: "btree", unique: false }
2248
- for (const member of element.members) {
2249
- if (!ts.isPropertySignature(member) || !member.type) continue
2250
- const key = getPropertyName(member.name)
2251
- if (!key) continue
2252
- if (key === "name" && ts.isLiteralTypeNode(member.type) && ts.isStringLiteral(member.type.literal)) {
2253
- indexDef.name = member.type.literal.text
2254
- } else if (key === "unique" && isBooleanLiteralType(member.type, true)) {
2255
- indexDef.unique = true
2256
- } else if (key === "fields" && ts.isTupleTypeNode(member.type)) {
2257
- indexDef.fields = member.type.elements
2258
- .map((fieldNode) => {
2259
- if (!ts.isLiteralTypeNode(fieldNode) || !ts.isStringLiteral(fieldNode.literal)) return null
2260
- return resolveIndexFieldName(fieldNode.literal.text, fields)
2261
- })
2262
- .filter((field): field is string => field !== null)
2263
- }
2264
- }
2265
- if (Array.isArray(indexDef.fields) && indexDef.fields.length > 0) {
2266
- indexes.push(indexDef)
2267
- }
2268
- }
2269
- return indexes
2270
- }
2271
-
2272
- function resolveIndexFieldName(fieldName: string, fields: Record<string, FieldAstV2>): string | null {
2273
- if (fields[fieldName] !== undefined) {
2274
- const field = fields[fieldName]
2275
- if (field.kind === "relation" && field.annotations?.db?.foreignKey) {
2276
- return field.annotations.db.foreignKey as string
2277
- }
2278
- return fieldName
2279
- }
2280
- return fieldName
2281
- }
2282
-
2283
- /**
2284
- * Resolve an `access:` annotation to its rule object.
2285
- *
2286
- * `access` may be written inline (`access: { read: Public }`) or factored into a
2287
- * shared type alias (`access: CmsPublicReadAdminWrite`), the latter is the
2288
- * natural way to reuse one policy set across many models, so it has to resolve
2289
- * through aliases and intersections, not just literals.
2290
- *
2291
- * Anything unresolvable throws. Returning `{}` here means "no access rules",
2292
- * which the differ treats as "emit no RLS policies", so a typo or an
2293
- * unsupported shape silently published a table with no row-level protection at
2294
- * all. Failing the extract is the only safe outcome.
2295
- */
2296
- /**
2297
- * Nodes that parse but that the engine's RLS renderer does not know.
2298
- *
2299
- * `Length`, `ItemCount` and `Matches` exist for `constraints`, and they share a parser with access
2300
- * rules because a constraint *is* an access rule with a narrower operand set. That reuse runs both
2301
- * ways: nothing stops someone writing `Gte<Length<"title">, Literal<5>>` in an `access` block, where
2302
- * it would parse cleanly, reach an engine that has no case for it, and produce a policy that does
2303
- * not say what the author wrote. Refusing here keeps the sharing honest until the RLS renderer
2304
- * learns them.
2305
- */
2306
- const CONSTRAINT_ONLY_NODES = new Set(["length", "itemCount", "matches"])
2307
-
2308
- function assertAccessRuleIsRenderable(node: unknown, model: string, operation: string): void {
2309
- if (Array.isArray(node)) {
2310
- for (const item of node) assertAccessRuleIsRenderable(item, model, operation)
2311
- return
2312
- }
2313
- if (typeof node !== "object" || node === null) return
2314
-
2315
- const record = node as Record<string, unknown>
2316
- // Operands are tagged `kind`, rules `type`, so both are checked: `Matches` is a rule.
2317
- const tag = [record["kind"], record["type"]].find(
2318
- (value) => typeof value === "string" && CONSTRAINT_ONLY_NODES.has(value),
2319
- )
2320
- if (typeof tag === "string") {
2321
- const spelled = { length: "Length", itemCount: "ItemCount", matches: "Matches" }[tag] ?? tag
2322
- throw new Error(
2323
- `Model "${model}": \`${spelled}<>\` is not supported in an \`access\` rule (\`${operation}\`). ` +
2324
- "It belongs in `constraints`, which the database enforces for every writer.",
2325
- )
2326
- }
2327
- for (const value of Object.values(record)) {
2328
- assertAccessRuleIsRenderable(value, model, operation)
2329
- }
2330
- }
2331
-
2332
- function parseModelAccess(
2333
- metaArg: ts.TypeNode | undefined,
2334
- sourceFile: ts.SourceFile,
2335
- modelName: string,
2336
- fields: Record<string, FieldAstV2>,
2337
- resolveCtx: ResolveContext,
2338
- ): Record<string, unknown> {
2339
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2340
- const accessProp = metaArg.members.find(
2341
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "access",
2342
- )
2343
- if (!accessProp || !ts.isPropertySignature(accessProp) || !accessProp.type) {
2344
- return {}
2345
- }
2346
-
2347
- const literal = resolveAccessLiteral(accessProp.type, sourceFile, resolveCtx)
2348
- if (!literal) {
2349
- throw new Error(
2350
- `Model "${modelName}": could not resolve its \`access\` rules from ` +
2351
- `\`${accessProp.type.getText(sourceFile)}\`.\n` +
2352
- ` access must be an object type, or a type alias for one:\n` +
2353
- ` export type PublicReadAdminWrite = { read: Public; create: Role<"admin"> }\n` +
2354
- ` A \`const … as const\` value cannot be used here, access is read from types, and\n` +
2355
- ` rule names like Public / Role are types, not values.\n` +
2356
- ` Refusing to continue: an unresolved access block would publish this table with no RLS.`,
2357
- )
2358
- }
2359
-
2360
- const access: Record<string, unknown> = {}
2361
- for (const member of literal.members) {
2362
- if (!ts.isPropertySignature(member) || !member.type) continue
2363
- const key = getPropertyName(member.name)
2364
- if (!key) continue
2365
-
2366
- // `update: { using, check }` splits which rows may be changed from what they
2367
- // may be changed into. Flattened here into the two AST fields the engine
2368
- // renders, so the engine never has to know about the sugar.
2369
- if (key === "update") {
2370
- const split = parseUpdateSplit(member.type, sourceFile, resolveCtx)
2371
- if (split) {
2372
- access["update"] = split.using
2373
- if (split.check !== undefined) access["updateCheck"] = split.check
2374
- continue
2375
- }
2376
- }
2377
-
2378
- if (key === "fields") {
2379
- const fieldRules = parseFieldAccess(member.type, sourceFile, modelName, fields, resolveCtx)
2380
- if (Object.keys(fieldRules).length > 0) access["fields"] = fieldRules
2381
- continue
2382
- }
2383
-
2384
- const rule = parseAccessRule(member.type, sourceFile, resolveCtx)
2385
- assertAccessRuleIsRenderable(rule, modelName, key)
2386
- access[key] = rule
2387
- }
2388
-
2389
- if (Object.keys(access).length === 0) {
2390
- throw new Error(
2391
- `Model "${modelName}": \`access\` resolved to an empty rule set ` +
2392
- `(from \`${accessProp.type.getText(sourceFile)}\`). Remove \`access\` if the table is ` +
2393
- `intentionally unrestricted, or declare at least one of read/create/update/delete.`,
2394
- )
2395
- }
2396
- return access
2397
- }
2398
-
2399
- /**
2400
- * `fields: { [column]: { read?, write? } }`, per-column narrowing of the table rules.
2401
- *
2402
- * Any rule the DSL can express is allowed. Enforcement is a query rewrite that
2403
- * evaluates the rule per row with the caller's claims, so ownership, membership and
2404
- * application roles all work here, none of which a column privilege could express.
2405
- */
2406
- function parseFieldAccess(
2407
- typeNode: ts.TypeNode,
2408
- sourceFile: ts.SourceFile,
2409
- modelName: string,
2410
- fields: Record<string, FieldAstV2>,
2411
- resolveCtx?: ResolveContext,
2412
- ): Record<string, Record<string, unknown>> {
2413
- const literal = resolveCtx
2414
- ? resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
2415
- : ts.isTypeLiteralNode(typeNode)
2416
- ? typeNode
2417
- : null
2418
- if (!literal) {
2419
- throw new Error(
2420
- `Model "${modelName}": could not resolve \`access.fields\` from ` +
2421
- `\`${typeNode.getText(sourceFile)}\`. It must be an object type, or a type ` +
2422
- `alias for one: \`fields: { salary: { read: Private } }\`.`,
2423
- )
2424
- }
2425
-
2426
- const out: Record<string, Record<string, unknown>> = {}
2427
- for (const member of literal.members) {
2428
- if (!ts.isPropertySignature(member) || !member.type) continue
2429
- const declared = getPropertyName(member.name)
2430
- if (!declared) continue
2431
- // A privilege is granted on a column, and a relation field is not one --
2432
- // `author` is stored as `author_id`. Same mapping the index builder uses.
2433
- // Names that match nothing are passed through rather than rejected: composite
2434
- // wrappers expand into columns this map never sees, so a hard error here would
2435
- // refuse valid schemas. Postgres rejects the unknown column at push instead.
2436
- const column = resolveIndexFieldName(declared, fields) ?? declared
2437
-
2438
- const columnLiteral = resolveCtx
2439
- ? resolveAccessLiteral(member.type, sourceFile, resolveCtx)
2440
- : ts.isTypeLiteralNode(member.type)
2441
- ? member.type
2442
- : null
2443
- if (!columnLiteral) {
2444
- throw new Error(
2445
- `Model "${modelName}": \`access.fields.${column}\` must be an object with ` +
2446
- `\`read\` and/or \`write\`, found \`${member.type.getText(sourceFile)}\`.`,
2447
- )
2448
- }
2449
-
2450
- const rules: Record<string, unknown> = {}
2451
- for (const opMember of columnLiteral.members) {
2452
- if (!ts.isPropertySignature(opMember) || !opMember.type) continue
2453
- const operation = getPropertyName(opMember.name)
2454
- if (operation !== "read" && operation !== "write") {
2455
- throw new Error(
2456
- `Model "${modelName}": \`access.fields.${column}\` may only contain ` +
2457
- `\`read\` and \`write\`, found "${operation}".`,
2458
- )
2459
- }
2460
- rules[operation] = parseAccessRule(opMember.type, sourceFile, resolveCtx)
2461
- }
2462
-
2463
- // An empty `{}` reads as "this column is restricted" but restricts nothing.
2464
- if (Object.keys(rules).length === 0) {
2465
- throw new Error(
2466
- `Model "${modelName}": \`access.fields.${column}\` declares no rules. ` +
2467
- `Give it a \`read\` or a \`write\`, or remove the entry.`,
2468
- )
2469
- }
2470
- out[column] = rules
2471
- }
2472
- return out
2473
- }
2474
-
2475
- /**
2476
- * `update: { using: …, check: … }`, or null when `update` is a plain rule.
2477
- *
2478
- * An update policy has two halves: `USING` picks which existing rows may be
2479
- * modified, `WITH CHECK` constrains what they may become. One rule for both is the
2480
- * right default and what every existing schema means, but it makes "an editor may
2481
- * move a post between their own sites" inexpressible, because the row they are
2482
- * changing and the row they are changing it into are judged by the same predicate.
2483
- */
2484
- function parseUpdateSplit(
2485
- typeNode: ts.TypeNode,
2486
- sourceFile: ts.SourceFile,
2487
- resolveCtx?: ResolveContext,
2488
- ): { using: Record<string, unknown>; check?: Record<string, unknown> } | null {
2489
- const literal = resolveCtx
2490
- ? resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
2491
- : ts.isTypeLiteralNode(typeNode)
2492
- ? typeNode
2493
- : null
2494
- if (!literal) return null
2495
-
2496
- let using: ts.TypeNode | undefined
2497
- let check: ts.TypeNode | undefined
2498
- for (const member of literal.members) {
2499
- if (!ts.isPropertySignature(member) || !member.type) continue
2500
- const name = getPropertyName(member.name)
2501
- if (name === "using") using = member.type
2502
- else if (name === "check") check = member.type
2503
- else if (name !== undefined) {
2504
- throw new Error(
2505
- `\`update\` may only contain \`using\` and \`check\`, found "${name}".`,
2506
- )
2507
- }
2508
- }
2509
-
2510
- // Not the split form at all, an object with neither key is some other shape.
2511
- if (!using && !check) return null
2512
- if (!using) {
2513
- throw new Error(
2514
- "`update: { check }` needs a `using` rule too, without it no row is " +
2515
- "selectable for update, so the check can never apply.",
2516
- )
2517
- }
2518
-
2519
- const parsed: { using: Record<string, unknown>; check?: Record<string, unknown> } = {
2520
- using: parseAccessRule(using, sourceFile, resolveCtx),
2521
- }
2522
- if (check) parsed.check = parseAccessRule(check, sourceFile, resolveCtx)
2523
- return parsed
2524
- }
2525
-
2526
- /** Walk aliases/intersections down to the object type holding the access rules. */
2527
- function resolveAccessLiteral(
2528
- typeNode: ts.TypeNode,
2529
- sourceFile: ts.SourceFile,
2530
- resolveCtx: ResolveContext,
2531
- depth = 0,
2532
- ): ts.TypeLiteralNode | null {
2533
- if (depth > 16) return null
2534
- if (ts.isTypeLiteralNode(typeNode)) return typeNode
2535
-
2536
- if (ts.isIntersectionTypeNode(typeNode)) {
2537
- const members: ts.TypeElement[] = []
2538
- for (const part of typeNode.types) {
2539
- const resolved = resolveAccessLiteral(part, sourceFile, resolveCtx, depth + 1)
2540
- if (!resolved) return null
2541
- members.push(...resolved.members)
2542
- }
2543
- return ts.factory.createTypeLiteralNode(members)
2544
- }
2545
-
2546
- if (ts.isTypeReferenceNode(typeNode)) {
2547
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
2548
- if (expanded) return resolveAccessLiteral(expanded, sourceFile, resolveCtx, depth + 1)
2549
- }
2550
-
2551
- if (needsChecker(typeNode)) {
2552
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
2553
- if (resolved !== typeNode) {
2554
- return resolveAccessLiteral(resolved, sourceFile, resolveCtx, depth + 1)
2555
- }
2556
- }
2557
-
2558
- return null
2559
- }
2560
-
2561
- /**
2562
- * `access` rules may be declared in a different file from the model (a shared
2563
- * alias), and `getText(file)` reads the given file's text at the node's offsets
2564
- *- so passing the model's file for a node owned by another one yielded garbage
2565
- * and every rule silently fell through to `private`. Always read a node's text
2566
- * from the file that actually owns it.
2567
- */
2568
- function ownerText(node: ts.Node, fallback: ts.SourceFile): string {
2569
- const own = node.pos >= 0 ? node.getSourceFile() : undefined
2570
- return node.getText(own ?? fallback)
2571
- }
2572
-
2573
- function parseAccessRule(
2574
- typeNode: ts.TypeNode,
2575
- sourceFile: ts.SourceFile,
2576
- resolveCtx?: ResolveContext,
2577
- depth = 0,
2578
- ): Record<string, unknown> {
2579
- // Reuse a single rule from a shared set: `access: { read: Rules["read"] }`.
2580
- if (ts.isIndexedAccessTypeNode(typeNode) && resolveCtx) {
2581
- const member = resolveIndexedAccessRule(typeNode, sourceFile, resolveCtx)
2582
- if (member) return parseAccessRule(member, sourceFile, resolveCtx)
2583
- throw new Error(
2584
- `Could not resolve access rule from \`${ownerText(typeNode, sourceFile)}\`. ` +
2585
- `Reference a rule set member as \`Rules["read"]\`, where Rules is a type alias.`,
2586
- )
2587
- }
2588
-
2589
- if (!ts.isTypeReferenceNode(typeNode)) return { type: "private" }
2590
-
2591
- // `Rules.read` is a qualified name (namespace lookup), not a member of a type
2592
- // alias: TypeScript rejects it, and it used to fall through to `private`,
2593
- // silently denying an operation the author meant to grant.
2594
- if (ts.isQualifiedName(typeNode.typeName)) {
2595
- const text = ownerText(typeNode.typeName, sourceFile)
2596
- const [head, ...rest] = text.split(".")
2597
- throw new Error(
2598
- `Access rule \`${text}\` is not valid: a member of a rule-set type must be written ` +
2599
- `\`${head}["${rest.join(".")}"]\`, not \`${text}\`.`,
2600
- )
2601
- }
2602
-
2603
- const ref = ownerText(typeNode.typeName, sourceFile)
2604
- switch (ref) {
2605
- case "Public":
2606
- case "BucketPublic":
2607
- return { type: "public" }
2608
- case "LoggedIn":
2609
- case "BucketLoggedIn":
2610
- return { type: "authenticated" }
2611
- case "Private":
2612
- case "BucketPrivate":
2613
- return { type: "private" }
2614
- case "BucketOwner":
2615
- return { type: "owner", field: "owner_id" }
2616
- case "Owner": {
2617
- const args = typeNode.typeArguments ?? []
2618
- const keyArg = args.length >= 2 ? args[1] : args[0]
2619
- // Must match engine `AccessRule::Owner { field }` (see supatype-schema-engine parser/ast.rs).
2620
- return {
2621
- type: "owner",
2622
- field: keyArg ? ownerText(keyArg, sourceFile).replace(/['"]/g, "") : "user_id",
2623
- }
2624
- }
2625
- case "OwnerFrom": {
2626
- const relationArg = typeNode.typeArguments?.[0]
2627
- const relationField = relationArg
2628
- ? ownerText(relationArg, sourceFile).replace(/['"]/g, "")
2629
- : "owner"
2630
- return { type: "owner", field: relationField }
2631
- }
2632
- case "Role":
2633
- case "BucketRole": {
2634
- const roleArg = typeNode.typeArguments?.[0]
2635
- return {
2636
- type: "role",
2637
- roles: [roleArg ? ownerText(roleArg, sourceFile).replace(/['"]/g, "") : "admin"],
2638
- }
2639
- }
2640
- case "Any": {
2641
- const listArg = typeNode.typeArguments?.[0]
2642
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2643
- throw new Error(
2644
- `\`Any<>\` takes a tuple of rules, as in ` +
2645
- `\`Any<[Role<"admin">, Owner<"author_id">]>\`.`,
2646
- )
2647
- }
2648
- // An empty list would compile to a policy that grants nothing while
2649
- // reading like a grant, the exact silent-denial failure the unknown-rule
2650
- // branch below exists to prevent.
2651
- if (listArg.elements.length === 0) {
2652
- throw new Error(
2653
- "`Any<[]>` grants nothing. List the rules that should allow access, or " +
2654
- "use `Private` if denying is the intent.",
2655
- )
2656
- }
2657
- return {
2658
- type: "any",
2659
- rules: listArg.elements.map((element) =>
2660
- parseAccessRule(element, sourceFile, resolveCtx),
2661
- ),
2662
- }
2663
- }
2664
- case "All": {
2665
- const listArg = typeNode.typeArguments?.[0]
2666
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2667
- throw new Error(
2668
- '`All<>` takes a tuple of rules, as in `All<[Role<"editor">, NotNull<"published_at">]>`.',
2669
- )
2670
- }
2671
- // Unlike `Any<[]>`, an empty `All` grants *everything*, an empty AND is
2672
- // true. Reading as a restriction while imposing none is worse than an error.
2673
- if (listArg.elements.length === 0) {
2674
- throw new Error(
2675
- "`All<[]>` restricts nothing and grants everything. List the rules that " +
2676
- "must hold, or use `Public` if that is the intent.",
2677
- )
2678
- }
2679
- return {
2680
- type: "all",
2681
- rules: listArg.elements.map((element) =>
2682
- parseAccessRule(element, sourceFile, resolveCtx),
2683
- ),
2684
- }
2685
- }
2686
- case "Not": {
2687
- const inner = typeNode.typeArguments?.[0]
2688
- if (!inner) {
2689
- throw new Error('`Not<>` takes one rule, as in `Not<Role<"banned">>`.')
2690
- }
2691
- return { type: "not", rule: parseAccessRule(inner, sourceFile, resolveCtx) }
2692
- }
2693
- case "Eq":
2694
- case "Neq":
2695
- case "Gt":
2696
- case "Gte":
2697
- case "Lt":
2698
- case "Lte":
2699
- case "Like": {
2700
- const args = typeNode.typeArguments ?? []
2701
- if (args.length !== 2) {
2702
- throw new Error(
2703
- `\`${ref}<>\` takes two operands, as in \`${ref}<"author_id", AuthUid>\`.`,
2704
- )
2705
- }
2706
- return {
2707
- type: "compare",
2708
- op: ref.toLowerCase(),
2709
- left: parseAccessOperand(args[0]!, sourceFile),
2710
- right: parseAccessOperand(args[1]!, sourceFile),
2711
- }
2712
- }
2713
- case "Matches": {
2714
- const args = typeNode.typeArguments ?? []
2715
- if (args.length !== 2) {
2716
- throw new Error(
2717
- '`Matches<>` takes a column and a pattern, as in `Matches<"sku", "^[A-Z]{3}$">`.',
2718
- )
2719
- }
2720
- const column = stringLiteralArg(args[0], "Matches", "column")
2721
- const pattern = literalStringType(args[1] as ts.TypeNode)
2722
- if (pattern === null) {
2723
- throw new Error(
2724
- '`Matches<>` needs a string literal pattern, as in `Matches<"sku", "^[A-Z]{3}$">`.',
2725
- )
2726
- }
2727
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) {
2728
- throw new Error(`\`Matches<"${column}", ...>\` does not name a valid column.`)
2729
- }
2730
- // Validated here so an unparseable pattern is a CLI error naming the field, rather than a
2731
- // Postgres error part way through a migration. Postgres regex is POSIX and JavaScript's is
2732
- // not, so this catches malformed patterns, not every dialect difference.
2733
- try {
2734
- new RegExp(pattern)
2735
- } catch {
2736
- throw new Error(
2737
- `\`Matches<"${column}", "${pattern}">\`: the pattern is not a valid regular expression.`,
2738
- )
2739
- }
2740
- return { type: "matches", column, pattern }
2741
- }
2742
- case "IsNull":
2743
- case "NotNull": {
2744
- const operand = typeNode.typeArguments?.[0]
2745
- if (!operand) {
2746
- throw new Error(`\`${ref}<>\` takes one operand, as in \`${ref}<"deleted_at">\`.`)
2747
- }
2748
- return {
2749
- type: "nullCheck",
2750
- operand: parseAccessOperand(operand, sourceFile),
2751
- isNull: ref === "IsNull",
2752
- }
2753
- }
2754
- case "Exists": {
2755
- const source = typeNode.typeArguments?.[0]
2756
- if (!source) {
2757
- throw new Error('`Exists<>` takes a source, as in `Exists<MySites>`.')
2758
- }
2759
- return {
2760
- type: "exists",
2761
- source: parseMembershipSource(source, sourceFile, resolveCtx),
2762
- }
2763
- }
2764
- case "In": {
2765
- const args = typeNode.typeArguments ?? []
2766
- if (args.length !== 2) {
2767
- throw new Error(
2768
- '`In<>` takes a column and a source, as in `In<"site_id", MySites>`.',
2769
- )
2770
- }
2771
- const column = parseAccessOperand(args[0]!, sourceFile)
2772
- if (column["kind"] !== "column") {
2773
- throw new Error(
2774
- "`In<>`'s first argument must be a column name, the membership test is " +
2775
- "about a column of the row being checked.",
2776
- )
2777
- }
2778
- return {
2779
- type: "in",
2780
- column: column["name"],
2781
- source: parseMembershipSource(args[1]!, sourceFile, resolveCtx),
2782
- }
2783
- }
2784
- default: {
2785
- // A named alias: possibly parameterised, standing for a rule. Expanded
2786
- // before giving up, so `SiteAccess<"site_id">` works.
2787
- if (resolveCtx && depth < 16) {
2788
- const expanded = resolveAccessAliasNode(typeNode, sourceFile, resolveCtx)
2789
- if (expanded) return parseAccessRule(expanded, sourceFile, resolveCtx, depth + 1)
2790
- }
2791
-
2792
- // Falling back to `private` here would silently deny an operation the
2793
- // author believed they had granted, and with deny-by-default there is no
2794
- // longer any need for a permissive guess. Name the offending rule instead.
2795
- throw new Error(
2796
- `Unknown access rule "${ref}". Supported: Public, Private, LoggedIn, ` +
2797
- `Owner<"field">, OwnerFrom<"relation">, Role<"name">, ` +
2798
- `Any<[rule, …]>, All<[rule, …]>, Not<rule>, ` +
2799
- `Eq/Neq/Gt/Gte/Lt/Lte/Like<left, right>, IsNull<operand>, NotNull<operand>` +
2800
- ` (buckets also accept BucketPublic, BucketPrivate, BucketLoggedIn, BucketOwner, BucketRole).`,
2801
- )
2802
- }
2803
- }
2804
- }
2805
-
2806
- /**
2807
- * Expands a named alias to the type it stands for.
2808
- *
2809
- * This is what makes rules parameterisable, the type-level equivalent of
2810
- * Payload's access-control factory:
2811
- *
2812
- * ```typescript
2813
- * type SiteAccess<F extends string> = Any<[Role<"admin">, In<F, MySites>]>
2814
- * access: { update: SiteAccess<"site_id"> }
2815
- * ```
2816
- *
2817
- * Without it a rule had to be written inline at every use, and any alias, even an
2818
- * unparameterised one: was reported as an unknown rule.
2819
- */
2820
- function resolveAccessAliasNode(
2821
- typeNode: ts.TypeReferenceNode,
2822
- sourceFile: ts.SourceFile,
2823
- resolveCtx: ResolveContext,
2824
- ): ts.TypeNode | undefined {
2825
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
2826
- if (expanded && expanded !== typeNode) return expanded
2827
-
2828
- if (needsChecker(typeNode)) {
2829
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
2830
- if (resolved !== typeNode) return resolved
2831
- }
2832
- return undefined
2833
- }
2834
-
2835
- /**
2836
- * The set on the right of an `In<>`.
2837
- *
2838
- * Resolved through the same alias machinery as rules, so a shared
2839
- * `type MySites = Rows<…>` can be reused across models, the parameterisation the
2840
- * plan calls the type-level equivalent of Payload's access factory.
2841
- */
2842
- function parseMembershipSource(
2843
- typeNode: ts.TypeNode,
2844
- sourceFile: ts.SourceFile,
2845
- resolveCtx?: ResolveContext,
2846
- ): Record<string, unknown> {
2847
- if (ts.isIndexedAccessTypeNode(typeNode) && resolveCtx) {
2848
- const member = resolveIndexedAccessRule(typeNode, sourceFile, resolveCtx)
2849
- if (member) return parseMembershipSource(member, sourceFile, resolveCtx)
2850
- }
2851
-
2852
- if (ts.isTypeReferenceNode(typeNode) && !ts.isQualifiedName(typeNode.typeName)) {
2853
- const ref = ownerText(typeNode.typeName, sourceFile)
2854
- const args = typeNode.typeArguments ?? []
2855
-
2856
- if (ref === "Claim") {
2857
- return parseAccessOperand(typeNode, sourceFile)
2858
- }
2859
-
2860
- if (ref === "Rows") {
2861
- const table = stringLiteralArg(args[0], "Rows", "table name")
2862
- const column = stringLiteralArg(args[1], "Rows", "column name")
2863
- const source: Record<string, unknown> = { kind: "rows", table, column }
2864
- // The third argument narrows the source rows. Absent means "every row",
2865
- // which is a lookup rather than a membership check, allowed, but rarely
2866
- // what was meant, so it stays explicit rather than being defaulted.
2867
- if (args[2]) {
2868
- source["where"] = parseAccessRule(args[2], sourceFile, resolveCtx)
2869
- }
2870
- return source
2871
- }
2872
-
2873
- if (ref === "Values") {
2874
- const listArg = args[0]
2875
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2876
- throw new Error('`Values<>` takes a tuple, as in `Values<["draft", "review"]>`.')
2877
- }
2878
- if (listArg.elements.length === 0) {
2879
- throw new Error("`Values<[]>` matches nothing. List the values, or use `Private`.")
2880
- }
2881
- // Not `parseAccessOperand`: there, a bare string is a *column*, which is
2882
- // right for a comparison and wrong here. Inside a value list a string can
2883
- // only be a value, so it is read as one, no `Literal<>` wrapper needed.
2884
- return {
2885
- kind: "literal",
2886
- values: listArg.elements.map((element) => literalFromNode(element, sourceFile)),
2887
- }
2888
- }
2889
-
2890
- // A named alias for a source: `type MySites = Rows<…>`.
2891
- if (resolveCtx) {
2892
- const resolved = resolveAccessAliasNode(typeNode, sourceFile, resolveCtx)
2893
- if (resolved) return parseMembershipSource(resolved, sourceFile, resolveCtx)
2894
- }
2895
- }
2896
-
2897
- throw new Error(
2898
- `\`${ownerText(typeNode, sourceFile)}\` is not a valid membership source. Use ` +
2899
- `Rows<"table", "column", Where>, Claim<"path"> or Values<[…]>.`,
2900
- )
2901
- }
2902
-
2903
- /** Interval units, matching `TimeUnit` in `@supatype/types` and the engine. */
2904
- const TIME_UNITS = [
2905
- "seconds",
2906
- "minutes",
2907
- "hours",
2908
- "days",
2909
- "weeks",
2910
- "months",
2911
- "years",
2912
- ] as const
2913
-
2914
- /** Granularities for `StartOf<>`. */
2915
- const TRUNC_UNITS = ["day", "week", "month", "year"] as const
2916
-
2917
- /**
2918
- * `After<Base, { days: 30, hours: 9 }>` / `Before<...>`: a point in time plus or minus a
2919
- * multi-unit duration.
2920
- *
2921
- * The interval is re-assembled from parsed integers and matched keywords, exactly as
2922
- * `parseDurationOperand` does, so no author-supplied text reaches Postgres. A permissive
2923
- * `"30 days 9 hours"` string would be raw SQL by another name.
2924
- *
2925
- * Direction is in the operand name rather than the sign of a component, which is the rule
2926
- * `Ago`/`FromNow` already follow: a negative amount is refused with a message naming the
2927
- * opposite operand, because relying on a double negative reads wrongly.
2928
- */
2929
- function parseOffsetOperand(
2930
- ref: "After" | "Before",
2931
- args: readonly ts.TypeNode[],
2932
- sourceFile: ts.SourceFile,
2933
- ): Record<string, unknown> {
2934
- if (args.length !== 2) {
2935
- throw new Error(
2936
- `\`${ref}<>\` takes a base and an interval, as in ` +
2937
- `\`${ref}<StartOf<"day">, { days: 30, hours: 9 }>\`.`,
2938
- )
2939
- }
2940
-
2941
- const base = parseAccessOperand(args[0]!, sourceFile)
2942
- const baseKind = typeof base["kind"] === "string" ? base["kind"] : ""
2943
- if (baseKind !== "now" && baseKind !== "startOf") {
2944
- throw new Error(
2945
- `\`${ref}<>\` measures from a point in time, so its base must be \`Now\` or ` +
2946
- `\`StartOf<unit>\`. A column or a claim depends on the row or the caller and ` +
2947
- `cannot be offset.`,
2948
- )
2949
- }
2950
-
2951
- const intervalNode = args[1]!
2952
- if (!ts.isTypeLiteralNode(intervalNode)) {
2953
- throw new Error(
2954
- `\`${ref}<>\` takes the interval as an object, as in \`{ days: 30, hours: 9 }\`.`,
2955
- )
2956
- }
2957
-
2958
- const opposite = ref === "After" ? "Before" : "After"
2959
- const interval: Record<string, number> = {}
2960
-
2961
- for (const member of intervalNode.members) {
2962
- if (!ts.isPropertySignature(member) || !member.name || !member.type) {
2963
- throw new Error(`\`${ref}<>\` interval members must be \`unit: amount\` pairs.`)
2964
- }
2965
- const unit = member.name.getText(sourceFile).replace(/["']/g, "")
2966
- if (!TIME_UNITS.includes(unit as (typeof TIME_UNITS)[number])) {
2967
- throw new Error(
2968
- `\`${unit}\` is not a unit of time. Use one of: ${TIME_UNITS.join(", ")} (plural).`,
2969
- )
2970
- }
2971
-
2972
- const amountNode = member.type
2973
- // A negative literal is a prefix-unary expression, not a numeric literal, so it has
2974
- // to be recognised separately or it is refused for the wrong reason and the message
2975
- // misses the real advice.
2976
- if (
2977
- ts.isLiteralTypeNode(amountNode) &&
2978
- ts.isPrefixUnaryExpression(amountNode.literal) &&
2979
- amountNode.literal.operator === ts.SyntaxKind.MinusToken
2980
- ) {
2981
- throw new Error(
2982
- `\`${ref}<>\` does not take a negative amount. For the other direction use ` +
2983
- `\`${opposite}<>\`, which reads correctly instead of relying on a double negative.`,
2984
- )
2985
- }
2986
- if (!ts.isLiteralTypeNode(amountNode) || !ts.isNumericLiteral(amountNode.literal)) {
2987
- throw new Error(`\`${unit}\` needs a number literal amount, as in \`{ ${unit}: 30 }\`.`)
2988
- }
2989
- const amount = Number(amountNode.literal.text)
2990
- if (!Number.isInteger(amount)) {
2991
- throw new Error(
2992
- `\`{ ${unit}: ${amount} }\` must be a whole number of units: Postgres intervals ` +
2993
- `take integers, so a fraction would be silently truncated or rejected.`,
2994
- )
2995
- }
2996
- if (unit in interval) {
2997
- throw new Error(`\`${ref}<>\` names \`${unit}\` twice; give each unit once.`)
2998
- }
2999
- interval[unit] = amount
3000
- }
3001
-
3002
- // An all-zero interval means the base unchanged, which is never what an author wrote.
3003
- // The engine refuses it too, but saying so here names the operand at the point it was
3004
- // written rather than at push.
3005
- if (Object.values(interval).every((amount) => amount === 0)) {
3006
- throw new Error(
3007
- `\`${ref}<>\` was given an empty interval, which means the base unchanged. ` +
3008
- `Give at least one non-zero unit, as in \`{ days: 30 }\`.`,
3009
- )
3010
- }
3011
-
3012
- return { kind: ref === "After" ? "after" : "before", base, interval }
3013
- }
3014
-
3015
- /**
3016
- * `Ago<30, "days">` / `FromNow<7, "days">`.
3017
- *
3018
- * The amount and unit are validated here and the interval is re-assembled from the
3019
- * parsed integer and the matched keyword, so no author-supplied text reaches
3020
- * Postgres. That is what keeps this from being a small escape hatch: a permissive
3021
- * `"30 days"` string would be raw SQL by another name.
3022
- */
3023
- function parseDurationOperand(
3024
- ref: "Ago" | "FromNow",
3025
- args: readonly ts.TypeNode[],
3026
- sourceFile: ts.SourceFile,
3027
- ): Record<string, unknown> {
3028
- if (args.length !== 2) {
3029
- throw new Error(`\`${ref}<>\` takes an amount and a unit, as in \`${ref}<30, "days">\`.`)
3030
- }
3031
-
3032
- const amountNode = args[0]!
3033
- const opposite = ref === "Ago" ? "FromNow" : "Ago"
3034
-
3035
- // A negative literal is a prefix-unary expression in the TypeScript AST, not a
3036
- // numeric literal, so it has to be recognised separately, otherwise `Ago<-5, …>`
3037
- // is refused for the wrong reason and the message misses the real advice.
3038
- if (
3039
- ts.isLiteralTypeNode(amountNode) &&
3040
- ts.isPrefixUnaryExpression(amountNode.literal) &&
3041
- amountNode.literal.operator === ts.SyntaxKind.MinusToken
3042
- ) {
3043
- throw new Error(
3044
- `\`${ref}<>\` does not take a negative amount. For the other direction use ` +
3045
- `\`${opposite}<>\`, which reads correctly instead of relying on a double negative.`,
3046
- )
3047
- }
3048
-
3049
- if (!ts.isLiteralTypeNode(amountNode) || !ts.isNumericLiteral(amountNode.literal)) {
3050
- throw new Error(`\`${ref}<>\` needs a number literal amount, as in \`${ref}<30, "days">\`.`)
3051
- }
3052
- const amount = Number(amountNode.literal.text)
3053
- if (!Number.isInteger(amount)) {
3054
- throw new Error(
3055
- `\`${ref}<${amount}, …>\` must be a whole number of units, Postgres intervals ` +
3056
- `take integers, so a fraction would be silently truncated or rejected.`,
3057
- )
3058
- }
3059
-
3060
- const unit = stringLiteralArg(args[1], ref, "unit")
3061
- if (!TIME_UNITS.includes(unit as (typeof TIME_UNITS)[number])) {
3062
- throw new Error(
3063
- `\`${ref}<${amount}, "${unit}">\` is not a valid unit. Use one of: ` +
3064
- `${TIME_UNITS.join(", ")} (plural).`,
3065
- )
3066
- }
3067
-
3068
- void sourceFile
3069
- return { kind: ref === "Ago" ? "ago" : "fromNow", amount, unit }
3070
- }
3071
-
3072
- /** A string, number or boolean literal as its plain JS value. */
3073
- function literalFromNode(
3074
- node: ts.TypeNode,
3075
- sourceFile: ts.SourceFile,
3076
- ): string | number | boolean {
3077
- if (ts.isLiteralTypeNode(node)) {
3078
- const literal = node.literal
3079
- if (ts.isStringLiteral(literal)) return literal.text
3080
- if (ts.isNumericLiteral(literal)) return Number(literal.text)
3081
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return true
3082
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return false
3083
- }
3084
- throw new Error(
3085
- `\`${ownerText(node, sourceFile)}\` is not a string, number or boolean literal.`,
3086
- )
3087
- }
3088
-
3089
- function stringLiteralArg(
3090
- node: ts.TypeNode | undefined,
3091
- owner: string,
3092
- what: string,
3093
- ): string {
3094
- if (!node || !ts.isLiteralTypeNode(node) || !ts.isStringLiteral(node.literal)) {
3095
- throw new Error(`\`${owner}<>\` needs a ${what} as a string literal.`)
3096
- }
3097
- const value = node.literal.text.trim()
3098
- // Rendered as a SQL identifier, so refuse anything that is not one.
3099
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
3100
- throw new Error(`"${value}" is not a valid ${what}.`)
3101
- }
3102
- return value
3103
- }
3104
-
3105
- /**
3106
- * One side of a comparison.
3107
- *
3108
- * A bare string literal is a **column** on the model the rule is attached to.
3109
- * That is the common case by a wide margin, and making it the default keeps
3110
- * `Eq<"author_id", AuthUid>` readable; a constant is written `Literal<"x">` so the
3111
- * two can never be confused. Numbers and booleans are unambiguous, so they are
3112
- * taken as constants directly.
3113
- */
3114
- function parseAccessOperand(
3115
- typeNode: ts.TypeNode,
3116
- sourceFile: ts.SourceFile,
3117
- ): Record<string, unknown> {
3118
- if (ts.isLiteralTypeNode(typeNode)) {
3119
- const literal = typeNode.literal
3120
- if (ts.isStringLiteral(literal)) {
3121
- const name = literal.text.trim()
3122
- if (name === "") {
3123
- throw new Error("An empty column name is not a valid operand.")
3124
- }
3125
- // Rendered into SQL as an identifier, so refuse anything that is not one
3126
- // rather than letting it through to the policy.
3127
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
3128
- throw new Error(
3129
- `"${name}" is not a valid column name. Use \`Literal<"${name}">\` for a ` +
3130
- `constant, or quote a real column.`,
3131
- )
3132
- }
3133
- return { kind: "column", name }
3134
- }
3135
- if (ts.isNumericLiteral(literal)) {
3136
- return { kind: "literal", value: Number(literal.text) }
3137
- }
3138
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return { kind: "literal", value: true }
3139
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return { kind: "literal", value: false }
3140
- }
3141
-
3142
- if (ts.isTypeReferenceNode(typeNode) && !ts.isQualifiedName(typeNode.typeName)) {
3143
- const ref = ownerText(typeNode.typeName, sourceFile)
3144
- const operandArgs = typeNode.typeArguments ?? []
3145
- switch (ref) {
3146
- case "Length":
3147
- case "ItemCount": {
3148
- const column = stringLiteralArg(operandArgs[0], ref, "column")
3149
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) {
3150
- throw new Error(`\`${ref}<"${column}">\` does not name a valid column.`)
3151
- }
3152
- return { kind: ref === "Length" ? "length" : "itemCount", column }
3153
- }
3154
- case "AuthUid":
3155
- return { kind: "authUid" }
3156
- case "AuthRole":
3157
- return { kind: "authRole" }
3158
- case "Now":
3159
- return { kind: "now" }
3160
- case "StartOf": {
3161
- const unit = stringLiteralArg(operandArgs[0], "StartOf", "unit")
3162
- if (!TRUNC_UNITS.includes(unit as (typeof TRUNC_UNITS)[number])) {
3163
- throw new Error(
3164
- `\`StartOf<"${unit}">\` is not a valid granularity. Use one of: ` +
3165
- `${TRUNC_UNITS.join(", ")}.`,
3166
- )
3167
- }
3168
- return { kind: "startOf", unit }
3169
- }
3170
- case "Ago":
3171
- case "FromNow":
3172
- return parseDurationOperand(ref, operandArgs, sourceFile)
3173
- case "After":
3174
- case "Before":
3175
- return parseOffsetOperand(ref, operandArgs, sourceFile)
3176
- case "Claim": {
3177
- const pathArg = typeNode.typeArguments?.[0]
3178
- if (!pathArg || !ts.isLiteralTypeNode(pathArg) || !ts.isStringLiteral(pathArg.literal)) {
3179
- throw new Error('`Claim<>` takes a dotted path literal, as in `Claim<"app_metadata.tier">`.')
3180
- }
3181
- const path = pathArg.literal.text.trim()
3182
- // The path is split on dots to walk the claims object, so an empty
3183
- // segment would silently look up a key that cannot exist.
3184
- if (path === "" || path.split(".").some((segment) => segment.trim() === "")) {
3185
- throw new Error(
3186
- `\`Claim<"${path}">\` is not a valid claim path, use dotted segments, ` +
3187
- `as in \`Claim<"app_metadata.tier">\`.`,
3188
- )
3189
- }
3190
- return { kind: "claim", path }
3191
- }
3192
- case "Literal": {
3193
- const valueArg = typeNode.typeArguments?.[0]
3194
- if (!valueArg || !ts.isLiteralTypeNode(valueArg)) {
3195
- throw new Error('`Literal<>` takes a string, number or boolean, as in `Literal<"published">`.')
3196
- }
3197
- const literal = valueArg.literal
3198
- if (ts.isStringLiteral(literal)) return { kind: "literal", value: literal.text }
3199
- if (ts.isNumericLiteral(literal)) return { kind: "literal", value: Number(literal.text) }
3200
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return { kind: "literal", value: true }
3201
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return { kind: "literal", value: false }
3202
- throw new Error('`Literal<>` takes a string, number or boolean.')
3203
- }
3204
- }
3205
- }
3206
-
3207
- throw new Error(
3208
- `\`${ownerText(typeNode, sourceFile)}\` is not a valid operand. Use a column name ` +
3209
- `("author_id"), AuthUid, AuthRole, Claim<"path"> or Literal<value>.`,
3210
- )
3211
- }
3212
-
3213
- interface ParsedRelationOptions {
3214
- required?: boolean
3215
- onDelete?: string
3216
- onUpdate?: string
3217
- through?: string
3218
- }
3219
-
3220
- function parseRelationOptions(
3221
- optsArg: ts.TypeNode | undefined,
3222
- sourceFile: ts.SourceFile,
3223
- ): ParsedRelationOptions {
3224
- const out: ParsedRelationOptions = {}
3225
- if (!optsArg || !ts.isTypeLiteralNode(optsArg)) return out
3226
-
3227
- for (const member of optsArg.members) {
3228
- if (!ts.isPropertySignature(member) || !member.name || !member.type) continue
3229
- const key = getPropertyName(member.name)
3230
- if (!key) continue
3231
-
3232
- if (key === "required" && isBooleanLiteralType(member.type, true)) {
3233
- out.required = true
3234
- continue
3235
- }
3236
-
3237
- if (
3238
- (key === "onDelete" || key === "onUpdate" || key === "through") &&
3239
- ts.isLiteralTypeNode(member.type) &&
3240
- ts.isStringLiteral(member.type.literal)
3241
- ) {
3242
- out[key] = member.type.literal.text
3243
- }
3244
- }
3245
-
3246
- return out
3247
- }
3248
-
3249
- function relationOptionsKernel(
3250
- opts: ParsedRelationOptions,
3251
- ): Pick<KernelFieldFacts, "required" | "onDelete" | "onUpdate" | "through"> {
3252
- return {
3253
- ...(opts.required === true && { required: true }),
3254
- ...(opts.onDelete !== undefined && { onDelete: opts.onDelete }),
3255
- ...(opts.onUpdate !== undefined && { onUpdate: opts.onUpdate }),
3256
- ...(opts.through !== undefined && { through: opts.through }),
3257
- }
3258
- }
3259
-
3260
- function parseNumericTypeArg(typeArg: ts.TypeNode | undefined, sourceFile: ts.SourceFile): number | undefined {
3261
- if (!typeArg) return undefined
3262
- if (ts.isLiteralTypeNode(typeArg) && ts.isNumericLiteral(typeArg.literal)) {
3263
- const value = Number(typeArg.literal.text)
3264
- return Number.isFinite(value) ? value : undefined
3265
- }
3266
- if (ts.isLiteralTypeNode(typeArg) && ts.isStringLiteral(typeArg.literal)) {
3267
- const value = Number(typeArg.literal.text)
3268
- return Number.isFinite(value) ? value : undefined
3269
- }
3270
- const raw = typeArg.getText(sourceFile).trim()
3271
- const value = Number(raw)
3272
- return Number.isFinite(value) ? value : undefined
3273
- }
3274
-
3275
- function mergeCheckConstraint(existing: string | undefined, next: string): string {
3276
- if (!existing) return next
3277
- return `(${existing}) AND (${next})`
3278
- }
3279
-
3280
- function relationTargetFromTypeArg(typeArg: ts.TypeNode | undefined, sourceFile: ts.SourceFile): string {
3281
- if (!typeArg) return "unknown"
3282
- const raw = typeArg.getText(sourceFile).replace(/\s/g, "")
3283
- if (raw === "SupatypeAuthUser") return "supatype:user"
3284
- return raw.replace(/\W/g, "")
3285
- }
3286
-
3287
- function toSnakeCase(s: string): string {
3288
- return s.replace(/([A-Z])/g, "_$1").replace(/^_/, "").toLowerCase()
3289
- }
3290
-
3291
- function relationForeignKeyFromField(fieldName: string): string {
3292
- const snake = fieldName
3293
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
3294
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
3295
- .toLowerCase()
3296
- const base = snake.replace(/_id$/i, "")
3297
- return `${base}_id`
3298
- }
3299
-
3300
- /** Resolve `Rules["read"]` to the rule type declared for that member. */
3301
- function resolveIndexedAccessRule(
3302
- node: ts.IndexedAccessTypeNode,
3303
- sourceFile: ts.SourceFile,
3304
- resolveCtx: ResolveContext,
3305
- ): ts.TypeNode | undefined {
3306
- const literal = resolveAccessLiteral(node.objectType, sourceFile, resolveCtx)
3307
- if (!literal) return undefined
3308
- if (!ts.isLiteralTypeNode(node.indexType) || !ts.isStringLiteral(node.indexType.literal)) {
3309
- return undefined
3310
- }
3311
- const key = node.indexType.literal.text
3312
- for (const member of literal.members) {
3313
- if (ts.isPropertySignature(member) && getPropertyName(member.name) === key) {
3314
- return member.type
3315
- }
3316
- }
3317
- return undefined
3318
- }
3319
-
3320
- // ─── cache declaration (P8, plan §13) ────────────────────────────────────────
3321
-
3322
- /** The parsed `cache` block. Absent entirely when the model declared none. */
3323
- export interface ParsedModelCache {
3324
- enabled?: boolean
3325
- maxTtl?: number
3326
- public?: boolean
3327
- rows?: boolean
3328
- }
3329
-
3330
- /**
3331
- * Parse `cache: { ... }` off a model's meta argument.
3332
- *
3333
- * Shaped like `parseModelHooks`, and travelling the same way: onto the route manifest beside
3334
- * `hooks`, not into `annotations.platform`. The schema engine re-serialises its own parsed AST
3335
- * (`serde_json::to_value(&ast)`), and `PlatformModelAnnotations` carries only `access` and
3336
- * `search_fields` with no catch-all, so a key placed there is silently dropped on the way to the
3337
- * server rather than riding through. Verified rather than assumed; see plan §13.1.
3338
- */
3339
- function parseModelCache(
3340
- metaArg: ts.TypeNode | undefined,
3341
- sourceFile: ts.SourceFile,
3342
- ): ParsedModelCache | undefined {
3343
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return undefined
3344
-
3345
- const prop = metaArg.members.find(
3346
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "cache",
3347
- )
3348
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return undefined
3349
- if (!ts.isTypeLiteralNode(prop.type)) return undefined
3350
-
3351
- const parsed: ParsedModelCache = {}
3352
- for (const member of prop.type.members) {
3353
- if (!ts.isPropertySignature(member) || !member.type) continue
3354
- switch (getPropertyName(member.name)) {
3355
- case "enabled":
3356
- if (isBooleanLiteralType(member.type, true)) parsed.enabled = true
3357
- else if (isBooleanLiteralType(member.type, false)) parsed.enabled = false
3358
- break
3359
- case "public":
3360
- if (isBooleanLiteralType(member.type, true)) parsed.public = true
3361
- else if (isBooleanLiteralType(member.type, false)) parsed.public = false
3362
- break
3363
- case "rows":
3364
- if (isBooleanLiteralType(member.type, true)) parsed.rows = true
3365
- else if (isBooleanLiteralType(member.type, false)) parsed.rows = false
3366
- break
3367
- case "maxTtl": {
3368
- const ttl = parseNumericTypeArg(member.type, sourceFile)
3369
- if (ttl !== undefined) parsed.maxTtl = ttl
3370
- break
3371
- }
3372
- }
3373
- }
3374
- // A `cache: {}` with nothing readable in it is not a declaration. Returning an empty object
3375
- // would make the model "declared but permitting nothing", which reads the same as no block at
3376
- // all and would put an empty entry in every manifest.
3377
- return Object.keys(parsed).length > 0 ? parsed : undefined
3378
- }