@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
@@ -1,22 +1,31 @@
1
1
  import { errorMessage } from "../error-message.js";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, unlinkSync, } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
3
3
  import { resolve, join, relative, isAbsolute } from "node:path";
4
- import { spawnSync } from "node:child_process";
5
- import { localKongBaseUrl, localPublicApiUrl } from "../local-gateway.js";
4
+ import { runUntilStopped } from "../run-until-stopped.js";
5
+ import { fetchWithin } from "../fetch-within.js";
6
+ import { targetRequest, targetStreamRequest } from "../target-request.js";
7
+ import { parseEnvText } from "../dotenv-parse.js";
8
+ import { withEnvValue, withoutEnvValue } from "../env-lines.js";
9
+ import { STOP_SIGNALS } from "../stop-signals.js";
10
+ import { sayTargetWarning } from "../target-warning.js";
6
11
  import { resolveProjectApiUrl } from "../resolve-api-url.js";
7
12
  import { loadConfig, rethrowIfConfigBroken } from "../config.js";
8
13
  import { ensureBinary } from "../ensure-binary.js";
9
- import { functionsPathCandidatesFromProject, preferredFunctionsPathFromProject, serviceRoleRoutes, } from "../project-config.js";
10
- import { discoverFunctionsOrExit, functionNameProblem, generateFunctionsRouterSource, } from "../functions-router-gen.js";
14
+ import { FUNCTIONS_SERVE_PORT, functionsPathCandidatesFromProject, hooksPathFromProject, preferredFunctionsPathFromProject, serviceRoleRoutes, } from "../project-config.js";
15
+ import { discoverFunctionsOrExit, functionNameProblem } from "../functions-discovery.js";
16
+ import { functionsServeDenoArgs, functionsWorkerEnv, installFunctionsWorker, } from "../functions-worker-files.js";
17
+ import { functionsServeKeyPath, sweepStaleServeKeyFiles, writeServiceRoleKeyFileUntilExit } from "../service-role-key-file.js";
11
18
  import { loadProjectLink } from "../link.js";
12
- import { resolveCloudAccessToken } from "../cloud-credentials.js";
13
- import { resolveTarget } from "../resolve-target.js";
14
- import { targetFetch } from "../target-client.js";
15
- import { isArrayOf, isJsonObject, isNumber, isShape, isString, nullable, optional, readJson } from "@supatype/shared";
19
+ import { resolveTarget, targetFunctions } from "../resolve-target.js";
20
+ import { targetFetch, targetStream } from "../target-client.js";
21
+ import { isArrayOf, isJsonObject, isNumber, isShape, isString, isUnknown, nullable, optional } from "@supatype/shared";
16
22
  import { ensureFunctionsDenoTypes, sharedFunctionsReadmeSource, } from "../functions-deno-types.js";
17
23
  import { functionTemplateSource } from "../functions-template.js";
24
+ import { readWorkerFiles } from "../worker-module-files.js";
18
25
  import { error, info, plain } from "../ui/messages.js";
26
+ import { withSpinner } from "../ui/progress.js";
19
27
  import { nextSteps } from "../ui/next-steps.js";
28
+ import { DENO_ENV } from "../native-dev-env.js";
20
29
  // ─── Constants ───────────────────────────────────────────────────────────────
21
30
  const SHARED_DIR = "_shared";
22
31
  const ENV_LOCAL = ".env.local";
@@ -24,11 +33,18 @@ const ENV_PRODUCTION = ".env.production";
24
33
  // The commands that exist: there is no `supatype cloud` group, login and link are top level.
25
34
  const NOT_LOGGED_IN = "Not logged in. Run: supatype login";
26
35
  const NOT_LINKED = "No linked project. Run: supatype link";
36
+ /**
37
+ * Where a function reads its env values, said in every help that sets them: a function reading
38
+ * `Deno.env.get` finds nothing, and help is where a user looks first.
39
+ */
40
+ const ENV_HELP = "Values set with `functions env set`, in .env.local or in .env.<name>.local arrive in `ctx.env` " +
41
+ "on each call, never in Deno.env, which every call running at once shares.";
27
42
  // ─── Registration ────────────────────────────────────────────────────────────
28
43
  export function registerFunctions(program) {
29
44
  const fnCmd = program
30
45
  .command("functions")
31
- .description("Manage Supatype Edge Functions (Deno-based serverless TypeScript)");
46
+ .summary("Manage Supatype Edge Functions (Deno-based serverless TypeScript)")
47
+ .description(`Manage Supatype Edge Functions (Deno-based serverless TypeScript).\n\n${ENV_HELP}`);
32
48
  fnCmd
33
49
  .command("new <name>")
34
50
  .description("Scaffold a new edge function")
@@ -38,7 +54,8 @@ export function registerFunctions(program) {
38
54
  fnCmd
39
55
  .command("serve")
40
56
  .description("Start a local Deno server that serves all functions with hot reload")
41
- .option("--port <port>", "Port to serve on", "54321")
57
+ .option("--port <port>", "Port to serve on", String(FUNCTIONS_SERVE_PORT))
58
+ .option("--host <host>", "Address to listen on (0.0.0.0 to be reachable from other machines)", "127.0.0.1")
42
59
  .option("--env-file <path>", "Path to env file", ENV_LOCAL)
43
60
  .action(async (opts) => {
44
61
  await serve(process.cwd(), opts);
@@ -75,14 +92,16 @@ export function registerFunctions(program) {
75
92
  .command("invoke <name>")
76
93
  .description("Invoke a local or deployed function")
77
94
  .option("--data <json>", "JSON body to send", "{}")
78
- .option("--auth", "Include a test JWT in the request")
79
- .option("--local", "Invoke the local dev server (default if serve is running)")
95
+ .option("--auth", "Send a token: your Cloud session on a Cloud link, a test JWT on this machine; refused for a self-hosted server")
96
+ .option("--local", "Invoke locally: a running `functions serve` on --port if one answers, otherwise the dev API (the default when no Cloud project is linked)")
97
+ .option("--port <port>", "Port of the local `functions serve` to try first", String(FUNCTIONS_SERVE_PORT))
80
98
  .action(async (name, opts) => {
81
99
  await invoke(process.cwd(), name, opts);
82
100
  });
83
101
  const envCmd = fnCmd
84
102
  .command("env")
85
- .description("Manage function environment variables");
103
+ .summary("Manage function environment variables")
104
+ .description(`Manage function environment variables: on the linked project, else in the functions directory's .env.local.\n\n${ENV_HELP}`);
86
105
  envCmd
87
106
  .command("list")
88
107
  .description("List environment variables (values masked)")
@@ -91,7 +110,8 @@ export function registerFunctions(program) {
91
110
  });
92
111
  envCmd
93
112
  .command("set <keyvalue>")
94
- .description("Set an environment variable (KEY=value)")
113
+ .summary("Set an environment variable (KEY=value)")
114
+ .description(`Set an environment variable (KEY=value).\n\n${ENV_HELP}`)
95
115
  .action(async (keyvalue) => {
96
116
  await envSet(process.cwd(), keyvalue);
97
117
  });
@@ -186,28 +206,10 @@ function discoverFunctions(cwd) {
186
206
  async function serve(cwd, opts) {
187
207
  const config = loadConfig(cwd);
188
208
  const functionsDir = resolveFunctionsDir(cwd, "read");
189
- const functionsDirLabel = relativeFunctionsDir(cwd, functionsDir);
190
- const routes = discoverFunctionsOrExit(functionsDir);
191
- if (routes.length === 0) {
192
- error(`No functions found in ${functionsDirLabel}/`);
193
- error("Create one with: npx supatype functions new <name>");
194
- process.exit(1);
195
- }
196
- plain(`Discovered ${routes.length} function(s):`);
197
- for (const fn of routes) {
198
- plain(` /${fn.name} → ${relative(cwd, fn.entrypoint)}`);
199
- }
200
- plain();
201
- // Generate a Deno entry script that routes requests to the correct function
202
- const routerPath = resolve(functionsDir, ".serve-router.ts");
203
- const routerScript = generateFunctionsRouterSource(routerPath, routes);
204
- writeFileSync(routerPath, routerScript, "utf8");
205
- const envFilePath = resolveEnvFilePath(cwd, functionsDir, opts.envFile);
206
- const envArgs = [];
207
- if (existsSync(envFilePath)) {
208
- envArgs.push("--env-file", envFilePath);
209
- }
210
- info(`Serving functions at http://localhost:${opts.port}/functions/v1/`);
209
+ listServeFunctions(cwd, functionsDir);
210
+ const project = { cwd, config, functionsDir, keyPath: writeServeKeyFile(cwd) };
211
+ const envArgs = denoEnvFileArgs(resolveEnvFilePath(cwd, functionsDir, opts.envFile));
212
+ info(`Serving functions at ${serveDisplayUrl(opts.host, opts.port)}`);
211
213
  info("Watching for changes...");
212
214
  plain();
213
215
  let denoBin;
@@ -218,37 +220,96 @@ async function serve(cwd, opts) {
218
220
  error(`Could not provision Deno: ${errorMessage(err)}`);
219
221
  process.exit(1);
220
222
  }
221
- const result = spawnSync(denoBin, [
222
- "run",
223
- "--allow-net",
224
- "--allow-env",
225
- "--allow-read",
226
- "--watch",
227
- ...envArgs,
228
- routerPath,
229
- ], {
230
- stdio: "inherit",
231
- cwd,
232
- env: {
233
- ...process.env,
234
- PORT: opts.port,
235
- SUPATYPE_DENO_FUNCTIONS_DIR: functionsDir,
236
- SUPATYPE_SHARED_ENV_FILE: resolve(functionsDir, ENV_LOCAL),
237
- SUPATYPE_URL: process.env["SUPATYPE_URL"] ?? localKongBaseUrl(),
238
- SUPATYPE_PUBLIC_URL: process.env["SUPATYPE_PUBLIC_URL"] ?? localPublicApiUrl(cwd),
239
- SUPATYPE_ANON_KEY: process.env["SUPATYPE_ANON_KEY"] ?? "",
240
- SUPATYPE_SERVICE_ROLE_KEY: process.env["SUPATYPE_SERVICE_ROLE_KEY"] ?? "",
241
- },
242
- });
243
- // Clean up router script
223
+ // The functions and hooks directories are watched too, so a function added while it serves is found.
224
+ const watchDirs = [functionsDir, hooksPathFromProject(config, cwd)].filter((dir) => existsSync(dir));
225
+ await runDenoServe(denoBin, functionsServeDenoArgs(installFunctionsWorker(), watchDirs, envArgs), { cwd, env: denoServeEnv(project, opts) });
226
+ }
227
+ /**
228
+ * Deno's flag for `envFilePath`, or nothing when there is no such file. One argument: `--env-file`
229
+ * takes an optional value, which Deno reads only after `=`, so with the path as its own argument
230
+ * Deno loaded `.env` and ran the env file as the script.
231
+ */
232
+ export function denoEnvFileArgs(envFilePath) {
233
+ return existsSync(envFilePath) ? [`--env-file=${envFilePath}`] : [];
234
+ }
235
+ /**
236
+ * Runs the serve's Deno until it stops, then ends the command, with an error when it failed. It
237
+ * exits on a clean stop too, in the same turn: a Ctrl+C heard once the stop listeners are gone
238
+ * would kill the CLI without the `exit` that removes the key file.
239
+ */
240
+ async function runDenoServe(denoBin, args, opts) {
241
+ let status;
244
242
  try {
245
- unlinkSync(routerPath);
243
+ status = await runUntilStopped(denoBin, args, opts);
244
+ }
245
+ catch (err) {
246
+ error(`Could not start Deno: ${errorMessage(err)}`);
247
+ process.exit(1);
246
248
  }
247
- catch { /* ignore */ }
248
- if (result.status !== 0) {
249
+ if (status !== 0)
249
250
  error("Function server exited with errors.");
250
- process.exit(result.status ?? 1);
251
+ process.exit(status);
252
+ }
253
+ /** The functions under `functionsDir`, listed for the terminal, ending the command when there are none. */
254
+ function listServeFunctions(cwd, functionsDir) {
255
+ const routes = discoverFunctionsOrExit(functionsDir);
256
+ if (routes.length === 0) {
257
+ error(`No functions found in ${relativeFunctionsDir(cwd, functionsDir)}/`);
258
+ error("Create one with: npx supatype functions new <name>");
259
+ process.exit(1);
251
260
  }
261
+ plain(`Discovered ${routes.length} function(s):`);
262
+ for (const fn of routes) {
263
+ plain(` /${fn.name} → ${relative(cwd, fn.entrypoint)}`);
264
+ }
265
+ plain();
266
+ }
267
+ /**
268
+ * Writes this serve's key file when the shell gave a key, removed when the serve stops, and returns
269
+ * its path. The worker reads the key from that file, as it still can after a --watch reload, and
270
+ * grants it only to the routes SUPATYPE_SERVICE_ROLE_ROUTES names. Key files of serves killed
271
+ * outright are swept first.
272
+ */
273
+ function writeServeKeyFile(cwd) {
274
+ sweepStaleServeKeyFiles(cwd);
275
+ const serviceRoleKey = process.env["SUPATYPE_SERVICE_ROLE_KEY"] ?? "";
276
+ if (serviceRoleKey === "")
277
+ return undefined;
278
+ const keyPath = functionsServeKeyPath(cwd);
279
+ writeServiceRoleKeyFileUntilExit(keyPath, serviceRoleKey);
280
+ return keyPath;
281
+ }
282
+ /**
283
+ * The address `functions serve` announces for `host`: localhost for a wildcard bind (`0.0.0.0`, `::`),
284
+ * which is no address a browser can open, and an IPv6 host in brackets, as a URL writes it.
285
+ */
286
+ export function serveDisplayUrl(host, port) {
287
+ const bare = unbracketedHost(host);
288
+ const shown = bare === "0.0.0.0" || bare === "::" ? "localhost" : bare.includes(":") ? `[${bare}]` : bare;
289
+ return `http://${shown}:${port}/functions/v1/`;
290
+ }
291
+ /** `host` without the brackets a URL puts round an IPv6 address: `[::1]` is `::1`, as Deno binds it. */
292
+ function unbracketedHost(host) {
293
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
294
+ }
295
+ /**
296
+ * The environment the serve's Deno runs with: this shell's, uncoloured, plus the worker's for
297
+ * `project`, listening where `listen` says. Handlers reach the project's API where it answers
298
+ * (resolve-api-url.ts): the native server for a native project, never a gateway a Docker run left
299
+ * in `.env`.
300
+ */
301
+ export function denoServeEnv(project, listen) {
302
+ const apiUrl = resolveProjectApiUrl(project.cwd, project.config);
303
+ return {
304
+ ...process.env,
305
+ ...DENO_ENV,
306
+ PORT: listen.port,
307
+ SUPATYPE_FUNCTIONS_HOST: unbracketedHost(listen.host),
308
+ SUPATYPE_URL: process.env["SUPATYPE_URL"] ?? apiUrl,
309
+ SUPATYPE_PUBLIC_URL: process.env["SUPATYPE_PUBLIC_URL"] ?? apiUrl,
310
+ SUPATYPE_ANON_KEY: process.env["SUPATYPE_ANON_KEY"] ?? "",
311
+ ...functionsWorkerEnv(project),
312
+ };
252
313
  }
253
314
  // ─── Deploy ──────────────────────────────────────────────────────────────────
254
315
  async function deploy(cwd, opts) {
@@ -275,34 +336,31 @@ async function deploy(cwd, opts) {
275
336
  plain(`\nTotal: ${fns.length} function(s)`);
276
337
  return;
277
338
  }
278
- const link = loadProjectLink(cwd);
279
- if (link) {
280
- try {
281
- const target = resolveTarget(cwd, { env: opts.env });
282
- if (target.mode !== "direct" && target.token) {
283
- await deployViaTarget(cwd, target, fns);
284
- return;
285
- }
286
- }
287
- catch {
288
- /* fall through to compose/local */
289
- }
339
+ // Ended outside the target's lookup: a failed deploy must not be taken for one, and deployed
340
+ // again another way.
341
+ const target = linkedTarget(cwd, opts.env);
342
+ if (target !== null) {
343
+ finishDeploy(fns.length, await deployViaTarget(cwd, target, fns));
344
+ info(`Invoke: ${targetFunctions(target).invokeBase}/<name>`);
345
+ return;
290
346
  }
291
347
  const { selfHostComposePaths } = await import("../self-host-compose.js");
292
348
  if (existsSync(selfHostComposePaths(cwd).composePath)) {
293
- deploySelfHosted(cwd, fns, FUNCTIONS_WORKER_RESTART_COMMAND);
349
+ deploySelfHosted(cwd, resolveFunctionsDir(cwd, "read"), fns, FUNCTIONS_WORKER_RESTART_COMMAND);
294
350
  return;
295
351
  }
296
- await deployCloud(cwd, fns, opts.env);
352
+ error(NOT_LINKED);
353
+ process.exit(1);
297
354
  }
298
355
  /**
299
356
  * The command that restarts this project's functions worker: the CLI's own, which recreates it
300
357
  * with the current config and .env under the right project name, wherever it is run from.
301
358
  */
302
359
  const FUNCTIONS_WORKER_RESTART_COMMAND = "supatype self-host compose restart functions-worker";
303
- function deploySelfHosted(cwd, fns, restartCommand) {
360
+ function deploySelfHosted(cwd, functionsDir, fns, restartCommand) {
304
361
  info("Self-host Compose deployment.");
305
- plain("Functions are served from your project functions/ directory (no bundle step).\n");
362
+ // The directory functions.path names, which the stack mounts; it is not always functions/.
363
+ plain(`Functions are served from ${relativeFunctionsDir(cwd, functionsDir)}/ in your project (no bundle step).\n`);
306
364
  for (const fn of fns) {
307
365
  plain(` ${fn.name} → ${relative(cwd, fn.entrypoint)}`);
308
366
  }
@@ -311,93 +369,104 @@ function deploySelfHosted(cwd, fns, restartCommand) {
311
369
  plain(` ${restartCommand}`);
312
370
  plain("\nKong → supatype-server → functions-worker (per-project worker).");
313
371
  }
314
- async function deployViaTarget(cwd, target, fns) {
315
- info(`Deploying to ${target.mode} project: ${target.projectRef} (${target.environment})`);
316
- plain();
317
- for (const fn of fns) {
318
- const start = Date.now();
319
- const source = readFunctionSource(fn);
320
- try {
321
- await targetFetch(target.apiBaseUrl, target.apiPrefix, {
322
- method: "POST",
323
- path: `/projects/${target.projectRef}/functions/deploy`,
324
- body: {
325
- functions: [{
326
- name: fn.name,
327
- source,
328
- entrypoint: `${fn.name}/index.ts`,
329
- }],
330
- // Sent every deploy, and replaced wholesale by the platform: the config file is the whole
331
- // truth, so a name removed from it must stop being entitled to the service-role key.
332
- serviceRole: serviceRoleRoutesFor(cwd),
333
- },
334
- token: target.token,
335
- orgId: target.orgId,
336
- environment: target.mode === "cloud" ? target.environment : undefined,
337
- });
338
- const duration = Date.now() - start;
339
- plain(` ${fn.name} ✓ deployed (${duration}ms)`);
340
- }
341
- catch (err) {
342
- plain(` ${fn.name} ✗ ${err instanceof Error ? err.message : "unknown error"}`);
343
- }
372
+ /**
373
+ * The linked project's target, or null when the project is not linked. A link that cannot be used,
374
+ * with no session or an environment that is not linked, ends the command and says why: it is never
375
+ * taken for no link, which would send the work somewhere else. `needsToken` false is for invoke,
376
+ * which calls a public function and needs no session.
377
+ */
378
+ function linkedTarget(cwd, env, needsToken = true) {
379
+ try {
380
+ return resolveLinkedTarget(cwd, env, needsToken);
381
+ }
382
+ catch (err) {
383
+ error(errorMessage(err));
384
+ process.exit(1);
344
385
  }
345
- info(`Deployed ${fns.length} function(s)`);
346
- void cwd;
347
386
  }
348
- async function deployCloud(cwd, fns, env) {
349
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
350
- const linked = getLinkedProject(cwd);
351
- if (!linked) {
387
+ /** {@link linkedTarget}, throwing rather than ending the command, for work under a spinner. */
388
+ function resolveLinkedTarget(cwd, env, needsToken) {
389
+ if (!loadProjectLink(cwd))
390
+ return null;
391
+ const target = resolveTarget(cwd, { env, tokenOptional: !needsToken });
392
+ if (needsToken && !target.token)
393
+ throw new Error(NOT_LOGGED_IN);
394
+ return target;
395
+ }
396
+ /** {@link linkedTarget}, ending the command when the project is not linked. */
397
+ function requireLinkedTarget(cwd) {
398
+ const target = linkedTarget(cwd, undefined);
399
+ if (target === null) {
352
400
  error(NOT_LINKED);
353
401
  process.exit(1);
354
402
  }
355
- const token = getCloudToken(cwd);
356
- if (!token) {
357
- error(NOT_LOGGED_IN);
403
+ return target;
404
+ }
405
+ /** Asks `target` for `subpath` of its project, ending the command with `what` and the reason when it fails. */
406
+ async function askTarget(target, what, call, guard) {
407
+ try {
408
+ const answer = await targetFetch(target.apiBaseUrl, target.apiPrefix, targetRequest(target, call), guard);
409
+ sayTargetWarning(answer);
410
+ return answer;
411
+ }
412
+ catch (err) {
413
+ error(`${what}: ${errorMessage(err)}`);
358
414
  process.exit(1);
359
415
  }
360
- const apiUrl = getCloudApiUrl(cwd);
361
- info(`Deploying to project: ${linked.ref}`);
416
+ }
417
+ /**
418
+ * Deploys through the linked target in one request carrying every function, so a self-hosted worker
419
+ * restarts once a deploy rather than once a function; saying how each went. A refused request fails
420
+ * every function it carried. Returns the names that failed.
421
+ */
422
+ async function deployViaTarget(cwd, target, fns) {
423
+ info(`Deploying to ${target.mode} project: ${target.projectRef} (${target.environment})`);
362
424
  plain();
425
+ const serviceRole = serviceRoleRoutesFor(cwd);
426
+ const { sent, failed } = readSources(fns);
427
+ if (sent.length === 0)
428
+ return failed;
429
+ const start = Date.now();
430
+ const body = { functions: sent, ...(serviceRole !== undefined && { serviceRole }) };
431
+ try {
432
+ const call = { method: "POST", subpath: "/functions/deploy", body, restartsWorker: true, handlers: sent.length };
433
+ sayTargetWarning(await targetFetch(target.apiBaseUrl, target.apiPrefix, targetRequest(target, call)));
434
+ }
435
+ catch (err) {
436
+ for (const fn of sent)
437
+ plain(` ${fn.name} ✗ ${errorMessage(err)}`);
438
+ return [...failed, ...sent.map((fn) => fn.name)];
439
+ }
440
+ for (const fn of sent)
441
+ plain(` ${fn.name} ✓ deployed (${Date.now() - start}ms)`);
442
+ return failed;
443
+ }
444
+ /**
445
+ * Each function's source, as the deploy request carries it; one that cannot be read is said and
446
+ * failed here, and the rest are still sent.
447
+ */
448
+ function readSources(fns) {
449
+ const sent = [];
450
+ const failed = [];
363
451
  for (const fn of fns) {
364
- const start = Date.now();
365
- // Read source code
366
- const source = readFunctionSource(fn);
367
452
  try {
368
- const res = await fetch(`${apiUrl}/api/v1/projects/${linked.ref}/functions/deploy`, {
369
- method: "POST",
370
- headers: {
371
- Authorization: `Bearer ${token}`,
372
- "Content-Type": "application/json",
373
- "X-Org-Id": linked.orgId ?? "",
374
- },
375
- body: JSON.stringify({
376
- functions: [{
377
- name: fn.name,
378
- source,
379
- entrypoint: `${fn.name}/index.ts`,
380
- }],
381
- // Same grants as the target path: both reach the same endpoint, and a project deployed one
382
- // way must not end up with a different credential surface than the other.
383
- serviceRole: serviceRoleRoutesFor(cwd),
384
- }),
385
- signal: AbortSignal.timeout(60_000),
386
- });
387
- if (!res.ok) {
388
- const reason = await failureReason(res);
389
- plain(` ${fn.name} ✗ ${reason}`);
390
- continue;
391
- }
392
- const duration = Date.now() - start;
393
- plain(` ${fn.name} ✓ deployed (${duration}ms)`);
453
+ sent.push({ name: fn.name, entrypoint: `${fn.name}/index.ts`, ...readFunctionFiles(fn) });
394
454
  }
395
455
  catch (err) {
396
- plain(` ${fn.name} ✗ ${err instanceof Error ? err.message : "unknown error"}`);
456
+ failed.push(fn.name);
457
+ plain(` ${fn.name} ✗ ${errorMessage(err)}`);
397
458
  }
398
459
  }
399
- info(`Deployed ${fns.length} function(s)`);
400
- info(`Invoke: https://${linked.ref}.supatype.dev/functions/v1/<name>`);
460
+ return { sent, failed };
461
+ }
462
+ /** Says how many deployed, or names those that failed and ends non-zero. */
463
+ function finishDeploy(total, failed) {
464
+ if (failed.length === 0) {
465
+ info(`Deployed ${total} function(s)`);
466
+ return;
467
+ }
468
+ error(`${failed.length} of ${total} function(s) failed to deploy: ${failed.join(", ")}`);
469
+ process.exit(1);
401
470
  }
402
471
  /**
403
472
  * The project's `functions.serviceRole` list, or undefined when the config cannot be read.
@@ -414,293 +483,271 @@ export function serviceRoleRoutesFor(cwd) {
414
483
  return undefined;
415
484
  }
416
485
  }
417
- /** The control plane's reason for a refusal: its `message`, else the status text. */
418
- async function failureReason(res) {
419
- const body = await res.json().catch(() => ({}));
420
- const message = isJsonObject(body) ? body["message"] : undefined;
421
- return typeof message === "string" ? message : res.statusText;
422
- }
423
486
  /** `GET /functions`: each deployed function, with its last day's use. */
424
- const isDeployedFunctions = isShape({
425
- data: isArrayOf(isShape({
426
- name: isString,
427
- deployedAt: optional(nullable(isString)),
428
- invocations24h: optional(nullable(isNumber)),
429
- avgDurationMs: optional(nullable(isNumber)),
430
- })),
431
- });
487
+ const isDeployedFunctions = isArrayOf(isShape({
488
+ name: isString,
489
+ deployedAt: optional(nullable(isString)),
490
+ invocations24h: optional(nullable(isNumber)),
491
+ avgDurationMs: optional(nullable(isNumber)),
492
+ }));
432
493
  /** `GET /functions/:name/logs`: the newest entries first. */
433
- const isFunctionLogs = isShape({
434
- data: isArrayOf(isShape({ timestamp: isString, level: isString, message: optional(nullable(isString)) })),
435
- });
436
- function readFunctionSource(fn) {
437
- const stat = statSync(fn.path);
438
- if (stat.isFile()) {
439
- return readFileSync(fn.path, "utf8");
440
- }
441
- // Directory function: read all .ts files
442
- const files = {};
443
- const entries = readdirSync(fn.path, { recursive: true, encoding: "utf8" });
444
- for (const entry of entries) {
445
- const fullPath = join(fn.path, entry);
446
- if (statSync(fullPath).isFile() && (entry.endsWith(".ts") || entry.endsWith(".js"))) {
447
- files[entry] = readFileSync(fullPath, "utf8");
448
- }
449
- }
450
- return JSON.stringify(files);
494
+ const isFunctionLogs = isArrayOf(isShape({ timestamp: isString, level: isString, message: optional(nullable(isString)) }));
495
+ /**
496
+ * A function's source as the deploy request carries it. A file function is its own entry. A
497
+ * directory function's entry is its index.ts, and every file under it the worker loads
498
+ * ({@link readWorkerFiles}) goes in `files`, by a path with `/` on every OS.
499
+ */
500
+ function readFunctionFiles(fn) {
501
+ if (statSync(fn.path).isFile())
502
+ return { source: readFileSync(fn.path, "utf8") };
503
+ const files = readWorkerFiles(fn.path);
504
+ return { source: files["index.ts"] ?? "", files };
451
505
  }
452
506
  // ─── List ────────────────────────────────────────────────────────────────────
453
507
  async function listFunctions(cwd) {
454
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
455
- const linked = getLinkedProject(cwd);
456
- if (!linked) {
457
- // Show local functions instead
458
- const fns = discoverFunctions(cwd);
459
- if (fns.length === 0) {
460
- info("No functions found locally or remotely.");
461
- return;
462
- }
463
- plain("Local functions (not linked to a cloud project):\n");
464
- for (const fn of fns) {
465
- plain(` ${fn.name.padEnd(30)} ${relative(cwd, fn.entrypoint)}`);
466
- }
508
+ const target = linkedTarget(cwd, undefined);
509
+ if (target === null)
510
+ return listLocalFunctions(cwd);
511
+ const data = await askTarget(target, "Failed to list functions", { method: "GET", subpath: "/functions" }, isDeployedFunctions);
512
+ if (data.length === 0) {
513
+ info("No deployed functions.");
467
514
  return;
468
515
  }
469
- const token = getCloudToken(cwd);
470
- if (!token) {
471
- error(NOT_LOGGED_IN);
472
- process.exit(1);
473
- }
474
- try {
475
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions`, {
476
- headers: {
477
- Authorization: `Bearer ${token}`,
478
- "X-Org-Id": linked.orgId ?? "",
479
- },
480
- signal: AbortSignal.timeout(10_000),
481
- });
482
- if (!res.ok) {
483
- error(`Failed to list functions: ${res.statusText}`);
484
- process.exit(1);
485
- }
486
- const { data } = await readJson(res, isDeployedFunctions);
487
- if (data.length === 0) {
488
- info("No deployed functions.");
489
- return;
490
- }
491
- plain("Deployed functions:\n");
492
- plain(` ${"Name".padEnd(28)} ${"Last Deployed".padEnd(24)} ${"Invocations (24h)".padEnd(20)} Avg Duration`);
493
- plain(` ${"─".repeat(28)} ${"─".repeat(24)} ${"─".repeat(20)} ${"─".repeat(12)}`);
494
- for (const fn of data) {
495
- const deployed = fn.deployedAt ? new Date(fn.deployedAt).toLocaleString() : "-";
496
- plain(` ${fn.name.padEnd(28)} ${deployed.padEnd(24)} ${String(fn.invocations24h ?? 0).padEnd(20)} ${fn.avgDurationMs ?? 0}ms`);
497
- }
516
+ plain("Deployed functions:\n");
517
+ plain(` ${"Name".padEnd(28)} ${"Last Deployed".padEnd(24)} ${"Invocations (24h)".padEnd(20)} Avg Duration`);
518
+ plain(` ${"─".repeat(28)} ${"─".repeat(24)} ${"─".repeat(20)} ${"─".repeat(12)}`);
519
+ for (const fn of data) {
520
+ const deployed = fn.deployedAt ? new Date(fn.deployedAt).toLocaleString() : "-";
521
+ plain(` ${fn.name.padEnd(28)} ${deployed.padEnd(24)} ${String(fn.invocations24h ?? 0).padEnd(20)} ${fn.avgDurationMs ?? 0}ms`);
498
522
  }
499
- catch (err) {
500
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
501
- process.exit(1);
523
+ }
524
+ /** The functions on disk, for a project that is not linked. */
525
+ function listLocalFunctions(cwd) {
526
+ const fns = discoverFunctions(cwd);
527
+ if (fns.length === 0) {
528
+ info("No functions found locally or remotely.");
529
+ return;
502
530
  }
531
+ plain("Local functions (not linked to a project):\n");
532
+ for (const fn of fns)
533
+ plain(` ${fn.name.padEnd(30)} ${relative(cwd, fn.entrypoint)}`);
503
534
  }
504
535
  // ─── Delete ──────────────────────────────────────────────────────────────────
505
536
  async function deleteFunction(cwd, name) {
506
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
507
- const linked = getLinkedProject(cwd);
508
- if (!linked) {
509
- error(NOT_LINKED);
510
- process.exit(1);
537
+ const target = requireLinkedTarget(cwd);
538
+ const call = { method: "DELETE", subpath: `/functions/${encodeURIComponent(name)}`, restartsWorker: true };
539
+ await askTarget(target, `Failed to delete "${name}"`, call, isUnknown);
540
+ info(`Function "${name}" deleted. It will return 404 immediately.`);
541
+ }
542
+ // ─── Logs ────────────────────────────────────────────────────────────────────
543
+ /**
544
+ * A function's logs from the linked target: a window of past lines from Supatype Cloud, or the
545
+ * worker's live stream from a server, tailed until Ctrl+C.
546
+ */
547
+ async function functionLogs(cwd, name, opts) {
548
+ const target = requireLinkedTarget(cwd);
549
+ const { logs } = targetFunctions(target);
550
+ if (logs.kind === "tail")
551
+ return tailServerLogs(target, logs.tail, name);
552
+ const subpath = `/functions/${encodeURIComponent(name)}/logs?since=${encodeURIComponent(opts.since)}`;
553
+ const lines = await askTarget(target, "Failed to fetch logs", { method: "GET", subpath }, isFunctionLogs);
554
+ if (lines.length === 0)
555
+ info(`No logs for "${name}" in the last ${opts.since}.`);
556
+ for (const entry of lines)
557
+ plain(formatLogLine(entry));
558
+ }
559
+ /** Tails the linked server's relay of the worker's log stream at `tail`, printing `name`'s lines. */
560
+ async function tailServerLogs(target, tail, name) {
561
+ info(`Tailing logs for "${name}" on ${tail.baseUrl}. Press Ctrl+C to stop.`);
562
+ let body;
563
+ try {
564
+ body = await targetStream(tail.baseUrl, tail.apiPrefix, targetStreamRequest(target, tail.path));
511
565
  }
512
- const token = getCloudToken(cwd);
513
- if (!token) {
514
- error(NOT_LOGGED_IN);
566
+ catch (err) {
567
+ error(`Failed to tail logs: ${errorMessage(err)}`);
515
568
  process.exit(1);
516
569
  }
570
+ await printLogStream(body, name);
571
+ }
572
+ /** Prints `name`'s lines from a server-sent event stream as they arrive, until it ends. */
573
+ async function printLogStream(body, name) {
574
+ const reader = body.getReader();
575
+ // Ctrl+C closes the stream and the command ends by itself, with exit 0, rather than being killed.
576
+ const stop = () => void reader.cancel().catch(() => undefined);
577
+ for (const signal of STOP_SIGNALS)
578
+ process.on(signal, stop);
517
579
  try {
518
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions/${name}`, {
519
- method: "DELETE",
520
- headers: {
521
- Authorization: `Bearer ${token}`,
522
- "X-Org-Id": linked.orgId ?? "",
523
- },
524
- signal: AbortSignal.timeout(10_000),
525
- });
526
- if (!res.ok) {
527
- const reason = await failureReason(res);
528
- error(`Failed to delete "${name}": ${reason}`);
529
- process.exit(1);
530
- }
531
- info(`Function "${name}" deleted. It will return 404 immediately.`);
580
+ await printEvents(reader, name);
532
581
  }
533
- catch (err) {
534
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
535
- process.exit(1);
582
+ finally {
583
+ for (const signal of STOP_SIGNALS)
584
+ process.off(signal, stop);
536
585
  }
537
586
  }
538
- // ─── Logs ────────────────────────────────────────────────────────────────────
539
- async function functionLogs(cwd, name, opts) {
540
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
541
- const linked = getLinkedProject(cwd);
542
- if (!linked) {
543
- error(NOT_LINKED);
544
- process.exit(1);
587
+ /** Prints `name`'s lines from `reader` until the stream ends or is cancelled. */
588
+ async function printEvents(reader, name) {
589
+ const decoder = new TextDecoder();
590
+ let pending = "";
591
+ // A reader rather than `for await`: the DOM lib the integration package compiles against gives a
592
+ // ReadableStream no async iterator.
593
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
594
+ pending += decoder.decode(chunk.value, { stream: true });
595
+ const lines = pending.split("\n");
596
+ pending = lines.pop() ?? "";
597
+ for (const line of lines)
598
+ printLogEvent(line, name);
599
+ }
600
+ printLogEvent(pending, name);
601
+ }
602
+ const isLogEvent = isShape({ timestamp: isString, level: isString, message: optional(nullable(isString)), function: optional(isString) });
603
+ /** One `data:` line of the worker's stream, printed when it is `name`'s. Others are skipped. */
604
+ function printLogEvent(line, name) {
605
+ if (!line.startsWith("data: "))
606
+ return;
607
+ let event;
608
+ try {
609
+ event = JSON.parse(line.slice("data: ".length));
545
610
  }
546
- const token = getCloudToken(cwd);
547
- if (!token) {
548
- error(NOT_LOGGED_IN);
549
- process.exit(1);
611
+ catch {
612
+ return;
550
613
  }
614
+ if (isLogEvent(event) && event.function === name)
615
+ plain(formatLogLine(event));
616
+ }
617
+ /** A log line as both paths print it: time of day, level, message. */
618
+ function formatLogLine(entry) {
619
+ const ts = new Date(entry.timestamp).toISOString().slice(11, 23);
620
+ return `${ts} [${entry.level.toUpperCase().padEnd(5)}] ${entry.message ?? ""}`;
621
+ }
622
+ async function invoke(cwd, name, opts) {
623
+ const body = jsonBodyOrExit(opts.data);
624
+ const { url, headers } = await invokeRequest(cwd, name, opts);
551
625
  try {
552
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions/${name}/logs?since=${opts.since}`, {
553
- headers: {
554
- Authorization: `Bearer ${token}`,
555
- "X-Org-Id": linked.orgId ?? "",
556
- },
557
- signal: AbortSignal.timeout(10_000),
558
- });
559
- if (!res.ok) {
560
- error(`Failed to fetch logs: ${res.statusText}`);
561
- process.exit(1);
562
- }
563
- const { data } = await readJson(res, isFunctionLogs);
564
- if (data.length === 0) {
565
- info(`No logs for "${name}" in the last ${opts.since}.`);
566
- return;
567
- }
568
- for (const entry of data) {
569
- const ts = new Date(entry.timestamp).toISOString().slice(11, 23);
570
- const level = entry.level.toUpperCase().padEnd(5);
571
- plain(`${ts} [${level}] ${entry.message}`);
572
- }
626
+ const start = Date.now();
627
+ const res = await fetchWithin(url, 30_000, { method: "POST", headers, body });
628
+ const duration = Date.now() - start;
629
+ printInvokeAnswer(res.status, duration, await res.text());
573
630
  }
574
631
  catch (err) {
575
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
632
+ reportInvokeFailure(url, err);
633
+ }
634
+ }
635
+ /** `data` when it is JSON; otherwise the command ends saying so. */
636
+ function jsonBodyOrExit(data) {
637
+ try {
638
+ JSON.parse(data);
639
+ return data;
640
+ }
641
+ catch {
642
+ error("Invalid JSON data. Use --data '{\"key\": \"value\"}'");
576
643
  process.exit(1);
577
644
  }
578
645
  }
579
- // ─── Invoke ──────────────────────────────────────────────────────────────────
580
- async function invoke(cwd, name, opts) {
581
- let url;
646
+ /** Where the function is, the linked target's or this machine's, and the headers to send it. */
647
+ async function invokeRequest(cwd, name, opts) {
648
+ const target = opts.local ? null : linkedTarget(cwd, undefined, false);
649
+ const url = target === null
650
+ ? `${await localFunctionsBase(cwd, opts.port)}/${name}`
651
+ : `${targetFunctions(target).invokeBase}/${name}`;
582
652
  const headers = { "Content-Type": "application/json" };
583
- // The project's own gateway, as every other command that calls the API finds it. A fixed
584
- // localhost:54321 reached whatever else on the machine listened there.
585
- const localUrl = `${resolveProjectApiUrl(cwd)}/functions/v1/${name}`;
586
- if (opts.local) {
587
- url = localUrl;
653
+ if (opts.auth)
654
+ headers["Authorization"] = `Bearer ${target === null ? LOCAL_TEST_JWT : invokeToken(target)}`;
655
+ return { url, headers };
656
+ }
657
+ /** The status, how long it took, and the body, as JSON when it is. */
658
+ function printInvokeAnswer(status, duration, responseBody) {
659
+ plain(`Status: ${status} (${duration}ms)`);
660
+ plain();
661
+ try {
662
+ const json = JSON.parse(responseBody);
663
+ plain(JSON.stringify(json, null, 2));
588
664
  }
589
- else {
590
- const { getLinkedProject, getCloudToken } = await loadCloudHelpers();
591
- const linked = getLinkedProject(cwd);
592
- if (linked) {
593
- url = `https://${linked.ref}.supatype.dev/functions/v1/${name}`;
594
- const token = getCloudToken(cwd);
595
- if (token && opts.auth) {
596
- headers["Authorization"] = `Bearer ${token}`;
597
- }
598
- }
599
- else {
600
- url = localUrl;
601
- }
665
+ catch {
666
+ plain(responseBody);
602
667
  }
603
- if (opts.auth && !headers["Authorization"]) {
604
- // Generate a test JWT for local invocation
605
- headers["Authorization"] = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0LXVzZXIiLCJyb2xlIjoiYXV0aGVudGljYXRlZCIsImlhdCI6MTcwMDAwMDAwMH0.test";
668
+ }
669
+ /** Ends the command with why the function could not be called. */
670
+ function reportInvokeFailure(url, err) {
671
+ if (err instanceof TypeError && errorMessage(err).includes("fetch")) {
672
+ error(`Cannot reach ${url}`);
673
+ error("Is the function server running? Start it with: npx supatype functions serve");
674
+ }
675
+ else {
676
+ error(`Error: ${errorMessage(err)}`);
606
677
  }
678
+ process.exit(1);
679
+ }
680
+ /** A placeholder user token for a function served on this machine; never sent to a linked server. */
681
+ const LOCAL_TEST_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0LXVzZXIiLCJyb2xlIjoiYXV0aGVudGljYXRlZCIsImlhdCI6MTcwMDAwMDAwMH0.test";
682
+ /**
683
+ * The token `invoke --auth` sends to a linked target ({@link targetFunctions}), or the command ends
684
+ * saying why there is none. A self-hosted server gets neither the placeholder nor the link's
685
+ * service-role key.
686
+ */
687
+ function invokeToken(target) {
688
+ const token = targetFunctions(target).invokeToken;
689
+ if (token !== undefined)
690
+ return token;
691
+ if (target.mode === "cloud")
692
+ error(`--auth sends your Supatype Cloud session. ${NOT_LOGGED_IN}`);
693
+ else
694
+ error(`--auth has no user token for ${target.apiBaseUrl}. Call the function with a signed-in user's access token instead.`);
695
+ process.exit(1);
696
+ }
697
+ /**
698
+ * An env command's work under one spinner, from the start (reading the link and the config, which
699
+ * runs it in a child process) to the target's answer, for every target: on a self-hosted stack it
700
+ * takes seconds, and nothing on screen said it was working. A failure ends the command once the
701
+ * spinner has stopped, saying what failed and why.
702
+ */
703
+ async function envWork(cwd, work) {
704
+ let outcome;
607
705
  try {
608
- let body;
609
- try {
610
- JSON.parse(opts.data);
611
- body = opts.data;
612
- }
613
- catch {
614
- error("Invalid JSON data. Use --data '{\"key\": \"value\"}'");
615
- process.exit(1);
616
- }
617
- const start = Date.now();
618
- const res = await fetch(url, {
619
- method: "POST",
620
- headers,
621
- body,
622
- signal: AbortSignal.timeout(30_000),
706
+ outcome = await withSpinner(work.spinner, async () => {
707
+ const target = resolveLinkedTarget(cwd, undefined, true);
708
+ if (target === null)
709
+ return { kind: "local", functionsDir: resolveFunctionsDir(cwd, work.local) };
710
+ const answer = await targetFetch(target.apiBaseUrl, target.apiPrefix, targetRequest(target, work.call), work.guard);
711
+ return { kind: "target", target, answer };
623
712
  });
624
- const duration = Date.now() - start;
625
- const responseBody = await res.text();
626
- plain(`Status: ${res.status} (${duration}ms)`);
627
- plain();
628
- // Try to pretty-print JSON
629
- try {
630
- const json = JSON.parse(responseBody);
631
- plain(JSON.stringify(json, null, 2));
632
- }
633
- catch {
634
- plain(responseBody);
635
- }
636
713
  }
637
714
  catch (err) {
638
- if (err instanceof TypeError && errorMessage(err).includes("fetch")) {
639
- error(`Cannot reach ${url}`);
640
- error("Is the function server running? Start it with: npx supatype functions serve");
641
- }
642
- else {
643
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
644
- }
715
+ error(`${work.failed}: ${errorMessage(err)}`);
645
716
  process.exit(1);
646
717
  }
718
+ if (outcome.kind === "target")
719
+ sayTargetWarning(outcome.answer);
720
+ return outcome;
647
721
  }
648
- // ─── Env management ──────────────────────────────────────────────────────────
649
722
  async function envList(cwd) {
650
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
651
- const linked = getLinkedProject(cwd);
652
- if (!linked) {
653
- // Show local env vars
654
- const envPath = resolve(resolveFunctionsDir(cwd, "read"), ENV_LOCAL);
655
- if (!existsSync(envPath)) {
656
- info("No environment variables configured.");
657
- return;
658
- }
659
- const lines = readFileSync(envPath, "utf8").split("\n");
660
- plain("Local environment variables:\n");
661
- for (const line of lines) {
662
- const trimmed = line.trim();
663
- if (!trimmed || trimmed.startsWith("#"))
664
- continue;
665
- const eqIdx = trimmed.indexOf("=");
666
- if (eqIdx > 0) {
667
- const key = trimmed.slice(0, eqIdx);
668
- plain(` ${key} = ••••••••`);
669
- }
670
- }
723
+ const call = { method: "GET", subpath: "/functions/env" };
724
+ const work = { spinner: "Listing environment variables", failed: "Failed to list env vars", call, guard: isEnvListing, local: "read" };
725
+ const outcome = await envWork(cwd, work);
726
+ if (outcome.kind === "local")
727
+ return listLocalEnv(outcome.functionsDir);
728
+ const listed = outcome.answer;
729
+ // Every target lists the names. An older self-hosted control plane answers a map of names to
730
+ // values, read here for its names alone.
731
+ const keys = Array.isArray(listed) ? listed : Object.keys(listed);
732
+ if (keys.length === 0) {
733
+ info("No environment variables set.");
671
734
  return;
672
735
  }
673
- const token = getCloudToken(cwd);
674
- if (!token) {
675
- error(NOT_LOGGED_IN);
676
- process.exit(1);
677
- }
678
- try {
679
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions/env`, {
680
- headers: {
681
- Authorization: `Bearer ${token}`,
682
- "X-Org-Id": linked.orgId ?? "",
683
- },
684
- signal: AbortSignal.timeout(10_000),
685
- });
686
- if (!res.ok) {
687
- error(`Failed to list env vars: ${res.statusText}`);
688
- process.exit(1);
689
- }
690
- const { data } = await readJson(res, isShape({ data: isArrayOf(isString) }));
691
- if (data.length === 0) {
692
- info("No environment variables set.");
693
- return;
694
- }
695
- plain("Environment variables (values masked):\n");
696
- for (const key of data) {
697
- plain(` ${key} = ••••••••`);
698
- }
699
- }
700
- catch (err) {
701
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
702
- process.exit(1);
736
+ plain("Environment variables (values masked):\n");
737
+ for (const key of keys)
738
+ plain(` ${key} = ••••••••`);
739
+ }
740
+ const isEnvListing = (value) => isArrayOf(isString)(value) || isJsonObject(value);
741
+ /** The variables in the functions' local env file, for a project that is not linked. */
742
+ function listLocalEnv(functionsDir) {
743
+ const envPath = resolve(functionsDir, ENV_LOCAL);
744
+ if (!existsSync(envPath)) {
745
+ info("No environment variables configured.");
746
+ return;
703
747
  }
748
+ plain("Local environment variables:\n");
749
+ for (const key of Object.keys(parseEnvText(readFileSync(envPath, "utf8"))))
750
+ plain(` ${key} = ••••••••`);
704
751
  }
705
752
  async function envSet(cwd, keyvalue) {
706
753
  const eqIdx = keyvalue.indexOf("=");
@@ -710,121 +757,70 @@ async function envSet(cwd, keyvalue) {
710
757
  }
711
758
  const key = keyvalue.slice(0, eqIdx);
712
759
  const value = keyvalue.slice(eqIdx + 1);
713
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
714
- const linked = getLinkedProject(cwd);
715
- if (!linked) {
716
- // Set in local env file
717
- const envPath = resolve(resolveFunctionsDir(cwd, "write"), ENV_LOCAL);
718
- let content = existsSync(envPath) ? readFileSync(envPath, "utf8") : "";
719
- // Replace existing or append
720
- const regex = new RegExp(`^${key}=.*$`, "m");
721
- if (regex.test(content)) {
722
- content = content.replace(regex, `${key}=${value}`);
723
- }
724
- else {
725
- content = content.trimEnd() + `\n${key}=${value}\n`;
726
- }
727
- writeFileSync(envPath, content, "utf8");
728
- info(`Set ${key} in local env file.`);
729
- return;
730
- }
731
- const token = getCloudToken(cwd);
732
- if (!token) {
733
- error(NOT_LOGGED_IN);
734
- process.exit(1);
735
- }
736
- try {
737
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions/env`, {
738
- method: "POST",
739
- headers: {
740
- Authorization: `Bearer ${token}`,
741
- "Content-Type": "application/json",
742
- "X-Org-Id": linked.orgId ?? "",
743
- },
744
- body: JSON.stringify({ key, value }),
745
- signal: AbortSignal.timeout(10_000),
746
- });
747
- if (!res.ok) {
748
- const reason = await failureReason(res);
749
- error(`Failed to set env var: ${reason}`);
750
- process.exit(1);
751
- }
752
- info(`Set ${key} for project ${linked.ref}.`);
753
- }
754
- catch (err) {
755
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
756
- process.exit(1);
757
- }
760
+ const call = { method: "POST", subpath: "/functions/env", body: { key, value }, restartsWorker: true };
761
+ const outcome = await envWork(cwd, { spinner: `Setting ${key}`, failed: "Failed to set env var", call, guard: isUnknown, local: "write" });
762
+ if (outcome.kind === "local")
763
+ return setLocalEnv(outcome.functionsDir, key, value);
764
+ info(`Set ${key} for project ${outcome.target.projectRef}.`);
765
+ }
766
+ /** Sets `key` in the functions' local env file, replacing its line or adding one. */
767
+ function setLocalEnv(functionsDir, key, value) {
768
+ const envPath = resolve(functionsDir, ENV_LOCAL);
769
+ const content = existsSync(envPath) ? readFileSync(envPath, "utf8") : "";
770
+ writeFileSync(envPath, withEnvValue(content, key, value), "utf8");
771
+ info(`Set ${key} in local env file.`);
758
772
  }
759
773
  async function envUnset(cwd, key) {
760
- const { getLinkedProject, getCloudToken, getCloudApiUrl } = await loadCloudHelpers();
761
- const linked = getLinkedProject(cwd);
762
- if (!linked) {
763
- const envPath = resolve(resolveFunctionsDir(cwd, "read"), ENV_LOCAL);
764
- if (!existsSync(envPath)) {
765
- error("No local env file found.");
766
- process.exit(1);
767
- }
768
- let content = readFileSync(envPath, "utf8");
769
- const regex = new RegExp(`^${key}=.*\n?`, "m");
770
- content = content.replace(regex, "");
771
- writeFileSync(envPath, content, "utf8");
772
- info(`Removed ${key} from local env file.`);
773
- return;
774
- }
775
- const token = getCloudToken(cwd);
776
- if (!token) {
777
- error(NOT_LOGGED_IN);
774
+ const call = { method: "DELETE", subpath: `/functions/env/${encodeURIComponent(key)}`, restartsWorker: true };
775
+ const outcome = await envWork(cwd, { spinner: `Removing ${key}`, failed: "Failed to unset env var", call, guard: isUnknown, local: "read" });
776
+ if (outcome.kind === "local")
777
+ return unsetLocalEnv(outcome.functionsDir, key);
778
+ const { answer, target } = outcome;
779
+ // A self-hosted server says whether the key was there to remove.
780
+ if (isJsonObject(answer) && answer["removed"] === false)
781
+ info(`${key} was not set for project ${target.projectRef}.`);
782
+ else
783
+ info(`Removed ${key} for project ${target.projectRef}.`);
784
+ }
785
+ /** Removes `key` from the functions' local env file. */
786
+ function unsetLocalEnv(functionsDir, key) {
787
+ const envPath = resolve(functionsDir, ENV_LOCAL);
788
+ if (!existsSync(envPath)) {
789
+ error("No local env file found.");
778
790
  process.exit(1);
779
791
  }
792
+ const { text, removed } = withoutEnvValue(readFileSync(envPath, "utf8"), key);
793
+ if (!removed) {
794
+ info(`${key} was not set in the local env file.`);
795
+ return;
796
+ }
797
+ writeFileSync(envPath, text, "utf8");
798
+ info(`Removed ${key} from local env file.`);
799
+ }
800
+ /**
801
+ * Where a local invoke goes: a running `functions serve` on `port` when one answers, otherwise the
802
+ * project's own dev API, as every other command that calls the API finds it. A fixed localhost port
803
+ * reached whatever else on the machine listened there.
804
+ */
805
+ async function localFunctionsBase(cwd, port) {
806
+ return (await runningServeBase(port)) ?? `${resolveProjectApiUrl(cwd)}/functions/v1`;
807
+ }
808
+ /** The functions worker's answer to a bare request: a 404 listing the functions it serves. */
809
+ const isServeListing = isShape({ available: isArrayOf(isString) });
810
+ /**
811
+ * The base URL of the `functions serve` listening on `port`, or undefined when none answers. A bare
812
+ * request is how the worker is recognised: it answers 404 with the list of functions it serves,
813
+ * which nothing else on that port would.
814
+ */
815
+ export async function runningServeBase(port) {
816
+ const base = `http://127.0.0.1:${port}/functions/v1`;
780
817
  try {
781
- const res = await fetch(`${getCloudApiUrl(cwd)}/api/v1/projects/${linked.ref}/functions/env/${key}`, {
782
- method: "DELETE",
783
- headers: {
784
- Authorization: `Bearer ${token}`,
785
- "X-Org-Id": linked.orgId ?? "",
786
- },
787
- signal: AbortSignal.timeout(10_000),
788
- });
789
- if (!res.ok) {
790
- const reason = await failureReason(res);
791
- error(`Failed to unset env var: ${reason}`);
792
- process.exit(1);
793
- }
794
- info(`Removed ${key} for project ${linked.ref}.`);
818
+ const res = await fetchWithin(`${base}/`, 1000);
819
+ const body = await res.json();
820
+ return isServeListing(body) ? base : undefined;
795
821
  }
796
- catch (err) {
797
- error(`Error: ${err instanceof Error ? err.message : "unknown"}`);
798
- process.exit(1);
822
+ catch {
823
+ return undefined;
799
824
  }
800
825
  }
801
- async function loadCloudHelpers() {
802
- return {
803
- getLinkedProject(cwd) {
804
- const link = loadProjectLink(cwd);
805
- if (!link?.projectRef)
806
- return null;
807
- return {
808
- ref: link.projectRef,
809
- kind: link.kind,
810
- ...(link.orgId !== undefined ? { orgId: link.orgId } : {}),
811
- };
812
- },
813
- getCloudToken(cwd) {
814
- if (process.env["SUPATYPE_ACCESS_TOKEN"]) {
815
- return process.env["SUPATYPE_ACCESS_TOKEN"];
816
- }
817
- // The link's own token, else the session `supatype login` saved. This used to read
818
- // ~/.supatype/token, which nothing writes, so a fresh login still read as logged out.
819
- const link = loadProjectLink(cwd);
820
- return link === null ? null : resolveCloudAccessToken(link) ?? null;
821
- },
822
- getCloudApiUrl(cwd) {
823
- const link = loadProjectLink(cwd);
824
- if (link?.cloudApiUrl)
825
- return link.cloudApiUrl;
826
- return process.env["SUPATYPE_API_URL"] ?? "https://api.supatype.com";
827
- },
828
- };
829
- }
830
826
  //# sourceMappingURL=functions.js.map