@supatype/cli 0.7.0 → 0.9.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 (671) hide show
  1. package/CHANGELOG.md +314 -0
  2. package/bin/supatype.js +40 -4
  3. package/deno.d.ts +1 -1
  4. package/dist/admin-prompt-state.d.ts +13 -0
  5. package/dist/admin-prompt-state.d.ts.map +1 -0
  6. package/dist/admin-prompt-state.js +30 -0
  7. package/dist/admin-prompt-state.js.map +1 -0
  8. package/dist/adopt-columns.d.ts.map +1 -1
  9. package/dist/adopt-columns.js +13 -17
  10. package/dist/adopt-columns.js.map +1 -1
  11. package/dist/after-hooks-health.d.ts +19 -0
  12. package/dist/after-hooks-health.d.ts.map +1 -0
  13. package/dist/after-hooks-health.js +69 -0
  14. package/dist/after-hooks-health.js.map +1 -0
  15. package/dist/app-config.d.ts +1 -1
  16. package/dist/app-config.d.ts.map +1 -1
  17. package/dist/app-config.js +103 -144
  18. package/dist/app-config.js.map +1 -1
  19. package/dist/app-vite-env.d.ts +5 -1
  20. package/dist/app-vite-env.d.ts.map +1 -1
  21. package/dist/app-vite-env.js +9 -15
  22. package/dist/app-vite-env.js.map +1 -1
  23. package/dist/applied-ast-artifacts.d.ts +16 -0
  24. package/dist/applied-ast-artifacts.d.ts.map +1 -0
  25. package/dist/applied-ast-artifacts.js +37 -0
  26. package/dist/applied-ast-artifacts.js.map +1 -0
  27. package/dist/archive-extract.d.ts +3 -0
  28. package/dist/archive-extract.d.ts.map +1 -0
  29. package/dist/archive-extract.js +19 -0
  30. package/dist/archive-extract.js.map +1 -0
  31. package/dist/augmentation-generator.d.ts +5 -0
  32. package/dist/augmentation-generator.d.ts.map +1 -1
  33. package/dist/augmentation-generator.js +13 -4
  34. package/dist/augmentation-generator.js.map +1 -1
  35. package/dist/binary-cache.d.ts +27 -3
  36. package/dist/binary-cache.d.ts.map +1 -1
  37. package/dist/binary-cache.js +117 -85
  38. package/dist/binary-cache.js.map +1 -1
  39. package/dist/binary-download-lock.d.ts.map +1 -1
  40. package/dist/binary-download-lock.js +1 -3
  41. package/dist/binary-download-lock.js.map +1 -1
  42. package/dist/byo-preflight.d.ts.map +1 -1
  43. package/dist/byo-preflight.js +2 -10
  44. package/dist/byo-preflight.js.map +1 -1
  45. package/dist/byte-size.d.ts +9 -0
  46. package/dist/byte-size.d.ts.map +1 -0
  47. package/dist/byte-size.js +36 -0
  48. package/dist/byte-size.js.map +1 -0
  49. package/dist/cache-clean.d.ts +0 -2
  50. package/dist/cache-clean.d.ts.map +1 -1
  51. package/dist/cache-clean.js +1 -27
  52. package/dist/cache-clean.js.map +1 -1
  53. package/dist/cache-pins.d.ts.map +1 -1
  54. package/dist/cache-pins.js +3 -20
  55. package/dist/cache-pins.js.map +1 -1
  56. package/dist/cache-root.d.ts +7 -0
  57. package/dist/cache-root.d.ts.map +1 -0
  58. package/dist/cache-root.js +11 -0
  59. package/dist/cache-root.js.map +1 -0
  60. package/dist/cli-artifacts.d.ts.map +1 -1
  61. package/dist/cli-artifacts.js +2 -1
  62. package/dist/cli-artifacts.js.map +1 -1
  63. package/dist/cli-install-method.d.ts.map +1 -1
  64. package/dist/cli-install-method.js +7 -1
  65. package/dist/cli-install-method.js.map +1 -1
  66. package/dist/cli-launcher.d.ts +21 -0
  67. package/dist/cli-launcher.d.ts.map +1 -0
  68. package/dist/cli-launcher.js +112 -0
  69. package/dist/cli-launcher.js.map +1 -0
  70. package/dist/cli-old-versions.d.ts +44 -0
  71. package/dist/cli-old-versions.d.ts.map +1 -0
  72. package/dist/cli-old-versions.js +83 -0
  73. package/dist/cli-old-versions.js.map +1 -0
  74. package/dist/cli-program-path.d.ts +20 -0
  75. package/dist/cli-program-path.d.ts.map +1 -0
  76. package/dist/cli-program-path.js +41 -0
  77. package/dist/cli-program-path.js.map +1 -0
  78. package/dist/cli-standalone.d.ts +2 -3
  79. package/dist/cli-standalone.d.ts.map +1 -1
  80. package/dist/cli-standalone.js +51 -24
  81. package/dist/cli-standalone.js.map +1 -1
  82. package/dist/cli-version-embedded.js +1 -1
  83. package/dist/cloud-credentials.d.ts +6 -0
  84. package/dist/cloud-credentials.d.ts.map +1 -1
  85. package/dist/cloud-credentials.js +13 -0
  86. package/dist/cloud-credentials.js.map +1 -1
  87. package/dist/commands/admin.d.ts.map +1 -1
  88. package/dist/commands/admin.js +18 -18
  89. package/dist/commands/admin.js.map +1 -1
  90. package/dist/commands/app.d.ts.map +1 -1
  91. package/dist/commands/app.js +27 -8
  92. package/dist/commands/app.js.map +1 -1
  93. package/dist/commands/cache.d.ts.map +1 -1
  94. package/dist/commands/cache.js +37 -11
  95. package/dist/commands/cache.js.map +1 -1
  96. package/dist/commands/cloud.js +2 -4
  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 +116 -106
  100. package/dist/commands/db.js.map +1 -1
  101. package/dist/commands/deploy.d.ts.map +1 -1
  102. package/dist/commands/deploy.js +3 -3
  103. package/dist/commands/deploy.js.map +1 -1
  104. package/dist/commands/dev.d.ts +50 -4
  105. package/dist/commands/dev.d.ts.map +1 -1
  106. package/dist/commands/dev.js +276 -267
  107. package/dist/commands/dev.js.map +1 -1
  108. package/dist/commands/doctor.d.ts +32 -0
  109. package/dist/commands/doctor.d.ts.map +1 -1
  110. package/dist/commands/doctor.js +66 -1
  111. package/dist/commands/doctor.js.map +1 -1
  112. package/dist/commands/functions.d.ts +30 -0
  113. package/dist/commands/functions.d.ts.map +1 -1
  114. package/dist/commands/functions.js +503 -507
  115. package/dist/commands/functions.js.map +1 -1
  116. package/dist/commands/generate.d.ts.map +1 -1
  117. package/dist/commands/generate.js +11 -8
  118. package/dist/commands/generate.js.map +1 -1
  119. package/dist/commands/hooks.d.ts.map +1 -1
  120. package/dist/commands/hooks.js +46 -23
  121. package/dist/commands/hooks.js.map +1 -1
  122. package/dist/commands/init.d.ts +37 -4
  123. package/dist/commands/init.d.ts.map +1 -1
  124. package/dist/commands/init.js +509 -386
  125. package/dist/commands/init.js.map +1 -1
  126. package/dist/commands/internal.d.ts.map +1 -1
  127. package/dist/commands/internal.js +2 -1
  128. package/dist/commands/internal.js.map +1 -1
  129. package/dist/commands/keys.d.ts +46 -20
  130. package/dist/commands/keys.d.ts.map +1 -1
  131. package/dist/commands/keys.js +196 -156
  132. package/dist/commands/keys.js.map +1 -1
  133. package/dist/commands/link-helpers.d.ts.map +1 -1
  134. package/dist/commands/link-helpers.js +30 -11
  135. package/dist/commands/link-helpers.js.map +1 -1
  136. package/dist/commands/logs.d.ts.map +1 -1
  137. package/dist/commands/logs.js +5 -4
  138. package/dist/commands/logs.js.map +1 -1
  139. package/dist/commands/migrate.js +1 -1
  140. package/dist/commands/migrate.js.map +1 -1
  141. package/dist/commands/pg.js +2 -0
  142. package/dist/commands/pg.js.map +1 -1
  143. package/dist/commands/plugins.d.ts.map +1 -1
  144. package/dist/commands/plugins.js +17 -7
  145. package/dist/commands/plugins.js.map +1 -1
  146. package/dist/commands/push.d.ts +39 -0
  147. package/dist/commands/push.d.ts.map +1 -1
  148. package/dist/commands/push.js +221 -77
  149. package/dist/commands/push.js.map +1 -1
  150. package/dist/commands/seed.d.ts +35 -0
  151. package/dist/commands/seed.d.ts.map +1 -1
  152. package/dist/commands/seed.js +72 -38
  153. package/dist/commands/seed.js.map +1 -1
  154. package/dist/commands/self-host.d.ts.map +1 -1
  155. package/dist/commands/self-host.js +71 -42
  156. package/dist/commands/self-host.js.map +1 -1
  157. package/dist/commands/self-update.d.ts.map +1 -1
  158. package/dist/commands/self-update.js +9 -3
  159. package/dist/commands/self-update.js.map +1 -1
  160. package/dist/commands/status.js +5 -5
  161. package/dist/commands/status.js.map +1 -1
  162. package/dist/commands/types.js +2 -5
  163. package/dist/commands/types.js.map +1 -1
  164. package/dist/commands/update.d.ts.map +1 -1
  165. package/dist/commands/update.js +212 -101
  166. package/dist/commands/update.js.map +1 -1
  167. package/dist/component-launch.d.ts +11 -0
  168. package/dist/component-launch.d.ts.map +1 -0
  169. package/dist/component-launch.js +35 -0
  170. package/dist/component-launch.js.map +1 -0
  171. package/dist/components.d.ts +7 -2
  172. package/dist/components.d.ts.map +1 -1
  173. package/dist/components.js +7 -2
  174. package/dist/components.js.map +1 -1
  175. package/dist/compose-db-roles.d.ts.map +1 -1
  176. package/dist/compose-db-roles.js +5 -14
  177. package/dist/compose-db-roles.js.map +1 -1
  178. package/dist/compose-engine-run.d.ts +6 -5
  179. package/dist/compose-engine-run.d.ts.map +1 -1
  180. package/dist/compose-engine-run.js +44 -37
  181. package/dist/compose-engine-run.js.map +1 -1
  182. package/dist/compose-engine-service.d.ts +10 -0
  183. package/dist/compose-engine-service.d.ts.map +1 -0
  184. package/dist/compose-engine-service.js +16 -0
  185. package/dist/compose-engine-service.js.map +1 -0
  186. package/dist/compose-host-path.d.ts +14 -0
  187. package/dist/compose-host-path.d.ts.map +1 -0
  188. package/dist/compose-host-path.js +18 -0
  189. package/dist/compose-host-path.js.map +1 -0
  190. package/dist/compose-image-pull.d.ts +43 -0
  191. package/dist/compose-image-pull.d.ts.map +1 -0
  192. package/dist/compose-image-pull.js +27 -0
  193. package/dist/compose-image-pull.js.map +1 -0
  194. package/dist/compose-kong.d.ts +4 -0
  195. package/dist/compose-kong.d.ts.map +1 -1
  196. package/dist/compose-kong.js +23 -9
  197. package/dist/compose-kong.js.map +1 -1
  198. package/dist/compose-local-server-image.d.ts.map +1 -1
  199. package/dist/compose-local-server-image.js +7 -3
  200. package/dist/compose-local-server-image.js.map +1 -1
  201. package/dist/compose-render-mode.d.ts.map +1 -1
  202. package/dist/compose-render-mode.js +7 -4
  203. package/dist/compose-render-mode.js.map +1 -1
  204. package/dist/compose-services.d.ts +12 -2
  205. package/dist/compose-services.d.ts.map +1 -1
  206. package/dist/compose-services.js +27 -12
  207. package/dist/compose-services.js.map +1 -1
  208. package/dist/config-snapshot.d.ts +6 -0
  209. package/dist/config-snapshot.d.ts.map +1 -0
  210. package/dist/config-snapshot.js +23 -0
  211. package/dist/config-snapshot.js.map +1 -0
  212. package/dist/config.d.ts +11 -1
  213. package/dist/config.d.ts.map +1 -1
  214. package/dist/config.js +20 -3
  215. package/dist/config.js.map +1 -1
  216. package/dist/database-url-owner.d.ts +59 -0
  217. package/dist/database-url-owner.d.ts.map +1 -0
  218. package/dist/database-url-owner.js +133 -0
  219. package/dist/database-url-owner.js.map +1 -0
  220. package/dist/db-port-offer.d.ts +18 -0
  221. package/dist/db-port-offer.d.ts.map +1 -0
  222. package/dist/db-port-offer.js +68 -0
  223. package/dist/db-port-offer.js.map +1 -0
  224. package/dist/db-port.d.ts +42 -18
  225. package/dist/db-port.d.ts.map +1 -1
  226. package/dist/db-port.js +34 -32
  227. package/dist/db-port.js.map +1 -1
  228. package/dist/db-preflight.d.ts +37 -0
  229. package/dist/db-preflight.d.ts.map +1 -1
  230. package/dist/db-preflight.js +219 -77
  231. package/dist/db-preflight.js.map +1 -1
  232. package/dist/db-rows.d.ts +11 -0
  233. package/dist/db-rows.d.ts.map +1 -1
  234. package/dist/db-rows.js +27 -0
  235. package/dist/db-rows.js.map +1 -1
  236. package/dist/debounce.d.ts +11 -0
  237. package/dist/debounce.d.ts.map +1 -0
  238. package/dist/debounce.js +23 -0
  239. package/dist/debounce.js.map +1 -0
  240. package/dist/dev-api-keys.d.ts +12 -2
  241. package/dist/dev-api-keys.d.ts.map +1 -1
  242. package/dist/dev-api-keys.js +33 -17
  243. package/dist/dev-api-keys.js.map +1 -1
  244. package/dist/dev-compose.d.ts +10 -12
  245. package/dist/dev-compose.d.ts.map +1 -1
  246. package/dist/dev-compose.js +252 -288
  247. package/dist/dev-compose.js.map +1 -1
  248. package/dist/dev-db-ready.d.ts.map +1 -1
  249. package/dist/dev-db-ready.js +2 -1
  250. package/dist/dev-db-ready.js.map +1 -1
  251. package/dist/dev-db-reset.d.ts.map +1 -1
  252. package/dist/dev-db-reset.js +5 -4
  253. package/dist/dev-db-reset.js.map +1 -1
  254. package/dist/dev-functions-watch.d.ts.map +1 -1
  255. package/dist/dev-functions-watch.js +5 -16
  256. package/dist/dev-functions-watch.js.map +1 -1
  257. package/dist/dev-log-bus.d.ts +8 -0
  258. package/dist/dev-log-bus.d.ts.map +1 -1
  259. package/dist/dev-log-bus.js +13 -0
  260. package/dist/dev-log-bus.js.map +1 -1
  261. package/dist/dev-ports.d.ts +27 -7
  262. package/dist/dev-ports.d.ts.map +1 -1
  263. package/dist/dev-ports.js +68 -41
  264. package/dist/dev-ports.js.map +1 -1
  265. package/dist/dev-schema-watch.d.ts.map +1 -1
  266. package/dist/dev-schema-watch.js +7 -12
  267. package/dist/dev-schema-watch.js.map +1 -1
  268. package/dist/dev-session-lock.js +4 -3
  269. package/dist/dev-session-lock.js.map +1 -1
  270. package/dist/dev-session.d.ts +15 -0
  271. package/dist/dev-session.d.ts.map +1 -1
  272. package/dist/dev-session.js +27 -1
  273. package/dist/dev-session.js.map +1 -1
  274. package/dist/dev-shutdown.d.ts +45 -0
  275. package/dist/dev-shutdown.d.ts.map +1 -1
  276. package/dist/dev-shutdown.js +221 -33
  277. package/dist/dev-shutdown.js.map +1 -1
  278. package/dist/diff-output.d.ts +7 -1
  279. package/dist/diff-output.d.ts.map +1 -1
  280. package/dist/diff-output.js +91 -2
  281. package/dist/diff-output.js.map +1 -1
  282. package/dist/docker-address-pool.d.ts +23 -0
  283. package/dist/docker-address-pool.d.ts.map +1 -0
  284. package/dist/docker-address-pool.js +56 -0
  285. package/dist/docker-address-pool.js.map +1 -0
  286. package/dist/docker-exec.d.ts +92 -0
  287. package/dist/docker-exec.d.ts.map +1 -0
  288. package/dist/docker-exec.js +139 -0
  289. package/dist/docker-exec.js.map +1 -0
  290. package/dist/docker-postgres.d.ts +1 -6
  291. package/dist/docker-postgres.d.ts.map +1 -1
  292. package/dist/docker-postgres.js +67 -85
  293. package/dist/docker-postgres.js.map +1 -1
  294. package/dist/docker-runtime.d.ts +14 -1
  295. package/dist/docker-runtime.d.ts.map +1 -1
  296. package/dist/docker-runtime.js +55 -24
  297. package/dist/docker-runtime.js.map +1 -1
  298. package/dist/dotenv-parse.d.ts +22 -0
  299. package/dist/dotenv-parse.d.ts.map +1 -0
  300. package/dist/dotenv-parse.js +63 -0
  301. package/dist/dotenv-parse.js.map +1 -0
  302. package/dist/engine-answers.d.ts +0 -2
  303. package/dist/engine-answers.d.ts.map +1 -1
  304. package/dist/engine-answers.js +4 -3
  305. package/dist/engine-answers.js.map +1 -1
  306. package/dist/engine-client.d.ts.map +1 -1
  307. package/dist/engine-client.js +13 -12
  308. package/dist/engine-client.js.map +1 -1
  309. package/dist/engine-floor.d.ts +29 -0
  310. package/dist/engine-floor.d.ts.map +1 -1
  311. package/dist/engine-floor.js +56 -0
  312. package/dist/engine-floor.js.map +1 -1
  313. package/dist/engine-ownership-gate.d.ts +13 -1
  314. package/dist/engine-ownership-gate.d.ts.map +1 -1
  315. package/dist/engine-ownership-gate.js +36 -6
  316. package/dist/engine-ownership-gate.js.map +1 -1
  317. package/dist/ensure-binary.d.ts +9 -0
  318. package/dist/ensure-binary.d.ts.map +1 -1
  319. package/dist/ensure-binary.js +38 -5
  320. package/dist/ensure-binary.js.map +1 -1
  321. package/dist/ensure-component-binaries.d.ts.map +1 -1
  322. package/dist/ensure-component-binaries.js +2 -1
  323. package/dist/ensure-component-binaries.js.map +1 -1
  324. package/dist/env-file.d.ts +30 -8
  325. package/dist/env-file.d.ts.map +1 -1
  326. package/dist/env-file.js +84 -57
  327. package/dist/env-file.js.map +1 -1
  328. package/dist/env-lines.d.ts +11 -0
  329. package/dist/env-lines.d.ts.map +1 -0
  330. package/dist/env-lines.js +36 -0
  331. package/dist/env-lines.js.map +1 -0
  332. package/dist/error-message.d.ts +34 -1
  333. package/dist/error-message.d.ts.map +1 -1
  334. package/dist/error-message.js +102 -2
  335. package/dist/error-message.js.map +1 -1
  336. package/dist/fetch-within.d.ts +10 -0
  337. package/dist/fetch-within.d.ts.map +1 -0
  338. package/dist/fetch-within.js +12 -0
  339. package/dist/fetch-within.js.map +1 -0
  340. package/dist/field-masking-tier.d.ts.map +1 -1
  341. package/dist/field-masking-tier.js +7 -5
  342. package/dist/field-masking-tier.js.map +1 -1
  343. package/dist/frontend-env.d.ts +43 -0
  344. package/dist/frontend-env.d.ts.map +1 -0
  345. package/dist/frontend-env.js +81 -0
  346. package/dist/frontend-env.js.map +1 -0
  347. package/dist/functions-context-refresh.d.ts +6 -2
  348. package/dist/functions-context-refresh.d.ts.map +1 -1
  349. package/dist/functions-context-refresh.js +11 -3
  350. package/dist/functions-context-refresh.js.map +1 -1
  351. package/dist/functions-deno-types.d.ts.map +1 -1
  352. package/dist/functions-deno-types.js +9 -2
  353. package/dist/functions-deno-types.js.map +1 -1
  354. package/dist/{functions-router-gen.d.ts → functions-discovery.d.ts} +8 -10
  355. package/dist/functions-discovery.d.ts.map +1 -0
  356. package/dist/functions-discovery.js +87 -0
  357. package/dist/functions-discovery.js.map +1 -0
  358. package/dist/functions-template.d.ts.map +1 -1
  359. package/dist/functions-template.js +20 -12
  360. package/dist/functions-template.js.map +1 -1
  361. package/dist/functions-worker-files.d.ts +55 -0
  362. package/dist/functions-worker-files.d.ts.map +1 -0
  363. package/dist/functions-worker-files.js +149 -0
  364. package/dist/functions-worker-files.js.map +1 -0
  365. package/dist/generated/functions-worker-source.d.ts +2 -0
  366. package/dist/generated/functions-worker-source.d.ts.map +1 -0
  367. package/dist/generated/functions-worker-source.js +12 -0
  368. package/dist/generated/functions-worker-source.js.map +1 -0
  369. package/dist/generated/release-images.d.ts +18 -0
  370. package/dist/generated/release-images.d.ts.map +1 -0
  371. package/dist/generated/release-images.js +8 -0
  372. package/dist/generated/release-images.js.map +1 -0
  373. package/dist/generated-files-engine.d.ts +33 -0
  374. package/dist/generated-files-engine.d.ts.map +1 -0
  375. package/dist/generated-files-engine.js +45 -0
  376. package/dist/generated-files-engine.js.map +1 -0
  377. package/dist/hook-actor.d.ts +17 -0
  378. package/dist/hook-actor.d.ts.map +1 -0
  379. package/dist/hook-actor.js +37 -0
  380. package/dist/hook-actor.js.map +1 -0
  381. package/dist/hook-columns.d.ts +30 -0
  382. package/dist/hook-columns.d.ts.map +1 -0
  383. package/dist/hook-columns.js +77 -0
  384. package/dist/hook-columns.js.map +1 -0
  385. package/dist/hook-events.d.ts +11 -0
  386. package/dist/hook-events.d.ts.map +1 -0
  387. package/dist/hook-events.js +11 -0
  388. package/dist/hook-events.js.map +1 -0
  389. package/dist/hook-upload.d.ts +29 -15
  390. package/dist/hook-upload.d.ts.map +1 -1
  391. package/dist/hook-upload.js +88 -59
  392. package/dist/hook-upload.js.map +1 -1
  393. package/dist/hooks-generator.d.ts +5 -0
  394. package/dist/hooks-generator.d.ts.map +1 -1
  395. package/dist/hooks-generator.js +92 -21
  396. package/dist/hooks-generator.js.map +1 -1
  397. package/dist/host-database.d.ts.map +1 -1
  398. package/dist/host-database.js +31 -4
  399. package/dist/host-database.js.map +1 -1
  400. package/dist/init-dependency-versions.d.ts +3 -1
  401. package/dist/init-dependency-versions.d.ts.map +1 -1
  402. package/dist/init-dependency-versions.js +32 -6
  403. package/dist/init-dependency-versions.js.map +1 -1
  404. package/dist/init-example.d.ts +48 -0
  405. package/dist/init-example.d.ts.map +1 -0
  406. package/dist/init-example.js +110 -0
  407. package/dist/init-example.js.map +1 -0
  408. package/dist/init-package-json.d.ts +38 -1
  409. package/dist/init-package-json.d.ts.map +1 -1
  410. package/dist/init-package-json.js +150 -37
  411. package/dist/init-package-json.js.map +1 -1
  412. package/dist/init-setup-steps.d.ts +37 -0
  413. package/dist/init-setup-steps.d.ts.map +1 -0
  414. package/dist/init-setup-steps.js +118 -0
  415. package/dist/init-setup-steps.js.map +1 -0
  416. package/dist/jwt-secret-length.d.ts +5 -13
  417. package/dist/jwt-secret-length.d.ts.map +1 -1
  418. package/dist/jwt-secret-length.js +7 -22
  419. package/dist/jwt-secret-length.js.map +1 -1
  420. package/dist/jwt-secret-rules.d.ts +24 -0
  421. package/dist/jwt-secret-rules.d.ts.map +1 -0
  422. package/dist/jwt-secret-rules.js +46 -0
  423. package/dist/jwt-secret-rules.js.map +1 -0
  424. package/dist/local-gateway.d.ts +3 -6
  425. package/dist/local-gateway.d.ts.map +1 -1
  426. package/dist/local-gateway.js +7 -9
  427. package/dist/local-gateway.js.map +1 -1
  428. package/dist/local-secrets.d.ts +95 -11
  429. package/dist/local-secrets.d.ts.map +1 -1
  430. package/dist/local-secrets.js +153 -18
  431. package/dist/local-secrets.js.map +1 -1
  432. package/dist/local-stack.d.ts.map +1 -1
  433. package/dist/local-stack.js +2 -7
  434. package/dist/local-stack.js.map +1 -1
  435. package/dist/local-storage.d.ts +7 -2
  436. package/dist/local-storage.d.ts.map +1 -1
  437. package/dist/local-storage.js +11 -3
  438. package/dist/local-storage.js.map +1 -1
  439. package/dist/mailer-env.d.ts +37 -0
  440. package/dist/mailer-env.d.ts.map +1 -0
  441. package/dist/mailer-env.js +98 -0
  442. package/dist/mailer-env.js.map +1 -0
  443. package/dist/model-cache.d.ts +4 -8
  444. package/dist/model-cache.d.ts.map +1 -1
  445. package/dist/model-cache.js.map +1 -1
  446. package/dist/model-hooks.d.ts +21 -7
  447. package/dist/model-hooks.d.ts.map +1 -1
  448. package/dist/model-hooks.js +62 -39
  449. package/dist/model-hooks.js.map +1 -1
  450. package/dist/native-dev-env.d.ts +37 -1
  451. package/dist/native-dev-env.d.ts.map +1 -1
  452. package/dist/native-dev-env.js +64 -2
  453. package/dist/native-dev-env.js.map +1 -1
  454. package/dist/native-functions-watch.d.ts +56 -5
  455. package/dist/native-functions-watch.d.ts.map +1 -1
  456. package/dist/native-functions-watch.js +119 -38
  457. package/dist/native-functions-watch.js.map +1 -1
  458. package/dist/native-keyspace.d.ts.map +1 -1
  459. package/dist/native-keyspace.js +2 -2
  460. package/dist/native-keyspace.js.map +1 -1
  461. package/dist/native-realtime.d.ts +11 -3
  462. package/dist/native-realtime.d.ts.map +1 -1
  463. package/dist/native-realtime.js +162 -10
  464. package/dist/native-realtime.js.map +1 -1
  465. package/dist/native-roles-sql.d.ts +14 -0
  466. package/dist/native-roles-sql.d.ts.map +1 -1
  467. package/dist/native-roles-sql.js +82 -1
  468. package/dist/native-roles-sql.js.map +1 -1
  469. package/dist/native-storage-import.d.ts +19 -0
  470. package/dist/native-storage-import.d.ts.map +1 -0
  471. package/dist/native-storage-import.js +327 -0
  472. package/dist/native-storage-import.js.map +1 -0
  473. package/dist/native-storage.d.ts +45 -0
  474. package/dist/native-storage.d.ts.map +1 -0
  475. package/dist/native-storage.js +140 -0
  476. package/dist/native-storage.js.map +1 -0
  477. package/dist/native-worker.d.ts +26 -0
  478. package/dist/native-worker.d.ts.map +1 -0
  479. package/dist/native-worker.js +63 -0
  480. package/dist/native-worker.js.map +1 -0
  481. package/dist/owner-default.d.ts +9 -1
  482. package/dist/owner-default.d.ts.map +1 -1
  483. package/dist/owner-default.js +17 -4
  484. package/dist/owner-default.js.map +1 -1
  485. package/dist/post-apply.d.ts +3 -0
  486. package/dist/post-apply.d.ts.map +1 -0
  487. package/dist/post-apply.js +17 -0
  488. package/dist/post-apply.js.map +1 -0
  489. package/dist/postgres-ctl.d.ts +98 -7
  490. package/dist/postgres-ctl.d.ts.map +1 -1
  491. package/dist/postgres-ctl.js +273 -40
  492. package/dist/postgres-ctl.js.map +1 -1
  493. package/dist/postgres-image.d.ts +15 -3
  494. package/dist/postgres-image.d.ts.map +1 -1
  495. package/dist/postgres-image.js +18 -15
  496. package/dist/postgres-image.js.map +1 -1
  497. package/dist/postgrest-release.d.ts +9 -0
  498. package/dist/postgrest-release.d.ts.map +1 -1
  499. package/dist/postgrest-release.js +23 -0
  500. package/dist/postgrest-release.js.map +1 -1
  501. package/dist/process-manager.d.ts.map +1 -1
  502. package/dist/process-manager.js +3 -1
  503. package/dist/process-manager.js.map +1 -1
  504. package/dist/project-config.d.ts +44 -7
  505. package/dist/project-config.d.ts.map +1 -1
  506. package/dist/project-config.js +48 -4
  507. package/dist/project-config.js.map +1 -1
  508. package/dist/pull-utils.d.ts +15 -0
  509. package/dist/pull-utils.d.ts.map +1 -1
  510. package/dist/pull-utils.js +149 -23
  511. package/dist/pull-utils.js.map +1 -1
  512. package/dist/push-refusal.d.ts.map +1 -1
  513. package/dist/push-refusal.js +3 -2
  514. package/dist/push-refusal.js.map +1 -1
  515. package/dist/realtime-launch.d.ts +2 -5
  516. package/dist/realtime-launch.d.ts.map +1 -1
  517. package/dist/realtime-launch.js +6 -23
  518. package/dist/realtime-launch.js.map +1 -1
  519. package/dist/recorded-field-masking-tier.d.ts.map +1 -1
  520. package/dist/recorded-field-masking-tier.js +4 -3
  521. package/dist/recorded-field-masking-tier.js.map +1 -1
  522. package/dist/release-images.d.ts +31 -0
  523. package/dist/release-images.d.ts.map +1 -0
  524. package/dist/release-images.js +90 -0
  525. package/dist/release-images.js.map +1 -0
  526. package/dist/required-host-components.d.ts.map +1 -1
  527. package/dist/required-host-components.js +4 -0
  528. package/dist/required-host-components.js.map +1 -1
  529. package/dist/resolve-api-url.d.ts +17 -3
  530. package/dist/resolve-api-url.d.ts.map +1 -1
  531. package/dist/resolve-api-url.js +71 -30
  532. package/dist/resolve-api-url.js.map +1 -1
  533. package/dist/resolve-target.d.ts +64 -0
  534. package/dist/resolve-target.d.ts.map +1 -1
  535. package/dist/resolve-target.js +75 -27
  536. package/dist/resolve-target.js.map +1 -1
  537. package/dist/rest-ready.d.ts.map +1 -1
  538. package/dist/rest-ready.js +2 -1
  539. package/dist/rest-ready.js.map +1 -1
  540. package/dist/route-manifest.d.ts +25 -2
  541. package/dist/route-manifest.d.ts.map +1 -1
  542. package/dist/route-manifest.js +48 -4
  543. package/dist/route-manifest.js.map +1 -1
  544. package/dist/run-until-stopped.d.ts +12 -0
  545. package/dist/run-until-stopped.d.ts.map +1 -0
  546. package/dist/run-until-stopped.js +42 -0
  547. package/dist/run-until-stopped.js.map +1 -0
  548. package/dist/schema-ast-v2.d.ts +2 -1
  549. package/dist/schema-ast-v2.d.ts.map +1 -1
  550. package/dist/schema-ast-v2.js.map +1 -1
  551. package/dist/schema-push-lock.d.ts.map +1 -1
  552. package/dist/schema-push-lock.js +59 -46
  553. package/dist/schema-push-lock.js.map +1 -1
  554. package/dist/schema-sources.d.ts +19 -4
  555. package/dist/schema-sources.d.ts.map +1 -1
  556. package/dist/schema-sources.js +56 -35
  557. package/dist/schema-sources.js.map +1 -1
  558. package/dist/seed-auth-connect.d.ts +14 -0
  559. package/dist/seed-auth-connect.d.ts.map +1 -0
  560. package/dist/seed-auth-connect.js +97 -0
  561. package/dist/seed-auth-connect.js.map +1 -0
  562. package/dist/seed-runner.d.ts.map +1 -1
  563. package/dist/seed-runner.js +22 -1
  564. package/dist/seed-runner.js.map +1 -1
  565. package/dist/seed.d.ts +6 -3
  566. package/dist/seed.d.ts.map +1 -1
  567. package/dist/self-host-compose.d.ts +44 -29
  568. package/dist/self-host-compose.d.ts.map +1 -1
  569. package/dist/self-host-compose.js +311 -159
  570. package/dist/self-host-compose.js.map +1 -1
  571. package/dist/service-role-key-file.d.ts +32 -0
  572. package/dist/service-role-key-file.d.ts.map +1 -0
  573. package/dist/service-role-key-file.js +90 -0
  574. package/dist/service-role-key-file.js.map +1 -0
  575. package/dist/shell-ports.d.ts +13 -2
  576. package/dist/shell-ports.d.ts.map +1 -1
  577. package/dist/shell-ports.js +20 -15
  578. package/dist/shell-ports.js.map +1 -1
  579. package/dist/stop-signals.d.ts +7 -0
  580. package/dist/stop-signals.d.ts.map +1 -0
  581. package/dist/stop-signals.js +12 -0
  582. package/dist/stop-signals.js.map +1 -0
  583. package/dist/storage-launch.d.ts +11 -0
  584. package/dist/storage-launch.d.ts.map +1 -0
  585. package/dist/storage-launch.js +41 -0
  586. package/dist/storage-launch.js.map +1 -0
  587. package/dist/storage-provision.d.ts +50 -5
  588. package/dist/storage-provision.d.ts.map +1 -1
  589. package/dist/storage-provision.js +101 -33
  590. package/dist/storage-provision.js.map +1 -1
  591. package/dist/systemd.d.ts +1 -1
  592. package/dist/systemd.d.ts.map +1 -1
  593. package/dist/systemd.js +26 -11
  594. package/dist/systemd.js.map +1 -1
  595. package/dist/tar-reader.d.ts +29 -0
  596. package/dist/tar-reader.d.ts.map +1 -0
  597. package/dist/tar-reader.js +99 -0
  598. package/dist/tar-reader.js.map +1 -0
  599. package/dist/target-client.d.ts +14 -1
  600. package/dist/target-client.d.ts.map +1 -1
  601. package/dist/target-client.js +134 -23
  602. package/dist/target-client.js.map +1 -1
  603. package/dist/target-request.d.ts +25 -0
  604. package/dist/target-request.d.ts.map +1 -0
  605. package/dist/target-request.js +33 -0
  606. package/dist/target-request.js.map +1 -0
  607. package/dist/target-warning.d.ts +7 -0
  608. package/dist/target-warning.d.ts.map +1 -0
  609. package/dist/target-warning.js +12 -0
  610. package/dist/target-warning.js.map +1 -0
  611. package/dist/tsx-runner.d.ts.map +1 -1
  612. package/dist/tsx-runner.js +2 -1
  613. package/dist/tsx-runner.js.map +1 -1
  614. package/dist/type-extractor.d.ts +6 -0
  615. package/dist/type-extractor.d.ts.map +1 -1
  616. package/dist/type-extractor.js +138 -70
  617. package/dist/type-extractor.js.map +1 -1
  618. package/dist/ui/clack.d.ts.map +1 -1
  619. package/dist/ui/clack.js +11 -1
  620. package/dist/ui/clack.js.map +1 -1
  621. package/dist/ui/dev/DevDashboard.d.ts.map +1 -1
  622. package/dist/ui/dev/DevDashboard.js +13 -5
  623. package/dist/ui/dev/DevDashboard.js.map +1 -1
  624. package/dist/ui/fatal.d.ts.map +1 -1
  625. package/dist/ui/fatal.js +6 -7
  626. package/dist/ui/fatal.js.map +1 -1
  627. package/dist/ui/flows/FlowApp.d.ts.map +1 -1
  628. package/dist/ui/flows/FlowApp.js +16 -1
  629. package/dist/ui/flows/FlowApp.js.map +1 -1
  630. package/dist/ui/flows/prompt-fields.d.ts +16 -6
  631. package/dist/ui/flows/prompt-fields.d.ts.map +1 -1
  632. package/dist/ui/flows/prompt-fields.js +19 -9
  633. package/dist/ui/flows/prompt-fields.js.map +1 -1
  634. package/dist/ui/messages.d.ts +6 -0
  635. package/dist/ui/messages.d.ts.map +1 -1
  636. package/dist/ui/messages.js +17 -0
  637. package/dist/ui/messages.js.map +1 -1
  638. package/dist/ui/progress.d.ts +7 -0
  639. package/dist/ui/progress.d.ts.map +1 -1
  640. package/dist/ui/progress.js +22 -8
  641. package/dist/ui/progress.js.map +1 -1
  642. package/dist/ui/runtime/command-chrome.d.ts.map +1 -1
  643. package/dist/ui/runtime/command-chrome.js +2 -0
  644. package/dist/ui/runtime/command-chrome.js.map +1 -1
  645. package/dist/ui/runtime/prompt-interrupt.d.ts +10 -0
  646. package/dist/ui/runtime/prompt-interrupt.d.ts.map +1 -0
  647. package/dist/ui/runtime/prompt-interrupt.js +24 -0
  648. package/dist/ui/runtime/prompt-interrupt.js.map +1 -0
  649. package/dist/ui/runtime/run-clack-flow.d.ts.map +1 -1
  650. package/dist/ui/runtime/run-clack-flow.js +5 -2
  651. package/dist/ui/runtime/run-clack-flow.js.map +1 -1
  652. package/dist/ui/runtime/stdin-after-ink.d.ts +14 -1
  653. package/dist/ui/runtime/stdin-after-ink.d.ts.map +1 -1
  654. package/dist/ui/runtime/stdin-after-ink.js +44 -3
  655. package/dist/ui/runtime/stdin-after-ink.js.map +1 -1
  656. package/dist/url-safe-passwords.d.ts +25 -0
  657. package/dist/url-safe-passwords.d.ts.map +1 -0
  658. package/dist/url-safe-passwords.js +70 -0
  659. package/dist/url-safe-passwords.js.map +1 -0
  660. package/dist/valkey-sidecar.d.ts +33 -6
  661. package/dist/valkey-sidecar.d.ts.map +1 -1
  662. package/dist/valkey-sidecar.js +90 -61
  663. package/dist/valkey-sidecar.js.map +1 -1
  664. package/dist/worker-module-files.d.ts +3 -0
  665. package/dist/worker-module-files.d.ts.map +1 -0
  666. package/dist/worker-module-files.js +18 -0
  667. package/dist/worker-module-files.js.map +1 -0
  668. package/package.json +22 -16
  669. package/dist/functions-router-gen.d.ts.map +0 -1
  670. package/dist/functions-router-gen.js +0 -302
  671. package/dist/functions-router-gen.js.map +0 -1
@@ -0,0 +1,149 @@
1
+ /**
2
+ * The functions worker native `dev` and `functions serve` run: packages/functions-worker itself,
3
+ * the code the deployed image runs, rather than a router generated to copy its rules. A copy
4
+ * drifted from the worker three times (which export it took, who got the service-role key, which
5
+ * env files it read), and every drift was a function that worked locally and failed once deployed.
6
+ *
7
+ * The CLI carries the worker's source (generated/functions-worker-source.ts) and writes it to the
8
+ * cache under a directory named for its content, so every project and every serve of one CLI
9
+ * version share one copy and nothing is left in a project when they stop.
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { cacheRoot } from "./binary-cache.js";
16
+ import { discoverHandlersInDir, discoverTsFunctionsInDir, InvalidFunctionNameError } from "./functions-discovery.js";
17
+ import { fatalError } from "./ui/fatal.js";
18
+ import { FUNCTIONS_WORKER_SOURCE } from "./generated/functions-worker-source.js";
19
+ import { hooksPathFromProject, serviceRoleRoutes } from "./project-config.js";
20
+ import { uniqueFileToken } from "./unique-file-token.js";
21
+ /** Where this CLI's worker source lives under `root`: one directory per distinct source. */
22
+ function functionsWorkerDir(root = cacheRoot()) {
23
+ const files = Object.entries(FUNCTIONS_WORKER_SOURCE).sort(([a], [b]) => a.localeCompare(b));
24
+ const hash = createHash("sha256").update(JSON.stringify(files)).digest("hex").slice(0, 16);
25
+ return join(root, "functions-worker", hash);
26
+ }
27
+ /** Writes the worker's files under `root` (the CLI's cache by default) and returns its main.ts. */
28
+ export function installFunctionsWorker(root) {
29
+ const dir = functionsWorkerDir(root);
30
+ mkdirSync(dir, { recursive: true });
31
+ for (const [name, text] of Object.entries(FUNCTIONS_WORKER_SOURCE))
32
+ writeIfChanged(join(dir, name), text);
33
+ return join(dir, "main.ts");
34
+ }
35
+ /**
36
+ * Writes `text` to `path` unless it already holds it. Through a temporary file and a rename, so a
37
+ * Deno another serve has running never reads a half-written module.
38
+ */
39
+ function writeIfChanged(path, text) {
40
+ if (existsSync(path) && readFileSync(path, "utf8") === text)
41
+ return;
42
+ const temporary = `${path}.${uniqueFileToken()}.tmp`;
43
+ writeFileSync(temporary, text, "utf8");
44
+ renameSync(temporary, path);
45
+ }
46
+ /** The routes the worker serves from `hooksDir`, each as `hooks/<name>`, as it routes them. */
47
+ function hookRoutes(hooksDir) {
48
+ return discoverHandlersInDir(hooksDir).map((hook) => `hooks/${hook.name}`);
49
+ }
50
+ /**
51
+ * Every route a local worker serves: the functions in `functionsDir`, then the hooks in `hooksDir`.
52
+ * Throws when a function's name is one the control plane would refuse.
53
+ */
54
+ export function localWorkerRoutes(functionsDir, hooksDir) {
55
+ const functions = functionsDir === undefined ? [] : discoverTsFunctionsInDir(functionsDir).map((fn) => fn.name);
56
+ return [...functions, ...hookRoutes(hooksDir)];
57
+ }
58
+ /** {@link localWorkerRoutes}, ending the command with why when a function's name would be refused. */
59
+ export function localWorkerRoutesOrExit(functionsDir, hooksDir) {
60
+ try {
61
+ return localWorkerRoutes(functionsDir, hooksDir);
62
+ }
63
+ catch (err) {
64
+ if (err instanceof InvalidFunctionNameError)
65
+ fatalError(err.message);
66
+ throw err;
67
+ }
68
+ }
69
+ /** Where native dev writes the entry its server runs Deno on. */
70
+ export function devFunctionsEntryPath(cwd) {
71
+ return join(resolve(cwd, ".supatype"), "functions-worker.ts");
72
+ }
73
+ const ADAPTER_LINE = "// Hooks adapter: ";
74
+ /**
75
+ * The entry native dev's server runs: an import of the worker, and the routes (functions and
76
+ * hooks) it found. The server runs Deno with a fixed `--watch` on this file, which reloads when a
77
+ * file the worker imported changes; a function or hook added later was imported by nothing, so the
78
+ * routes are rewritten when the set changes, and that change is what makes Deno reload and find it.
79
+ *
80
+ * It names the generated hooks adapter's content too ({@link hooksAdapterHash}): a hook made before
81
+ * any model named it failed to import the adapter, which only a push writes, and Deno does not
82
+ * watch a module that failed to import, so the push's adapter reloaded nothing (round 6c, N30).
83
+ */
84
+ export function devFunctionsEntrySource(routes, workerMain, adapter = "none") {
85
+ return [
86
+ "// Written by supatype dev, do not edit. Runs packages/functions-worker, as the deployed image does.",
87
+ `// Routes: ${routes.join(", ")}`,
88
+ `${ADAPTER_LINE}${adapter}`,
89
+ `import ${JSON.stringify(pathToFileURL(workerMain).href)}`,
90
+ "",
91
+ ].join("\n");
92
+ }
93
+ /** Writes {@link devFunctionsEntrySource} to {@link devFunctionsEntryPath} and returns that path. */
94
+ export function writeDevFunctionsEntry(cwd, routes, workerMain, hooksDir) {
95
+ const path = devFunctionsEntryPath(cwd);
96
+ mkdirSync(dirname(path), { recursive: true });
97
+ writeFileSync(path, devFunctionsEntrySource(routes, workerMain, hooksAdapterHash(hooksDir)), "utf8");
98
+ return path;
99
+ }
100
+ /** A short hash of `hooks/_supatype/hooks.ts` under `hooksDir`, or "none" when there is none. */
101
+ export function hooksAdapterHash(hooksDir) {
102
+ const file = join(hooksDir, "_supatype", "hooks.ts");
103
+ if (!existsSync(file))
104
+ return "none";
105
+ return createHash("sha256").update(readFileSync(file)).digest("hex").slice(0, 16);
106
+ }
107
+ /** The adapter hash the entry in `cwd` was written with: "none" when it names none or is not there. */
108
+ export function entryAdapterHash(cwd) {
109
+ const path = devFunctionsEntryPath(cwd);
110
+ if (!existsSync(path))
111
+ return "none";
112
+ const line = readFileSync(path, "utf8").split(/\r?\n/).find((l) => l.startsWith(ADAPTER_LINE));
113
+ return line === undefined ? "none" : line.slice(ADAPTER_LINE.length).trim();
114
+ }
115
+ /**
116
+ * `deno run` arguments for `functions serve`: the worker under `--watch`, which reloads when a file
117
+ * it imported changes, also watching `watchDirs`, so a function added while it serves is found.
118
+ */
119
+ export function functionsServeDenoArgs(workerMain, watchDirs, envFileArgs) {
120
+ const watch = watchDirs.length > 0 ? `--watch=${watchDirs.join(",")}` : "--watch";
121
+ return ["run", "--allow-net", "--allow-env", "--allow-read", watch, ...envFileArgs, workerMain];
122
+ }
123
+ /**
124
+ * The worker's environment for `project`, as self-host compose gives it to the image: functions
125
+ * and hooks roots, the project ref its log lines carry, and the routes `functions.serviceRole`
126
+ * grants the key. The key file stands in for the key itself, which a `--watch` reload would
127
+ * otherwise not find again. The shared env file is left to the worker's own default,
128
+ * `<functions root>/.env.local`.
129
+ */
130
+ export function functionsWorkerEnv(project) {
131
+ const { cwd, config, keyPath } = project;
132
+ return {
133
+ SUPATYPE_FUNCTIONS_ROOT: project.functionsDir,
134
+ SUPATYPE_HOOKS_ROOT: hooksPathFromProject(config, cwd),
135
+ SUPATYPE_PROJECT_REF: config.project.name,
136
+ SUPATYPE_SERVICE_ROLE_ROUTES: serviceRoleRoutes(config).join(","),
137
+ ...(keyPath !== undefined && { SUPATYPE_SERVICE_ROLE_KEY_FILE: keyPath }),
138
+ };
139
+ }
140
+ /** Where native dev keeps `functions.serviceRole` for its worker, which reads it on every reload. */
141
+ export function devServiceRoleRoutesPath(cwd) {
142
+ return join(resolve(cwd, ".supatype"), "service-role-routes");
143
+ }
144
+ /** Writes the routes `functions.serviceRole` grants the key, comma-separated, as the worker reads them. */
145
+ export function writeServiceRoleRoutesFile(path, routes) {
146
+ mkdirSync(dirname(path), { recursive: true });
147
+ writeFileSync(path, routes.join(","), "utf8");
148
+ }
149
+ //# sourceMappingURL=functions-worker-files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions-worker-files.js","sourceRoot":"","sources":["../src/functions-worker-files.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ export declare const FUNCTIONS_WORKER_SOURCE: Readonly<Record<string, string>>;
2
+ //# sourceMappingURL=functions-worker-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions-worker-source.d.ts","sourceRoot":"","sources":["../../src/generated/functions-worker-source.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQpE,CAAA"}
@@ -0,0 +1,12 @@
1
+ // Generated from packages/functions-worker/*.ts by scripts/functions-worker-source.mjs. Do not
2
+ // edit: the CLI's build regenerates it, and native dev and `functions serve` run these files.
3
+ export const FUNCTIONS_WORKER_SOURCE = {
4
+ "deno.d.ts": "/**\n * Ambient types for IDE / tsserver (runtime is Deno in Docker).\n * Kept in sync with `@supatype/cli` edge-function ambient (`packages/cli/deno.d.ts`).\n */\n\ninterface DenoEnv {\n get(key: string): string | undefined\n set(key: string, value: string): void\n delete(key: string): void\n has(key: string): boolean\n toObject(): { [key: string]: string }\n}\n\ndeclare namespace Deno {\n const env: DenoEnv\n\n namespace errors {\n class NotFound extends Error {}\n class PermissionDenied extends Error {}\n }\n\n interface DirEntry {\n name: string\n isFile: boolean\n isDirectory: boolean\n isSymlink: boolean\n }\n\n interface FileInfo {\n isFile: boolean\n isDirectory: boolean\n isSymlink: boolean\n size: number\n mtime: Date | null\n }\n\n function readDir(path: string): AsyncIterable<DirEntry>\n function stat(path: string): Promise<FileInfo>\n function utime(path: string, atime: Date | number, mtime: Date | number): Promise<void>\n function readTextFile(path: string | URL): Promise<string>\n\n /** What `serve` returns: stopping it (stop.ts) waits for the requests in flight. */\n interface HttpServer {\n /** Stops taking connections; resolves once the requests in flight have finished. */\n shutdown(): Promise<void>\n /** Resolves when the server has closed. */\n readonly finished: Promise<void>\n }\n\n function serve(\n options: { port: number; hostname?: string; onListen?: (params: { hostname: string; port: number }) => void },\n handler: (req: Request) => Response | Promise<Response>,\n ): HttpServer\n\n // What stop.ts uses to exit on a stop signal.\n const build: { readonly os: \"darwin\" | \"linux\" | \"android\" | \"windows\" | \"freebsd\" | \"netbsd\" | \"aix\" | \"solaris\" | \"illumos\" }\n function addSignalListener(signal: \"SIGTERM\" | \"SIGINT\", handler: () => void): void\n function exit(code?: number): never\n\n // What tests/ uses to start the worker as a child process and give it a functions directory.\n function test(name: string, fn: () => void | Promise<void>): void\n function execPath(): string\n function makeTempDir(options?: { prefix?: string }): Promise<string>\n function makeTempFile(options?: { prefix?: string; suffix?: string }): Promise<string>\n function mkdir(path: string, options?: { recursive?: boolean }): Promise<void>\n function writeTextFile(path: string, data: string): Promise<void>\n function remove(path: string, options?: { recursive?: boolean }): Promise<void>\n\n interface CommandOptions {\n args?: string[]\n env?: Record<string, string>\n clearEnv?: boolean\n stdout?: \"piped\" | \"inherit\" | \"null\"\n stderr?: \"piped\" | \"inherit\" | \"null\"\n }\n\n interface ChildProcess {\n readonly stdout: ReadableStream<Uint8Array>\n readonly status: Promise<{ success: boolean; code: number }>\n kill(signal?: \"SIGTERM\" | \"SIGKILL\"): void\n }\n\n class Command {\n constructor(command: string, options?: CommandOptions)\n spawn(): ChildProcess\n }\n}\n\n/**\n * The slice of Node's `async_hooks` the worker uses. Deno provides the module at runtime; tsc has no\n * `@types/node` here, and without this the import resolved to nothing and `store` was untyped.\n */\ndeclare module \"node:async_hooks\" {\n export class AsyncLocalStorage<T> {\n getStore(): T | undefined\n run<R>(store: T, callback: () => R): R\n }\n}\n",
5
+ "dotenv.ts": "// Generated from packages/cli/src/dotenv-parse.ts by scripts/functions-worker-source.mjs. Do not\n// edit: change that file and run the script, so the CLI and the worker read .env files alike.\n/**\n * The dotenv parser: one for every reader of a `.env` file, the CLI's and the functions worker's.\n *\n * No imports and no runtime APIs, so the same file runs under Node and Deno. The functions worker\n * carries an exact copy (packages/functions-worker/dotenv.ts), written from this one by\n * scripts/functions-worker-source.mjs and checked in CI, so a function's `ctx.env` reads a value\n * the way the CLI and compose do.\n */\n\n/** `KEY` and the text after its `=` for an assignment line, or null for anything else. */\nexport function splitAssignment(line: string): { key: string; rest: string } | null {\n const trimmed = line.trim().replace(/^export\\s+/, \"\")\n if (trimmed.startsWith(\"#\")) return null\n const eq = trimmed.indexOf(\"=\")\n if (eq <= 0) return null\n const key = trimmed.slice(0, eq).trim()\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) ? { key, rest: trimmed.slice(eq + 1) } : null\n}\n\n/** Index of the quote closing `value`'s opening one, skipping escaped quotes, or -1. */\nfunction closingQuote(value: string, quote: string): number {\n for (let i = 1; i < value.length; i++) {\n if (value[i] === quote && value[i - 1] !== \"\\\\\") return i\n }\n return -1\n}\n\n/**\n * The value of one assignment, read the way Docker Compose's dotenv parser reads it.\n *\n * A quoted value runs to its closing quote and keeps any `#` inside; text after the quote is\n * ignored. An unquoted value ends at the first space followed by `#`, and trailing whitespace is\n * dropped, so `KEY=x # note` is `x` while `KEY=x#y` is `x#y`. Reading ` # note` into the value\n * signed tokens with a secret the stack, reading the same line through compose, did not have.\n */\nfunction envValueOf(rest: string): string {\n const value = rest.trim()\n const quote = value[0]\n if (quote === '\"' || quote === \"'\") {\n const close = closingQuote(value, quote)\n if (close > 0) return value.slice(1, close)\n }\n const comment = value.indexOf(\" #\")\n return (comment === -1 ? value : value.slice(0, comment)).trimEnd()\n}\n\n/**\n * Parse `.env` text into key/value pairs, the one parser every reader of `.env` goes through.\n *\n * Follows Compose on what it shares with it: `#` comments, an optional `export `, quotes, inline\n * comments, and the last assignment of a key winning. Not interpolation or escape sequences in\n * double quotes, which nothing the CLI writes or reads relies on.\n */\nexport function parseEnvText(text: string): Record<string, string> {\n const out: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const assignment = splitAssignment(line)\n if (assignment !== null) out[assignment.key] = envValueOf(assignment.rest)\n }\n return out\n}\n",
6
+ "invocation.ts": "import { AsyncLocalStorage } from \"node:async_hooks\"\n\n/**\n * What a function is told about the call it is serving, and the store that carries it.\n *\n * # Why this exists at all\n *\n * The worker used to deliver this through `Deno.env`: it set `SUPATYPE_SERVICE_ROLE_KEY` and the\n * rest before calling the handler and restored them afterwards. `Deno.env` is process-global, so\n * two concurrent invocations would read each other's values, a service-role key granted to one\n * route and not the other among them. The defence was a lock held across the *whole* handler, so the\n * worker executed exactly one invocation at a time.\n *\n * That is a throughput property nobody chose: a function waiting two seconds on a third-party API\n * blocked every other function in the project for two seconds, and on cloud there is one worker per\n * project. It was invisible because `supatype dev` generates a router with the same lock, so local\n * behaved exactly like production.\n *\n * Nothing per-invocation goes into the environment now. It is passed to the handler as a second\n * argument and carried here for the things a handler cannot be handed directly, so there is no\n * global to protect and no reason to serialise.\n *\n * # What is *not* here\n *\n * `SUPATYPE_URL`, `SUPATYPE_ANON_KEY` and the other invariants. Those are set once by compose or by\n * the deployment and never differ between invocations, so they stay in the environment where they\n * already are. The old code read each one out of the environment and set it straight back, which\n * looked like scoping and achieved nothing.\n */\nexport interface FunctionContext {\n /** Unique to this invocation. Every log line it writes carries the same value. */\n readonly executionId: string\n /** The function or hook route being served. */\n readonly functionName: string\n /**\n * The project's API base URL, reachable from inside this container: for calling the API from the\n * function. Under compose it is `http://kong:8000`, a name nothing outside the stack resolves.\n */\n readonly url: string\n /**\n * The project's public address, the gateway URL a browser or an app uses: for links you give to\n * people (an email, a redirect, a URL in a response). Falls back to `url` when the deployment did\n * not set `SUPATYPE_PUBLIC_URL`, and the worker warns once at start when it does.\n */\n readonly publicUrl: string\n readonly anonKey: string\n /**\n * Present only for a route the project granted it.\n *\n * Withheld from the process environment before any handler is imported, so a function that was\n * not granted it cannot reach it by reading `Deno.env` either.\n */\n readonly serviceRoleKey?: string\n /**\n * A raw Postgres connection URL. Off by default: present only when the operator sets\n * `SUPATYPE_FUNCTIONS_DB_URL`, which compose hands this worker as `SUPATYPE_DB_URL` (and joins it\n * to the `functions-db` network when the URL names the stack's `db`).\n *\n * It connects as whatever role the URL names and is not a request through the API, so row rules\n * and field masking do not apply to it. The operator should give it a least-privilege role\n * granted only what the functions need, never the admin URL. A credential: never returned or\n * logged.\n */\n readonly dbUrl?: string\n readonly region: string\n /**\n * Values from the functions directory's `.env.local` (or `SUPATYPE_SHARED_ENV_FILE`), then those\n * `functions env set` gave a self-hosted project (`SUPATYPE_FUNCTION_ENV_FILE`), then\n * `.env.<function>.local`, which wins. Per route, and read again on every call.\n *\n * They are here, never in `Deno.env`: that is the worker's one process environment, shared by\n * every call running at once, so a value put there for one function would reach every other.\n */\n readonly env: Readonly<Record<string, string>>\n}\n\n/** The parts the worker needs internally but a handler has no use for. */\ninterface InvocationStore {\n readonly context: FunctionContext\n /**\n * The hook-depth header to carry onto outbound calls, when this invocation is a hook.\n *\n * Here rather than patched onto `globalThis.fetch` per call. That patch was the second global\n * mutation the lock was protecting: two concurrent hooks would patch over each other, and the\n * first to finish would restore the other's patch.\n */\n readonly hookDepth: string | null\n}\n\nconst store = new AsyncLocalStorage<InvocationStore>()\n\n/** Run an invocation with its context available to everything it calls. */\nexport function runInvocation<T>(\n context: FunctionContext,\n hookDepth: string | null,\n run: () => Promise<T>,\n): Promise<T> {\n return store.run({ context, hookDepth }, run)\n}\n\n/** The invocation being served on this call stack, or undefined outside one. */\nexport function currentInvocation(): FunctionContext | undefined {\n return store.getStore()?.context\n}\n\n/** The hook depth to propagate, or null when this is not a hook call. */\nexport function currentHookDepth(): string | null {\n return store.getStore()?.hookDepth ?? null\n}\n",
7
+ "logging.ts": "import { currentInvocation } from \"./invocation.ts\"\n\n/**\n * Structured invocation logging, and a live tail over it.\n *\n * # Why structured, and why this exact shape\n *\n * The worker used to write `GET /functions/v1/foo → 200 (12ms)` to its own stdout and nothing else.\n * On cloud, `infra/k8s/platform/logging.yaml` runs Promtail into Loki with a pipeline that parses\n * each line as JSON and labels on `project_ref`, `service` and `level`, taking the timestamp from a\n * `timestamp` field in Go's `2006-01-02T15:04:05.000Z` layout. A plain-text line survives none of\n * that: it is collected, matches no expression, and is indexed under no project.\n *\n * So the fields below are not a taste; they are the contract that pipeline already expects.\n * `toISOString()` produces exactly three fractional digits and a `Z`, which is that layout.\n *\n * # Why a tail rather than a store\n *\n * Cloud has Loki, with retention per tier. Self-host has eleven services and no log store, and\n * adding one changes the footprint of every self-hosted deployment, so for release the self-host\n * answer is a live tail: attach, see what happens while attached, detach. Nothing is written down,\n * nothing lands in the project's own Postgres, and no service is added.\n *\n * The ring buffer exists only so that attaching does not start from an empty screen.\n *\n * # Why the context comes from AsyncLocalStorage\n *\n * `console` is global and invocations now genuinely run concurrently, so a captured line has to be\n * attributed to the invocation that wrote it rather than to whichever one happens to be current. A\n * module-level \"current request\" would mis-attribute every interleaved line.\n *\n * The store is `invocation.ts`, shared with the context a handler is passed, so a log line and the\n * function that wrote it cannot disagree about which call they belong to.\n */\n\n/** What every line carries, whether the worker wrote it or a function did. */\nexport interface LogLine {\n timestamp: string\n level: \"debug\" | \"info\" | \"warn\" | \"error\"\n service: \"functions-worker\"\n project_ref: string\n /** The invocation, or absent for a line the worker wrote outside one. */\n request_id?: string\n /** The function or hook route, when there is one. */\n function?: string\n message: string\n /** Present on the line that completes an invocation. */\n duration_ms?: number\n status?: number\n}\n\n/**\n * The real console methods, captured before anything is patched.\n *\n * Emitting through the patched `console` would call the patch again, which is an unbounded\n * recursion that takes the worker down on its first log line.\n */\nconst realConsole = {\n debug: console.debug.bind(console),\n info: console.info.bind(console),\n log: console.log.bind(console),\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n}\n\nfunction projectRef(): string {\n const env = (key: string): string => Deno.env.get(key)?.trim() ?? \"\"\n // Self-host sets the first; cloud's templates use the managed and dedicated spellings. Falling\n // back to \"unknown\" rather than \"\" keeps the Loki label present, since a line with no\n // `project_ref` is indexed under no project and is effectively lost.\n return env(\"SUPATYPE_PROJECT_REF\") || env(\"SUPATYPE_MANAGED_PROJECT_REF\") || env(\"DEDICATED_PROJECT_REF\") || \"unknown\"\n}\n\nconst TAIL_BUFFER_LINES = Math.max(\n 0,\n parseInt(Deno.env.get(\"SUPATYPE_LOG_TAIL_BUFFER\") ?? \"500\", 10) || 500,\n)\n\nconst buffer: LogLine[] = []\nconst subscribers = new Set<(line: LogLine) => void>()\n/** How to end each open tail, so a stopping worker is not held by a stream that never ends. */\nconst openTails = new Set<() => void>()\n\n/** Ends every open tail; a tailing client reconnects to the worker that replaces this one. */\nexport function closeTails(): void {\n for (const close of [...openTails]) close()\n}\n\nfunction record(line: LogLine): void {\n if (TAIL_BUFFER_LINES > 0) {\n buffer.push(line)\n if (buffer.length > TAIL_BUFFER_LINES) buffer.shift()\n }\n for (const send of subscribers) {\n try {\n send(line)\n } catch {\n // A subscriber whose stream has gone is removed when its cancel handler runs. Throwing here\n // would lose the line for everybody else, and drop it from stdout too.\n }\n }\n}\n\n/** Everything except the message, so a caller only has to supply what it knows. */\nfunction baseLine(level: LogLine[\"level\"]): Omit<LogLine, \"message\"> {\n const current = currentInvocation()\n return {\n timestamp: new Date().toISOString(),\n level,\n service: \"functions-worker\",\n project_ref: projectRef(),\n ...(current !== undefined && {\n request_id: current.executionId,\n function: current.functionName,\n }),\n }\n}\n\n/** Write one line as JSON on stdout, and give it to anybody tailing. */\nexport function emit(line: LogLine): void {\n record(line)\n const write = line.level === \"error\" ? realConsole.error : realConsole.log\n write(JSON.stringify(line))\n}\n\n/** A line the worker itself is writing, at this level, inside whatever invocation is current. */\nexport function log(level: LogLine[\"level\"], message: string, extra: Partial<LogLine> = {}): void {\n emit({ ...baseLine(level), message, ...extra })\n}\n\n/**\n * Replace `console` so that a function's own output is structured and attributable.\n *\n * A function author writes `console.log(\"saved\", id)` and expects it to appear. It used to reach the\n * container's stdout unstructured and unlabelled, so on cloud it was dropped by the pipeline and on\n * self-host it was mixed in with every other invocation's output with nothing to tell them apart.\n *\n * Arguments are formatted the way a console does rather than JSON-stringified: `console.error(err)`\n * on an `Error` should say what went wrong, not `{}`.\n */\nexport function installStructuredLogging(): void {\n const levels: Array<[keyof typeof realConsole, LogLine[\"level\"]]> = [\n [\"debug\", \"debug\"],\n [\"info\", \"info\"],\n [\"log\", \"info\"],\n [\"warn\", \"warn\"],\n [\"error\", \"error\"],\n ]\n for (const [method, level] of levels) {\n console[method] = (...args: unknown[]): void => {\n emit({ ...baseLine(level), message: args.map(format).join(\" \") })\n }\n }\n}\n\nfunction format(value: unknown): string {\n if (typeof value === \"string\") return value\n if (value instanceof Error) return value.stack ?? `${value.name}: ${value.message}`\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n // Circular, or a BigInt. Neither is a reason to lose the line.\n return String(value)\n }\n}\n\n/**\n * The live tail, as server-sent events.\n *\n * Replays the buffer first so attaching does not start blank, then streams. `retry` is set so a\n * dropped connection reconnects on its own; a tail that silently stops is worse than no tail.\n */\nexport function tailResponse(): Response {\n const encoder = new TextEncoder()\n let unsubscribe = (): void => {}\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const send = (line: LogLine): void => {\n controller.enqueue(encoder.encode(`data: ${JSON.stringify(line)}\\n\\n`))\n }\n controller.enqueue(encoder.encode(\"retry: 2000\\n\\n\"))\n for (const line of buffer) send(line)\n\n const close = (): void => {\n unsubscribe()\n controller.close()\n }\n subscribers.add(send)\n openTails.add(close)\n unsubscribe = () => {\n subscribers.delete(send)\n openTails.delete(close)\n }\n },\n cancel() {\n unsubscribe()\n },\n })\n\n return new Response(stream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n // Nothing between here and the reader may buffer a stream whose whole purpose is to arrive as\n // it happens.\n \"X-Accel-Buffering\": \"no\",\n },\n })\n}\n\n/** For tests: what is currently in the replay buffer. */\nexport function bufferedLines(): readonly LogLine[] {\n return buffer\n}\n",
8
+ "main.ts": "/**\n * Standalone edge-functions worker (per-project or per-function).\n * The image runs it, and so do native `supatype dev` and `supatype functions serve`, from the copy\n * the CLI carries (scripts/functions-worker-source.mjs), so a function behaves the same in each.\n */\n\nimport { parseEnvText } from \"./dotenv.ts\"\nimport { FUNCTION_ENTRY_FILE, functionRouteName, isHookName } from \"./routes.ts\"\nimport { exitOnStop } from \"./stop.ts\"\nimport {\n currentHookDepth,\n runInvocation,\n type FunctionContext,\n} from \"./invocation.ts\"\nimport {\n closeTails,\n installStructuredLogging,\n log,\n tailResponse,\n} from \"./logging.ts\"\n\ninstallStructuredLogging()\n// Once, at startup. Hook depth then comes from the invocation store rather than from a patch\n// applied and reverted around every call.\ninstallHookDepthPropagation()\n\n/**\n * Route names the worker answers itself.\n *\n * Underscore-prefixed, the convention Deno Deploy and Supabase both use, so a reserved route cannot\n * collide with a function somebody has already deployed. Discovery warns if one is shadowed rather\n * than silently winning.\n */\nconst RESERVED_ROUTES = new Set([\"_logs\"])\n\ntype Handler = (req: Request, ctx: FunctionContext) => Response | Promise<Response>\n\ninterface DiscoveredRoute {\n name: string\n entrypoint: string\n}\n\n/**\n * Root for public functions, or \"\" when this worker serves none.\n *\n * Empty is a real configuration, not a mistake: a per-hook worker mounts a hooks root and nothing else,\n * and its pod has no functions directory to point at. Requiring this one made such a pod crashloop,\n * which the API server sees as the hook refusing to answer, failing every write to its table. Startup\n * still fails when *both* roots are empty, since a worker with no source at all is a misconfiguration.\n */\nfunction functionsRoot(): string {\n const root = (\n Deno.env.get(\"SUPATYPE_FUNCTIONS_ROOT\") ??\n Deno.env.get(\"SUPATYPE_DENO_FUNCTIONS_DIR\") ??\n \"\"\n ).trim()\n if (!root) return \"\"\n return root.endsWith(\"/\") ? root.slice(0, -1) : root\n}\n\n/**\n * Root for **model hooks**, served under a `hooks/` route prefix.\n *\n * Hooks are procedural: the API server calls them around a write, while everything under the\n * functions root is a public endpoint anyone holding the anon key can invoke. Keeping them in one\n * worker rather than two costs a project no extra pod; keeping them under a route prefix is what lets\n * the gateway refuse them from outside, so the separation is structural rather than a deny-list that\n * a stale manifest could empty.\n */\nfunction hooksRoot(): string {\n const root = (Deno.env.get(\"SUPATYPE_HOOKS_ROOT\") ?? \"\").trim()\n if (!root) return \"\"\n return root.endsWith(\"/\") ? root.slice(0, -1) : root\n}\n\n/** Route prefix for hook handlers. The gateway refuses this prefix on the public path. */\nconst HOOKS_ROUTE_PREFIX = \"hooks/\"\n\n/** A comma-separated route list as a set, empty entries dropped. */\nfunction parseRoutes(text: string): Set<string> {\n return new Set(\n text\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0),\n )\n}\n\n/** The routes file as last read: kept while its modification time and size are unchanged. */\nlet routesFileRead: { mtime: number; size: number; routes: Set<string> } | null = null\n\n/**\n * The routes in `file`, read again only when its modification time or size changed: one stat a\n * call. Undefined when it has not been written (the environment's list applies); none when it is\n * there but cannot be read.\n */\nasync function routesFromFile(file: string): Promise<Set<string> | undefined> {\n let info: Deno.FileInfo\n try {\n info = await Deno.stat(file)\n } catch (err) {\n return err instanceof Deno.errors.NotFound ? undefined : new Set()\n }\n const mtime = info.mtime?.getTime() ?? -1\n if (routesFileRead !== null && routesFileRead.mtime === mtime && routesFileRead.size === info.size) return routesFileRead.routes\n try {\n routesFileRead = { mtime, size: info.size, routes: parseRoutes(await Deno.readTextFile(file)) }\n } catch {\n routesFileRead = null\n return new Set()\n }\n return routesFileRead.routes\n}\n\n/**\n * Public function routes allowed to see `SUPATYPE_SERVICE_ROLE_KEY`, looked up on every call: from\n * the file `SUPATYPE_SERVICE_ROLE_ROUTES_FILE` names once it is written, else\n * `SUPATYPE_SERVICE_ROLE_ROUTES`. Native dev writes the file when `functions.serviceRole` changes,\n * and a self-hosted control plane on every deploy, so a route taken off the list loses the key on its\n * next call, with no restart; the environment is fixed when the worker starts. A routes file that is\n * there but cannot be read grants nothing.\n *\n * Hooks do not appear here: they get the key by default (see serviceRoleGranted). This list is for\n * the public surface, where the default is nothing.\n */\nasync function serviceRoleRoutes(): Promise<Set<string>> {\n const file = Deno.env.get(\"SUPATYPE_SERVICE_ROLE_ROUTES_FILE\")\n const fromFile = file ? await routesFromFile(file) : undefined\n return fromFile ?? parseRoutes(Deno.env.get(\"SUPATYPE_SERVICE_ROLE_ROUTES\") ?? \"\")\n}\n\n/** The function every entry of a hook or validator map names (table, then event or column, then the entry). */\nfunction functionsNamed(map: unknown): string[] {\n if (typeof map !== \"object\" || map === null) return []\n return Object.values(map).flatMap((entries: unknown) =>\n typeof entries !== \"object\" || entries === null\n ? []\n : Object.values(entries).flatMap((entry: unknown) =>\n typeof entry === \"object\" && entry !== null && \"function\" in entry && typeof entry.function === \"string\" ? [entry.function] : [],\n ),\n )\n}\n\n/**\n * The hooks the stack's manifest maps (its `hooks` and `validators`), from the file\n * `SUPATYPE_MANIFEST_PATH` names, the one the server reads; read on each call, which only a hook\n * route with no code makes. Null when no manifest is named (Cloud's worker), or the one named cannot\n * be read or parsed (caught mid-rewrite, say): the caller then fails closed.\n */\nasync function mappedHookNames(): Promise<Set<string> | null> {\n const path = (Deno.env.get(\"SUPATYPE_MANIFEST_PATH\") ?? \"\").trim()\n if (!path) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(await Deno.readTextFile(path))\n } catch {\n return null\n }\n if (typeof parsed !== \"object\" || parsed === null) return null\n const maps = [\"hooks\" in parsed ? parsed.hooks : undefined, \"validators\" in parsed ? parsed.validators : undefined]\n return new Set(maps.flatMap(functionsNamed))\n}\n\n/**\n * Whether a hook route the worker has no code for answers 503 (the hook cannot be reached, and the\n * server refuses the write for it) rather than 404 (no such hook). With the manifest's map, only a\n * name it maps. Without one, every name that passes the hook-name rule: it fails closed, since a 404\n * is read by the server as the hook rejecting the write.\n */\nasync function unreachableHook(name: string): Promise<boolean> {\n const mapped = await mappedHookNames()\n if (mapped !== null) return mapped.has(name)\n return isHookName(name)\n}\n\n/**\n * Whether a route may see the service-role key.\n *\n * **Hooks: yes.** A hook is procedural, only the API server calls it, around a write the caller was\n * already permitted to make, and the gateway refuses its route from outside, so it is not reachable\n * by anyone who could choose to invoke it. Requiring each one to be listed would be friction with no\n * attacker to stop, and it is the same trust a trigger or a migration already has.\n *\n * **Public functions: only if named.** Those *are* invocable by anyone holding the anon key, so an\n * ambient admin credential there is read and write access past every access rule in the schema,\n * handed to code the internet can call.\n */\nasync function serviceRoleGranted(route: string): Promise<boolean> {\n if (route.startsWith(HOOKS_ROUTE_PREFIX)) return true\n return (await serviceRoleRoutes()).has(route)\n}\n\n/**\n * Take the service-role key out of the process environment, returning it for scoped re-injection.\n *\n * **Before handlers are imported**, which is the whole point: a handler's module body runs at import\n * time, so a key still in `Deno.env` then is a key any handler can copy and keep. Withholding it\n * afterwards would be theatre.\n *\n * The default is now \"no admin credential\". A function is a public endpoint, anyone holding the anon\n * key can invoke one, and an ambient service-role key made every one of them able to read and write\n * past every access rule in the schema. Opting in is a line in `supatype.config.ts`, which is\n * reviewable; ambient privilege is not.\n */\nasync function withholdServiceRoleKey(): Promise<string> {\n const key = Deno.env.get(\"SUPATYPE_SERVICE_ROLE_KEY\") ?? \"\"\n if (key) Deno.env.delete(\"SUPATYPE_SERVICE_ROLE_KEY\")\n const keyFile = (Deno.env.get(\"SUPATYPE_SERVICE_ROLE_KEY_FILE\") ?? \"\").trim()\n return keyFile ? await readServiceRoleKeyFile(keyFile) : key\n}\n\n/**\n * The service-role key from `path`, or \"\" (no function is given it) when the file cannot be read.\n *\n * For a worker run under `deno run --watch`, as native `supatype dev` and `supatype functions serve`\n * run it. A reload evaluates this module again in the same process, whose environment the first\n * evaluation already took the key out of, so a key from the environment is there once only. The\n * file is still there however the earlier evaluation ended. Its path stays in the environment: a\n * function able to read the disk can read the file whether or not it is told where it is, and the\n * key a function is handed is still decided by serviceRoleGranted alone.\n */\nasync function readServiceRoleKeyFile(path: string): Promise<string> {\n try {\n return (await Deno.readTextFile(path)).trim()\n } catch (err) {\n log(\"error\", `No function is given the service-role key: could not read ${path} (${errorText(err)})`)\n return \"\"\n }\n}\n\nasync function discoverRoutes(root: string): Promise<DiscoveredRoute[]> {\n const single = Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")?.trim()\n const out: DiscoveredRoute[] = []\n\n // The catch has to wrap the *iteration*: `Deno.readDir` returns its iterable without touching the\n // filesystem, so a missing directory raises NotFound on the first `next()`, not here. A root that\n // does not exist is ordinary, a project with functions but no hooks has no hooks directory, and\n // letting it throw would fail startup and take that project's working functions down with it.\n try {\n // routes.ts is the rule a self-hosted control plane lists functions by too.\n for await (const entry of Deno.readDir(root)) {\n const fullPath = `${root}/${entry.name}`\n const name = entry.isDirectory || entry.isFile ? functionRouteName(entry.name, entry.isDirectory ? \"directory\" : \"file\") : undefined\n if (name === undefined || (single && name !== single)) continue\n const entrypoint = entry.isDirectory ? `${fullPath}/${FUNCTION_ENTRY_FILE}` : fullPath\n try {\n await Deno.stat(entrypoint)\n out.push({ name, entrypoint })\n } catch {\n // A directory with no entry module is not a route.\n }\n }\n } catch (err) {\n if (!(err instanceof Deno.errors.NotFound)) throw err\n }\n\n return out.sort((a, b) => a.name.localeCompare(b.name))\n}\n\nfunction entrypointImportUrl(entrypoint: string): string {\n const normalized = entrypoint.replace(/\\\\/g, \"/\")\n if (normalized.startsWith(\"file://\")) return normalized\n // A Windows absolute path is not a URL: `new URL(\"C:/x\")` reads the drive letter as the scheme, and\n // Deno then refuses to import scheme \"c\". Invisible in a Linux container, where every root starts\n // with \"/\", and fatal the moment this worker runs on a developer's machine.\n if (/^[A-Za-z]:\\//.test(normalized)) return `file:///${normalized}`\n if (normalized.startsWith(\"/\")) return `file://${normalized}`\n return new URL(normalized, import.meta.url).href\n}\n\n/**\n * A function's exported handler. A boundary: what can be checked is that it is a function; what it\n * takes and returns is the function author's contract with the worker, which only calling it tests.\n */\nfunction isHandler(value: unknown): value is Handler {\n return typeof value === \"function\"\n}\n\n/** The module's `default` export, else its `handler` export. */\nfunction exportedHandler(mod: unknown): unknown {\n if (typeof mod !== \"object\" || mod === null) return undefined\n const fallback = \"handler\" in mod ? mod.handler : undefined\n return (\"default\" in mod ? mod.default : undefined) ?? fallback\n}\n\nasync function loadHandlers(routes: DiscoveredRoute[]): Promise<Record<string, Handler>> {\n const handlers: Record<string, Handler> = {}\n\n for (const route of routes) {\n // The reserved route wins, because the worker answers it before the handler lookup. Say so\n // rather than leaving an author wondering why their function returns an event stream.\n if (RESERVED_ROUTES.has(route.name)) {\n log(\"warn\", `Function \"${route.name}\" is shadowed: the worker reserves that route`, {\n function: route.name,\n })\n continue\n }\n handlers[route.name] = await loadHandler(route)\n }\n\n return handlers\n}\n\n/**\n * The route's handler, or, when its module fails to import or exports no handler, one that answers\n * the route with a 500 saying why. The first such module used to stop the worker starting, so one\n * broken function took every function in the project down with it. The message goes out as JSON,\n * so the escape codes come out of it: a client has no terminal to colour.\n */\nasync function loadHandler(route: DiscoveredRoute): Promise<Handler> {\n try {\n // A module loaded by URL is typed `any`; read its exports as unknown until checked.\n const mod: unknown = await import(entrypointImportUrl(route.entrypoint))\n const handler = exportedHandler(mod)\n if (!isHandler(handler)) throw new Error('it has neither a default export nor a named \"handler\" export')\n return handler\n } catch (err) {\n const message = `Function \"${route.name}\" failed to load: ${errorText(err)}`\n log(\"error\", message, { function: route.name })\n return () => jsonError(\"function_load_failed\", message, 500)\n }\n}\n\n/**\n * Terminal escape codes. Deno colours a missing module's location in its message, piped or not,\n * and a handler's own error can carry them too.\n */\nconst TERMINAL_ESCAPES = /\\u001b\\[[0-9;?]*[A-Za-z]/g\n\n/**\n * What a thrown value says: an Error's message, anything else as a string, without escape codes,\n * since it goes out as JSON and a client has no terminal to colour.\n */\nfunction errorText(err: unknown): string {\n return (err instanceof Error ? err.message : String(err)).replace(TERMINAL_ESCAPES, \"\")\n}\n\n/** A JSON error answer, `{ error: code, message, ...extra }`, as every route of the worker gives one. */\nfunction jsonError(code: string, message: string, status: number, extra: Record<string, unknown> = {}): Response {\n return new Response(JSON.stringify({ error: code, message, ...extra }), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n })\n}\n\nconst port = parseInt(Deno.env.get(\"PORT\") ?? \"8001\", 10)\n// Order matters: withhold, then import. See withholdServiceRoleKey.\nconst serviceRoleKey = await withholdServiceRoleKey()\nconst root = functionsRoot()\nconst routes = root ? await discoverRoutes(root) : []\nconst handlers = await loadHandlers(routes)\n\n// Hooks are namespaced so one worker can serve both without a name in `hooks/` ever shadowing, or\n// being reachable as: a public function of the same name.\nconst hooksDir = hooksRoot()\nif (!root && !hooksDir) {\n throw new Error(\n \"SUPATYPE_FUNCTIONS_ROOT or SUPATYPE_HOOKS_ROOT is required (a worker with neither serves nothing)\",\n )\n}\nif (hooksDir) {\n const hookRoutes = await discoverRoutes(hooksDir)\n const hookHandlers = await loadHandlers(hookRoutes)\n for (const [name, handler] of Object.entries(hookHandlers)) {\n handlers[HOOKS_ROUTE_PREFIX + name] = handler\n }\n}\n\n// A worker pinned to one route still has to find it, and with two roots \"absent from this one\" is not\n// \"absent everywhere\": a per-hook pod names its hook and has no functions directory at all. Checked\n// once, after both roots, so the failure means what it says, and it stays a failure, because a pod\n// serving nothing would answer 404 to the API server, which reads as the hook refusing to answer and\n// fails every write to its table.\nconst single = Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")?.trim()\nif (single && Object.keys(handlers).length === 0) {\n throw new Error(\n `Handler \"${single}\" not found under ${root}` + (hooksDir ? ` or ${hooksDir}` : \"\"),\n )\n}\n\nconsole.log(\n `[functions-worker] ${Object.keys(handlers).length} handler(s) on :${port}` +\n (Deno.env.get(\"SUPATYPE_FUNCTION_NAME\") ? ` (single: ${Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")})` : \"\"),\n)\n\n// Falls back to the hooks root: a per-hook worker has no functions directory, and the shared env file\n// is looked for beside whichever source this worker actually has.\nconst normalizedFunctionsDir = root || hooksDir\nconst sharedEnvPath =\n Deno.env.get(\"SUPATYPE_SHARED_ENV_FILE\") ?? `${normalizedFunctionsDir}/.env.local`\n\n\n\n/** The variables in the env file at `path`, read as the CLI and compose read one; none if it is absent. */\nasync function readEnvFile(path: string): Promise<Record<string, string>> {\n if (!path) return {}\n try {\n return parseEnvText(await Deno.readTextFile(path))\n } catch {\n return {}\n }\n}\n\n/**\n * The values `functions env set` gave a self-hosted project: the control plane's JSON map, which\n * compose names here. Without it a value set through the control plane never reached a function.\n * Read on every call, like the env files, so a set or unset is seen without a restart.\n */\nconst managedEnvPath = (Deno.env.get(\"SUPATYPE_FUNCTION_ENV_FILE\") ?? \"\").trim()\n\nasync function readManagedEnv(): Promise<Record<string, string>> {\n if (!managedEnvPath) return {}\n let parsed: unknown\n try {\n parsed = JSON.parse(await Deno.readTextFile(managedEnvPath))\n } catch {\n return {}\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return {}\n return Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"))\n}\n\n/**\n * The shared env file, then the managed values, then the function's own file, which wins. The three\n * are read together: every call waits for them.\n */\nasync function scopedEnvForFunction(fnName: string): Promise<Record<string, string>> {\n const [shared, managed, fnVars] = await Promise.all([\n readEnvFile(sharedEnvPath),\n readManagedEnv(),\n readEnvFile(`${normalizedFunctionsDir}/.env.${fnName}.local`),\n ])\n return { ...shared, ...managed, ...fnVars }\n}\n\nconst HOOK_DEPTH_HEADER = \"x-supatype-hook-depth\"\n\n/**\n * Carry the hook-depth header onto calls a hook makes back into the stack.\n *\n * Patched once, at startup, rather than per invocation. The old version replaced `globalThis.fetch`\n * for the duration of a call and restored it afterwards, which is only safe while exactly one\n * invocation runs at a time: two concurrent hooks would patch over each other, and the first to\n * finish would restore the other's patch. That mutation was half the reason for the lock.\n *\n * Depth comes from the invocation store, so this closure holds no per-call state at all.\n */\nfunction installHookDepthPropagation(): void {\n const original = globalThis.fetch\n globalThis.fetch = (input: Request | URL | string, init?: RequestInit): Promise<Response> => {\n const depth = currentHookDepth()\n const stack = stackOrigin()\n if (depth === null || stack === null) return original(input, init)\n\n const url = input instanceof Request ? input.url : String(input)\n if (!url.startsWith(stack)) return original(input, init)\n\n const request = new Request(input, init)\n request.headers.set(HOOK_DEPTH_HEADER, depth)\n return original(request)\n }\n}\n\n/**\n * The database URL a function may use, when the deployment gave the worker one: off unless the\n * operator set SUPATYPE_FUNCTIONS_DB_URL (see `FunctionContext.dbUrl`).\n */\nfunction dbUrlForFunctions(): string | undefined {\n const raw = Deno.env.get(\"SUPATYPE_DB_URL\") ?? Deno.env.get(\"DATABASE_URL\")\n return raw === undefined || raw.trim() === \"\" ? undefined : raw\n}\n\n/** The stack's own origin, or null when this worker was not told how to reach it. */\nfunction stackOrigin(): string | null {\n const raw = Deno.env.get(\"SUPATYPE_INTERNAL_URL\") ?? Deno.env.get(\"SUPATYPE_URL\")\n if (raw === undefined || raw.trim() === \"\") return null\n try {\n return new URL(raw).origin\n } catch {\n return null\n }\n}\n\n/**\n * The project's public address, handed to every function as `ctx.publicUrl` (see FunctionContext).\n *\n * Read once, at start: it never differs between invocations, and a deployment that left it unset\n * should be told once rather than on every call. The fallback is `ctx.url`, which under compose is\n * an in-stack name, so a link built from it would reach nobody; the warning says so.\n */\nfunction resolvePublicUrl(): string {\n const configured = (Deno.env.get(\"SUPATYPE_PUBLIC_URL\") ?? \"\").trim()\n if (configured !== \"\") return configured\n const internal = Deno.env.get(\"SUPATYPE_URL\") ?? \"\"\n log(\n \"warn\",\n \"SUPATYPE_PUBLIC_URL is not set, so ctx.publicUrl falls back to ctx.url \" +\n `(${internal || \"unset\"}), which may be an address only this stack can reach`,\n )\n return internal\n}\n\nconst publicUrl = resolvePublicUrl()\n\n\n// `onListen` is supplied so Deno does not print its own \"Listening on …\" line. That line goes to\n// stderr, which this worker's patched console reports as `level: \"error\"`, and on cloud `level` is\n// a Loki label, so every startup would appear in the dashboards as an error.\n// Every address in its container; `functions serve` and native dev name 127.0.0.1.\nconst hostname = Deno.env.get(\"SUPATYPE_FUNCTIONS_HOST\") ?? \"0.0.0.0\"\nconst server = Deno.serve({\n hostname,\n port,\n onListen: ({ hostname, port: bound }) => {\n log(\"info\", `functions-worker listening on http://${hostname}:${bound}`)\n },\n}, async (req: Request): Promise<Response> => {\n const url = new URL(req.url)\n const pathParts = url.pathname.replace(/^\\/functions\\/v1\\/?/, \"\").split(\"/\").filter(Boolean)\n // A hook is addressed as `hooks/<name>`, so the first segment alone is not the handler key. With no\n // second segment no hook name is built: the path is looked up as the plain route \"hooks\", a 404\n // unless a function has that name, so `hooks/<name>` always carries a name the request sent.\n const fnName =\n pathParts[0] === \"hooks\" && pathParts[1]\n ? HOOKS_ROUTE_PREFIX + pathParts[1]\n : pathParts[0] ?? \"\"\n\n // Answered by the worker itself, before the handler lookup, so a project with no functions at all\n // still has a tail.\n if (RESERVED_ROUTES.has(fnName)) {\n if (fnName === \"_logs\") return tailResponse()\n }\n\n // A hook the map names with no code here (a new hook whose deploy failed) cannot be reached: 503,\n // which the server's hook dispatch treats as unavailable and refuses the write for. A 404 read as\n // the hook rejecting the write, with a \"not found\" message. Any other name stays a 404\n // (unreachableHook).\n if (fnName.startsWith(HOOKS_ROUTE_PREFIX) && !handlers[fnName]) {\n const hook = fnName.slice(HOOKS_ROUTE_PREFIX.length)\n if (await unreachableHook(hook)) return jsonError(\"hook_unavailable\", `Hook \"${hook}\" is not deployed`, 503)\n }\n if (!fnName || !handlers[fnName]) {\n const message = fnName ? `Function \"${fnName}\" not found` : \"No function specified\"\n return jsonError(\"not_found\", message, 404, { available: Object.keys(handlers) })\n }\n\n // Nothing goes into the process environment, so nothing has to be taken back out and nothing has\n // to be serialised. This used to hold a lock across the whole handler, which meant the worker ran\n // one invocation at a time: a function waiting on a third-party API blocked every other function\n // in the project for as long as it waited.\n const dbUrl = dbUrlForFunctions()\n const context: FunctionContext = {\n executionId: crypto.randomUUID(),\n functionName: fnName,\n url: Deno.env.get(\"SUPATYPE_URL\") ?? \"\",\n publicUrl,\n anonKey: Deno.env.get(\"SUPATYPE_ANON_KEY\") ?? \"\",\n // From the closure, not the environment: the key was withheld before any handler was imported,\n // and only a route the project granted it receives it here.\n ...(serviceRoleKey && (await serviceRoleGranted(fnName)) && { serviceRoleKey }),\n ...(dbUrl !== undefined && { dbUrl }),\n region: Deno.env.get(\"SUPATYPE_REGION\") ?? \"local\",\n env: await scopedEnvForFunction(fnName),\n }\n\n const start = performance.now()\n\n try {\n const response = await runInvocation(context, req.headers.get(HOOK_DEPTH_HEADER), async () =>\n handlers[fnName]!(req, context),\n )\n log(\"info\", `${req.method} /functions/v1/${fnName} → ${response.status}`, {\n request_id: context.executionId,\n function: fnName,\n status: response.status,\n duration_ms: Number((performance.now() - start).toFixed(1)),\n })\n return response\n } catch (err) {\n const message = errorText(err)\n log(\"error\", message, {\n request_id: context.executionId,\n function: fnName,\n status: 500,\n duration_ms: Number((performance.now() - start).toFixed(1)),\n })\n return jsonError(\"function_error\", message, 500)\n }\n})\n// A restart of its container waited out the stop timeout without this, and must not cut off the\n// requests in flight (stop.ts). A log tail never ends on its own, so it is closed first.\nexitOnStop(() => {\n closeTails()\n return server.shutdown()\n})\n",
9
+ "routes.ts": "// Generated from packages/shared/src/function-routes.ts by scripts/functions-worker-source.mjs. Do\n// not edit: change that file and run the script, so the worker and the control plane agree.\n/**\n * Which entries of a functions or hooks directory the functions worker serves, and by what route\n * name. The worker discovers its routes by this rule and a self-hosted control plane lists them by\n * it, so the list names exactly what answers. The worker cannot import this package: the generator\n * (scripts/functions-worker-source.mjs) copies this file into it as routes.ts, so it must import\n * nothing.\n */\n\n/** The module a directory route runs; a directory without one is not a route. */\nexport const FUNCTION_ENTRY_FILE = \"index.ts\"\n\n/**\n * The route the worker serves for `entry`, or undefined for an entry it skips. `_` and `.` prefixed\n * entries are never routes (`_shared`, `.git`). A directory is the route of its name, when it holds\n * {@link FUNCTION_ENTRY_FILE}, which the caller checks. A file is the route of its name without\n * `.ts`; a declaration file (`.d.ts`) and anything else is not one.\n */\nexport function functionRouteName(entry: string, kind: \"directory\" | \"file\"): string | undefined {\n if (entry.startsWith(\"_\") || entry.startsWith(\".\")) return undefined\n if (kind === \"directory\") return entry\n return entry.endsWith(\".ts\") && !entry.endsWith(\".d.ts\") ? entry.slice(0, -\".ts\".length) : undefined\n}\n\n/**\n * A hook name: letters of either case, digits, `-` and `_`, starting with a letter or digit. Wider\n * than a function name, because the CLI and Cloud take a hook's name from the schema and its folder\n * as written (`onUserCreate`): Cloud stores it as a ConfigMap key, and the worker skips a name that\n * starts with `_` or `.`. Still one path segment: nothing in it can name a parent, a separator or a\n * hidden entry.\n */\nexport const HOOK_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\n/** The hook rule, said for a person. */\nexport const HOOK_NAME_RULE = 'use letters, digits, \"-\" and \"_\", starting with a letter or digit'\n\n/** Whether `name` passes the hook-name rule. */\nexport function isHookName(name: unknown): name is string {\n return typeof name === \"string\" && HOOK_NAME.test(name)\n}\n",
10
+ "stop.ts": "/**\n * The worker stops when it is told to. In its container it runs as PID 1, and PID 1 gets no default\n * action for SIGTERM or SIGINT: with no handler, `docker restart` and `docker stop` waited out the\n * whole stop timeout (10 s) before killing it, so every self-host deploy that restarted the worker\n * took more than ten seconds. The compose file also gives it an init (`init: true`).\n *\n * On SIGTERM it does not exit mid-request: a deploy restarts the worker, and exiting at once cut off\n * every invocation in flight. It stops taking requests, lets those it has finish, then exits; bounded\n * by {@link drainGraceMs}. SIGINT (Ctrl+C in dev or `functions serve`) and a second signal while\n * draining exit at once: someone at a terminal is not kept waiting.\n */\n\n/**\n * How long in-flight requests get to finish when nothing says otherwise: under the 5 s the dev\n * process manager waits before it kills the worker, so a stop in dev is never slower than a kill.\n */\nexport const DRAIN_GRACE_MS = 4_000\n\n/** The longest drain the environment may ask for; more would outlast any stop timeout in use. */\nexport const MAX_DRAIN_GRACE_MS = 60_000\n\n/**\n * The drain grace `SUPATYPE_FUNCTIONS_DRAIN_MS` asks for, in whole milliseconds, capped at\n * {@link MAX_DRAIN_GRACE_MS}; {@link DRAIN_GRACE_MS} when it is unset or not a whole number. The\n * self-host compose sets it under its stop_grace_period: there Docker allows 10 s, and a 4 s drain\n * cut off every function with more left at each restart (round 6b, N29).\n */\nexport function drainGraceMs(value: string | undefined): number {\n const text = value?.trim() ?? \"\"\n if (!/^\\d+$/.test(text)) return DRAIN_GRACE_MS\n return Math.min(Number(text), MAX_DRAIN_GRACE_MS)\n}\n\n/** What stopping needs of Deno, replaceable in tests. */\nexport interface StopHooks {\n os: string\n addSignalListener(signal: \"SIGTERM\" | \"SIGINT\", handler: () => void): void\n exit(code: number): void\n}\n\nconst DENO_HOOKS: StopHooks = {\n os: Deno.build.os,\n addSignalListener: (signal, handler) => Deno.addSignalListener(signal, handler),\n exit: (code) => Deno.exit(code),\n}\n\n/** `drain()`, or `graceMs`, whichever ends first; the timer is cleared either way. */\nasync function drainWithin(drain: () => Promise<void>, graceMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const grace = new Promise<void>((done) => (timer = setTimeout(done, graceMs)))\n try {\n await Promise.race([drain().catch(() => undefined), grace])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * On SIGTERM, drains with `drain` (closing the log tails and the server's `shutdown()`, which stops\n * taking requests and resolves once those in flight have finished) for at most `graceMs`, then exits\n * 0. SIGINT, and any signal while draining, exits at once. Not on Windows, where Deno takes no SIGTERM\n * listener and a process is stopped some other way.\n */\nexport function exitOnStop(\n drain: () => Promise<void>,\n hooks: StopHooks = DENO_HOOKS,\n graceMs = drainGraceMs(Deno.env.get(\"SUPATYPE_FUNCTIONS_DRAIN_MS\")),\n): void {\n if (hooks.os === \"windows\") return\n let draining = false\n const exitNow = (): void => hooks.exit(0)\n hooks.addSignalListener(\"SIGINT\", exitNow)\n hooks.addSignalListener(\"SIGTERM\", () => {\n if (draining) return exitNow()\n draining = true\n void drainWithin(drain, graceMs).then(exitNow)\n })\n}\n",
11
+ };
12
+ //# sourceMappingURL=functions-worker-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions-worker-source.js","sourceRoot":"","sources":["../../src/generated/functions-worker-source.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,8FAA8F;AAC9F,MAAM,CAAC,MAAM,uBAAuB,GAAqC;IACvE,WAAW,EAAE,62GAA62G;IAC13G,WAAW,EAAE,m4FAAm4F;IACh5F,eAAe,EAAE,0iKAA0iK;IAC3jK,YAAY,EAAE,+iQAA+iQ;IAC7jQ,SAAS,EAAE,69zBAA69zB;IACx+zB,WAAW,EAAE,ovEAAovE;IACjwE,SAAS,EAAE,w5GAAw5G;CACp6G,CAAA"}
@@ -0,0 +1,18 @@
1
+ export declare const PINNED_IMAGES: {
2
+ readonly engine: {
3
+ readonly image: "supatype/schema-engine";
4
+ readonly tag: "v0.8.0";
5
+ readonly commit: "878b4980e53dfd959ad65eecf9df4224f4d611d6";
6
+ };
7
+ readonly server: {
8
+ readonly image: "supatype/server";
9
+ readonly tag: "v2.2.2";
10
+ readonly commit: "00f0ad3e782dbcf5fbb3d2e607aa044d66ba0138";
11
+ };
12
+ readonly postgres: {
13
+ readonly image: "supatype/postgres";
14
+ readonly tag: "17.2.12";
15
+ readonly commit: "ab9020f7691dced4875634dc88dfe500968faa5a";
16
+ };
17
+ };
18
+ //# sourceMappingURL=release-images.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release-images.d.ts","sourceRoot":"","sources":["../../src/generated/release-images.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;CAIhB,CAAA"}
@@ -0,0 +1,8 @@
1
+ // Generated from release/images.json by scripts/release-images.mjs. Do not edit: run
2
+ // `bash scripts/pin.sh set <engine|server|postgres> <tag>`, which rewrites both.
3
+ export const PINNED_IMAGES = {
4
+ engine: { image: "supatype/schema-engine", tag: "v0.8.0", commit: "878b4980e53dfd959ad65eecf9df4224f4d611d6" },
5
+ server: { image: "supatype/server", tag: "v2.2.2", commit: "00f0ad3e782dbcf5fbb3d2e607aa044d66ba0138" },
6
+ postgres: { image: "supatype/postgres", tag: "17.2.12", commit: "ab9020f7691dced4875634dc88dfe500968faa5a" },
7
+ };
8
+ //# sourceMappingURL=release-images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release-images.js","sourceRoot":"","sources":["../../src/generated/release-images.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,iFAAiF;AACjF,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,MAAM,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,0CAA0C,EAAE;IAC9G,MAAM,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,0CAA0C,EAAE;IACvG,QAAQ,EAAE,EAAE,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,0CAA0C,EAAE;CACpG,CAAA"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The engine that writes a project's generated files (the types, the client's seed builder, the
3
+ * admin config): `supatype generate` and Docker dev's refresh after a push both ask here.
4
+ *
5
+ * The host engine program, resolved as push resolves the one it writes types with: the pin, else
6
+ * this build's default, or `overrides.engine`. Generating needs no database, and running it in the
7
+ * compose image cost two `docker compose run`s and left the project's network and volume behind
8
+ * (local test round 3, N7). The two used to choose differently, so the types a save wrote and the
9
+ * ones `generate` wrote could come from two engines (decision, round 3).
10
+ *
11
+ * Only a host program that cannot be fetched (`BinaryUnavailable`: offline, a platform or libc with
12
+ * no build) falls back, and only for a Docker project with no engine override, to its own compose
13
+ * engine image. A refusal, an engine too old, or a config error is the answer as it is. A failed
14
+ * fetch is remembered for the process, so an offline dev session does not try the download again
15
+ * on every save, and the caller is told why once, after it has written with the image.
16
+ */
17
+ import type { ComposeEngine } from "./engine-client.js";
18
+ import { type SupatypeProjectConfig } from "./project-config.js";
19
+ /** How the engine is found, replaceable in tests. */
20
+ export interface GeneratedFilesEngineDeps {
21
+ hostEngine: () => Promise<void>;
22
+ composeEngine: (cwd: string, config: SupatypeProjectConfig) => Promise<ComposeEngine | undefined>;
23
+ }
24
+ /** The engine to write with (undefined: the host program) and, the first time it fell back, why. */
25
+ export interface EngineChoice {
26
+ engine: ComposeEngine | undefined;
27
+ fellBack?: string;
28
+ }
29
+ /** What a caller says, once it has written with the image, about the fallback. */
30
+ export declare const ENGINE_FALLBACK = "The engine program could not be fetched, so the project's engine image wrote the generated files";
31
+ /** The engine to write generated files with: see the file's comment. */
32
+ export declare function generatedFilesEngine(cwd: string, config: SupatypeProjectConfig, deps?: Partial<GeneratedFilesEngineDeps>): Promise<EngineChoice>;
33
+ //# sourceMappingURL=generated-files-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generated-files-engine.d.ts","sourceRoot":"","sources":["../src/generated-files-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAIvD,OAAO,EAA0B,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAA;AAExF,qDAAqD;AACrD,MAAM,WAAW,wBAAwB;IACvC,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC/B,aAAa,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,qBAAqB,KAAK,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAA;CAClG;AAOD,oGAAoG;AACpG,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,aAAa,GAAG,SAAS,CAAA;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,kFAAkF;AAClF,eAAO,MAAM,eAAe,qGAAqG,CAAA;AAKjI,wEAAwE;AACxE,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,qBAAqB,EAC7B,IAAI,GAAE,OAAO,CAAC,wBAAwB,CAAM,GAC3C,OAAO,CAAC,YAAY,CAAC,CAavB"}
@@ -0,0 +1,45 @@
1
+ import { hasEngineOverride, pinnedVersion } from "./binary-cache.js";
2
+ import { BinaryUnavailable } from "./ensure-binary.js";
3
+ import { errorMessage } from "./error-message.js";
4
+ import { resolveRuntimeProvider } from "./project-config.js";
5
+ const DEFAULT_DEPS = {
6
+ hostEngine: async () => (await import("./engine-client.js")).ensureEngine(),
7
+ composeEngine: async (cwd, config) => (await import("./dev-compose.js")).projectComposeEngine(cwd, config),
8
+ };
9
+ /** What a caller says, once it has written with the image, about the fallback. */
10
+ export const ENGINE_FALLBACK = "The engine program could not be fetched, so the project's engine image wrote the generated files";
11
+ /** Engine versions whose host program could not be fetched in this process. */
12
+ const unavailable = new Set();
13
+ /** The engine to write generated files with: see the file's comment. */
14
+ export async function generatedFilesEngine(cwd, config, deps = {}) {
15
+ const use = { ...DEFAULT_DEPS, ...deps };
16
+ const version = pinnedVersion("engine", config) ?? "this build's";
17
+ if (unavailable.has(version))
18
+ return { engine: await imageOrThrow(cwd, config, use, undefined) };
19
+ try {
20
+ await use.hostEngine();
21
+ return { engine: undefined };
22
+ }
23
+ catch (err) {
24
+ if (!(err instanceof BinaryUnavailable) || resolveRuntimeProvider(config) !== "docker" || hasEngineOverride(config))
25
+ throw err;
26
+ const engine = await imageOrThrow(cwd, config, use, err);
27
+ unavailable.add(version);
28
+ return { engine, fellBack: errorMessage(err) };
29
+ }
30
+ }
31
+ /** The project's engine image, or an error that keeps the host program's reason beside the image's. */
32
+ async function imageOrThrow(cwd, config, use, hostError) {
33
+ const host = hostError === undefined ? "the engine program could not be fetched earlier" : errorMessage(hostError);
34
+ let image;
35
+ try {
36
+ image = await use.composeEngine(cwd, config);
37
+ }
38
+ catch (err) {
39
+ throw new Error(`${host}; the project's engine image could not be used either: ${errorMessage(err)}`, { cause: err });
40
+ }
41
+ if (image === undefined)
42
+ throw hostError instanceof Error ? hostError : new Error(host);
43
+ return image;
44
+ }
45
+ //# sourceMappingURL=generated-files-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generated-files-engine.js","sourceRoot":"","sources":["../src/generated-files-engine.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,sBAAsB,EAA8B,MAAM,qBAAqB,CAAA;AAQxF,MAAM,YAAY,GAA6B;IAC7C,UAAU,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC,CAAC,YAAY,EAAE;IAC3E,aAAa,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC;CAC3G,CAAA;AAQD,kFAAkF;AAClF,MAAM,CAAC,MAAM,eAAe,GAAG,kGAAkG,CAAA;AAEjI,+EAA+E;AAC/E,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAA;AAErC,wEAAwE;AACxE,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,GAAW,EACX,MAA6B,EAC7B,OAA0C,EAAE;IAE5C,MAAM,GAAG,GAAG,EAAE,GAAG,YAAY,EAAE,GAAG,IAAI,EAAE,CAAA;IACxC,MAAM,OAAO,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,cAAc,CAAA;IACjE,IAAI,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,CAAC,EAAE,CAAA;IAChG,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,UAAU,EAAE,CAAA;QACtB,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAA;IAC9B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,CAAC,GAAG,YAAY,iBAAiB,CAAC,IAAI,sBAAsB,CAAC,MAAM,CAAC,KAAK,QAAQ,IAAI,iBAAiB,CAAC,MAAM,CAAC;YAAE,MAAM,GAAG,CAAA;QAC9H,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;QACxD,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QACxB,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,CAAC,GAAG,CAAC,EAAE,CAAA;IAChD,CAAC;AACH,CAAC;AAED,uGAAuG;AACvG,KAAK,UAAU,YAAY,CACzB,GAAW,EACX,MAA6B,EAC7B,GAA6B,EAC7B,SAAkB;IAElB,MAAM,IAAI,GAAG,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,iDAAiD,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,CAAC,CAAA;IAClH,IAAI,KAAgC,CAAA;IACpC,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IAC9C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,0DAA0D,YAAY,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;IACvH,CAAC;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,MAAM,SAAS,YAAY,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAA;IACvF,OAAO,KAAK,CAAA;AACd,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { SupatypeProjectConfig } from "./project-config.js";
2
+ /** The setting, as compose and native dev pass it to PostgREST. */
3
+ export declare const POSTGREST_HOOK_ACTOR_ENV: {
4
+ readonly PGRST_DB_PRE_REQUEST: "auth.emit_hook_actor";
5
+ };
6
+ /**
7
+ * The first server release whose migrations create `auth.emit_hook_actor()` (server migration
8
+ * 20261103180000_add_hook_actor_marker). Must equal that release's version: set it when the server
9
+ * is released, before the CLI release that pins it.
10
+ */
11
+ export declare const SERVER_MIN_FOR_HOOK_ACTOR = "2.3.0";
12
+ /**
13
+ * {@link POSTGREST_HOOK_ACTOR_ENV} when the project's server creates the function, else nothing.
14
+ * The server is the project's `versions.server` pin, or the one this CLI release pins.
15
+ */
16
+ export declare function postgrestHookActorEnv(config: SupatypeProjectConfig): typeof POSTGREST_HOOK_ACTOR_ENV | Record<string, never>;
17
+ //# sourceMappingURL=hook-actor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-actor.d.ts","sourceRoot":"","sources":["../src/hook-actor.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAA;AAEhE,mEAAmE;AACnE,eAAO,MAAM,wBAAwB;;CAA4D,CAAA;AAEjG;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,UAAU,CAAA;AAKhD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,qBAAqB,GAAG,OAAO,wBAAwB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAM5H"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * PostgREST's db-pre-request for after-hooks, and which servers it may be named for.
3
+ *
4
+ * The server's `auth.emit_hook_actor()`, run by PostgREST before each request in that request's own
5
+ * transaction, writes the caller into the change log beside the request's writes. That is how the
6
+ * after-hook listener tells an API write, and who made it, from a write made in SQL.
7
+ *
8
+ * PostgREST calls the pre-request function on every request, and one that does not exist fails them
9
+ * all. So it is named only for a server whose migrations create it: a project pinned to an older
10
+ * server keeps a working API, and its after-hooks get no caller.
11
+ */
12
+ import { compareVersions } from "./engine-floor.js";
13
+ import { defaultComponentVersion } from "./release-images.js";
14
+ /** The setting, as compose and native dev pass it to PostgREST. */
15
+ export const POSTGREST_HOOK_ACTOR_ENV = { PGRST_DB_PRE_REQUEST: "auth.emit_hook_actor" };
16
+ /**
17
+ * The first server release whose migrations create `auth.emit_hook_actor()` (server migration
18
+ * 20261103180000_add_hook_actor_marker). Must equal that release's version: set it when the server
19
+ * is released, before the CLI release that pins it.
20
+ */
21
+ export const SERVER_MIN_FOR_HOOK_ACTOR = "2.3.0";
22
+ /** Server pins that are not a release number, and run the server built from source or the newest. */
23
+ const UNNUMBERED_SERVER_PINS = new Set(["local", "latest"]);
24
+ /**
25
+ * {@link POSTGREST_HOOK_ACTOR_ENV} when the project's server creates the function, else nothing.
26
+ * The server is the project's `versions.server` pin, or the one this CLI release pins.
27
+ */
28
+ export function postgrestHookActorEnv(config) {
29
+ const pinned = config.versions?.server?.trim();
30
+ const server = pinned !== undefined && pinned !== "" ? pinned : defaultComponentVersion("server");
31
+ if (server === undefined)
32
+ return {};
33
+ if (UNNUMBERED_SERVER_PINS.has(server))
34
+ return POSTGREST_HOOK_ACTOR_ENV;
35
+ return compareVersions(server, SERVER_MIN_FOR_HOOK_ACTOR) >= 0 ? POSTGREST_HOOK_ACTOR_ENV : {};
36
+ }
37
+ //# sourceMappingURL=hook-actor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-actor.js","sourceRoot":"","sources":["../src/hook-actor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAA;AAG7D,mEAAmE;AACnE,MAAM,CAAC,MAAM,wBAAwB,GAAG,EAAE,oBAAoB,EAAE,sBAAsB,EAAW,CAAA;AAEjG;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAO,CAAA;AAEhD,qGAAqG;AACrG,MAAM,sBAAsB,GAAwB,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAA;AAEhF;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAA6B;IACjE,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,CAAA;IAC9C,MAAM,MAAM,GAAG,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAA;IACjG,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,EAAE,CAAA;IACnC,IAAI,sBAAsB,CAAC,GAAG,CAAC,MAAM,CAAC;QAAE,OAAO,wBAAwB,CAAA;IACvE,OAAO,eAAe,CAAC,MAAM,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,EAAE,CAAA;AAChG,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Which columns an after-hook's rows carry, per hooked table.
3
+ *
4
+ * After-hooks are fed from the database's change log, which no row or field rule filters, so the
5
+ * row a hook receives would otherwise hold every column. A column with a field `read` rule is left
6
+ * out unless the hook declares `columns: "all"`, so a hook that forwards a row to email or chat
7
+ * cannot leak a column the person who saved it could never see. The listener also needs each
8
+ * table's key to name a delivery.
9
+ *
10
+ * One function computes all of it, for the generated hook types and for whatever the server is sent,
11
+ * so the two cannot disagree about which columns a hook sees.
12
+ */
13
+ import { type AfterHookColumns, type ManifestTableEntry } from "@supatype/shared";
14
+ import { type AstModel } from "./augmentation-generator.js";
15
+ import type { AfterHookEvent } from "./hook-events.js";
16
+ export { isAfterHookEvent, type AfterHookEvent } from "./hook-events.js";
17
+ /**
18
+ * The manifest's `tables` entry, with both events always said: `restrictedColumns` and `primaryKey`
19
+ * in declaration order, and per after-hook what it declared (`"safe"` when it declared nothing).
20
+ */
21
+ export interface HookTableColumns extends ManifestTableEntry {
22
+ columns: Record<AfterHookEvent, AfterHookColumns>;
23
+ }
24
+ /** Per table that declares a hook, keyed by the table as Postgres keeps it. */
25
+ export declare function hookTableColumns(ast: unknown): Record<string, HookTableColumns>;
26
+ /** {@link HookTableColumns} for one model, whether or not it declares a hook. */
27
+ export declare function modelHookColumns(model: AstModel): HookTableColumns;
28
+ /** The restricted columns `event`'s rows leave out: none when it declared `columns: "all"`. */
29
+ export declare function hiddenColumns(table: HookTableColumns, event: AfterHookEvent): string[];
30
+ //# sourceMappingURL=hook-columns.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-columns.d.ts","sourceRoot":"","sources":["../src/hook-columns.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAgB,KAAK,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAE/F,OAAO,EAA+C,KAAK,QAAQ,EAAE,MAAM,6BAA6B,CAAA;AACxG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAEtD,OAAO,EAAE,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAExE;;;GAGG;AACH,MAAM,WAAW,gBAAiB,SAAQ,kBAAkB;IAC1D,OAAO,EAAE,MAAM,CAAC,cAAc,EAAE,gBAAgB,CAAC,CAAA;CAClD;AAED,+EAA+E;AAC/E,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAO/E;AAED,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,QAAQ,GAAG,gBAAgB,CAUlE;AAED,+FAA+F;AAC/F,wBAAgB,aAAa,CAAC,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,cAAc,GAAG,MAAM,EAAE,CAEtF"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Which columns an after-hook's rows carry, per hooked table.
3
+ *
4
+ * After-hooks are fed from the database's change log, which no row or field rule filters, so the
5
+ * row a hook receives would otherwise hold every column. A column with a field `read` rule is left
6
+ * out unless the hook declares `columns: "all"`, so a hook that forwards a row to email or chat
7
+ * cannot leak a column the person who saved it could never see. The listener also needs each
8
+ * table's key to name a delivery.
9
+ *
10
+ * One function computes all of it, for the generated hook types and for whatever the server is sent,
11
+ * so the two cannot disagree about which columns a hook sees.
12
+ */
13
+ import { isJsonObject } from "@supatype/shared";
14
+ import { isNonEmptyObject, objectAt } from "./ast-read.js";
15
+ import { astModelsOf, columnNameOf, resolveTableName } from "./augmentation-generator.js";
16
+ export { isAfterHookEvent } from "./hook-events.js";
17
+ /** Per table that declares a hook, keyed by the table as Postgres keeps it. */
18
+ export function hookTableColumns(ast) {
19
+ const out = {};
20
+ for (const model of astModelsOf(ast)) {
21
+ if (!isNonEmptyObject(objectAt(model, "annotations", "platform", "hooks")))
22
+ continue;
23
+ out[resolveTableName(model)] = modelHookColumns(model);
24
+ }
25
+ return out;
26
+ }
27
+ /** {@link HookTableColumns} for one model, whether or not it declares a hook. */
28
+ export function modelHookColumns(model) {
29
+ const hooks = objectAt(model, "annotations", "platform", "hooks");
30
+ return {
31
+ restrictedColumns: restrictedColumnsOf(model),
32
+ primaryKey: primaryKeyOf(model),
33
+ columns: {
34
+ afterChange: declaredColumns(hooks?.["afterChange"]),
35
+ afterDelete: declaredColumns(hooks?.["afterDelete"]),
36
+ },
37
+ };
38
+ }
39
+ /** The restricted columns `event`'s rows leave out: none when it declared `columns: "all"`. */
40
+ export function hiddenColumns(table, event) {
41
+ return table.columns[event] === "all" ? [] : table.restrictedColumns;
42
+ }
43
+ function declaredColumns(entry) {
44
+ return isJsonObject(entry) && entry["columns"] === "all" ? "all" : "safe";
45
+ }
46
+ /**
47
+ * Columns with a field `read` rule. A `write` rule alone hides nothing from a reader, so it does not
48
+ * restrict a hook either. A rule on a relation names its foreign key column, which is what a row
49
+ * carries.
50
+ */
51
+ function restrictedColumnsOf(model) {
52
+ const rules = objectAt(model, "annotations", "platform", "access", "fields");
53
+ if (rules === undefined)
54
+ return [];
55
+ return Object.entries(rules)
56
+ .filter(([, rule]) => isJsonObject(rule) && rule["read"] !== undefined)
57
+ .flatMap(([name]) => columnOf(model, name));
58
+ }
59
+ /** The key columns, in the order the fields are declared. */
60
+ function primaryKeyOf(model) {
61
+ return Object.entries(model.fields)
62
+ .filter(([, meta]) => meta["primaryKey"] === true)
63
+ .flatMap(([name]) => columnOf(model, name));
64
+ }
65
+ /**
66
+ * The column `name` names, as the generated Row type names it, or none for a relation that keeps
67
+ * its key on the other table. A name that is no declared field is already a column (a field rule on
68
+ * a relation is written against its foreign key).
69
+ */
70
+ function columnOf(model, name) {
71
+ const meta = model.fields[name];
72
+ if (meta === undefined)
73
+ return [name];
74
+ const column = columnNameOf(name, meta);
75
+ return column === null ? [] : [column];
76
+ }
77
+ //# sourceMappingURL=hook-columns.js.map