@neta-art/cohub-cli 10.23.0 → 10.25.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 (369) hide show
  1. package/README.md +18 -5
  2. package/bin/cohub.js +4 -1
  3. package/dist/board-gpu/page.js +1566 -71230
  4. package/dist/bootstrap.js +67 -27
  5. package/dist/build.json +1 -1
  6. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  7. package/dist/chunks/about.js +102 -0
  8. package/dist/chunks/app-realtime.js +2216 -0
  9. package/dist/chunks/app-realtime2.js +2 -0
  10. package/dist/chunks/app-ref.js +88 -0
  11. package/dist/chunks/apps.js +1423 -0
  12. package/dist/chunks/auth.js +175 -0
  13. package/dist/chunks/avatar.js +146 -0
  14. package/dist/chunks/board-export-resources.js +232 -0
  15. package/dist/chunks/board-export.js +874 -0
  16. package/dist/chunks/board-export2.js +2 -0
  17. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  18. package/dist/chunks/board-kernel2.js +4 -0
  19. package/dist/chunks/board-profile.js +69 -0
  20. package/dist/chunks/board-simulate.js +315 -0
  21. package/dist/chunks/board-time.js +34 -0
  22. package/dist/chunks/boards.js +1943 -0
  23. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  24. package/dist/chunks/channels.js +64 -0
  25. package/dist/chunks/client.js +12606 -0
  26. package/dist/chunks/command-input.js +17 -0
  27. package/dist/chunks/commander.js +2962 -0
  28. package/dist/chunks/cron-jobs.js +163 -0
  29. package/dist/chunks/daemon.js +545 -0
  30. package/dist/chunks/daemon2.js +2 -0
  31. package/dist/chunks/desktop.js +172 -0
  32. package/dist/chunks/endpoint-options.js +26 -0
  33. package/dist/chunks/env-proxy.js +35 -0
  34. package/dist/chunks/environment.js +154 -0
  35. package/dist/chunks/feedback.js +120 -0
  36. package/dist/chunks/generations.js +379 -0
  37. package/dist/chunks/host.js +9 -0
  38. package/dist/chunks/http-put.js +131 -0
  39. package/dist/chunks/id.js +2416 -0
  40. package/dist/{board-kernel → chunks}/init.js +1 -1
  41. package/dist/chunks/install.js +11959 -0
  42. package/dist/chunks/launch.js +374 -0
  43. package/dist/chunks/local-media.js +47 -0
  44. package/dist/chunks/me.js +134 -0
  45. package/dist/chunks/media.js +315 -0
  46. package/dist/chunks/models.js +242 -0
  47. package/dist/chunks/operands.js +46 -0
  48. package/dist/chunks/package-paths.js +13 -0
  49. package/dist/chunks/policy.js +221 -0
  50. package/dist/chunks/preferences.js +29 -0
  51. package/dist/chunks/profile.js +64 -0
  52. package/dist/chunks/prompts.js +41 -0
  53. package/dist/chunks/public.js +2 -0
  54. package/dist/chunks/public2.js +244 -0
  55. package/dist/chunks/references.js +197 -0
  56. package/dist/chunks/referrals.js +90 -0
  57. package/dist/chunks/rolldown-runtime.js +26 -0
  58. package/dist/chunks/rooms-connect.js +2 -0
  59. package/dist/chunks/rooms-connect2.js +151 -0
  60. package/dist/chunks/rooms-rtc.js +309 -0
  61. package/dist/chunks/rooms.js +211 -0
  62. package/dist/chunks/run.js +220 -0
  63. package/dist/chunks/runtime.js +638 -0
  64. package/dist/chunks/runtime2.js +286 -0
  65. package/dist/chunks/runtimes.js +48 -0
  66. package/dist/chunks/safe-remote-image.js +198 -0
  67. package/dist/chunks/schemas.js +6017 -0
  68. package/dist/chunks/search.js +113 -0
  69. package/dist/chunks/self-update.js +238 -0
  70. package/dist/chunks/serve.js +1246 -0
  71. package/dist/chunks/session-status.js +24 -0
  72. package/dist/chunks/skills.js +35 -0
  73. package/dist/chunks/spaces.js +5080 -0
  74. package/dist/chunks/src.js +405 -0
  75. package/dist/chunks/supervisor.js +2511 -0
  76. package/dist/chunks/supervisor2.js +2 -0
  77. package/dist/chunks/tasks.js +82 -0
  78. package/dist/chunks/themes.js +2898 -0
  79. package/dist/chunks/version.js +2 -0
  80. package/dist/chunks/version2.js +22 -0
  81. package/dist/chunks/version3.js +18 -0
  82. package/dist/chunks/web.js +7 -0
  83. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  84. package/dist/runtime/native/pi-extension.js +174 -166
  85. package/dist/runtime/worker.js +27 -16
  86. package/package.json +8 -9
  87. package/dist/about.d.ts +0 -2
  88. package/dist/about.js +0 -71
  89. package/dist/app-download.d.ts +0 -11
  90. package/dist/app-download.js +0 -252
  91. package/dist/app-ref.d.ts +0 -5
  92. package/dist/app-ref.js +0 -8
  93. package/dist/app-target.d.ts +0 -26
  94. package/dist/app-target.js +0 -55
  95. package/dist/auth.d.ts +0 -45
  96. package/dist/auth.js +0 -307
  97. package/dist/avatar.d.ts +0 -55
  98. package/dist/avatar.js +0 -104
  99. package/dist/board-command-support.d.ts +0 -6
  100. package/dist/board-command-support.js +0 -88
  101. package/dist/board-export-resources.d.ts +0 -12
  102. package/dist/board-export-resources.js +0 -51
  103. package/dist/board-export.d.ts +0 -110
  104. package/dist/board-export.js +0 -592
  105. package/dist/board-fonts.d.ts +0 -11
  106. package/dist/board-fonts.js +0 -10
  107. package/dist/board-gpu/daemon.d.ts +0 -11
  108. package/dist/board-gpu/daemon.js +0 -295
  109. package/dist/board-gpu/index.d.ts +0 -33
  110. package/dist/board-gpu/index.js +0 -189
  111. package/dist/board-gpu/protocol.d.ts +0 -77
  112. package/dist/board-gpu/protocol.js +0 -1
  113. package/dist/board-kernel.d.ts +0 -5
  114. package/dist/board-media-export.d.ts +0 -17
  115. package/dist/board-media-export.js +0 -164
  116. package/dist/board-media.d.ts +0 -5
  117. package/dist/board-media.js +0 -66
  118. package/dist/board-profile.d.ts +0 -21
  119. package/dist/board-profile.js +0 -67
  120. package/dist/board-simulate.d.ts +0 -67
  121. package/dist/board-simulate.js +0 -259
  122. package/dist/board-time.d.ts +0 -3
  123. package/dist/board-time.js +0 -34
  124. package/dist/bootstrap.d.ts +0 -2
  125. package/dist/client.d.ts +0 -5
  126. package/dist/client.js +0 -24
  127. package/dist/command-input.d.ts +0 -4
  128. package/dist/command-input.js +0 -16
  129. package/dist/commands/app-commerce.d.ts +0 -2
  130. package/dist/commands/app-commerce.js +0 -228
  131. package/dist/commands/app-domains.d.ts +0 -2
  132. package/dist/commands/app-domains.js +0 -133
  133. package/dist/commands/apps.d.ts +0 -4
  134. package/dist/commands/apps.js +0 -827
  135. package/dist/commands/auth.d.ts +0 -2
  136. package/dist/commands/auth.js +0 -186
  137. package/dist/commands/boards/authoring.d.ts +0 -2
  138. package/dist/commands/boards/authoring.js +0 -166
  139. package/dist/commands/boards/examples.d.ts +0 -10
  140. package/dist/commands/boards/examples.js +0 -118
  141. package/dist/commands/boards.d.ts +0 -13
  142. package/dist/commands/boards.js +0 -836
  143. package/dist/commands/channels.d.ts +0 -2
  144. package/dist/commands/channels.js +0 -74
  145. package/dist/commands/cron-jobs.d.ts +0 -2
  146. package/dist/commands/cron-jobs.js +0 -155
  147. package/dist/commands/decision.d.ts +0 -4
  148. package/dist/commands/decision.js +0 -113
  149. package/dist/commands/desktop.d.ts +0 -10
  150. package/dist/commands/desktop.js +0 -233
  151. package/dist/commands/feedback.d.ts +0 -2
  152. package/dist/commands/feedback.js +0 -131
  153. package/dist/commands/generations.d.ts +0 -2
  154. package/dist/commands/generations.js +0 -427
  155. package/dist/commands/host.d.ts +0 -2
  156. package/dist/commands/host.js +0 -11
  157. package/dist/commands/me.d.ts +0 -2
  158. package/dist/commands/me.js +0 -118
  159. package/dist/commands/models.d.ts +0 -28
  160. package/dist/commands/models.js +0 -271
  161. package/dist/commands/profile.d.ts +0 -2
  162. package/dist/commands/profile.js +0 -81
  163. package/dist/commands/prompts.d.ts +0 -2
  164. package/dist/commands/prompts.js +0 -37
  165. package/dist/commands/public.d.ts +0 -20
  166. package/dist/commands/public.js +0 -291
  167. package/dist/commands/references.d.ts +0 -2
  168. package/dist/commands/references.js +0 -193
  169. package/dist/commands/referrals.d.ts +0 -2
  170. package/dist/commands/referrals.js +0 -88
  171. package/dist/commands/rooms-connect.d.ts +0 -17
  172. package/dist/commands/rooms-connect.js +0 -140
  173. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  174. package/dist/commands/rooms-rtc-binary.js +0 -107
  175. package/dist/commands/rooms-rtc.d.ts +0 -21
  176. package/dist/commands/rooms-rtc.js +0 -171
  177. package/dist/commands/rooms.d.ts +0 -3
  178. package/dist/commands/rooms.js +0 -277
  179. package/dist/commands/run.d.ts +0 -13
  180. package/dist/commands/run.js +0 -246
  181. package/dist/commands/runtime.d.ts +0 -3
  182. package/dist/commands/runtime.js +0 -320
  183. package/dist/commands/sandboxd-binary.d.ts +0 -11
  184. package/dist/commands/sandboxd-binary.js +0 -238
  185. package/dist/commands/search.d.ts +0 -2
  186. package/dist/commands/search.js +0 -114
  187. package/dist/commands/session-access.d.ts +0 -2
  188. package/dist/commands/session-access.js +0 -70
  189. package/dist/commands/skills.d.ts +0 -2
  190. package/dist/commands/skills.js +0 -34
  191. package/dist/commands/space-activity.d.ts +0 -26
  192. package/dist/commands/space-activity.js +0 -147
  193. package/dist/commands/space-commerce.d.ts +0 -2
  194. package/dist/commands/space-commerce.js +0 -514
  195. package/dist/commands/space-displays.d.ts +0 -2
  196. package/dist/commands/space-displays.js +0 -620
  197. package/dist/commands/space-files.d.ts +0 -5
  198. package/dist/commands/space-files.js +0 -215
  199. package/dist/commands/space-invitations.d.ts +0 -29
  200. package/dist/commands/space-invitations.js +0 -189
  201. package/dist/commands/space-turns.d.ts +0 -49
  202. package/dist/commands/space-turns.js +0 -205
  203. package/dist/commands/space-wallet.d.ts +0 -2
  204. package/dist/commands/space-wallet.js +0 -64
  205. package/dist/commands/space-webhooks.d.ts +0 -7
  206. package/dist/commands/space-webhooks.js +0 -73
  207. package/dist/commands/spaces.d.ts +0 -25
  208. package/dist/commands/spaces.js +0 -2139
  209. package/dist/commands/tasks.d.ts +0 -8
  210. package/dist/commands/tasks.js +0 -80
  211. package/dist/commands/version.d.ts +0 -2
  212. package/dist/commands/version.js +0 -21
  213. package/dist/endpoint-options.d.ts +0 -4
  214. package/dist/endpoint-options.js +0 -26
  215. package/dist/env-proxy.d.ts +0 -5
  216. package/dist/env-proxy.js +0 -20
  217. package/dist/help-path.d.ts +0 -18
  218. package/dist/help-path.js +0 -223
  219. package/dist/host/auth.d.ts +0 -20
  220. package/dist/host/auth.js +0 -119
  221. package/dist/host/login-env.d.ts +0 -1
  222. package/dist/host/login-env.js +0 -31
  223. package/dist/host/runtime.d.ts +0 -35
  224. package/dist/host/runtime.js +0 -395
  225. package/dist/host/runtimes.d.ts +0 -9
  226. package/dist/host/runtimes.js +0 -42
  227. package/dist/host/serve.d.ts +0 -2
  228. package/dist/host/serve.js +0 -117
  229. package/dist/host/workspaces.d.ts +0 -2
  230. package/dist/host/workspaces.js +0 -18
  231. package/dist/http-put.d.ts +0 -25
  232. package/dist/http-put.js +0 -132
  233. package/dist/index.d.ts +0 -2
  234. package/dist/index.js +0 -129
  235. package/dist/launcher.d.ts +0 -4
  236. package/dist/launcher.js +0 -38
  237. package/dist/local-media.d.ts +0 -2
  238. package/dist/local-media.js +0 -30
  239. package/dist/network-error.d.ts +0 -3
  240. package/dist/network-error.js +0 -22
  241. package/dist/output.d.ts +0 -46
  242. package/dist/output.js +0 -244
  243. package/dist/runtime/archive-store.d.ts +0 -54
  244. package/dist/runtime/archive-store.js +0 -379
  245. package/dist/runtime/cli-path.d.ts +0 -5
  246. package/dist/runtime/cli-path.js +0 -27
  247. package/dist/runtime/codex-usage.d.ts +0 -7
  248. package/dist/runtime/codex-usage.js +0 -11
  249. package/dist/runtime/connection.d.ts +0 -42
  250. package/dist/runtime/connection.js +0 -789
  251. package/dist/runtime/diagnostics.d.ts +0 -107
  252. package/dist/runtime/diagnostics.js +0 -392
  253. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  254. package/dist/runtime/harnesses/chained-projection.js +0 -95
  255. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  256. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  257. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  258. package/dist/runtime/harnesses/claude-approval.js +0 -124
  259. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  260. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  261. package/dist/runtime/harnesses/claude.d.ts +0 -8
  262. package/dist/runtime/harnesses/claude.js +0 -225
  263. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  264. package/dist/runtime/harnesses/codex-approval.js +0 -69
  265. package/dist/runtime/harnesses/codex.d.ts +0 -4
  266. package/dist/runtime/harnesses/codex.js +0 -269
  267. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  268. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  269. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  270. package/dist/runtime/harnesses/cursor.js +0 -620
  271. package/dist/runtime/harnesses/index.d.ts +0 -16
  272. package/dist/runtime/harnesses/index.js +0 -73
  273. package/dist/runtime/harnesses/pi.d.ts +0 -4
  274. package/dist/runtime/harnesses/pi.js +0 -247
  275. package/dist/runtime/harnesses/process.d.ts +0 -31
  276. package/dist/runtime/harnesses/process.js +0 -75
  277. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  278. package/dist/runtime/harnesses/stream-json.js +0 -336
  279. package/dist/runtime/harnesses/types.d.ts +0 -117
  280. package/dist/runtime/harnesses/types.js +0 -1
  281. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  282. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  283. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  284. package/dist/runtime/harnesses/workbuddy.js +0 -123
  285. package/dist/runtime/instance.d.ts +0 -20
  286. package/dist/runtime/instance.js +0 -247
  287. package/dist/runtime/json-rpc.d.ts +0 -53
  288. package/dist/runtime/json-rpc.js +0 -212
  289. package/dist/runtime/launch.d.ts +0 -25
  290. package/dist/runtime/launch.js +0 -247
  291. package/dist/runtime/local-workspace.d.ts +0 -15
  292. package/dist/runtime/local-workspace.js +0 -52
  293. package/dist/runtime/model-catalog.d.ts +0 -12
  294. package/dist/runtime/model-catalog.js +0 -84
  295. package/dist/runtime/native/adapters.d.ts +0 -15
  296. package/dist/runtime/native/adapters.js +0 -11
  297. package/dist/runtime/native/approvals.d.ts +0 -18
  298. package/dist/runtime/native/approvals.js +0 -54
  299. package/dist/runtime/native/archive.d.ts +0 -19
  300. package/dist/runtime/native/archive.js +0 -142
  301. package/dist/runtime/native/attach.d.ts +0 -36
  302. package/dist/runtime/native/attach.js +0 -128
  303. package/dist/runtime/native/codex-link.d.ts +0 -60
  304. package/dist/runtime/native/codex-link.js +0 -322
  305. package/dist/runtime/native/config.d.ts +0 -16
  306. package/dist/runtime/native/config.js +0 -24
  307. package/dist/runtime/native/daemon.d.ts +0 -92
  308. package/dist/runtime/native/daemon.js +0 -380
  309. package/dist/runtime/native/execution.d.ts +0 -26
  310. package/dist/runtime/native/execution.js +0 -34
  311. package/dist/runtime/native/identity.d.ts +0 -9
  312. package/dist/runtime/native/identity.js +0 -15
  313. package/dist/runtime/native/ingest.d.ts +0 -263
  314. package/dist/runtime/native/ingest.js +0 -884
  315. package/dist/runtime/native/install.d.ts +0 -9
  316. package/dist/runtime/native/install.js +0 -113
  317. package/dist/runtime/native/paths.d.ts +0 -2
  318. package/dist/runtime/native/paths.js +0 -7
  319. package/dist/runtime/native/pi-extension.d.ts +0 -36
  320. package/dist/runtime/native/pi-link.d.ts +0 -69
  321. package/dist/runtime/native/pi-link.js +0 -269
  322. package/dist/runtime/native/results.d.ts +0 -41
  323. package/dist/runtime/native/results.js +0 -128
  324. package/dist/runtime/native/sessions.d.ts +0 -45
  325. package/dist/runtime/native/sessions.js +0 -87
  326. package/dist/runtime/native/transcript.d.ts +0 -89
  327. package/dist/runtime/native/transcript.js +0 -656
  328. package/dist/runtime/native/translate.d.ts +0 -46
  329. package/dist/runtime/native/translate.js +0 -299
  330. package/dist/runtime/native/transport.d.ts +0 -7
  331. package/dist/runtime/native/transport.js +0 -16
  332. package/dist/runtime/native/version.d.ts +0 -5
  333. package/dist/runtime/native/version.js +0 -21
  334. package/dist/runtime/preferences.d.ts +0 -7
  335. package/dist/runtime/preferences.js +0 -22
  336. package/dist/runtime/presentation.d.ts +0 -32
  337. package/dist/runtime/presentation.js +0 -124
  338. package/dist/runtime/process-group.d.ts +0 -5
  339. package/dist/runtime/process-group.js +0 -161
  340. package/dist/runtime/projection-store.d.ts +0 -27
  341. package/dist/runtime/projection-store.js +0 -30
  342. package/dist/runtime/space-binding.d.ts +0 -48
  343. package/dist/runtime/space-binding.js +0 -342
  344. package/dist/runtime/supervisor.d.ts +0 -19
  345. package/dist/runtime/supervisor.js +0 -441
  346. package/dist/runtime/turn-projection.d.ts +0 -41
  347. package/dist/runtime/turn-projection.js +0 -120
  348. package/dist/runtime/worker.d.ts +0 -1
  349. package/dist/safe-remote-image.d.ts +0 -36
  350. package/dist/safe-remote-image.js +0 -191
  351. package/dist/self-update.d.ts +0 -7
  352. package/dist/self-update.js +0 -202
  353. package/dist/session-status.d.ts +0 -6
  354. package/dist/session-status.js +0 -16
  355. package/dist/space-files/limit.d.ts +0 -2
  356. package/dist/space-files/limit.js +0 -16
  357. package/dist/space-files/operands.d.ts +0 -17
  358. package/dist/space-files/operands.js +0 -33
  359. package/dist/space-files/transfer.d.ts +0 -53
  360. package/dist/space-files/transfer.js +0 -297
  361. package/dist/space-files/upload.d.ts +0 -17
  362. package/dist/space-files/upload.js +0 -76
  363. package/dist/space.d.ts +0 -44
  364. package/dist/space.js +0 -192
  365. package/dist/version.d.ts +0 -2
  366. package/dist/version.js +0 -17
  367. package/dist/web.d.ts +0 -1
  368. package/dist/web.js +0 -4
  369. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
@@ -0,0 +1,1423 @@
1
+ import { C as error, D as json, E as handleHttp, O as jsonRequested, T as formatLocalDateTime, b as resolveSpace, ft as isHttpErrorCode, j as table, k as ok, n as createClientWithAccessToken, t as createClient } from "./client.js";
2
+ import { s as HttpError } from "./app-realtime.js";
3
+ import { r as getCohubContext, s as resolveExecutionAppId } from "./environment.js";
4
+ import { n as parseAppRef, t as getAppByRef } from "./app-ref.js";
5
+ import { n as putBytes, r as putLocalFile } from "./http-put.js";
6
+ import { t as collectOption$1 } from "./command-input.js";
7
+ import { t as collectPublicUpload } from "./public2.js";
8
+ import { createWriteStream } from "node:fs";
9
+ import { basename, dirname, join, posix, resolve } from "node:path";
10
+ import { createHash, randomUUID } from "node:crypto";
11
+ import { Readable, Transform } from "node:stream";
12
+ import { link, lstat, mkdir, mkdtemp, rename, rm, rmdir } from "node:fs/promises";
13
+ import { pipeline } from "node:stream/promises";
14
+ //#region ../protocol/src/app-domains.ts
15
+ const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
16
+ const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/;
17
+ /**
18
+ * Normalizes user input into a lowercase ASCII (punycode) hostname, or null
19
+ * when it is not a plain multi-label hostname (no scheme, port, path, wildcard
20
+ * or IP literal).
21
+ */
22
+ function normalizeAppDomainHostname(input) {
23
+ const raw = input.trim().toLowerCase().replace(/\.$/, "");
24
+ if (!raw || /[\s/:@*?#\\]/.test(raw)) return null;
25
+ let hostname;
26
+ try {
27
+ hostname = new URL(`https://${raw}`).hostname;
28
+ } catch {
29
+ return null;
30
+ }
31
+ if (hostname.length > 253 || IPV4_RE.test(hostname)) return null;
32
+ const labels = hostname.split(".");
33
+ if (labels.length < 2) return null;
34
+ if (!labels.every((label) => LABEL_RE.test(label))) return null;
35
+ if (/^\d+$/.test(labels.at(-1) ?? "")) return null;
36
+ return hostname;
37
+ }
38
+ //#endregion
39
+ //#region src/app-download.ts
40
+ const MANIFEST_MAX_BYTES = 4194304;
41
+ const MAX_CONTENT_FILE_BYTES = 1073741824;
42
+ const DOWNLOAD_CONCURRENCY = 4;
43
+ function safeRelativePath(value, label) {
44
+ if (!value || value.includes("\\") || value.includes("\0") || posix.isAbsolute(value)) throw new Error(`Invalid ${label} in app manifest`);
45
+ if (value.split("/").some((segment) => !segment || segment === "." || segment === "..")) throw new Error(`Invalid ${label} in app manifest`);
46
+ return posix.normalize(value);
47
+ }
48
+ function isManifestFile(value) {
49
+ if (!value || typeof value !== "object") return false;
50
+ const file = value;
51
+ return typeof file.artifactPath === "string" && typeof file.outputPath === "string" && (typeof file.mimeType === "string" || file.mimeType === null) && Number.isSafeInteger(file.sizeBytes) && Number(file.sizeBytes) >= 0 && typeof file.sha256 === "string" && /^[0-9a-f]{64}$/i.test(file.sha256);
52
+ }
53
+ function parseManifest(value) {
54
+ if (!value || typeof value !== "object") throw new Error("App download manifest is invalid");
55
+ const manifest = value;
56
+ if (manifest.kind !== "cohub.work.artifact-manifest" || manifest.version !== 1 || manifest.targetType !== "file" && manifest.targetType !== "directory" || typeof manifest.targetRef !== "string" || typeof manifest.entrypoint !== "string" || !Number.isSafeInteger(manifest.fileCount) || Number(manifest.fileCount) < 1 || !Number.isSafeInteger(manifest.sizeBytes) || Number(manifest.sizeBytes) < 0 || !Array.isArray(manifest.files) || !manifest.files.every(isManifestFile) || manifest.files.length !== manifest.fileCount) throw new Error("App download manifest is invalid");
57
+ const seenArtifactPaths = /* @__PURE__ */ new Set();
58
+ const seenOutputPaths = /* @__PURE__ */ new Set();
59
+ let sizeBytes = 0;
60
+ for (const file of manifest.files) {
61
+ file.artifactPath = safeRelativePath(file.artifactPath, "artifact path");
62
+ file.outputPath = safeRelativePath(file.outputPath, "output path");
63
+ if (seenArtifactPaths.has(file.artifactPath) || seenOutputPaths.has(file.outputPath)) throw new Error("App download manifest contains duplicate paths");
64
+ seenArtifactPaths.add(file.artifactPath);
65
+ seenOutputPaths.add(file.outputPath);
66
+ sizeBytes += file.sizeBytes;
67
+ }
68
+ if (sizeBytes !== manifest.sizeBytes) throw new Error("App download manifest size is invalid");
69
+ safeRelativePath(manifest.entrypoint, "entrypoint");
70
+ return manifest;
71
+ }
72
+ async function readManifest(url, expectedSha256, fetcher) {
73
+ const response = await fetcher(url);
74
+ if (!response.ok) throw new Error(`Failed to download app manifest (${response.status})`);
75
+ if (!response.body) throw new Error("App download manifest is invalid");
76
+ const contentLength = Number(response.headers.get("content-length") ?? 0);
77
+ if (Number.isFinite(contentLength) && contentLength > MANIFEST_MAX_BYTES) throw new Error("App download manifest is too large");
78
+ const chunks = [];
79
+ let sizeBytes = 0;
80
+ for await (const chunk of Readable.fromWeb(response.body)) {
81
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
82
+ sizeBytes += bytes.byteLength;
83
+ if (sizeBytes > MANIFEST_MAX_BYTES) throw new Error("App download manifest is too large");
84
+ chunks.push(bytes);
85
+ }
86
+ const bytes = Buffer.concat(chunks, sizeBytes);
87
+ if (createHash("sha256").update(bytes).digest("hex") !== expectedSha256) throw new Error("App download manifest checksum mismatch");
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(bytes.toString("utf8"));
91
+ } catch {
92
+ throw new Error("App download manifest is invalid");
93
+ }
94
+ return parseManifest(parsed);
95
+ }
96
+ function artifactUrl(contentUrl, artifactPath) {
97
+ const base = new URL("./", contentUrl);
98
+ const encodedPath = safeRelativePath(artifactPath, "artifact path").split("/").map(encodeURIComponent).join("/");
99
+ return new URL(encodedPath, base).toString();
100
+ }
101
+ async function downloadFile(url, output, expected, fetcher) {
102
+ const response = await fetcher(url);
103
+ if (!response.ok || !response.body) throw new Error(`Failed to download ${expected.outputPath} (${response.status})`);
104
+ await mkdir(dirname(output), { recursive: true });
105
+ let sizeBytes = 0;
106
+ const verifier = new Transform({ transform(chunk, _encoding, callback) {
107
+ sizeBytes += chunk.byteLength;
108
+ if (sizeBytes > MAX_CONTENT_FILE_BYTES) {
109
+ callback(/* @__PURE__ */ new Error(`Downloaded file is too large: ${expected.outputPath}`));
110
+ return;
111
+ }
112
+ callback(null, chunk);
113
+ } });
114
+ await pipeline(Readable.fromWeb(response.body), verifier, createWriteStream(output, { flags: "wx" }));
115
+ return sizeBytes;
116
+ }
117
+ function outputExistsError(output) {
118
+ return /* @__PURE__ */ new Error(`Output already exists: ${output}`);
119
+ }
120
+ async function outputExists(output) {
121
+ return Boolean(await lstat(output).catch((cause) => {
122
+ if (cause.code === "ENOENT") return null;
123
+ throw cause;
124
+ }));
125
+ }
126
+ async function assertOutputMissing(output) {
127
+ if (await outputExists(output)) throw outputExistsError(output);
128
+ }
129
+ async function installFileNoReplace(stagedFile, output) {
130
+ try {
131
+ await link(stagedFile, output);
132
+ } catch (cause) {
133
+ if (cause.code === "EEXIST") throw outputExistsError(output);
134
+ throw cause;
135
+ }
136
+ }
137
+ async function installDirectoryNoReplace(stage, output) {
138
+ if (process.platform === "win32") try {
139
+ await rename(stage, output);
140
+ return;
141
+ } catch (cause) {
142
+ if (await outputExists(output)) throw outputExistsError(output);
143
+ throw cause;
144
+ }
145
+ try {
146
+ await mkdir(output);
147
+ } catch (cause) {
148
+ if (cause.code === "EEXIST") throw outputExistsError(output);
149
+ throw cause;
150
+ }
151
+ try {
152
+ await rename(stage, output);
153
+ } catch (cause) {
154
+ await rmdir(output).catch(() => void 0);
155
+ throw cause;
156
+ }
157
+ }
158
+ async function downloadFiles(input) {
159
+ const downloadedBytes = new Array(input.files.length);
160
+ let next = 0;
161
+ let failed = false;
162
+ let failure;
163
+ const workers = Array.from({ length: Math.min(DOWNLOAD_CONCURRENCY, input.files.length) }, async () => {
164
+ while (!failed && next < input.files.length) {
165
+ const index = next++;
166
+ const file = input.files[index];
167
+ if (!file) continue;
168
+ try {
169
+ downloadedBytes[index] = await downloadFile(artifactUrl(input.contentUrl, file.artifactPath), join(input.stage, ...file.outputPath.split("/")), file, input.fetcher);
170
+ } catch (cause) {
171
+ if (!failed) failure = cause;
172
+ failed = true;
173
+ }
174
+ }
175
+ });
176
+ await Promise.all(workers);
177
+ if (failed) throw failure;
178
+ return downloadedBytes.reduce((sum, size) => sum + size, 0);
179
+ }
180
+ async function downloadApp(detail, outputOption, fetcher = fetch) {
181
+ const { app, content } = detail;
182
+ if (!content) throw new Error("This app has no published downloadable artifact");
183
+ if (content.kind === "port") throw new Error("Port apps do not have a downloadable artifact");
184
+ if (content.kind === "board") throw new Error("Board apps do not have a restorable file or directory artifact");
185
+ if (!content.download) throw new Error("This app version does not support download");
186
+ const manifest = await readManifest(content.download.manifestUrl, content.download.manifestSha256, fetcher);
187
+ if (manifest.targetType !== content.targetType || manifest.targetRef !== content.path) throw new Error("App download manifest does not match the published artifact");
188
+ const entry = manifest.files.find((file) => file.artifactPath === manifest.entrypoint);
189
+ if (!entry) throw new Error("App download manifest entrypoint is missing");
190
+ const hasDirectoryOutput = manifest.targetType === "directory" || manifest.files.length > 1;
191
+ const output = resolve(outputOption ?? (hasDirectoryOutput ? app.slug : basename(manifest.targetRef)));
192
+ await assertOutputMissing(output);
193
+ await mkdir(dirname(output), { recursive: true });
194
+ const stage = await mkdtemp(join(dirname(output), `.${basename(output)}.cohub-download-`));
195
+ try {
196
+ const files = hasDirectoryOutput ? manifest.files : [entry];
197
+ const downloadedBytes = await downloadFiles({
198
+ files,
199
+ contentUrl: content.url,
200
+ stage,
201
+ fetcher
202
+ });
203
+ if (hasDirectoryOutput) await installDirectoryNoReplace(stage, output);
204
+ else {
205
+ await installFileNoReplace(join(stage, ...entry.outputPath.split("/")), output);
206
+ await rm(stage, {
207
+ recursive: true,
208
+ force: true
209
+ });
210
+ }
211
+ return {
212
+ appId: app.id,
213
+ version: app.latestVersion,
214
+ kind: hasDirectoryOutput ? "directory" : "file",
215
+ output,
216
+ files: files.length,
217
+ bytes: downloadedBytes
218
+ };
219
+ } catch (cause) {
220
+ await rm(stage, {
221
+ recursive: true,
222
+ force: true
223
+ }).catch(() => void 0);
224
+ throw cause;
225
+ }
226
+ }
227
+ //#endregion
228
+ //#region src/app-target.ts
229
+ /** Normalize a user-supplied Space path for comparison with fs entries. */
230
+ function normalizeSpacePath(path) {
231
+ return path.replace(/^\.\//, "").replace(/\/+$/, "");
232
+ }
233
+ function posixDirname(path) {
234
+ const index = path.lastIndexOf("/");
235
+ return index <= 0 ? "" : path.slice(0, index);
236
+ }
237
+ /**
238
+ * Verify a Space-relative publish target exists with the expected node type.
239
+ * Empty targetRef (the Space workspace root, directory publishes only) passes.
240
+ * Returns null when the target is valid or the check itself cannot run —
241
+ * the preflight is advisory and must never block a publish the worker can do.
242
+ */
243
+ async function checkAppTarget(client, spaceId, target) {
244
+ const targetPath = normalizeSpacePath(target.targetRef);
245
+ if (!targetPath) return null;
246
+ try {
247
+ const entry = (await client.space(spaceId).files.list(posixDirname(targetPath))).entries.find((candidate) => candidate.path === targetPath);
248
+ if (!entry) return {
249
+ status: 404,
250
+ code: "path_not_found",
251
+ message: `"${targetPath}" does not exist in the Space workspace`
252
+ };
253
+ const wanted = target.targetType === "directory" ? "dir" : "file";
254
+ if (entry.type !== wanted) {
255
+ const foundKind = entry.type === "dir" ? "a directory" : entry.type === "symlink" ? "a symlink" : "a file";
256
+ const wantedKind = wanted === "dir" ? "a directory" : "a file";
257
+ return {
258
+ status: 400,
259
+ code: entry.type === "symlink" ? "symlink_not_supported" : wanted === "dir" ? "not_a_directory" : "not_a_file",
260
+ message: `"${targetPath}" is ${foundKind}, but the publish target must be ${wantedKind}`
261
+ };
262
+ }
263
+ return null;
264
+ } catch (e) {
265
+ if (isHttpErrorCode(e, "path_not_found")) return {
266
+ status: 404,
267
+ code: "path_not_found",
268
+ message: `"${targetPath}" does not exist in the Space workspace`
269
+ };
270
+ return null;
271
+ }
272
+ }
273
+ //#endregion
274
+ //#region src/commands/app-commerce.ts
275
+ function requireText(value, label, flag) {
276
+ const text = value?.trim();
277
+ if (text) return text;
278
+ return error(`Missing ${label}`, `Pass ${flag}.`);
279
+ }
280
+ function requireAppId(value) {
281
+ return requireText(value ?? resolveExecutionAppId() ?? void 0, "app ID", "--app-id <id>");
282
+ }
283
+ function requireList(values, label, flag) {
284
+ const items = [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
285
+ if (items.length > 0) return items;
286
+ return error(`Missing ${label}`, `Pass ${flag}.`);
287
+ }
288
+ function formatUsd(amount) {
289
+ return `$${amount.toLocaleString("en-US", {
290
+ minimumFractionDigits: 2,
291
+ maximumFractionDigits: 2
292
+ })}`;
293
+ }
294
+ function formatMinorUsd(amountMinor) {
295
+ return formatUsd(amountMinor / 100);
296
+ }
297
+ function printProducts(products) {
298
+ table(products.map((product) => ({
299
+ key: product.key,
300
+ name: product.name,
301
+ status: product.status,
302
+ visibility: product.visibility,
303
+ price: formatUsd(product.pricing.amountUsd),
304
+ credits: product.display.creditsAmount ?? ""
305
+ })), [
306
+ {
307
+ key: "key",
308
+ label: "Key"
309
+ },
310
+ {
311
+ key: "name",
312
+ label: "Name"
313
+ },
314
+ {
315
+ key: "status",
316
+ label: "Status"
317
+ },
318
+ {
319
+ key: "visibility",
320
+ label: "Visibility"
321
+ },
322
+ {
323
+ key: "price",
324
+ label: "Price"
325
+ },
326
+ {
327
+ key: "credits",
328
+ label: "Credits"
329
+ }
330
+ ]);
331
+ }
332
+ function printEntitlements(result) {
333
+ table(result.entitlements.map((item) => ({
334
+ benefitKey: item.benefitKey,
335
+ enabled: item.enabled ? "yes" : "no",
336
+ metadata: item.metadata ? JSON.stringify(item.metadata) : ""
337
+ })), [
338
+ {
339
+ key: "benefitKey",
340
+ label: "Benefit"
341
+ },
342
+ {
343
+ key: "enabled",
344
+ label: "Enabled"
345
+ },
346
+ {
347
+ key: "metadata",
348
+ label: "Metadata"
349
+ }
350
+ ]);
351
+ console.log(`\nCredits available: ${result.credits.available} (net: ${result.credits.net})`);
352
+ }
353
+ function printOrder(order) {
354
+ table([{
355
+ id: order.id,
356
+ product: order.productKeySnapshot,
357
+ status: order.status,
358
+ amount: formatMinorUsd(order.amountSnapshot),
359
+ paid: formatMinorUsd(order.paidAmountSnapshot),
360
+ created: order.createdAt,
361
+ paidAt: order.paidAt ?? ""
362
+ }], [
363
+ {
364
+ key: "id",
365
+ label: "ID"
366
+ },
367
+ {
368
+ key: "product",
369
+ label: "Product"
370
+ },
371
+ {
372
+ key: "status",
373
+ label: "Status"
374
+ },
375
+ {
376
+ key: "amount",
377
+ label: "Amount"
378
+ },
379
+ {
380
+ key: "paid",
381
+ label: "Paid"
382
+ },
383
+ {
384
+ key: "created",
385
+ label: "Created",
386
+ format: formatLocalDateTime
387
+ },
388
+ {
389
+ key: "paidAt",
390
+ label: "Paid At"
391
+ }
392
+ ]);
393
+ }
394
+ function registerAppCommerce(appsCmd) {
395
+ const commerceCmd = appsCmd.command("commerce").description("App commerce operations").addHelpText("after", `
396
+ Examples:
397
+ cohub apps commerce products resolve --app-id <app-id> --product-key pro_pack
398
+ cohub apps commerce entitlements --app-id <app-id>
399
+ cohub apps commerce credits consume --app-id <app-id> --amount 100
400
+ `);
401
+ commerceCmd.command("products").description("Resolve commerce products").command("resolve").description("Resolve public products for an app").option("--app-id <id>", "App ID").option("--product-key <key>", "Product key", collectOption$1).option("--json", "Output as JSON").action(async (opts) => {
402
+ const appId = requireAppId(opts.appId);
403
+ const productKeys = requireList(opts.productKey, "product key", "--product-key <key>");
404
+ const client = createClient();
405
+ try {
406
+ const result = await client.appCommerce.resolveProducts(appId, { productKeys });
407
+ if (jsonRequested(opts)) return json(result);
408
+ printProducts(result.products);
409
+ } catch (e) {
410
+ handleHttp(e);
411
+ }
412
+ });
413
+ commerceCmd.command("entitlements").description("Show viewer entitlements and credit balance for an app").option("--app-id <id>", "App ID").option("--json", "Output as JSON").action(async (opts) => {
414
+ const appId = requireAppId(opts.appId);
415
+ const client = createClient();
416
+ try {
417
+ const result = await client.appCommerce.getEntitlements(appId);
418
+ if (jsonRequested(opts)) return json(result);
419
+ printEntitlements(result);
420
+ } catch (e) {
421
+ handleHttp(e);
422
+ }
423
+ });
424
+ commerceCmd.command("credits").description("Consume credits for an app").command("consume").description("Consume credits for an app (self by default)").option("--app-id <id>", "App ID").option("--amount <n>", "Positive integer credit amount").option("--operation-id <id>", "Idempotency key (generated when omitted)").option("--reason <text>", "Reason for the consumption").option("--json", "Output as JSON").action(async (opts) => {
425
+ const appId = requireAppId(opts.appId);
426
+ const amountText = requireText(opts.amount, "amount", "--amount <n>");
427
+ const amount = Number.parseInt(amountText, 10);
428
+ if (!Number.isSafeInteger(amount) || amount <= 0) return error("Invalid amount", "--amount must be a positive integer.");
429
+ const operationId = opts.operationId?.trim() || crypto.randomUUID();
430
+ const client = createClient();
431
+ try {
432
+ const result = await client.appCommerce.consumeCredits(appId, {
433
+ amount,
434
+ operationId,
435
+ reason: opts.reason
436
+ });
437
+ if (jsonRequested(opts)) return json({
438
+ ...result,
439
+ operationId
440
+ });
441
+ ok(`Consumed ${result.amount} credits (operation: ${operationId})`);
442
+ table([{
443
+ status: result.status,
444
+ amount: result.amount,
445
+ remaining: result.remaining,
446
+ shortfall: result.shortfall ?? ""
447
+ }], [
448
+ {
449
+ key: "status",
450
+ label: "Status"
451
+ },
452
+ {
453
+ key: "amount",
454
+ label: "Amount"
455
+ },
456
+ {
457
+ key: "remaining",
458
+ label: "Remaining"
459
+ },
460
+ {
461
+ key: "shortfall",
462
+ label: "Shortfall"
463
+ }
464
+ ]);
465
+ } catch (e) {
466
+ handleHttp(e);
467
+ }
468
+ });
469
+ commerceCmd.command("purchase").description("Create an app purchase checkout").option("--app-id <id>", "App ID").option("--product-key <key>", "Product key").option("--json", "Output as JSON").action(async (opts) => {
470
+ const appId = requireAppId(opts.appId);
471
+ const productKey = requireText(opts.productKey, "product key", "--product-key <key>");
472
+ const client = createClient();
473
+ try {
474
+ const result = await client.appCommerce.purchase(appId, { productKey });
475
+ if (jsonRequested(opts)) return json(result);
476
+ ok(`Checkout created: ${result.checkout.orderId}`);
477
+ table([{
478
+ orderId: result.checkout.orderId,
479
+ productKey: result.checkout.productKey,
480
+ usable: result.checkout.checkoutUsable ? "yes" : "no",
481
+ status: result.checkout.status ?? "",
482
+ checkoutUrl: result.checkout.checkoutUrl ?? "",
483
+ message: result.checkout.message ?? ""
484
+ }], [
485
+ {
486
+ key: "orderId",
487
+ label: "Order"
488
+ },
489
+ {
490
+ key: "productKey",
491
+ label: "Product"
492
+ },
493
+ {
494
+ key: "usable",
495
+ label: "Usable"
496
+ },
497
+ {
498
+ key: "status",
499
+ label: "Status"
500
+ },
501
+ {
502
+ key: "checkoutUrl",
503
+ label: "Checkout URL"
504
+ },
505
+ {
506
+ key: "message",
507
+ label: "Message"
508
+ }
509
+ ]);
510
+ } catch (e) {
511
+ handleHttp(e);
512
+ }
513
+ });
514
+ commerceCmd.command("orders").description("Look up commerce orders").command("get").description("Show an app commerce order").option("--app-id <id>", "App ID").option("--order-id <id>", "Order ID").option("--json", "Output as JSON").action(async (opts) => {
515
+ const appId = requireAppId(opts.appId);
516
+ const orderId = requireText(opts.orderId, "order ID", "--order-id <id>");
517
+ const client = createClient();
518
+ try {
519
+ const result = await client.appCommerce.getOrder(appId, orderId);
520
+ if (jsonRequested(opts)) return json(result);
521
+ printOrder(result.order);
522
+ } catch (e) {
523
+ handleHttp(e);
524
+ }
525
+ });
526
+ }
527
+ //#endregion
528
+ //#region src/commands/app-domains.ts
529
+ async function confirm(question, opts, hint) {
530
+ if (opts.yes) return;
531
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return error("Confirmation required", hint);
532
+ process.stdout.write(`${question} [y/N] `);
533
+ const chunks = [];
534
+ for await (const chunk of process.stdin) {
535
+ chunks.push(chunk);
536
+ break;
537
+ }
538
+ const answer = Buffer.concat(chunks).toString().trim().toLowerCase();
539
+ if (answer !== "y" && answer !== "yes") return error("Cancelled");
540
+ }
541
+ async function findDomain(client, appId, ref) {
542
+ const { domains } = await client.apps.listDomains(appId);
543
+ const target = normalizeAppDomainHostname(ref) ?? ref.trim().toLowerCase();
544
+ return domains.find((item) => item.id === ref || item.hostname === target) ?? error(`Domain not found: ${ref}`, "Run `cohub apps domains ls <app>` to see the App's domains.");
545
+ }
546
+ const info = (message) => console.log(message);
547
+ function printDomain(domain) {
548
+ table([{
549
+ hostname: domain.hostname,
550
+ status: domain.status,
551
+ certificate: domain.certificateStatus ?? "-",
552
+ error: domain.error?.message ?? ""
553
+ }], [
554
+ {
555
+ key: "hostname",
556
+ label: "Hostname"
557
+ },
558
+ {
559
+ key: "status",
560
+ label: "Status"
561
+ },
562
+ {
563
+ key: "certificate",
564
+ label: "Certificate"
565
+ },
566
+ {
567
+ key: "error",
568
+ label: "Error"
569
+ }
570
+ ]);
571
+ if (domain.status === "active") return;
572
+ info("Add these DNS records at your DNS provider:");
573
+ table(domain.dnsRecords.map((record) => ({
574
+ ...record,
575
+ state: record.satisfied === true ? "ok" : record.satisfied === false ? "missing" : "-"
576
+ })), [
577
+ {
578
+ key: "type",
579
+ label: "Type"
580
+ },
581
+ {
582
+ key: "name",
583
+ label: "Name"
584
+ },
585
+ {
586
+ key: "value",
587
+ label: "Value"
588
+ },
589
+ {
590
+ key: "state",
591
+ label: "State"
592
+ }
593
+ ]);
594
+ }
595
+ function registerAppDomains(appsCmd) {
596
+ const domainsCmd = appsCmd.command("domains").description("Custom domains for published Apps");
597
+ domainsCmd.command("list <app>").alias("ls").description("List the App's custom domains").option("--json", "Output as JSON").action(async (appRef, opts) => {
598
+ const client = createClient();
599
+ try {
600
+ const detail = await getAppByRef(client, appRef);
601
+ const result = await client.apps.listDomains(detail.app.id);
602
+ if (jsonRequested(opts)) return json(result);
603
+ if (!result.enabled && result.domains.length === 0) return info("Custom domains are not enabled on this deployment.");
604
+ if (result.domains.length === 0) return info(`No custom domain. Add one with \`cohub apps domains add ${appRef} <hostname>\` ($${result.priceUsd}, one-time).`);
605
+ result.domains.forEach(printDomain);
606
+ } catch (e) {
607
+ handleHttp(e);
608
+ }
609
+ });
610
+ domainsCmd.command("add <app> <hostname>").description("Bind a custom domain; charged once when it goes live").option("-y, --yes", "Confirm the one-time charge").option("--json", "Output as JSON").action(async (appRef, hostname, opts) => {
611
+ const client = createClient();
612
+ try {
613
+ const detail = await getAppByRef(client, appRef);
614
+ const { priceUsd } = await client.apps.listDomains(detail.app.id);
615
+ await confirm(`Binding ${hostname} costs $${priceUsd}, charged once when the domain goes live. Continue?`, opts, `Pass --yes to accept the one-time $${priceUsd} charge.`);
616
+ const { domain } = await client.apps.addDomain(detail.app.id, hostname);
617
+ if (jsonRequested(opts)) return json(domain);
618
+ ok(`Domain added: ${domain.hostname}`);
619
+ printDomain(domain);
620
+ } catch (e) {
621
+ handleHttp(e);
622
+ }
623
+ });
624
+ domainsCmd.command("check <app> <domain>").description("Check DNS and certificate status now").option("--json", "Output as JSON").action(async (appRef, domainRef, opts) => {
625
+ const client = createClient();
626
+ try {
627
+ const detail = await getAppByRef(client, appRef);
628
+ const target = await findDomain(client, detail.app.id, domainRef);
629
+ const { domain } = await client.apps.checkDomain(detail.app.id, target.id);
630
+ if (jsonRequested(opts)) return json(domain);
631
+ printDomain(domain);
632
+ } catch (e) {
633
+ handleHttp(e);
634
+ }
635
+ });
636
+ domainsCmd.command("rm <app> <domain>").alias("remove").description("Remove a custom domain").option("-y, --yes", "Confirm removal").action(async (appRef, domainRef, opts) => {
637
+ const client = createClient();
638
+ try {
639
+ const detail = await getAppByRef(client, appRef);
640
+ const target = await findDomain(client, detail.app.id, domainRef);
641
+ await confirm(`Remove ${target.hostname}? The one-time charge is not refunded.`, opts, "Pass --yes to remove the domain.");
642
+ const result = await client.apps.removeDomain(detail.app.id, target.id);
643
+ ok(result.domain ? `Removing ${target.hostname}; its certificate is being released` : `Domain removed: ${target.hostname}`);
644
+ } catch (e) {
645
+ handleHttp(e);
646
+ }
647
+ });
648
+ }
649
+ //#endregion
650
+ //#region src/commands/apps.ts
651
+ const APP_STATUSES = ["published", "disabled"];
652
+ const APP_VISIBILITIES = ["public", "space"];
653
+ const collectOption = (value, previous = []) => [...previous, value];
654
+ function parseChoice(value, name, choices) {
655
+ if (choices.includes(value)) return value;
656
+ return error(`Invalid ${name}`, `Use one of: ${choices.join(", ")}`);
657
+ }
658
+ function parseJsonObject(value, name) {
659
+ if (!value) return void 0;
660
+ try {
661
+ const parsed = JSON.parse(value);
662
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
663
+ } catch {}
664
+ return error(`Invalid ${name}`, `${name} must be a JSON object`);
665
+ }
666
+ /** Human-readable version provenance: a session title, a channel, or blank. */
667
+ function formatVersionSource(value) {
668
+ if (!value || typeof value !== "object") return "";
669
+ const source = value;
670
+ if (source?.session) return source.session.title?.trim() || source.session.id;
671
+ return source?.via ? `via ${source.via}` : "";
672
+ }
673
+ function parseJsonValue(value, name) {
674
+ if (!value) return null;
675
+ try {
676
+ return JSON.parse(value);
677
+ } catch {
678
+ return error(`Invalid ${name}`, `${name} must be valid JSON`);
679
+ }
680
+ }
681
+ function compactObject(input) {
682
+ return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
683
+ }
684
+ function withCohubBarMeta(input) {
685
+ if (!input.hideCohubBar && !input.showCohubBar) return input.meta;
686
+ const meta = input.meta ? { ...input.meta } : {};
687
+ const presentation = meta.presentation && typeof meta.presentation === "object" && !Array.isArray(meta.presentation) ? { ...meta.presentation } : {};
688
+ if (input.hideCohubBar) presentation.hideCohubBar = true;
689
+ if (input.showCohubBar) delete presentation.hideCohubBar;
690
+ if (Object.keys(presentation).length > 0) meta.presentation = presentation;
691
+ else delete meta.presentation;
692
+ return Object.keys(meta).length > 0 ? meta : null;
693
+ }
694
+ const MAX_APP_SOURCE_FILES = 1e3;
695
+ const MAX_APP_SOURCE_BYTES = 1073741824;
696
+ const APP_SOURCE_UPLOAD_CONCURRENCY = 4;
697
+ async function uploadLocalAppSource(client, spaceId, source) {
698
+ if (source.targetType === "port") return null;
699
+ const upload = await collectPublicUpload(source.targetRef);
700
+ const totalBytes = upload.files.reduce((sum, file) => sum + file.size, 0);
701
+ if (upload.files.length > MAX_APP_SOURCE_FILES) return error("App source is too large", `Use no more than ${MAX_APP_SOURCE_FILES} files.`);
702
+ if (totalBytes > MAX_APP_SOURCE_BYTES) return error("App source is too large", "The total source size must not exceed 1 GiB.");
703
+ const uploadId = randomUUID();
704
+ const directoryPrefix = source.targetType === "directory" ? upload.destination.replace(/\/$/, "") : "";
705
+ const files = new Array(upload.files.length);
706
+ let nextIndex = 0;
707
+ const workers = Array.from({ length: Math.min(APP_SOURCE_UPLOAD_CONCURRENCY, upload.files.length) }, async () => {
708
+ while (nextIndex < upload.files.length) {
709
+ const index = nextIndex++;
710
+ const file = upload.files[index];
711
+ if (!file) return;
712
+ const plan = await client.publicAssets.createUpload({
713
+ purpose: "app_source",
714
+ uploadProtocol: "presigned_put_v1",
715
+ spaceId,
716
+ sessionId: uploadId,
717
+ file: {
718
+ size: file.size,
719
+ mimeType: file.mimeType,
720
+ filename: basename(file.publicPath)
721
+ }
722
+ });
723
+ await putLocalFile({
724
+ url: plan.asset.uploadUrl,
725
+ filePath: file.localPath,
726
+ size: file.size,
727
+ headers: plan.asset.uploadHeaders,
728
+ label: file.publicPath
729
+ });
730
+ const path = directoryPrefix && file.publicPath.startsWith(`${directoryPrefix}/`) ? file.publicPath.slice(directoryPrefix.length + 1) : basename(file.publicPath);
731
+ files[index] = {
732
+ path,
733
+ objectKey: plan.asset.objectKey,
734
+ size: file.size,
735
+ mimeType: file.mimeType
736
+ };
737
+ }
738
+ });
739
+ await Promise.all(workers);
740
+ const manifest = JSON.stringify({
741
+ kind: "cohub.app-source",
742
+ version: 1,
743
+ targetType: source.targetType,
744
+ files
745
+ });
746
+ const manifestBlob = new Blob([manifest], { type: "application/json" });
747
+ const manifestPlan = await client.publicAssets.createUpload({
748
+ purpose: "app_source",
749
+ uploadProtocol: "presigned_put_v1",
750
+ spaceId,
751
+ sessionId: uploadId,
752
+ file: {
753
+ size: manifestBlob.size,
754
+ mimeType: "application/json",
755
+ filename: "manifest.json"
756
+ }
757
+ });
758
+ await putBytes({
759
+ url: manifestPlan.asset.uploadUrl,
760
+ body: manifestBlob,
761
+ size: manifestBlob.size,
762
+ headers: manifestPlan.asset.uploadHeaders,
763
+ label: "app source manifest"
764
+ });
765
+ return {
766
+ sourceRef: manifestPlan.asset.objectKey,
767
+ targetRef: source.targetType === "file" ? files[0]?.path ?? "" : "."
768
+ };
769
+ }
770
+ function resolveDefaultAppSource() {
771
+ return getCohubContext().runtime.kind === "sandbox" ? "workspace" : "local";
772
+ }
773
+ function resolveTarget(opts) {
774
+ const targets = [
775
+ opts.file ? {
776
+ targetType: "file",
777
+ targetRef: opts.file
778
+ } : null,
779
+ opts.dir ? {
780
+ targetType: "directory",
781
+ targetRef: opts.dir
782
+ } : null,
783
+ opts.port ? {
784
+ targetType: "port",
785
+ targetRef: opts.port
786
+ } : null
787
+ ].filter((target) => Boolean(target));
788
+ if (targets.length === 0) return null;
789
+ if (targets.length > 1) return error("Conflicting target", "Use only one of --file, --dir, or --port");
790
+ return targets[0] ?? null;
791
+ }
792
+ function resolveStatus(opts) {
793
+ const values = [opts.status, opts.disabled ? "disabled" : void 0].filter(Boolean);
794
+ if (values.length > 1) return error("Conflicting status", "Use only one of --status or --disabled");
795
+ return values[0] ? parseChoice(values[0], "status", APP_STATUSES) : "published";
796
+ }
797
+ /**
798
+ * Fail early when a Space-relative `--file` / `--dir` target cannot be a valid
799
+ * publish source. The publish worker resolves targets inside the target
800
+ * Space's workspace, not on the local filesystem.
801
+ */
802
+ async function guardAppTarget(client, spaceId, target) {
803
+ const failure = await checkAppTarget(client, spaceId, target);
804
+ if (failure) error(failure.status === 404 ? "Publish target not found" : "Publish target is invalid", `${failure.message} (--${target.targetType === "directory" ? "dir" : "file"} takes a Space workspace path, not a local path).`);
805
+ }
806
+ /**
807
+ * Translate the publish worker's bare fs errors (e.g. a target removed between
808
+ * preflight and snapshot) into the same explicit wording as the preflight.
809
+ */
810
+ function translateTargetWorkerError(e) {
811
+ if (!(e instanceof HttpError)) return;
812
+ if (e.code !== "path_not_found" && e.code !== "not_a_directory" && e.code !== "not_a_file" && e.code !== "symlink_not_supported") return;
813
+ error(e.code === "path_not_found" ? "Publish target not found" : "Publish target is invalid", "The publish target is a Space workspace path; the Space workspace no longer contains a valid target at that path.");
814
+ }
815
+ function resolveVisibility(value) {
816
+ return value ? parseChoice(value, "visibility", APP_VISIBILITIES) : void 0;
817
+ }
818
+ function printApp(app) {
819
+ table([app], [
820
+ {
821
+ key: "id",
822
+ label: "ID"
823
+ },
824
+ {
825
+ key: "slug",
826
+ label: "Slug"
827
+ },
828
+ {
829
+ key: "status",
830
+ label: "Status"
831
+ },
832
+ {
833
+ key: "visibility",
834
+ label: "Visibility"
835
+ },
836
+ {
837
+ key: "targetType",
838
+ label: "Target"
839
+ },
840
+ {
841
+ key: "targetRef",
842
+ label: "Ref"
843
+ },
844
+ {
845
+ key: "latestVersion",
846
+ label: "Version"
847
+ },
848
+ {
849
+ key: "publishedAt",
850
+ label: "Published"
851
+ }
852
+ ]);
853
+ }
854
+ function printAppDetails(result) {
855
+ const lines = [
856
+ result.publicUrl ? `Public URL: ${result.publicUrl}` : null,
857
+ result.content?.url ? `Content URL: ${result.content.url}` : null,
858
+ typeof result.likeCount === "number" ? `Likes: ${result.likeCount}` : null
859
+ ].filter((line) => Boolean(line));
860
+ if (lines.length) console.log(`\n${lines.join("\n")}`);
861
+ }
862
+ function promotionUrl(publicUrl, promotion) {
863
+ if (!publicUrl) return null;
864
+ const url = new URL(publicUrl);
865
+ url.searchParams.set("cohub_campaign", promotion.id);
866
+ for (const [key, value] of Object.entries(promotion.parameters)) url.searchParams.set(key, value);
867
+ return url.toString();
868
+ }
869
+ function printAppStats(stats) {
870
+ table([stats.summary], [
871
+ {
872
+ key: "totalViews",
873
+ label: "Total"
874
+ },
875
+ {
876
+ key: "views24h",
877
+ label: "24h"
878
+ },
879
+ {
880
+ key: "views7d",
881
+ label: "7d"
882
+ },
883
+ {
884
+ key: "views30d",
885
+ label: "30d"
886
+ },
887
+ ...stats.summary.totalLikes === void 0 ? [] : [{
888
+ key: "totalLikes",
889
+ label: "Likes"
890
+ }]
891
+ ]);
892
+ if (stats.sources.length) {
893
+ console.log("");
894
+ table(stats.sources, [{
895
+ key: "source",
896
+ label: "Source"
897
+ }, {
898
+ key: "views",
899
+ label: "Views"
900
+ }]);
901
+ }
902
+ }
903
+ async function getAppStatsByRef(client, app) {
904
+ const ref = parseAppRef(app);
905
+ if ("id" in ref) return client.apps.getStats(ref.id);
906
+ const detail = await getAppByRef(client, app);
907
+ return client.apps.getStats(detail.app.id);
908
+ }
909
+ async function confirmDelete(opts) {
910
+ if (opts.yes) return;
911
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return error("Confirmation required", "Pass --yes to delete the app.");
912
+ process.stdout.write("Deleting an app also removes its versions and viewer grants. Continue? [y/N] ");
913
+ const chunks = [];
914
+ for await (const chunk of process.stdin) {
915
+ chunks.push(chunk);
916
+ break;
917
+ }
918
+ const answer = Buffer.concat(chunks).toString().trim().toLowerCase();
919
+ if (answer !== "y" && answer !== "yes") return error("Cancelled");
920
+ }
921
+ async function publishAppVersion(id, opts) {
922
+ const client = createClient();
923
+ try {
924
+ const result = await client.apps.publishVersion(id);
925
+ if (jsonRequested(opts)) return json(result);
926
+ ok(`App version updated: v${result.version.version}`);
927
+ printApp(result.app);
928
+ } catch (e) {
929
+ translateTargetWorkerError(e);
930
+ handleHttp(e);
931
+ }
932
+ }
933
+ function registerApps(program) {
934
+ const appsCmd = program.command("apps").description("App management").alias("works").hook("preAction", () => {
935
+ if (process.argv.slice(2).includes("works")) ok("Deprecated: `cohub works` is now `cohub apps`.");
936
+ });
937
+ appsCmd.command("ls").alias("list").description("List apps in the target space").option("--json", "Output as JSON").action(async (opts) => {
938
+ const spaceId = await resolveSpace(appsCmd, { home: true });
939
+ const client = createClient();
940
+ try {
941
+ const result = await client.apps.listBySpace(spaceId);
942
+ if (jsonRequested(opts)) return json(result);
943
+ table(result.apps, [
944
+ {
945
+ key: "id",
946
+ label: "ID"
947
+ },
948
+ {
949
+ key: "slug",
950
+ label: "Slug"
951
+ },
952
+ {
953
+ key: "status",
954
+ label: "Status"
955
+ },
956
+ {
957
+ key: "visibility",
958
+ label: "Visibility"
959
+ },
960
+ {
961
+ key: "targetType",
962
+ label: "Target"
963
+ },
964
+ {
965
+ key: "targetRef",
966
+ label: "Ref"
967
+ },
968
+ {
969
+ key: "latestVersion",
970
+ label: "Version"
971
+ },
972
+ {
973
+ key: "publishedAt",
974
+ label: "Published"
975
+ }
976
+ ]);
977
+ } catch (e) {
978
+ handleHttp(e);
979
+ }
980
+ });
981
+ appsCmd.command("get <app>").description("Show app details by id, URL, mention URI, or username/space/app").option("--json", "Output as JSON").action(async (app, opts) => {
982
+ const client = createClient();
983
+ try {
984
+ const result = await getAppByRef(client, app);
985
+ if (jsonRequested(opts)) return json(result);
986
+ printApp(result.app);
987
+ printAppDetails(result);
988
+ } catch (e) {
989
+ handleHttp(e);
990
+ }
991
+ });
992
+ appsCmd.command("stats <app>").description("Show view statistics by id, URL, mention URI, or username/space/app").option("--json", "Output as JSON").action(async (app, opts) => {
993
+ const client = createClient();
994
+ try {
995
+ const result = await getAppStatsByRef(client, app);
996
+ if (jsonRequested(opts)) return json(result);
997
+ printAppStats(result);
998
+ } catch (e) {
999
+ handleHttp(e);
1000
+ }
1001
+ });
1002
+ for (const liked of [true, false]) appsCmd.command(`${liked ? "like" : "unlike"} <app>`).description(`${liked ? "Like" : "Unlike"} an app by id, URL, mention URI, or username/space/app`).option("--json", "Output as JSON").action(async (app, opts) => {
1003
+ const client = createClient();
1004
+ try {
1005
+ const ref = parseAppRef(app);
1006
+ const appId = "id" in ref ? ref.id : (await getAppByRef(client, app)).app.id;
1007
+ const result = {
1008
+ appId,
1009
+ liked: await client.user.likes.set("app", appId, liked)
1010
+ };
1011
+ if (jsonRequested(opts)) return json(result);
1012
+ ok(result.liked ? "Liked" : "Unliked");
1013
+ } catch (e) {
1014
+ handleHttp(e);
1015
+ }
1016
+ });
1017
+ appsCmd.command("download <app>").description("Download a published file or directory app").option("-o, --output <path>", "Output file or directory").option("--json", "Output as JSON").action(async (app, opts) => {
1018
+ const client = createClient();
1019
+ try {
1020
+ const result = await downloadApp(await getAppByRef(client, app), opts.output);
1021
+ if (jsonRequested(opts)) return json(result);
1022
+ ok(`Downloaded ${result.files} file${result.files === 1 ? "" : "s"} to ${result.output}`);
1023
+ } catch (e) {
1024
+ handleHttp(e);
1025
+ }
1026
+ });
1027
+ appsCmd.command("actions").description("Run published App Actions").command("run <app> <action>").description("Run an App Action").option("--input <json>", "JSON input", "null").option("--json", "Output as JSON").action(async (appRef, action, opts) => {
1028
+ const client = createClient();
1029
+ try {
1030
+ const ref = parseAppRef(appRef);
1031
+ const detail = "id" in ref ? await client.apps.getPublicById(ref.id) : await client.apps.getBySlug(ref.username, ref.spaceSlug, ref.appSlug);
1032
+ const session = await client.apps.createSession(detail.app.id);
1033
+ const result = await createClientWithAccessToken(session.token).apps.runAction(detail.app.id, action, parseJsonValue(opts.input, "input"));
1034
+ if (jsonRequested(opts)) return json(result);
1035
+ ok(`App Action queued: ${result.taskRunId}`);
1036
+ } catch (e) {
1037
+ handleHttp(e);
1038
+ }
1039
+ });
1040
+ appsCmd.command("resolve <appSlug>").description("Resolve a published app by owner and space slug").option("--owner <username>", "Owner username").option("--space-slug <slug>", "Space slug").option("--json", "Output as JSON").action(async (appSlug, opts) => {
1041
+ if (!opts.owner?.trim()) return error("Missing owner username", "Pass --owner <username>.");
1042
+ if (!opts.spaceSlug?.trim()) return error("Missing space slug", "Pass --space-slug <slug>.");
1043
+ const client = createClient();
1044
+ try {
1045
+ const result = await client.apps.getBySlug(opts.owner.trim(), opts.spaceSlug.trim(), appSlug);
1046
+ if (jsonRequested(opts)) return json(result);
1047
+ printApp(result.app);
1048
+ printAppDetails(result);
1049
+ } catch (e) {
1050
+ handleHttp(e);
1051
+ }
1052
+ });
1053
+ appsCmd.command("publish <slug>").description("Create or publish an app in the target space").option("--source <source>", "Source: workspace or local (auto-detected from runtime by default)").option("--file <path>", "Publish a file from the selected source").option("--dir <path>", "Publish a directory site from the selected source").option("--port <port>", "Publish a public sandbox port").option("--disabled", "Create as disabled").option("--status <status>", "App status: published, disabled").option("--visibility <visibility>", "App visibility: public, space").option("--app-scope <scope>", "Scope granted directly to the app runtime (space.view, session.view, file.view, file.edit, taskrun.view, session.prompt.readonly, session.prompt.fullaccess, command.execute)", collectOption, []).option("--viewer-scope <scope>", "Deprecated: viewer grants are no longer gated by the app configuration", collectOption, []).option("--meta <json>", "App metadata as a JSON object").option("--hide-cohub-bar", "Hide the Cohub footer bar on the public app page").option("--show-cohub-bar", "Show the Cohub footer bar on the public app page").option("--json", "Output as JSON").action(async (slug, opts) => {
1054
+ if (opts.hideCohubBar && opts.showCohubBar) return error("Conflicting Cohub bar options", "Use either --hide-cohub-bar or --show-cohub-bar.");
1055
+ const target = resolveTarget(opts);
1056
+ if (!target) return error("Missing target", "Use one of --file, --dir, or --port.");
1057
+ const source = opts.source ? parseChoice(opts.source, "source", ["workspace", "local"]) : resolveDefaultAppSource();
1058
+ if (target.targetType === "port" && opts.source) return error("Invalid source", "--source applies only to --file and --dir.");
1059
+ const spaceId = await resolveSpace(appsCmd, { home: true });
1060
+ const client = createClient();
1061
+ let { targetType, targetRef } = target;
1062
+ let sourceRef = null;
1063
+ if (source === "local") {
1064
+ const uploaded = await uploadLocalAppSource(client, spaceId, target);
1065
+ if (!uploaded) return error("Invalid source", "--source local applies only to --file and --dir.");
1066
+ targetRef = uploaded.targetRef;
1067
+ sourceRef = uploaded.sourceRef;
1068
+ } else if (targetType !== "port") await guardAppTarget(client, spaceId, {
1069
+ targetType,
1070
+ targetRef
1071
+ });
1072
+ const status = resolveStatus(opts);
1073
+ const meta = withCohubBarMeta({
1074
+ meta: parseJsonObject(opts.meta, "meta"),
1075
+ hideCohubBar: opts.hideCohubBar,
1076
+ showCohubBar: opts.showCohubBar
1077
+ });
1078
+ const publishMeta = source === "local" ? {
1079
+ ...meta ?? {},
1080
+ runtime: { source: {
1081
+ type: "upload",
1082
+ ref: sourceRef
1083
+ } }
1084
+ } : meta;
1085
+ const input = {
1086
+ spaceId,
1087
+ slug,
1088
+ status,
1089
+ visibility: resolveVisibility(opts.visibility),
1090
+ targetType: target.targetType,
1091
+ targetRef,
1092
+ appScopes: opts.appScope,
1093
+ allowedViewerScopes: opts.viewerScope,
1094
+ meta: publishMeta
1095
+ };
1096
+ try {
1097
+ const result = await client.apps.create(input);
1098
+ if (jsonRequested(opts)) return json(result);
1099
+ ok(`App published: ${result.app.id}`);
1100
+ printApp(result.app);
1101
+ } catch (e) {
1102
+ translateTargetWorkerError(e);
1103
+ if (!(e instanceof HttpError) || e.status !== 409) handleHttp(e);
1104
+ try {
1105
+ const { apps } = await client.apps.listBySpace(spaceId);
1106
+ const existingApp = apps.find((app) => app.slug === slug);
1107
+ if (!existingApp) return handleHttp(e);
1108
+ const { app } = await client.apps.update(existingApp.id, {
1109
+ status: status === "published" && existingApp.status !== "published" ? existingApp.status : status,
1110
+ visibility: resolveVisibility(opts.visibility),
1111
+ targetType: target.targetType,
1112
+ targetRef,
1113
+ appScopes: opts.appScope,
1114
+ allowedViewerScopes: opts.viewerScope,
1115
+ meta: publishMeta
1116
+ });
1117
+ const publishedVersion = status === "published" ? await client.apps.publishVersion(app.id) : null;
1118
+ const result = publishedVersion ?? { app };
1119
+ if (jsonRequested(opts)) return json(result);
1120
+ ok(status === "published" && publishedVersion ? `App version updated: v${publishedVersion.version.version}` : `App updated: ${app.id}`);
1121
+ printApp(result.app);
1122
+ } catch (fallbackError) {
1123
+ translateTargetWorkerError(fallbackError);
1124
+ handleHttp(fallbackError);
1125
+ }
1126
+ }
1127
+ });
1128
+ appsCmd.command("update <id>").description("Update app settings").option("--slug <slug>", "New app slug").option("--file <path>", "Use a file target (HTML page, board, or any other file) from the Space workspace").option("--dir <path>", "Use a directory site target from the Space workspace").option("--port <port>", "Use a public sandbox port target").option("--disabled", "Set status to disabled").option("--status <status>", "App status: published, disabled").option("--visibility <visibility>", "App visibility: public, space").option("--app-scope <scope>", "Scope granted directly to the app runtime (space.view, session.view, file.view, file.edit, taskrun.view, session.prompt.readonly, session.prompt.fullaccess, command.execute)", collectOption, []).option("--viewer-scope <scope>", "Deprecated: viewer grants are no longer gated by the app configuration", collectOption, []).option("--clear-app-scopes", "Clear app runtime scopes").option("--clear-viewer-scopes", "Deprecated: clear legacy scope metadata").option("--meta <json>", "App metadata as a JSON object").option("--hide-cohub-bar", "Hide the Cohub footer bar on the public app page").option("--show-cohub-bar", "Show the Cohub footer bar on the public app page").option("--json", "Output as JSON").action(async (id, opts) => {
1129
+ if (opts.hideCohubBar && opts.showCohubBar) return error("Conflicting Cohub bar options", "Use either --hide-cohub-bar or --show-cohub-bar.");
1130
+ const target = resolveTarget(opts);
1131
+ if (opts.clearAppScopes && opts.appScope?.length) return error("Conflicting app scopes", "Use either --app-scope or --clear-app-scopes.");
1132
+ if (opts.clearViewerScopes && opts.viewerScope?.length) return error("Conflicting viewer scopes", "Use either --viewer-scope or --clear-viewer-scopes.");
1133
+ const hasMetaUpdate = opts.meta !== void 0 || opts.hideCohubBar || opts.showCohubBar;
1134
+ const client = createClient();
1135
+ if (target) try {
1136
+ const current = await client.apps.get(id);
1137
+ const { targetType, targetRef } = target;
1138
+ if (targetType !== "port") await guardAppTarget(client, current.app.spaceId, {
1139
+ targetType,
1140
+ targetRef
1141
+ });
1142
+ } catch {}
1143
+ let meta;
1144
+ if (hasMetaUpdate) {
1145
+ let baseMeta = opts.meta !== void 0 ? parseJsonObject(opts.meta, "meta") ?? null : void 0;
1146
+ if (baseMeta === void 0 && (opts.hideCohubBar || opts.showCohubBar)) try {
1147
+ baseMeta = (await client.apps.get(id)).app.meta;
1148
+ } catch (e) {
1149
+ handleHttp(e);
1150
+ }
1151
+ meta = withCohubBarMeta({
1152
+ meta: baseMeta,
1153
+ hideCohubBar: opts.hideCohubBar,
1154
+ showCohubBar: opts.showCohubBar
1155
+ });
1156
+ }
1157
+ const nextStatus = opts.status || opts.disabled ? resolveStatus(opts) : void 0;
1158
+ const currentApp = nextStatus === "published" ? (await client.apps.get(id)).app : null;
1159
+ const input = compactObject({
1160
+ slug: opts.slug,
1161
+ status: nextStatus === "published" && currentApp?.status !== "published" ? currentApp?.status : nextStatus,
1162
+ visibility: resolveVisibility(opts.visibility),
1163
+ targetType: target?.targetType,
1164
+ targetRef: target?.targetRef,
1165
+ appScopes: opts.clearAppScopes ? [] : opts.appScope?.length ? opts.appScope : void 0,
1166
+ allowedViewerScopes: opts.clearViewerScopes ? [] : opts.viewerScope?.length ? opts.viewerScope : void 0,
1167
+ meta
1168
+ });
1169
+ if (Object.keys(input).length === 0) return error("Nothing to update", "Pass --slug, --file, --dir, --port, --status, --visibility, --app-scope, --viewer-scope, --clear-app-scopes, --clear-viewer-scopes, --meta, --hide-cohub-bar, or --show-cohub-bar.");
1170
+ try {
1171
+ const updated = await client.apps.update(id, input);
1172
+ const publishedVersion = nextStatus === "published" && currentApp?.status !== "published" ? await client.apps.publishVersion(updated.app.id) : null;
1173
+ const result = publishedVersion ?? { app: updated.app };
1174
+ if (jsonRequested(opts)) return json(result);
1175
+ ok(publishedVersion ? `App published: v${publishedVersion.version.version}` : "App updated");
1176
+ printApp(result.app);
1177
+ } catch (e) {
1178
+ translateTargetWorkerError(e);
1179
+ handleHttp(e);
1180
+ }
1181
+ });
1182
+ appsCmd.command("publish-version <id>").description("Publish or update the current app version").option("--json", "Output as JSON").action(publishAppVersion);
1183
+ appsCmd.command("release <id>", { hidden: true }).description("Deprecated alias for publish-version").option("--json", "Output as JSON").action(publishAppVersion);
1184
+ appsCmd.command("versions <id>").description("List app versions").option("--json", "Output as JSON").action(async (id, opts) => {
1185
+ const client = createClient();
1186
+ try {
1187
+ const result = await client.apps.listVersions(id);
1188
+ if (jsonRequested(opts)) return json(result);
1189
+ table(result.versions, [
1190
+ {
1191
+ key: "version",
1192
+ label: "Version"
1193
+ },
1194
+ {
1195
+ key: "id",
1196
+ label: "ID"
1197
+ },
1198
+ {
1199
+ key: "targetType",
1200
+ label: "Target"
1201
+ },
1202
+ {
1203
+ key: "targetRef",
1204
+ label: "Ref"
1205
+ },
1206
+ {
1207
+ key: "source",
1208
+ label: "Source",
1209
+ format: formatVersionSource
1210
+ },
1211
+ {
1212
+ key: "createdAt",
1213
+ label: "Created"
1214
+ }
1215
+ ]);
1216
+ } catch (e) {
1217
+ handleHttp(e);
1218
+ }
1219
+ });
1220
+ const promotionsCmd = appsCmd.command("promotions").description("App promotion links and analytics");
1221
+ promotionsCmd.command("list <app>").alias("ls").description("List promotion links").option("--json", "Output as JSON").action(async (appRef, opts) => {
1222
+ const client = createClient();
1223
+ try {
1224
+ const detail = await getAppByRef(client, appRef);
1225
+ const result = await client.apps.listPromotions(detail.app.id);
1226
+ const promotions = result.promotions.map((promotion) => ({
1227
+ ...promotion,
1228
+ url: promotionUrl(detail.publicUrl, promotion)
1229
+ }));
1230
+ if (jsonRequested(opts)) return json({
1231
+ ...result,
1232
+ promotions
1233
+ });
1234
+ table(promotions, [
1235
+ {
1236
+ key: "name",
1237
+ label: "Name"
1238
+ },
1239
+ {
1240
+ key: "provider",
1241
+ label: "Provider"
1242
+ },
1243
+ {
1244
+ key: "id",
1245
+ label: "ID"
1246
+ },
1247
+ {
1248
+ key: "url",
1249
+ label: "URL"
1250
+ }
1251
+ ]);
1252
+ } catch (e) {
1253
+ handleHttp(e);
1254
+ }
1255
+ });
1256
+ promotionsCmd.command("create <app>").description("Create an immutable promotion link").requiredOption("--name <name>", "Promotion name").option("--provider <provider>", "Promotion provider", "generic").option("--utm-id <value>", "UTM campaign ID").option("--utm-source <value>", "UTM source").option("--utm-medium <value>", "UTM medium").option("--utm-campaign <value>", "UTM campaign").option("--utm-term <value>", "UTM term").option("--utm-content <value>", "UTM content").option("--json", "Output as JSON").action(async (appRef, opts) => {
1257
+ const client = createClient();
1258
+ try {
1259
+ const detail = await getAppByRef(client, appRef);
1260
+ const parameters = Object.fromEntries(Object.entries({
1261
+ utm_id: opts.utmId,
1262
+ utm_source: opts.utmSource,
1263
+ utm_medium: opts.utmMedium,
1264
+ utm_campaign: opts.utmCampaign,
1265
+ utm_term: opts.utmTerm,
1266
+ utm_content: opts.utmContent
1267
+ }).filter((entry) => typeof entry[1] === "string"));
1268
+ const result = await client.apps.createPromotion(detail.app.id, {
1269
+ name: opts.name,
1270
+ provider: opts.provider,
1271
+ parameters
1272
+ });
1273
+ const url = promotionUrl(detail.publicUrl, result.promotion);
1274
+ if (jsonRequested(opts)) return json({
1275
+ ...result,
1276
+ url
1277
+ });
1278
+ ok("Promotion created");
1279
+ table([{
1280
+ ...result.promotion,
1281
+ url
1282
+ }], [
1283
+ {
1284
+ key: "name",
1285
+ label: "Name"
1286
+ },
1287
+ {
1288
+ key: "provider",
1289
+ label: "Provider"
1290
+ },
1291
+ {
1292
+ key: "id",
1293
+ label: "ID"
1294
+ },
1295
+ {
1296
+ key: "url",
1297
+ label: "URL"
1298
+ }
1299
+ ]);
1300
+ } catch (e) {
1301
+ handleHttp(e);
1302
+ }
1303
+ });
1304
+ promotionsCmd.command("stats <app> <promotionId>").description("Show promotion analytics").option("--json", "Output as JSON").action(async (appRef, promotionId, opts) => {
1305
+ const client = createClient();
1306
+ try {
1307
+ const detail = await getAppByRef(client, appRef);
1308
+ const result = await client.apps.getPromotionStats(detail.app.id, promotionId);
1309
+ if (jsonRequested(opts)) return json(result);
1310
+ table([{
1311
+ name: result.promotion.name,
1312
+ landing: result.summary.landing,
1313
+ ready: result.summary.ready,
1314
+ registered: result.summary.registrationCompleted,
1315
+ paywall: result.summary.paywallViewed,
1316
+ checkout: result.summary.checkoutStarted,
1317
+ readyRate: `${(result.summary.readyRate * 100).toFixed(1)}%`
1318
+ }], [
1319
+ {
1320
+ key: "name",
1321
+ label: "Name"
1322
+ },
1323
+ {
1324
+ key: "landing",
1325
+ label: "Landing"
1326
+ },
1327
+ {
1328
+ key: "ready",
1329
+ label: "Ready"
1330
+ },
1331
+ {
1332
+ key: "registered",
1333
+ label: "Registered"
1334
+ },
1335
+ {
1336
+ key: "paywall",
1337
+ label: "Paywall"
1338
+ },
1339
+ {
1340
+ key: "checkout",
1341
+ label: "Checkout"
1342
+ },
1343
+ {
1344
+ key: "readyRate",
1345
+ label: "Ready rate"
1346
+ }
1347
+ ]);
1348
+ } catch (e) {
1349
+ handleHttp(e);
1350
+ }
1351
+ });
1352
+ registerAppCommerce(appsCmd);
1353
+ registerAppDomains(appsCmd);
1354
+ appsCmd.command("authorize <app>").description("Grant an app scopes as the current user").requiredOption("--scope <scope>", "Scope to grant (repeatable)", collectOption, []).option("--space <spaceId>", "Target space; defaults to the app's own space").option("--extend", "Add scopes without replacing active grants").option("--json", "Output as JSON").action(async (appRef, opts) => {
1355
+ const client = createClient();
1356
+ try {
1357
+ const detail = await getAppByRef(client, appRef);
1358
+ const result = await client.apps.authorize(detail.app.id, {
1359
+ scopes: opts.scope,
1360
+ ...opts.space ? { spaceId: opts.space } : {},
1361
+ ...opts.extend ? { scopeMode: "extend" } : {}
1362
+ });
1363
+ if (jsonRequested(opts)) return json(result);
1364
+ ok(`Granted ${result.grant.scopes.join(", ")} on space ${result.grant.spaceId}`);
1365
+ } catch (e) {
1366
+ handleHttp(e);
1367
+ }
1368
+ });
1369
+ appsCmd.command("grants <app>").description("List your grants for an app").option("--json", "Output as JSON").action(async (appRef, opts) => {
1370
+ const client = createClient();
1371
+ try {
1372
+ const detail = await getAppByRef(client, appRef);
1373
+ const result = await client.apps.listMyGrants(detail.app.id);
1374
+ if (jsonRequested(opts)) return json(result);
1375
+ table(result.grants, [
1376
+ {
1377
+ key: "id",
1378
+ label: "ID"
1379
+ },
1380
+ {
1381
+ key: "spaceId",
1382
+ label: "Space"
1383
+ },
1384
+ {
1385
+ key: "scopes",
1386
+ label: "Scopes"
1387
+ },
1388
+ {
1389
+ key: "expiresAt",
1390
+ label: "Expires"
1391
+ },
1392
+ {
1393
+ key: "revokedAt",
1394
+ label: "Revoked"
1395
+ }
1396
+ ]);
1397
+ } catch (e) {
1398
+ handleHttp(e);
1399
+ }
1400
+ });
1401
+ appsCmd.command("revoke <app> <grantId>").description("Revoke one of your grants for an app").action(async (appRef, grantId) => {
1402
+ const client = createClient();
1403
+ try {
1404
+ const detail = await getAppByRef(client, appRef);
1405
+ await client.apps.revokeMyGrant(detail.app.id, grantId);
1406
+ ok("Grant revoked");
1407
+ } catch (e) {
1408
+ handleHttp(e);
1409
+ }
1410
+ });
1411
+ appsCmd.command("rm <id>").alias("delete").description("Delete an app").option("-y, --yes", "Confirm deletion").action(async (id, opts) => {
1412
+ await confirmDelete(opts);
1413
+ const client = createClient();
1414
+ try {
1415
+ await client.apps.delete(id);
1416
+ ok("App deleted");
1417
+ } catch (e) {
1418
+ handleHttp(e);
1419
+ }
1420
+ });
1421
+ }
1422
+ //#endregion
1423
+ export { registerApps };