allyhub 0.11.0 → 0.13.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 (391) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/bin/allyhub.js +2 -2
  3. package/dist/commands/frames/report.js +1 -1
  4. package/dist/commands/frames.js +11 -11
  5. package/dist/main.js +6 -6
  6. package/dist/node_modules/@allyhub/3d-extension/package.json +1 -1
  7. package/dist/node_modules/@allyhub/audio/dist/render.js +1 -1
  8. package/dist/node_modules/@allyhub/audio/package.json +1 -1
  9. package/dist/node_modules/@allyhub/browser/package.json +1 -1
  10. package/dist/node_modules/@allyhub/build/dist/media.js +1 -1
  11. package/dist/node_modules/@allyhub/build/package.json +1 -1
  12. package/dist/node_modules/@allyhub/canvas-extension/package.json +1 -1
  13. package/dist/node_modules/@allyhub/canvas-model/package.json +1 -1
  14. package/dist/node_modules/@allyhub/chart/dist/chart-file.js +1 -1
  15. package/dist/node_modules/@allyhub/chart/dist/chart-xml.js +3 -2
  16. package/dist/node_modules/@allyhub/chart/dist/chart.js +2 -1
  17. package/dist/node_modules/@allyhub/chart/dist/color.js +2 -0
  18. package/dist/node_modules/@allyhub/chart/dist/index.js +1 -1
  19. package/dist/node_modules/@allyhub/chart/dist/svg.js +1 -1
  20. package/dist/node_modules/@allyhub/chart/package.json +1 -1
  21. package/dist/node_modules/@allyhub/check/package.json +1 -1
  22. package/dist/node_modules/@allyhub/cloud/dist/call.js +4 -4
  23. package/dist/node_modules/@allyhub/cloud/dist/client.d.ts +2 -0
  24. package/dist/node_modules/@allyhub/cloud/dist/client.js +1 -1
  25. package/dist/node_modules/@allyhub/cloud/dist/config.d.ts +6 -0
  26. package/dist/node_modules/@allyhub/cloud/dist/config.js +1 -1
  27. package/dist/node_modules/@allyhub/cloud/dist/credentials.js +2 -2
  28. package/dist/node_modules/@allyhub/cloud/dist/device.d.ts +2 -0
  29. package/dist/node_modules/@allyhub/cloud/dist/device.js +1 -1
  30. package/dist/node_modules/@allyhub/cloud/dist/records.d.ts +1 -1
  31. package/dist/node_modules/@allyhub/cloud/dist/signin.d.ts +11 -3
  32. package/dist/node_modules/@allyhub/cloud/dist/signin.js +2 -2
  33. package/dist/node_modules/@allyhub/cloud/dist/uploads.d.ts +1 -1
  34. package/dist/node_modules/@allyhub/cloud/dist/uploads.js +2 -2
  35. package/dist/node_modules/@allyhub/cloud/package.json +1 -1
  36. package/dist/node_modules/@allyhub/components/package.json +1 -1
  37. package/dist/node_modules/@allyhub/dev-server/dist/live.js +1 -1
  38. package/dist/node_modules/@allyhub/dev-server/dist/server.js +1 -1
  39. package/dist/node_modules/@allyhub/dev-server/package.json +1 -1
  40. package/dist/node_modules/@allyhub/diagnostics/package.json +1 -1
  41. package/dist/node_modules/@allyhub/doc/package.json +1 -1
  42. package/dist/node_modules/@allyhub/doc-extension/package.json +1 -1
  43. package/dist/node_modules/@allyhub/doc-print/package.json +1 -1
  44. package/dist/node_modules/@allyhub/export/package.json +1 -1
  45. package/dist/node_modules/@allyhub/extension-api/package.json +1 -1
  46. package/dist/node_modules/@allyhub/extension-host/package.json +1 -1
  47. package/dist/node_modules/@allyhub/formats/dist/data/deck-code.d.ts +130 -0
  48. package/dist/node_modules/@allyhub/formats/dist/data/deck-code.js +1 -1
  49. package/dist/node_modules/@allyhub/formats/dist/data/gen.d.ts +3 -1
  50. package/dist/node_modules/@allyhub/formats/dist/data/gen.js +1 -1
  51. package/dist/node_modules/@allyhub/formats/dist/data/sheet.d.ts +512 -166
  52. package/dist/node_modules/@allyhub/formats/dist/data/sheet.js +1 -1
  53. package/dist/node_modules/@allyhub/formats/dist/data/slides.d.ts +2523 -136
  54. package/dist/node_modules/@allyhub/formats/dist/data/slides.js +1 -1
  55. package/dist/node_modules/@allyhub/formats/dist/schemas.d.ts +931 -87
  56. package/dist/node_modules/@allyhub/formats/dist/schemas.js +1 -1
  57. package/dist/node_modules/@allyhub/formats/package.json +1 -1
  58. package/dist/node_modules/@allyhub/i18n/package.json +1 -1
  59. package/dist/node_modules/@allyhub/image-draw/package.json +1 -1
  60. package/dist/node_modules/@allyhub/image-extension/package.json +1 -1
  61. package/dist/node_modules/@allyhub/image-measure/package.json +1 -1
  62. package/dist/node_modules/@allyhub/image-psd/package.json +1 -1
  63. package/dist/node_modules/@allyhub/image-render/package.json +1 -1
  64. package/dist/node_modules/@allyhub/image-runtime/package.json +1 -1
  65. package/dist/node_modules/@allyhub/image-sdk/package.json +1 -1
  66. package/dist/node_modules/@allyhub/jobs/package.json +1 -1
  67. package/dist/node_modules/@allyhub/linkedin-extension/package.json +1 -1
  68. package/dist/node_modules/@allyhub/linkedin-model/package.json +1 -1
  69. package/dist/node_modules/@allyhub/linkedin-view/package.json +1 -1
  70. package/dist/node_modules/@allyhub/measure/package.json +1 -1
  71. package/dist/node_modules/@allyhub/media/dist/run.d.ts +6 -1
  72. package/dist/node_modules/@allyhub/media/dist/run.js +2 -2
  73. package/dist/node_modules/@allyhub/media/package.json +1 -1
  74. package/dist/node_modules/@allyhub/media-extension/package.json +1 -1
  75. package/dist/node_modules/@allyhub/model/package.json +1 -1
  76. package/dist/node_modules/@allyhub/ooxml/dist/color.js +1 -1
  77. package/dist/node_modules/@allyhub/ooxml/dist/ext.js +1 -1
  78. package/dist/node_modules/@allyhub/ooxml/dist/index.js +1 -1
  79. package/dist/node_modules/@allyhub/ooxml/dist/transform.js +2 -0
  80. package/dist/node_modules/@allyhub/ooxml/package.json +5 -1
  81. package/dist/node_modules/@allyhub/piece/dist/gen.d.ts +4 -4
  82. package/dist/node_modules/@allyhub/piece/dist/media.d.ts +2 -2
  83. package/dist/node_modules/@allyhub/piece/package.json +1 -1
  84. package/dist/node_modules/@allyhub/project/dist/part-keys.js +1 -1
  85. package/dist/node_modules/@allyhub/project/package.json +1 -1
  86. package/dist/node_modules/@allyhub/protocol/dist/account.d.ts +49 -5
  87. package/dist/node_modules/@allyhub/protocol/dist/account.js +1 -1
  88. package/dist/node_modules/@allyhub/protocol/dist/auth.d.ts +56 -0
  89. package/dist/node_modules/@allyhub/protocol/dist/auth.js +1 -1
  90. package/dist/node_modules/@allyhub/protocol/dist/cloud.d.ts +72 -9
  91. package/dist/node_modules/@allyhub/protocol/dist/cloud.js +1 -1
  92. package/dist/node_modules/@allyhub/protocol/dist/editor.d.ts +35 -20
  93. package/dist/node_modules/@allyhub/protocol/dist/editor.js +1 -1
  94. package/dist/node_modules/@allyhub/protocol/dist/errors.d.ts +7 -0
  95. package/dist/node_modules/@allyhub/protocol/dist/errors.js +2 -0
  96. package/dist/node_modules/@allyhub/protocol/dist/events.d.ts +328 -0
  97. package/dist/node_modules/@allyhub/protocol/dist/events.js +2 -0
  98. package/dist/node_modules/@allyhub/protocol/dist/frame.d.ts +28 -2
  99. package/dist/node_modules/@allyhub/protocol/dist/frame.js +1 -1
  100. package/dist/node_modules/@allyhub/protocol/dist/index.d.ts +2 -0
  101. package/dist/node_modules/@allyhub/protocol/dist/index.js +1 -1
  102. package/dist/node_modules/@allyhub/protocol/dist/jobs.d.ts +6 -6
  103. package/dist/node_modules/@allyhub/protocol/dist/mail.d.ts +2 -2
  104. package/dist/node_modules/@allyhub/protocol/dist/routes.js +1 -1
  105. package/dist/node_modules/@allyhub/protocol/dist/snapshots.d.ts +69 -6
  106. package/dist/node_modules/@allyhub/protocol/dist/snapshots.js +1 -1
  107. package/dist/node_modules/@allyhub/protocol/dist/tools.d.ts +9 -9
  108. package/dist/node_modules/@allyhub/protocol/package.json +1 -1
  109. package/dist/node_modules/@allyhub/registry/package.json +1 -1
  110. package/dist/node_modules/@allyhub/render/package.json +1 -1
  111. package/dist/node_modules/@allyhub/report-extension/dist/cli/find.js +1 -1
  112. package/dist/node_modules/@allyhub/report-extension/dist/cli/index.js +3 -3
  113. package/dist/node_modules/@allyhub/report-extension/dist/cli/picture.js +29 -1
  114. package/dist/node_modules/@allyhub/report-extension/package.json +1 -1
  115. package/dist/node_modules/@allyhub/report-extension/styles/allyhub/STYLE.md +11 -4
  116. package/dist/node_modules/@allyhub/report-extension/styles/allyhub/style.css +6 -2
  117. package/dist/node_modules/@allyhub/report-extension/styles/allyhub/style.json +1 -1
  118. package/dist/node_modules/@allyhub/report-extension/styles/allyhub/tokens.js +3 -1
  119. package/dist/node_modules/@allyhub/runtime/package.json +1 -1
  120. package/dist/node_modules/@allyhub/runtimes/package.json +1 -1
  121. package/dist/node_modules/@allyhub/scaffold/package.json +1 -1
  122. package/dist/node_modules/@allyhub/scenery/package.json +1 -1
  123. package/dist/node_modules/@allyhub/scenery-host/package.json +1 -1
  124. package/dist/node_modules/@allyhub/sheet/dist/annotations.js +2 -0
  125. package/dist/node_modules/@allyhub/sheet/dist/api/capabilities.js +1 -1
  126. package/dist/node_modules/@allyhub/sheet/dist/api/index.js +1 -1
  127. package/dist/node_modules/@allyhub/sheet/dist/api/rules.js +1 -1
  128. package/dist/node_modules/@allyhub/sheet/dist/api/styles.js +1 -1
  129. package/dist/node_modules/@allyhub/sheet/dist/api/workbook.js +1 -1
  130. package/dist/node_modules/@allyhub/sheet/dist/arrange.js +1 -1
  131. package/dist/node_modules/@allyhub/sheet/dist/data-tools.js +2 -0
  132. package/dist/node_modules/@allyhub/sheet/dist/edit.js +1 -1
  133. package/dist/node_modules/@allyhub/sheet/dist/fill.js +1 -1
  134. package/dist/node_modules/@allyhub/sheet/dist/filter.js +1 -1
  135. package/dist/node_modules/@allyhub/sheet/dist/formula/rewrite.js +1 -1
  136. package/dist/node_modules/@allyhub/sheet/dist/html.js +10 -10
  137. package/dist/node_modules/@allyhub/sheet/dist/index.js +1 -1
  138. package/dist/node_modules/@allyhub/sheet/dist/outline.js +2 -0
  139. package/dist/node_modules/@allyhub/sheet/dist/rich.js +2 -0
  140. package/dist/node_modules/@allyhub/sheet/dist/rules.js +1 -1
  141. package/dist/node_modules/@allyhub/sheet/dist/table-style.js +1 -1
  142. package/dist/node_modules/@allyhub/sheet/dist/table-styles.js +1 -1
  143. package/dist/node_modules/@allyhub/sheet/dist/workbook.js +1 -1
  144. package/dist/node_modules/@allyhub/sheet/dist/xlsx/charts.js +1 -1
  145. package/dist/node_modules/@allyhub/sheet/dist/xlsx/import.js +1 -1
  146. package/dist/node_modules/@allyhub/sheet/dist/xlsx/read.js +2 -2
  147. package/dist/node_modules/@allyhub/sheet/dist/xlsx/runs.js +2 -0
  148. package/dist/node_modules/@allyhub/sheet/dist/xlsx/styles.js +1 -1
  149. package/dist/node_modules/@allyhub/sheet/dist/xlsx/write.js +1 -1
  150. package/dist/node_modules/@allyhub/sheet/package.json +1 -1
  151. package/dist/node_modules/@allyhub/sheet-extension/package.json +1 -1
  152. package/dist/node_modules/@allyhub/slides-core/dist/animation.js +1 -1
  153. package/dist/node_modules/@allyhub/slides-core/dist/api.js +3 -3
  154. package/dist/node_modules/@allyhub/slides-core/dist/capabilities.js +1 -1
  155. package/dist/node_modules/@allyhub/slides-core/dist/chart-api.js +1 -1
  156. package/dist/node_modules/@allyhub/slides-core/dist/check.js +1 -1
  157. package/dist/node_modules/@allyhub/slides-core/dist/enums.js +1 -1
  158. package/dist/node_modules/@allyhub/slides-core/dist/file.js +3 -3
  159. package/dist/node_modules/@allyhub/slides-core/dist/generated/table-styles.js +2 -0
  160. package/dist/node_modules/@allyhub/slides-core/dist/index.js +1 -1
  161. package/dist/node_modules/@allyhub/slides-core/dist/merge.js +1 -1
  162. package/dist/node_modules/@allyhub/slides-core/dist/numbering.js +2 -0
  163. package/dist/node_modules/@allyhub/slides-core/dist/office.js +1 -1
  164. package/dist/node_modules/@allyhub/slides-core/dist/patterns.js +2 -0
  165. package/dist/node_modules/@allyhub/slides-core/dist/resolve.js +1 -1
  166. package/dist/node_modules/@allyhub/slides-core/dist/script.js +2 -2
  167. package/dist/node_modules/@allyhub/slides-core/dist/sdk.js +1 -1
  168. package/dist/node_modules/@allyhub/slides-core/dist/table-style.js +2 -0
  169. package/dist/node_modules/@allyhub/slides-core/package.json +1 -1
  170. package/dist/node_modules/@allyhub/slides-extension/dist/deck-pptx.js +1 -1
  171. package/dist/node_modules/@allyhub/slides-extension/dist/workspace.js +1 -1
  172. package/dist/node_modules/@allyhub/slides-extension/package.json +1 -1
  173. package/dist/node_modules/@allyhub/slides-pptx/dist/audio-icon.js +2 -0
  174. package/dist/node_modules/@allyhub/slides-pptx/dist/import/code.js +3 -3
  175. package/dist/node_modules/@allyhub/slides-pptx/dist/import/index.js +2 -2
  176. package/dist/node_modules/@allyhub/slides-pptx/dist/import/script.js +1 -1
  177. package/dist/node_modules/@allyhub/slides-pptx/dist/read/chart.js +2 -1
  178. package/dist/node_modules/@allyhub/slides-pptx/dist/read/common.js +1 -1
  179. package/dist/node_modules/@allyhub/slides-pptx/dist/read/index.js +2 -2
  180. package/dist/node_modules/@allyhub/slides-pptx/dist/read/shapes.js +1 -1
  181. package/dist/node_modules/@allyhub/slides-pptx/dist/read/table.js +1 -1
  182. package/dist/node_modules/@allyhub/slides-pptx/dist/read/text.js +1 -1
  183. package/dist/node_modules/@allyhub/slides-pptx/dist/read/timing.js +1 -1
  184. package/dist/node_modules/@allyhub/slides-pptx/dist/shapes.js +1 -1
  185. package/dist/node_modules/@allyhub/slides-pptx/dist/table-styles.js +2 -0
  186. package/dist/node_modules/@allyhub/slides-pptx/dist/text.js +1 -1
  187. package/dist/node_modules/@allyhub/slides-pptx/dist/theme.js +1 -1
  188. package/dist/node_modules/@allyhub/slides-pptx/dist/timing.js +1 -1
  189. package/dist/node_modules/@allyhub/slides-pptx/dist/write.js +2 -2
  190. package/dist/node_modules/@allyhub/slides-pptx/dist/xml.js +2 -2
  191. package/dist/node_modules/@allyhub/slides-pptx/package.json +1 -1
  192. package/dist/node_modules/@allyhub/slides-runtime/dist/draw.js +2 -2
  193. package/dist/node_modules/@allyhub/slides-runtime/dist/index.js +1 -1
  194. package/dist/node_modules/@allyhub/slides-runtime/dist/ink.js +1 -1
  195. package/dist/node_modules/@allyhub/slides-runtime/dist/load.js +5 -5
  196. package/dist/node_modules/@allyhub/slides-runtime/package.json +1 -1
  197. package/dist/node_modules/@allyhub/stage/package.json +1 -1
  198. package/dist/node_modules/@allyhub/stage-page/package.json +1 -1
  199. package/dist/node_modules/@allyhub/stage-runtime/dist/runtime.js +101 -49
  200. package/dist/node_modules/@allyhub/stage-runtime/package.json +1 -1
  201. package/dist/node_modules/@allyhub/telemetry/LICENSE +241 -0
  202. package/dist/node_modules/@allyhub/telemetry/dist/doc.js +47 -0
  203. package/dist/node_modules/@allyhub/telemetry/dist/errors.js +2 -0
  204. package/dist/node_modules/@allyhub/telemetry/dist/index.js +2 -0
  205. package/dist/node_modules/@allyhub/telemetry/dist/level.js +3 -0
  206. package/dist/node_modules/@allyhub/telemetry/dist/scrub.js +2 -0
  207. package/dist/node_modules/@allyhub/telemetry/dist/telemetry.js +5 -0
  208. package/dist/node_modules/@allyhub/telemetry/package.json +21 -0
  209. package/dist/node_modules/@allyhub/video-core/dist/mix-plan.js +1 -1
  210. package/dist/node_modules/@allyhub/video-core/package.json +1 -1
  211. package/dist/node_modules/@allyhub/video-extension/dist/inspect/timeline-text.js +1 -1
  212. package/dist/node_modules/@allyhub/video-extension/package.json +3 -3
  213. package/dist/node_modules/@allyhub/video-measure/package.json +1 -1
  214. package/dist/node_modules/@allyhub/video-sdk/package.json +1 -1
  215. package/dist/node_modules/@allyhub/website/package.json +1 -1
  216. package/dist/node_modules/@allyhub/website-extension/package.json +1 -1
  217. package/dist/node_modules/@allyhub/x-extension/package.json +1 -1
  218. package/dist/node_modules/@allyhub/x-model/package.json +1 -1
  219. package/dist/node_modules/@allyhub/x-view/package.json +1 -1
  220. package/dist/package.json +12 -12
  221. package/dist/telemetry.js +4 -0
  222. package/dist/turn.js +2 -0
  223. package/editor-web/assets/{abnfDiagram-WEYOIA3C-BKmMA6gn.js → abnfDiagram-WEYOIA3C-D70jg8mE.js} +1 -1
  224. package/editor-web/assets/{architecture-WOLXFQ4H-BEFBgb4k.js → architecture-WOLXFQ4H-CrXS3E8e.js} +1 -1
  225. package/editor-web/assets/{architectureDiagram-ZHVYKT53-_u5YfCjY.js → architectureDiagram-ZHVYKT53-JrBljCOx.js} +1 -1
  226. package/editor-web/assets/arrow-down-DzZjFrBL.js +1 -0
  227. package/editor-web/assets/arrow-up-hdmh9LVD.js +1 -0
  228. package/editor-web/assets/{article-BUmD3xtR.js → article-BWrfVMRA.js} +6 -6
  229. package/editor-web/assets/article-hxHjqzV1.js +7 -0
  230. package/editor-web/assets/{audio-lines-CzuzsGjI.js → audio-lines-1s1eRs4Q.js} +1 -1
  231. package/editor-web/assets/{blockDiagram-RJAE7QA3-DybfaO3Z.js → blockDiagram-RJAE7QA3-BzfC1xTS.js} +1 -1
  232. package/editor-web/assets/{bookmark-Dsd3kHJJ.js → bookmark-Dfji3syX.js} +1 -1
  233. package/editor-web/assets/{button-eGxLxbv9.js → button-EftXSfev.js} +1 -1
  234. package/editor-web/assets/{c4Diagram-XDPPPE54-BfqLHB5i.js → c4Diagram-XDPPPE54-s2TpXKgH.js} +1 -1
  235. package/editor-web/assets/calc-worker-jImBXoeb.js +45 -0
  236. package/editor-web/assets/channel-BFbXY6R0.js +1 -0
  237. package/editor-web/assets/chart-BC3kUUDD.js +2 -0
  238. package/editor-web/assets/{chart-no-axes-column-BVkeF_Mr.js → chart-no-axes-column-CJmeYOSo.js} +1 -1
  239. package/editor-web/assets/{chunk-2E7WHVMD-BVp1I_d0.js → chunk-2E7WHVMD-DyE9v6UX.js} +1 -1
  240. package/editor-web/assets/{chunk-4EMNKR2T-CTdgWEMr.js → chunk-4EMNKR2T-CCunMMcT.js} +1 -1
  241. package/editor-web/assets/{chunk-55XCU76K-7pnsxeaP.js → chunk-55XCU76K-CZgJYrN4.js} +1 -1
  242. package/editor-web/assets/{chunk-7S6XSTFO-Dc0Dvkq7.js → chunk-7S6XSTFO-B01FlTFf.js} +1 -1
  243. package/editor-web/assets/{chunk-AQDTSKZB-VAILIsfx.js → chunk-AQDTSKZB-latWUvVu.js} +1 -1
  244. package/editor-web/assets/{chunk-DSNLSHJZ-CUDx1Rv5.js → chunk-DSNLSHJZ-BHFiQInN.js} +1 -1
  245. package/editor-web/assets/{chunk-HAGFOTED-DAoEe-dJ.js → chunk-HAGFOTED-C4hR36ab.js} +1 -1
  246. package/editor-web/assets/{chunk-HNE4Q36P-g0akya12.js → chunk-HNE4Q36P-CNrxiD2Q.js} +1 -1
  247. package/editor-web/assets/{chunk-NQOKRVIF-hTGjzXdJ.js → chunk-NQOKRVIF-DpyEHKEY.js} +1 -1
  248. package/editor-web/assets/{chunk-UHW7PFBP-BgLV8BIJ.js → chunk-UHW7PFBP-SIEJdixh.js} +1 -1
  249. package/editor-web/assets/{chunk-VQ5W62QI-Bw19OOSD.js → chunk-VQ5W62QI-CxWnQRxx.js} +1 -1
  250. package/editor-web/assets/{chunk-WQQL4CDK-CMST9dyE.js → chunk-WQQL4CDK-CbRuCBm6.js} +1 -1
  251. package/editor-web/assets/{chunk-YZO67HFG-Bbpu36XF.js → chunk-YZO67HFG-Cgu-EQvs.js} +1 -1
  252. package/editor-web/assets/{chunk-ZAUX2LTX-C48Ri0Gs.js → chunk-ZAUX2LTX-pAl5CV3o.js} +1 -1
  253. package/editor-web/assets/{chunk-ZCHMQSOR-DN1g01Oe.js → chunk-ZCHMQSOR-Du5hY-FP.js} +1 -1
  254. package/editor-web/assets/{classDiagram-v2-4MYWR3UA-U6jbPr2d.js → classDiagram-v2-4MYWR3UA-CevU94T6.js} +1 -1
  255. package/editor-web/assets/{collaborator-B1u2td9m.js → collaborator-C6IJkcGR.js} +1 -1
  256. package/editor-web/assets/copy-DvOiv9Ra.js +1 -0
  257. package/editor-web/assets/{createLucideIcon-GFZ_fxLc.js → createLucideIcon-REX213UO.js} +1 -1
  258. package/editor-web/assets/{cynefin-EF2NZ3EQ-gzkai_7-.js → cynefin-EF2NZ3EQ-DBHwpMRJ.js} +1 -1
  259. package/editor-web/assets/{cynefinDiagram-WF24UDRP-DtSekSr6.js → cynefinDiagram-WF24UDRP-CxUzpjvG.js} +1 -1
  260. package/editor-web/assets/{dagre-NK4GIZVX-CiUwYVT6.js → dagre-NK4GIZVX-BAJNBDYO.js} +1 -1
  261. package/editor-web/assets/{diagram-CBK3MWTC-r9XHCV-k.js → diagram-CBK3MWTC-BQW9Fbw-.js} +1 -1
  262. package/editor-web/assets/{diagram-I5XIIV2D-DxVsDZ34.js → diagram-I5XIIV2D-DQBROUfn.js} +1 -1
  263. package/editor-web/assets/{diagram-ODIL2UCW-B0eNQoHV.js → diagram-ODIL2UCW-DEoK31qy.js} +1 -1
  264. package/editor-web/assets/{diagram-PFBEJUXE-C7f2MfJT.js → diagram-PFBEJUXE-BTCa2We1.js} +1 -1
  265. package/editor-web/assets/{diagram-RJA3I4VV-CSXcnvct.js → diagram-RJA3I4VV-DNM8qWC3.js} +1 -1
  266. package/editor-web/assets/{diagram-TYUNFSNR-DXzOD_ii.js → diagram-TYUNFSNR-BcKpED4d.js} +1 -1
  267. package/editor-web/assets/dist-90dg0B0d.js +2 -0
  268. package/editor-web/assets/dist-BSPs7tZR.js +1 -0
  269. package/editor-web/assets/dist-CP9XwbBS.js +45 -0
  270. package/editor-web/assets/dist-CRxtC7DG.js +24 -0
  271. package/editor-web/assets/{dist-CC7OeU1e.js → dist-Cmnq14RO.js} +3 -3
  272. package/editor-web/assets/dist-CrZwqOm2.js +1 -0
  273. package/editor-web/assets/dist-CzUWTcvC.js +38 -0
  274. package/editor-web/assets/dist-D2a_y4AE.js +1 -0
  275. package/editor-web/assets/{dist-DDv_SbKw.js → dist-DMZ1VHPK.js} +1 -1
  276. package/editor-web/assets/dist-DYnXIW8F.js +16 -0
  277. package/editor-web/assets/{dist-BuWaZ3Y4.js → dist-Dpet39Yp.js} +30 -30
  278. package/editor-web/assets/dist-Dre4Cwpz.js +1 -0
  279. package/editor-web/assets/dist-RkxskWGK.js +5 -0
  280. package/editor-web/assets/dist-aANR6S2I.js +3 -0
  281. package/editor-web/assets/{dist-Gz6NDS0J.js → dist-qSuFWuVB.js} +3 -3
  282. package/editor-web/assets/{ebnfDiagram-V4P3TTPT-Cs4YRvDD.js → ebnfDiagram-V4P3TTPT-D-1x27Eh.js} +1 -1
  283. package/editor-web/assets/{elk-QONTBCTQ-Bh3LZ9WI.js → elk-QONTBCTQ-BJSCxiTH.js} +1 -1
  284. package/editor-web/assets/{erDiagram-KYQIGQAA-C4vYTYXp.js → erDiagram-KYQIGQAA-C7Q357iD.js} +1 -1
  285. package/editor-web/assets/{eventmodeling-K75KTNOO-BN1kkHWS.js → eventmodeling-K75KTNOO-kXrQLSF5.js} +1 -1
  286. package/editor-web/assets/flowDiagram-IUGLLWBU-GSC4btef.js +1 -0
  287. package/editor-web/assets/{ganttDiagram-R7GPNTJY-CA1LkkC5.js → ganttDiagram-R7GPNTJY-Bt3SRgK7.js} +1 -1
  288. package/editor-web/assets/{gitGraph-VSP46ZUC-Dy5tA7dG.js → gitGraph-VSP46ZUC-DS4CkhfK.js} +1 -1
  289. package/editor-web/assets/{gitGraphDiagram-PDYL7XHY-hJIB8EkH.js → gitGraphDiagram-PDYL7XHY-BgfmSVdI.js} +1 -1
  290. package/editor-web/assets/group-pebHQTdP.js +1 -0
  291. package/editor-web/assets/{hint-B8JpEypy.js → hint-BmRKl2nL.js} +1 -1
  292. package/editor-web/assets/index-D8qc_ipi.js +28 -0
  293. package/editor-web/assets/index-DDtZpLDF.css +2 -0
  294. package/editor-web/assets/{info-OHQRW6UA-DvzSf7rQ.js → info-OHQRW6UA-BZjctF3x.js} +1 -1
  295. package/editor-web/assets/{infoDiagram-MVDRKAX5-BjIMm4Af.js → infoDiagram-MVDRKAX5-BAp5oUXk.js} +1 -1
  296. package/editor-web/assets/{ishikawaDiagram-HPEHV2GE-Bpz71S40.js → ishikawaDiagram-HPEHV2GE-DGL7ZfUu.js} +1 -1
  297. package/editor-web/assets/{italic-D10w8n6C.js → italic-CtlNOXN9.js} +1 -1
  298. package/editor-web/assets/{journeyDiagram-BOSHW7O7-DAB-pZjD.js → journeyDiagram-BOSHW7O7-DOOoBGx-.js} +1 -1
  299. package/editor-web/assets/{kanban-definition-FNSA4HC5-cYeyh3P6.js → kanban-definition-FNSA4HC5-lbLuUiMW.js} +1 -1
  300. package/editor-web/assets/katex-UWCZofcd.js +257 -0
  301. package/editor-web/assets/{link-BC5xK1-1.js → link-CW2KxKT_.js} +1 -1
  302. package/editor-web/assets/{mermaid-parser.core-req5LE0X.js → mermaid-parser.core-RkCFmJcg.js} +3 -3
  303. package/editor-web/assets/{mermaid.core-zFwZug4C.js → mermaid.core-BVUl-afX.js} +4 -4
  304. package/editor-web/assets/{mindmap-definition-6OY57UG3-TStWb7DG.js → mindmap-definition-6OY57UG3-C3DC4T1J.js} +1 -1
  305. package/editor-web/assets/minus-D1tgAHbU.js +1 -0
  306. package/editor-web/assets/{packet-JDAUHWVQ-smFhVKcB.js → packet-JDAUHWVQ-Bkd6YpX8.js} +1 -1
  307. package/editor-web/assets/{palette-BIOudGkm.js → palette-INFK0Zsr.js} +1 -1
  308. package/editor-web/assets/{pegDiagram-ECIUJNBX-DvSNRv0-.js → pegDiagram-ECIUJNBX-B5Seh4Oe.js} +1 -1
  309. package/editor-web/assets/{pie-XZMESJXO-qjaGsBZG.js → pie-XZMESJXO-BNbb4Q8k.js} +1 -1
  310. package/editor-web/assets/{pieDiagram-GNMPY74T-Dd9P-Pdc.js → pieDiagram-GNMPY74T-_hnbUloZ.js} +1 -1
  311. package/editor-web/assets/play-DvMyq5xW.js +1 -0
  312. package/editor-web/assets/{progress-DE4C5_3x.js → progress-D6wSFdpY.js} +1 -1
  313. package/editor-web/assets/props-form-BfwEi6jW.js +1 -0
  314. package/editor-web/assets/{quadrantDiagram-D57K4MC3-h2IIKUUA.js → quadrantDiagram-D57K4MC3-1rbqW-KO.js} +1 -1
  315. package/editor-web/assets/{radar-ABXABTNO-DlVrSA1d.js → radar-ABXABTNO-BWSnhBSp.js} +1 -1
  316. package/editor-web/assets/{railroad-I3PHUGI6-nFbuLAtc.js → railroad-I3PHUGI6-BNB-OKs1.js} +1 -1
  317. package/editor-web/assets/{railroad-abnf-LNEFI6M7-Daj8h2iV.js → railroad-abnf-LNEFI6M7-BKgidf_B.js} +1 -1
  318. package/editor-web/assets/{railroad-ebnf-DWYD2UWJ-eYJyl5PH.js → railroad-ebnf-DWYD2UWJ-CNCnxtHp.js} +1 -1
  319. package/editor-web/assets/{railroad-peg-JR7BVNR7-BTRhKZQq.js → railroad-peg-JR7BVNR7-CyBW6_0o.js} +1 -1
  320. package/editor-web/assets/{railroadDiagram-Y72NRBL7-CeLGUjdp.js → railroadDiagram-Y72NRBL7-Cud3SJ7O.js} +1 -1
  321. package/editor-web/assets/{react-WA6wlt8S.js → react-Bk7NnOLX.js} +1 -1
  322. package/editor-web/assets/{repeat-2-VQP1EVOZ.js → repeat-2-DfPmKp4w.js} +1 -1
  323. package/editor-web/assets/{requirementDiagram-EQYSW5RA-Dmk9XRM5.js → requirementDiagram-EQYSW5RA-BrSCcpqV.js} +1 -1
  324. package/editor-web/assets/{row-BRlEWRrK.js → row-VwyPfa1b.js} +1 -1
  325. package/editor-web/assets/{sankeyDiagram-SY24JHO5-Yn4zlrAM.js → sankeyDiagram-SY24JHO5-rJV4dJFn.js} +1 -1
  326. package/editor-web/assets/scissors-D9WmgvNP.js +1 -0
  327. package/editor-web/assets/{sequenceDiagram-BLEHNHQU-BTRnp_PW.js → sequenceDiagram-BLEHNHQU-CEUuD2n6.js} +1 -1
  328. package/editor-web/assets/{session-Do9AqS38.js → session-DE0fvAcs.js} +1 -1
  329. package/editor-web/assets/sigma-CY2Chbro.js +1 -0
  330. package/editor-web/assets/slides-BgacyjJW.js +1 -0
  331. package/editor-web/assets/{snapshots-BUGlKQIB.js → snapshots-D8TtZp1x.js} +1 -1
  332. package/editor-web/assets/{sound-Bj3o9_Fa.js → sound-DUCxe9eC.js} +1 -1
  333. package/editor-web/assets/split-Cx2MMnC_.js +3 -0
  334. package/editor-web/assets/{stateDiagram-v2-A6IESKWZ-kstrRKv2.js → stateDiagram-v2-A6IESKWZ-BRE_C2he.js} +1 -1
  335. package/editor-web/assets/sticky-note-C5qUDHhC.js +1 -0
  336. package/editor-web/assets/{strikethrough-CfXx6IYH.js → strikethrough-DP-7tMz0.js} +1 -1
  337. package/editor-web/assets/svg-nJtFNJ-7.js +1 -0
  338. package/editor-web/assets/{swatch-WeJD41aW.js → swatch-lxK4C8fD.js} +1 -1
  339. package/editor-web/assets/{swimlanes-B3ENRKFQ-DaZsZkeP.js → swimlanes-B3ENRKFQ-BEPqWgVe.js} +1 -1
  340. package/editor-web/assets/swimlanesDiagram-AYQRV4AK-DAcNszZ6.js +8 -0
  341. package/editor-web/assets/{switch-N0G_sbqt.js → switch-DaG6OuAi.js} +1 -1
  342. package/editor-web/assets/{syntax-oWsKBWFw.js → syntax-9LD8MzGy.js} +1 -1
  343. package/editor-web/assets/{syntax-BVsgRJ4I.js → syntax-CLaCSmoi.js} +1 -1
  344. package/editor-web/assets/{table-B6hVZAMi.js → table-CTjNpE4W.js} +1 -1
  345. package/editor-web/assets/tabs-DjhzblAG.js +1 -0
  346. package/editor-web/assets/{textarea-tEWvBY9p.js → textarea-DBwRbOyF.js} +1 -1
  347. package/editor-web/assets/{timeline-definition-JXYKGLGB-CLCvY-Yf.js → timeline-definition-JXYKGLGB-p8Qeg4pS.js} +1 -1
  348. package/editor-web/assets/{trash-2-BP6nqpg2.js → trash-2-DrnRa91l.js} +1 -1
  349. package/editor-web/assets/{treeView-D4JQ5SDB-BmN0gwdC.js → treeView-D4JQ5SDB-C9FTdXKq.js} +1 -1
  350. package/editor-web/assets/{treemap-SAJKECNS-DN29G_E_.js → treemap-SAJKECNS-XAeLVOtI.js} +1 -1
  351. package/editor-web/assets/{undo-2-CHR0nvWL.js → undo-2-DUGGyBdX.js} +1 -1
  352. package/editor-web/assets/{usecaseDiagram-WPOLBNNX-DTRS54cB.js → usecaseDiagram-WPOLBNNX-BV3AMRuH.js} +1 -1
  353. package/editor-web/assets/{vennDiagram-Q3Y3IDCW-DAAc11Hx.js → vennDiagram-Q3Y3IDCW-CJdKcYyA.js} +1 -1
  354. package/editor-web/assets/{video-BlvmR8BK.js → video-He8p6dr6.js} +1 -1
  355. package/editor-web/assets/{wardley-7MLQ67FV-B-UYkmdB.js → wardley-7MLQ67FV-DZh6Mf22.js} +1 -1
  356. package/editor-web/assets/{wardleyDiagram-IVAIDKWA-BmbwCaky.js → wardleyDiagram-IVAIDKWA-XtvKSX-m.js} +1 -1
  357. package/editor-web/assets/{words-D_4T9Adq.js → words-CPHp_0tt.js} +1 -1
  358. package/editor-web/assets/{words-WgdEQdYP.js → words-CjW-1tZI.js} +1 -1
  359. package/editor-web/assets/{xychartDiagram-4URNHDU4-ChAfAq1U.js → xychartDiagram-4URNHDU4-CGkL42sz.js} +1 -1
  360. package/editor-web/assets/zoom-in-C4lxmIDE.js +1 -0
  361. package/editor-web/index.html +6 -6
  362. package/package.json +2 -2
  363. package/editor-web/assets/arrow-up-B5rJbBv0.js +0 -1
  364. package/editor-web/assets/article-DNioBb3p.js +0 -7
  365. package/editor-web/assets/calc-worker-D2pGis6e.js +0 -45
  366. package/editor-web/assets/channel-TNPgFDrw.js +0 -1
  367. package/editor-web/assets/chart-C37xvZT2.js +0 -1
  368. package/editor-web/assets/dist-BGRwhCQO.js +0 -1
  369. package/editor-web/assets/dist-BW4X7BrF.js +0 -1
  370. package/editor-web/assets/dist-BgDRE85b.js +0 -2
  371. package/editor-web/assets/dist-Blq5nJnU.js +0 -24
  372. package/editor-web/assets/dist-C1emZ9wX.js +0 -37
  373. package/editor-web/assets/dist-CX-fiPSn.js +0 -38
  374. package/editor-web/assets/dist-C_VvG-_9.js +0 -5
  375. package/editor-web/assets/dist-Ce7HrBxv.js +0 -3
  376. package/editor-web/assets/dist-D2k6w-_a.js +0 -1
  377. package/editor-web/assets/dist-DEoEO4zs.js +0 -1
  378. package/editor-web/assets/dist-DlDxxPIP.js +0 -16
  379. package/editor-web/assets/flowDiagram-IUGLLWBU-B04NGsyi.js +0 -1
  380. package/editor-web/assets/index-CgB5osVc.js +0 -28
  381. package/editor-web/assets/index-Daytem9N.css +0 -2
  382. package/editor-web/assets/katex-5Z2zF-9g.js +0 -257
  383. package/editor-web/assets/minus-DaWs5i8B.js +0 -1
  384. package/editor-web/assets/play-CrMmPghG.js +0 -1
  385. package/editor-web/assets/props-form-CsmDBqzy.js +0 -1
  386. package/editor-web/assets/schemas-VikZYZIK.js +0 -1
  387. package/editor-web/assets/slides-diTEQ3C5.js +0 -1
  388. package/editor-web/assets/split-CNU1RHcX.js +0 -3
  389. package/editor-web/assets/svg-Cx50MpxK.js +0 -1
  390. package/editor-web/assets/swimlanesDiagram-AYQRV4AK-CBZAujYY.js +0 -8
  391. package/editor-web/assets/tabs-DIFDqj-l.js +0 -1
@@ -1,5 +1,5 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{mkdir as A,readdir as X,readFile as E,rm as Y,writeFile as D}from"node:fs/promises";import{basename as $,dirname as k,extname as S,join as j}from"node:path";import{EXIT as p,FileContentResponseSchema as q,ToolCallSchema as _,callPath as Q,fileContentPath as V,parseAllyFilePath as I,toolCallsPath as tt}from"@allyhub/protocol";import{genFileFor as H}from"@allyhub/formats";import{CloudError as d}from"./errors.js";import{genRecord as M,inputHash as et,namedFile as nt,readGen as it,toolWords as at,writeGen as L,writeWords as ot}from"./records.js";import{withKnownUploads as rt}from"./uploads.js";export const WAIT_SECONDS=900,POLL_SECONDS={least:1,most:60},RETRY_SECONDS={least:1,most:30},READ_SECONDS=120;const st=new Set([408,429,500,502,503,504]),lt=t=>t instanceof d&&(t.code==="network"||t.status!==void 0&&st.has(t.status));function ut(t){if(!/^https?:\/\//iu.test(t))return t;let e;try{e=new URL(t)}catch{return t}if(e.search==="")return t.replace(/^https?:\/\//iu,"");const i=/filename\*?=(?:UTF-8'')?"?([^";]+)/iu.exec(e.searchParams.get("response-content-disposition")??"")?.[1];return i===void 0?void 0:decodeURIComponent(i)}export function inputSlug(t){return Object.values(t).flatMap(e=>Array.isArray(e)?e:[e]).filter(e=>typeof e=="string").flatMap(e=>ut(e)??[]).join("-").replace(/[^\p{L}\p{N}._]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,40).replace(/-+$/u,"")}const U=t=>t.replace(/[^A-Za-z0-9_-]/gu,"_").slice(0,8),W=(t,e)=>{const i=S(t);return`${$(t,i)}-${U(e)}${i}`};async function ft(t,e,i,n,o){await A(t,{recursive:!0});const s=[e,inputSlug(i),U(n)].filter(Boolean).join("-"),r=j(t,`${s}.output.json`);return await D(r,`${JSON.stringify(o,null,2)}
3
- `),r}async function ct(t,e){const i=S(t)===""?`${t}.json`:t;return await A(k(i),{recursive:!0}),await D(i,`${JSON.stringify(e,null,2)}
4
- `),i}const T=t=>j(t.config.cacheDir,"jobs"),C=(t,e)=>j(T(t),`${e.replace(/[^A-Za-z0-9_-]/gu,"_")}.json`);async function dt(t,e,i){await A(k(C(t,e)),{recursive:!0}),await D(C(t,e),`${JSON.stringify(i,null,2)}
5
- `)}const P=(t,e)=>Y(C(t,e),{force:!0});async function wt(t,e,i){const n=await X(T(t)).catch(()=>[]);for(const o of n.filter(s=>s.endsWith(".json")).sort()){const s=await E(j(T(t),o),"utf8").then(r=>JSON.parse(r)).catch(()=>{});if(s?.jobId!==void 0&&s.file===e&&s.inputHash===i)return s.jobId}}async function ht(t,e){try{return JSON.parse(await E(C(t,e),"utf8"))}catch{throw new d("unknown-job",`No job ${e} was started on this computer.`,{exit:p.notFound,hint:"Call the tool again: that is a new call."})}}async function B(t,e,i,n,o){const{url:s}=q.parse(await t.json(V(e,"attachment"),{signal:v(o)}));let r;try{const f=await t.config.fetch(s,o?{signal:o}:{});if(!f.ok)throw new d("download-failed",`Downloading ${i} answered ${String(f.status)}.`,{exit:p.platform,status:f.status});r=Buffer.from(await f.arrayBuffer())}catch(f){throw f instanceof d||o?.aborted===!0?f:new d("network",`Downloading ${i} failed: ${f instanceof Error?f.message:String(f)}`,{exit:p.platform,cause:f})}const w="dir"in n?j(n.dir,$(n.name??i)):S(n.file)?n.file:`${n.file}${S(i)}`;return await A(k(w),{recursive:!0}),await D(w,r),w}const v=t=>t?AbortSignal.any([t,AbortSignal.timeout(READ_SECONDS*1e3)]):AbortSignal.timeout(READ_SECONDS*1e3),z=(t,e)=>new Promise((i,n)=>{const o=setTimeout(i,t*1e3);e?.addEventListener("abort",()=>{clearTimeout(o),n(e.reason instanceof Error?e.reason:new Error("Stopped."))},{once:!0})});export async function callTool(t,e,i,n){const o=n.file,s=await rt(t,i,n.base),r=et(e,s);let w=n.jobId,f=!1;if(o!==void 0&&w===void 0){w=await wt(t,o,r);const u=w===void 0?await nt(o):void 0,l=u?await it(u):void 0;if(n.force===!0)f=l!==void 0;else{if(u&&!l)throw new d("file-exists",`${u} is there, without a record (${$(H(u))}) saying a tool call made it.`,{exit:p.conflict,hint:"Choose another --file, or pass --force to replace it."});if(u&&l){if(l.tool===e&&l.inputHash===r)return{tool:e,output:typeof l.output?.allyFilePath=="string"?l.output:JSON.parse(await E(u,"utf8")),file:u,gen:H(u),kept:{at:l.at}};throw new d("file-exists",`${u} was made by ${l.tool??"another tool"} from another input on ${l.at}.`,{exit:p.conflict,hint:"Choose another --file to keep it, or pass --force to make it again over it (charged again)."})}}}const m=Date.now()+(n.timeoutSeconds??WAIT_SECONDS)*1e3,g=n.signal;let a=w===void 0?_.parse(await t.json(tt(e),{method:"POST",body:{input:i},...g?{signal:g}:{}})):await G(t,w,m,n);a.status==="working"&&w===void 0&&await dt(t,a.id,{jobId:a.id,tool:e,input:{...i},inputHash:r,outDir:n.outDir,...o===void 0?{}:{file:o}});const Z=()=>({tool:e,jobId:a.id,status:"running",elapsedSeconds:(Date.now()-Date.parse(a.createdAt))/1e3,...o===void 0?{}:{file:o}});for(;a.status==="working";){if(n.wait===!1||Date.now()>m)return Z();n.onRunning?.(a),await z(Math.min(Math.max((a.pollAfterMs??0)/1e3,POLL_SECONDS.least),POLL_SECONDS.most),g),a=await G(t,a.id,m,n)}if(a.status==="failed")throw await P(t,a.id),new d(`tool-${(a.error?.kind??"failed").replaceAll("_","-")}`,a.error?.message??"The tool failed.",{exit:a.error?.kind==="input"?p.usage:p.platform,hint:a.error?.kind==="input"||a.error?.kind==="not_found"?"A failed call is not charged. Change the input and call again.":a.error?.kind==="unavailable"?"A failed call is not charged. Calling it again will not help until AllyHub sets it up.":"A failed call is not charged. Call it again; a supplier's failure often passes."});if(a.status!=="completed")throw new d("tool-state",`The call ${a.id} is ${a.status}, a state this version of allyhub does not know.`,{exit:p.platform,hint:"Update allyhub in the project (npm install allyhub@latest) and call it again."});const h=typeof a.output=="object"&&a.output!==null?a.output:{value:a.output},R=h.allyFilePath,y=typeof R=="string"?I(R):void 0,b=!y&&o!==void 0?await ct(o,h):void 0,c={tool:e,output:h,outputFile:b??await ft(n.outputDir??n.outDir,e,i,a.id,h),...a.credits===void 0?{}:{credits:a.credits}};if(y){const u=a.id,l=await J(u,()=>B(t,y.id,y.name,o!==void 0?{file:o}:{dir:n.outDir,name:W(y.name,u)},g),m,n);c.file=l,c.gen=await L(l,await M(l,{tool:e,input:s,output:h,credits:a.credits}));const x=at(h),N=h.durationSeconds;x&&(c.words=await ot(l,x,typeof N=="number"&&N>=0?N:void 0)),f&&(c.replaced=!0)}else b!==void 0&&(c.file=b,c.gen=await L(b,await M(b,{tool:e,input:s,output:h,credits:a.credits})),f&&(c.replaced=!0));const O={},K=c.file===void 0?n.outDir:k(c.file),F=c.file;for(const u of pt(h)){const l=I(u);if(!l)continue;const x=F===void 0?W(l.name,a.id):`${$(F,S(F))}.${$(l.name)}`;O[u]=await J(a.id,()=>B(t,l.id,l.name,{dir:K,name:x},g),m,n)}return Object.keys(O).length>0&&(c.more=O),await P(t,a.id),c}function pt(t){const e=[],i=(n,o)=>{if(Array.isArray(n))for(const s of n)i(s,!1);else if(typeof n=="object"&&n!==null)for(const[s,r]of Object.entries(n))s==="allyFilePath"&&!o&&typeof r=="string"?e.push(r):i(r,!1)};return i(t,!0),e}async function G(t,e,i,n){try{return await J(e,async()=>_.parse(await t.json(Q(e),{signal:v(n.signal)})),i,n)}catch(o){throw o instanceof d&&o.status===404&&await P(t,e),o}}async function J(t,e,i,n){const o=n.retrySeconds??RETRY_SECONDS;for(let s=o.least;;)try{return await e()}catch(r){if(!lt(r)||n.signal?.aborted===!0)throw r;if(Date.now()+s*1e3>i)throw new d(r.code,r.message,{exit:r.exit,...r.status===void 0?{}:{status:r.status},hint:`Call ${t} goes on at AllyHub, charged once when it works: --resume ${t} waits for it again (so does the same call to the same --file).`,cause:r});n.onRetry?.(t,r,s),await z(s,n.signal),s=Math.min(s*2,o.most)}}export async function resumeJob(t,e,i){const n=await ht(t,e);if(i.tool!==void 0&&i.tool!==n.tool)throw new d("wrong-job",`Job ${e} is ${n.tool}'s, not ${i.tool}'s.`,{exit:p.usage,hint:`Resume it with ${n.tool}.`});return await callTool(t,n.tool,n.input,{...i,outDir:n.outDir,...n.file===void 0?{}:{file:n.file},jobId:e})}
2
+ import{randomUUID as X}from"node:crypto";import{mkdir as D,readdir as Y,readFile as E,rm as q,writeFile as A}from"node:fs/promises";import{basename as $,dirname as k,extname as S,join as j}from"node:path";import{EXIT as p,FileContentResponseSchema as Q,ToolCallSchema as _,callPath as V,fileContentPath as tt,parseAllyFilePath as I,toolCallsPath as et}from"@allyhub/protocol";import{genFileFor as U}from"@allyhub/formats";import{CloudError as d}from"./errors.js";import{genRecord as H,inputHash as nt,namedFile as it,readGen as at,toolWords as ot,writeGen as M,writeWords as rt}from"./records.js";import{withKnownUploads as st}from"./uploads.js";export const WAIT_SECONDS=900,POLL_SECONDS={least:1,most:60},RETRY_SECONDS={least:1,most:30},READ_SECONDS=120;const lt=new Set([408,429,500,502,503,504]),ut=t=>t instanceof d&&(t.code==="network"||t.status!==void 0&&lt.has(t.status));function ft(t){if(!/^https?:\/\//iu.test(t))return t;let e;try{e=new URL(t)}catch{return t}if(e.search==="")return t.replace(/^https?:\/\//iu,"");const i=/filename\*?=(?:UTF-8'')?"?([^";]+)/iu.exec(e.searchParams.get("response-content-disposition")??"")?.[1];return i===void 0?void 0:decodeURIComponent(i)}export function inputSlug(t){return Object.values(t).flatMap(e=>Array.isArray(e)?e:[e]).filter(e=>typeof e=="string").flatMap(e=>ft(e)??[]).join("-").replace(/[^\p{L}\p{N}._]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,40).replace(/-+$/u,"")}const L=t=>t.replace(/[^A-Za-z0-9_-]/gu,"_").slice(0,8),W=(t,e)=>{const i=S(t);return`${$(t,i)}-${L(e)}${i}`};async function ct(t,e,i,n,o){await D(t,{recursive:!0});const s=[e,inputSlug(i),L(n)].filter(Boolean).join("-"),r=j(t,`${s}.output.json`);return await A(r,`${JSON.stringify(o,null,2)}
3
+ `),r}async function dt(t,e){const i=S(t)===""?`${t}.json`:t;return await D(k(i),{recursive:!0}),await A(i,`${JSON.stringify(e,null,2)}
4
+ `),i}const T=t=>j(t.config.cacheDir,"jobs"),C=(t,e)=>j(T(t),`${e.replace(/[^A-Za-z0-9_-]/gu,"_")}.json`);async function wt(t,e,i){await D(k(C(t,e)),{recursive:!0}),await A(C(t,e),`${JSON.stringify(i,null,2)}
5
+ `)}const P=(t,e)=>q(C(t,e),{force:!0});async function ht(t,e,i){const n=await Y(T(t)).catch(()=>[]);for(const o of n.filter(s=>s.endsWith(".json")).sort()){const s=await E(j(T(t),o),"utf8").then(r=>JSON.parse(r)).catch(()=>{});if(s?.jobId!==void 0&&s.file===e&&s.inputHash===i)return s.jobId}}async function pt(t,e){try{return JSON.parse(await E(C(t,e),"utf8"))}catch{throw new d("unknown-job",`No job ${e} was started on this computer.`,{exit:p.notFound,hint:"Call the tool again: that is a new call."})}}async function B(t,e,i,n,o){const{url:s}=Q.parse(await t.json(tt(e,"attachment"),{signal:v(o)}));let r;try{const f=await t.config.fetch(s,o?{signal:o}:{});if(!f.ok)throw new d("download-failed",`Downloading ${i} answered ${String(f.status)}.`,{exit:p.platform,status:f.status});r=Buffer.from(await f.arrayBuffer())}catch(f){throw f instanceof d||o?.aborted===!0?f:new d("network",`Downloading ${i} failed: ${f instanceof Error?f.message:String(f)}`,{exit:p.platform,cause:f})}const w="dir"in n?j(n.dir,$(n.name??i)):S(n.file)?n.file:`${n.file}${S(i)}`;return await D(k(w),{recursive:!0}),await A(w,r),w}const v=t=>t?AbortSignal.any([t,AbortSignal.timeout(READ_SECONDS*1e3)]):AbortSignal.timeout(READ_SECONDS*1e3),z=(t,e)=>new Promise((i,n)=>{const o=setTimeout(i,t*1e3);e?.addEventListener("abort",()=>{clearTimeout(o),n(e.reason instanceof Error?e.reason:new Error("Stopped."))},{once:!0})});export async function callTool(t,e,i,n){const o=n.file,s=await st(t,i,n.base),r=nt(e,s);let w=n.jobId,f=!1;if(o!==void 0&&w===void 0){w=await ht(t,o,r);const u=w===void 0?await it(o):void 0,l=u?await at(u):void 0;if(n.force===!0)f=l!==void 0;else{if(u&&!l)throw new d("file-exists",`${u} is there, without a record (${$(U(u))}) saying a tool call made it.`,{exit:p.conflict,hint:"Choose another --file, or pass --force to replace it."});if(u&&l){if(l.tool===e&&l.inputHash===r)return{tool:e,output:typeof l.output?.allyFilePath=="string"?l.output:JSON.parse(await E(u,"utf8")),file:u,gen:U(u),kept:{at:l.at}};throw new d("file-exists",`${u} was made by ${l.tool??"another tool"} from another input on ${l.at}.`,{exit:p.conflict,hint:"Choose another --file to keep it, or pass --force to make it again over it (charged again)."})}}}const m=Date.now()+(n.timeoutSeconds??WAIT_SECONDS)*1e3,g=n.signal;let a=w===void 0?_.parse(await t.json(et(e),{method:"POST",body:{input:i},idempotencyKey:X(),...g?{signal:g}:{}})):await G(t,w,m,n);a.status==="working"&&w===void 0&&await wt(t,a.id,{jobId:a.id,tool:e,input:{...i},inputHash:r,outDir:n.outDir,...o===void 0?{}:{file:o}});const K=()=>({tool:e,jobId:a.id,status:"running",elapsedSeconds:(Date.now()-Date.parse(a.createdAt))/1e3,...o===void 0?{}:{file:o}});for(;a.status==="working";){if(n.wait===!1||Date.now()>m)return K();n.onRunning?.(a),await z(Math.min(Math.max((a.pollAfterMs??0)/1e3,POLL_SECONDS.least),POLL_SECONDS.most),g),a=await G(t,a.id,m,n)}if(a.status==="failed")throw await P(t,a.id),new d(`tool-${(a.error?.kind??"failed").replaceAll("_","-")}`,a.error?.message??"The tool failed.",{exit:a.error?.kind==="input"?p.usage:p.platform,hint:a.error?.kind==="input"||a.error?.kind==="not_found"?"A failed call is not charged. Change the input and call again.":a.error?.kind==="unavailable"?"A failed call is not charged. Calling it again will not help until AllyHub sets it up or fixes it.":"A failed call is not charged. Call it again; a supplier's failure often passes."});if(a.status!=="completed")throw new d("tool-state",`The call ${a.id} is ${a.status}, a state this version of allyhub does not know.`,{exit:p.platform,hint:"Update allyhub in the project (npm install allyhub@latest) and call it again."});const h=typeof a.output=="object"&&a.output!==null?a.output:{value:a.output},R=h.allyFilePath,y=typeof R=="string"?I(R):void 0,b=!y&&o!==void 0?await dt(o,h):void 0,c={tool:e,output:h,outputFile:b??await ct(n.outputDir??n.outDir,e,i,a.id,h),...a.credits===void 0?{}:{credits:a.credits}};if(y){const u=a.id,l=await J(u,()=>B(t,y.id,y.name,o!==void 0?{file:o}:{dir:n.outDir,name:W(y.name,u)},g),m,n);c.file=l,c.gen=await M(l,await H(l,{tool:e,input:s,output:h,credits:a.credits}));const x=ot(h),N=h.durationSeconds;x&&(c.words=await rt(l,x,typeof N=="number"&&N>=0?N:void 0)),f&&(c.replaced=!0)}else b!==void 0&&(c.file=b,c.gen=await M(b,await H(b,{tool:e,input:s,output:h,credits:a.credits})),f&&(c.replaced=!0));const O={},Z=c.file===void 0?n.outDir:k(c.file),F=c.file;for(const u of mt(h)){const l=I(u);if(!l)continue;const x=F===void 0?W(l.name,a.id):`${$(F,S(F))}.${$(l.name)}`;O[u]=await J(a.id,()=>B(t,l.id,l.name,{dir:Z,name:x},g),m,n)}return Object.keys(O).length>0&&(c.more=O),await P(t,a.id),c}function mt(t){const e=[],i=(n,o)=>{if(Array.isArray(n))for(const s of n)i(s,!1);else if(typeof n=="object"&&n!==null)for(const[s,r]of Object.entries(n))s==="allyFilePath"&&!o&&typeof r=="string"?e.push(r):i(r,!1)};return i(t,!0),e}async function G(t,e,i,n){try{return await J(e,async()=>_.parse(await t.json(V(e),{signal:v(n.signal)})),i,n)}catch(o){throw o instanceof d&&o.status===404&&await P(t,e),o}}async function J(t,e,i,n){const o=n.retrySeconds??RETRY_SECONDS;for(let s=o.least;;)try{return await e()}catch(r){if(!ut(r)||n.signal?.aborted===!0)throw r;if(Date.now()+s*1e3>i)throw new d(r.code,r.message,{exit:r.exit,...r.status===void 0?{}:{status:r.status},hint:`Call ${t} goes on at AllyHub, charged once when it works: --resume ${t} waits for it again (so does the same call to the same --file).`,cause:r});n.onRetry?.(t,r,s),await z(s,n.signal),s=Math.min(s*2,o.most)}}export async function resumeJob(t,e,i){const n=await pt(t,e);if(i.tool!==void 0&&i.tool!==n.tool)throw new d("wrong-job",`Job ${e} is ${n.tool}'s, not ${i.tool}'s.`,{exit:p.usage,hint:`Resume it with ${n.tool}.`});return await callTool(t,n.tool,n.input,{...i,outDir:n.outDir,...n.file===void 0?{}:{file:n.file},jobId:e})}
@@ -48,6 +48,8 @@ export declare class Cloud {
48
48
  signal?: AbortSignal;
49
49
  /** The team it acts in, when not the one this computer works in. */
50
50
  organization?: string;
51
+ /** A change's key (IDEMPOTENCY_KEY_HEADER): sent again with it, the change is made once. */
52
+ idempotencyKey?: string;
51
53
  }): Promise<unknown>;
52
54
  }
53
55
  //# sourceMappingURL=client.d.ts.map
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{createHash as g}from"node:crypto";import{BILLING_PAGE_PATH as h,DEVICE_HEADER as w,EXIT as a,ORGANIZATION_HEADER as f}from"@allyhub/protocol";import{accessOf as p,SignedOut as m}from"./credentials.js";import{CloudError as d,notSignedIn as l,unreachable as y}from"./errors.js";export function scrub(u,n){let t=u.replace(/(authorization)\s*[:=]\s*[^\r\n]+/giu,"$1: <redacted>");return t=t.replace(/\bahk_[A-Za-z0-9_-]+/gu,"<api-key>"),t=t.replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/gu,"<token>"),n&&(t=t.split(n).join("<key>")),t}export class Cloud{config;constructor(n){this.config=n}async tellStudio(){const n=this.config.studioHost;n!==void 0&&await fetch(`${n}/out-of-credits`,{method:"POST",signal:AbortSignal.timeout(1e3)}).then(t=>t.body?.cancel(),()=>{})}get url(){return this.config.url}async key(n={}){const t=this.config.apiKey;if(t)return{key:t,source:"env",account:g("sha256").update(t).digest("hex")};try{const i=await p(this.config,n);if(!i)return;const o=i.credentials.account.organization?.id,e=i.credentials.device;return{key:i.token,source:"oauth",account:i.credentials.account.id,expiresAt:i.expiresAt,...o===void 0?{}:{organization:o},...e===void 0?{}:{device:e}}}catch(i){if(i instanceof m)return;throw y(this.url,i)}}async requireKey(){const n=await this.key();if(!n)throw l();return n}keyedFetch=async(n,t)=>{const i=s=>{const c=new Headers(t?.headers);return c.set("authorization",`Bearer ${s.key}`),s.organization!==void 0&&!c.has(f)&&c.set(f,s.organization),s.device!==void 0&&c.set(w,s.device),this.config.fetch(n,{...t,headers:c})},o=await this.requireKey(),e=await i(o);if(e.status!==401||o.source!=="oauth"||t?.body instanceof ReadableStream||n instanceof Request)return e;const r=await this.key({refused:o.key});return r===void 0?e:(await e.body?.cancel(),i(r))};async json(n,t={}){const i=t.auth!==!1,o=i?(await this.requireKey()).key:void 0;let e;try{e=await(i?this.keyedFetch:this.config.fetch)(`${this.url}${n}`,{redirect:"error",signal:t.signal??AbortSignal.timeout(3e4),method:t.method??"GET",headers:{accept:"application/json",...t.body===void 0?{}:{"content-type":"application/json"},...t.organization===void 0?{}:{[f]:t.organization}},...t.body===void 0?{}:{body:JSON.stringify(t.body)}})}catch(c){throw c instanceof d?c:y(this.url,c)}const r=await e.text(),s=e.ok?void 0:_(r,e.status,o,this.url);if(s?.code==="insufficient-credits"&&await this.tellStudio(),s&&e.status!==401)throw s;if(e.status===403)throw new d("forbidden","This AllyHub account does not have access to this operation.",{exit:a.auth,status:403});if(e.status===401)throw l(i?"This computer's AllyHub sign-in is not valid any more.":void 0);if(!e.ok)throw new d("api-error",`${this.url}${n} answered ${String(e.status)}: ${scrub(r.slice(0,300),o)}`,{exit:e.status>=500?a.platform:a.usage,status:e.status});try{return JSON.parse(r)}catch{throw new d("api-error",`${this.url}${n} did not answer JSON.`,{exit:a.platform,status:e.status})}}}const b={bad_input:a.usage,insufficient_credits:a.auth,plan_required:a.auth,tool_off:a.auth,limit_reached:a.auth,forbidden:a.auth,not_found:a.notFound,conflict:a.conflict,worked_elsewhere:a.conflict};function _(u,n,t,i){let o;try{o=JSON.parse(u)}catch{return}const e=o?.error;if(typeof e?.code!="string"||typeof e.message!="string")return;const r=e.code==="insufficient_credits"?`Buy credits at ${i}${h}?view=credits, or ask an owner or admin of the team to.`:e.code==="plan_required"?`Subscribe at ${i}${h}?view=plans, or ask an owner or admin of the team to.`:e.code==="tool_off"?`Turn it on in Capabilities at ${i}/, or ask an owner or admin of the team to.`:typeof e.hint=="string"?e.hint:void 0;return new d(e.code.replaceAll("_","-"),scrub(e.message,t),{exit:b[e.code]??a.platform,status:n,...r===void 0?{}:{hint:r},...typeof e.data=="object"&&e.data!==null?{data:e.data}:{}})}
2
+ import{createHash as w}from"node:crypto";import{DEVICE_HEADER as m,EXIT as r,IDEMPOTENCY_KEY_HEADER as b,ORGANIZATION_HEADER as l,planPageAddress as g}from"@allyhub/protocol";import{accessOf as _,SignedOut as k}from"./credentials.js";import{userAgent as E}from"./device.js";import{CloudError as u,notSignedIn as y,unreachable as p}from"./errors.js";export function scrub(f,t){let e=f.replace(/(authorization)\s*[:=]\s*[^\r\n]+/giu,"$1: <redacted>");return e=e.replace(/\bahk_[A-Za-z0-9_-]+/gu,"<api-key>"),e=e.replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/gu,"<token>"),t&&(e=e.split(t).join("<key>")),e}export class Cloud{config;constructor(t){this.config=t}async tellStudio(){const t=this.config.studioHost;t!==void 0&&await fetch(`${t}/out-of-credits`,{method:"POST",signal:AbortSignal.timeout(1e3)}).then(e=>e.body?.cancel(),()=>{})}get url(){return this.config.url}async key(t={}){const e=this.config.apiKey;if(e)return{key:e,source:"env",account:w("sha256").update(e).digest("hex")};try{const n=await _(this.config,t);if(!n)return;const c=n.credentials.account.organization?.id,s=n.credentials.device;return{key:n.token,source:"oauth",account:n.credentials.account.id,expiresAt:n.expiresAt,...c===void 0?{}:{organization:c},...s===void 0?{}:{device:s}}}catch(n){if(n instanceof k)return;throw p(this.url,n)}}async requireKey(){const t=await this.key();if(!t)throw y();return t}keyedFetch=async(t,e)=>{const n=this.config.client===void 0?void 0:await E(this.config.client),c=d=>{const o=new Headers(e?.headers);return o.set("authorization",`Bearer ${d.key}`),n!==void 0&&!o.has("user-agent")&&o.set("user-agent",n),this.config.traceparent!==void 0&&!o.has("traceparent")&&o.set("traceparent",this.config.traceparent),d.organization!==void 0&&!o.has(l)&&o.set(l,d.organization),d.device!==void 0&&o.set(m,d.device),this.config.fetch(t,{...e,headers:o})},s=await this.requireKey(),i=await c(s);if(i.status!==401||s.source!=="oauth"||e?.body instanceof ReadableStream||t instanceof Request)return i;const a=await this.key({refused:s.key});return a===void 0?i:(await i.body?.cancel(),c(a))};async json(t,e={}){const n=e.auth!==!1,c=n?await this.requireKey():void 0,s=c?.key,i=e.organization??c?.organization;let a;try{a=await(n?this.keyedFetch:this.config.fetch)(`${this.url}${t}`,{redirect:"error",signal:e.signal??AbortSignal.timeout(3e4),method:e.method??"GET",headers:{accept:"application/json",...e.body===void 0?{}:{"content-type":"application/json"},...e.organization===void 0?{}:{[l]:e.organization},...e.idempotencyKey===void 0?{}:{[b]:e.idempotencyKey}},...e.body===void 0?{}:{body:JSON.stringify(e.body)}})}catch(h){throw h instanceof u?h:p(this.url,h)}const d=await a.text(),o=a.ok?void 0:S(d,a.status,s,this.url,i);if(o?.code==="insufficient-credits"&&await this.tellStudio(),o&&a.status!==401)throw o;if(a.status===403)throw new u("forbidden","This AllyHub account does not have access to this operation.",{exit:r.auth,status:403});if(a.status===401)throw y(n?"This computer's AllyHub sign-in is not valid any more.":void 0);if(!a.ok)throw new u("api-error",`${this.url}${t} answered ${String(a.status)}: ${scrub(d.slice(0,300),s)}`,{exit:a.status>=500?r.platform:r.usage,status:a.status});try{return JSON.parse(d)}catch{throw new u("api-error",`${this.url}${t} did not answer JSON.`,{exit:r.platform,status:a.status})}}}const A={bad_input:r.usage,insufficient_credits:r.auth,plan_required:r.auth,tool_off:r.auth,storage_full:r.auth,limit_reached:r.auth,forbidden:r.auth,not_found:r.notFound,conflict:r.conflict,worked_elsewhere:r.conflict};function S(f,t,e,n,c){let s;try{s=JSON.parse(f)}catch{return}const i=s?.error;if(typeof i?.code!="string"||typeof i.message!="string")return;const a=i.code==="insufficient_credits"?`Buy credits at ${g(n,{organization:c,open:"credits"})}, or ask an owner or admin of the team to.`:i.code==="plan_required"?`Subscribe at ${g(n,{organization:c,open:"plans"})}, or ask an owner or admin of the team to.`:i.code==="tool_off"?`Turn it on in Capabilities at ${n}/, or ask an owner or admin of the team to.`:typeof i.hint=="string"?i.hint:void 0;return new u(i.code.replaceAll("_","-"),scrub(i.message,e),{exit:A[i.code]??r.platform,status:t,...a===void 0?{}:{hint:a},...typeof i.data=="object"&&i.data!==null?{data:i.data}:{}})}
@@ -17,6 +17,12 @@ export interface CloudConfig {
17
17
  fetch: typeof fetch;
18
18
  /** The program, as its User-Agent's product names it ("AllyHub-Studio/0.9.1"): told to AllyHub as it signs in. */
19
19
  client?: string;
20
+ /**
21
+ * The trace this process is part of (W3C Trace Context's `traceparent`,
22
+ * from `TRACEPARENT`, OpenTelemetry's carrier for a child process): sent
23
+ * with every request, so the calls a turn makes are known as its own.
24
+ */
25
+ traceparent?: string;
20
26
  /**
21
27
  * Studio's Host, when an agent in Studio runs this (`ALLYHUB_STUDIO_HOST`,
22
28
  * a loopback address with its token): told when a call is refused for
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{homedir as s}from"node:os";import{join as m}from"node:path";import{API_KEY_ENV as l,CREDENTIALS_FILE as d}from"@allyhub/protocol";import{cacheHome as _}from"@allyhub/runtimes";import{osKeychain as h}from"./keychain.js";const H="https://app.allyhub.com",U=["ALLYHUB_URL"],A=o=>o.replace(/\/+$/u,"");export function cloudConfig(o,r={}){const i=o[l]?.trim(),t=A(o.ALLYHUB_URL??H),e=o.ALLYHUB_HOME,c=r.client??o.ALLYHUB_CLIENT,n=m(e??s(),d),f=o.ALLYHUB_CREDENTIALS_STORE,L=f==="keychain"||f!=="file"&&e===void 0?h({service:"AllyHub",account:e===void 0?t:`${t} ${n}`}):void 0;return{url:t,from:U.filter(u=>o[u]!==void 0),credentialsFile:n,...L?{keychain:L}:{},cacheDir:m(_(o),"cloud"),...i?{apiKey:i}:{},fetch:r.fetch??fetch,...c===void 0?{}:{client:c},...o.ALLYHUB_STUDIO_HOST?{studioHost:o.ALLYHUB_STUDIO_HOST}:{}}}export function hostsText(o){return o.from.length>0?`${o.url} (from ${o.from.join(", ")})`:o.url}
2
+ import{homedir as d}from"node:os";import{join as u}from"node:path";import{API_KEY_ENV as l,CREDENTIALS_FILE as a}from"@allyhub/protocol";import{cacheHome as A}from"@allyhub/runtimes";import{osKeychain as E}from"./keychain.js";const T="https://app.allyhub.com",_=["ALLYHUB_URL"],h=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/u,H=o=>o.replace(/\/+$/u,"");export function cloudConfig(o,r={}){const c=o[l]?.trim(),t=H(o.ALLYHUB_URL??T),e=o.ALLYHUB_HOME,i=r.client??o.ALLYHUB_CLIENT,n=h.exec(o.TRACEPARENT?.trim()??"")?.[0],f=u(e??d(),a),L=o.ALLYHUB_CREDENTIALS_STORE,m=L==="keychain"||L!=="file"&&e===void 0?E({service:"AllyHub",account:e===void 0?t:`${t} ${f}`}):void 0;return{url:t,from:_.filter(s=>o[s]!==void 0),credentialsFile:f,...m?{keychain:m}:{},cacheDir:u(A(o),"cloud"),...c?{apiKey:c}:{},fetch:r.fetch??fetch,...i===void 0?{}:{client:i},...n===void 0?{}:{traceparent:n},...o.ALLYHUB_STUDIO_HOST?{studioHost:o.ALLYHUB_STUDIO_HOST}:{}}}export function hostsText(o){return o.from.length>0?`${o.url} (from ${o.from.join(", ")})`:o.url}
@@ -1,3 +1,3 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{randomBytes as T}from"node:crypto";import{chmod as C,mkdir as m,readFile as b,rename as P,rm as h,stat as O,writeFile as z}from"node:fs/promises";import{dirname as x}from"node:path";import*as y from"zod";import{ACCOUNT_PATH as I,AccountSchema as j,AuthServerSchema as N,CLIENT_ID as w,CredentialsFileSchema as $,DeviceAuthorizationSchema as R,METADATA_PATH as J,OAuthErrorSchema as L,SCOPES as U,TokenResponseSchema as B}from"@allyhub/protocol";import{deviceHeaders as W,newDeviceId as E}from"./device.js";import{notSignedIn as G}from"./errors.js";export class SignedOut extends Error{}const K=6e4,p={waitMs:15e3,staleMs:3e4,stepMs:50},g=new Map;export function authServer(e){let n=g.get(e.url);return n||(n=(async()=>{const t=await e.fetch(`${e.url}${J}`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(!t.ok)throw new Error(`AllyHub's sign-in metadata answered ${String(t.status)}.`);return N.parse(await t.json())})(),n.catch(()=>g.delete(e.url)),g.set(e.url,n)),n}const V=y.object({revision:y.string().min(1),refreshToken:y.string().min(1),access:$.shape.access}),k=new Map;async function q(e,n,t){const r=k.get(e.credentialsFile);if(!t&&r?.revision===n)return r;if(e.keychain)try{const i=await e.keychain.get(),a=V.safeParse(i===void 0?void 0:JSON.parse(i));return!a.success||a.data.revision!==n?void 0:(k.set(e.credentialsFile,a.data),a.data)}catch{return}}export async function readCredentials(e,n=!1){for(let t=0;t<3;t+=1){let r;try{const a=$.safeParse(JSON.parse(await b(e.credentialsFile,"utf8")));if(!a.success||a.data.url!==e.url)return;r=a.data}catch{return}if(r.keychain===void 0)return r.refreshToken===void 0?void 0:{...r,refreshToken:r.refreshToken};const i=await q(e,r.keychain,n||t>0);if(i){const{access:a,refreshToken:o}=i;return{...r,refreshToken:o,...a?{access:a}:{}}}await new Promise(a=>setTimeout(a,p.stepMs))}}export async function writeCredentials(e,n){const{refreshToken:t,access:r,...i}=n,a={version:i.version,url:i.url,issuer:i.issuer,account:i.account,since:i.since};let o={...a,refreshToken:t,...r?{access:r}:{}};if(e.keychain){const f={revision:T(9).toString("base64url"),refreshToken:t,...r?{access:r}:{}},A=JSON.stringify(f);try{if(await e.keychain.set(A),await e.keychain.get()!==A)throw new Error(`${e.keychain.name} did not keep the sign-in.`);k.set(e.credentialsFile,f),o={...a,keychain:f.revision}}catch{}}const d=e.credentialsFile,u=`${JSON.stringify(o,null,2)}
3
- `,c=await O(d).catch(()=>{});if(c!==void 0&&(c.mode&511)===384&&await b(d,"utf8").catch(()=>{})===u)return;await m(x(d),{recursive:!0,mode:448});const s=`${d}.${T(6).toString("hex")}.tmp`;try{await z(s,u,{mode:384}),await C(s,384),await P(s,d)}finally{await h(s,{force:!0})}}export async function forgetCredentials(e,n){if(n!==void 0){const t=await readCredentials(e,!0);if(t!==void 0&&t.refreshToken!==n)return}await h(e.credentialsFile,{force:!0}),k.delete(e.credentialsFile),await e.keychain?.delete().catch(()=>{})}async function _(e,n){const t=`${e}.lock`;await m(x(e),{recursive:!0,mode:448});const r=Date.now()+p.waitMs;for(;;)try{await m(t);break}catch{const i=await O(t).catch(()=>{});if(i&&Date.now()-i.mtimeMs>p.staleMs){await h(t,{recursive:!0,force:!0});continue}if(Date.now()>r)throw new Error("Another AllyHub program holds the sign-in's lock.");await new Promise(a=>setTimeout(a,p.stepMs))}try{return await n()}finally{await h(t,{recursive:!0,force:!0})}}async function l(e,n,t,r,i={}){return e.fetch(n,{method:"POST",redirect:"error",headers:{...i,"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t).toString(),signal:r??AbortSignal.timeout(3e4)})}async function S(e){const n=await e.json().catch(()=>({}));if(e.ok)return B.parse(n);const t=L.safeParse(n);return{error:t.success?t.data.error:`http_${String(e.status)}`}}const D=e=>({token:e.access_token,expiresAt:new Date(Date.now()+e.expires_in*1e3).toISOString()});export async function accountOf(e,n){const t=await e.fetch(`${e.url}${I}`,{redirect:"error",headers:{authorization:`Bearer ${n}`,accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(t.status===401)throw new SignedOut("This computer is signed out of AllyHub.");if(!t.ok)throw new Error(`Reading the account: AllyHub answered ${String(t.status)}.`);const r=await t.json();return j.parse({id:r.id,email:r.email,...r.name?{name:r.name}:{},...r.organization?{organization:r.organization}:{}})}const Q=e=>e.client??"AllyHub",v=(e,n)=>W(Q(e),n),F=async e=>(await readCredentials(e).catch(()=>{}))?.device??E();async function H(e,n,t){if(n.refresh_token===void 0)throw new Error("AllyHub gave no refresh token.");const r=await authServer(e),i={version:1,url:e.url,issuer:r.issuer,account:await accountOf(e,n.access_token),refreshToken:n.refresh_token,access:D(n),since:new Date().toISOString(),device:t},a=await readCredentials(e).catch(()=>{});return await writeCredentials(e,i),a!==void 0&&a.refreshToken!==i.refreshToken&&await M(e,r.revocation_endpoint,a.refreshToken).then(o=>o.body?.cancel()).catch(()=>{}),i}const M=(e,n,t)=>l(e,n,{token:t,token_type_hint:"refresh_token",client_id:w});export async function signInWithCode(e,n){const t=await authServer(e),r=await F(e),i=await S(await l(e,t.token_endpoint,{grant_type:"authorization_code",client_id:w,code:n.code,redirect_uri:n.redirectUri,code_verifier:n.codeVerifier,resource:e.url},void 0,await v(e,r)));if("error"in i)throw new Error(`Signing in: AllyHub refused the code (${i.error}).`);return H(e,i,r)}export async function signInWithDevice(e,n,t){const r=await authServer(e),i=await l(e,r.device_authorization_endpoint,{client_id:w,scope:U,resource:e.url});if(!i.ok)throw new Error(`Asking for a device's code: AllyHub answered ${String(i.status)}.`);const a=R.parse(await i.json()),o=await F(e),d=await v(e,o);n(a);let u=(a.interval??5)*1e3;const c=Date.now()+a.expires_in*1e3;for(;Date.now()<c;){if(await new Promise(f=>setTimeout(f,u)),t?.aborted===!0)throw new Error("Signing in was stopped.");const s=await S(await l(e,r.token_endpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w,device_code:a.device_code,resource:e.url},void 0,d));if(!("error"in s))return H(e,s,o);if(s.error!=="authorization_pending"){if(s.error==="slow_down"){u+=5e3;continue}throw new Error(s.error==="access_denied"?"The sign-in was turned down.":`Signing in: AllyHub refused (${s.error}).`)}}throw new Error("The device's code ran out before it was entered.")}export async function accessOf(e,n={}){const t=o=>o?.access!==void 0&&o.access.token!==n.refused&&Date.parse(o.access.expiresAt)-K>Date.now()?{token:o.access.token,expiresAt:o.access.expiresAt,credentials:o}:void 0;let r=await readCredentials(e);if(!r||(e.keychain&&r.keychain===void 0&&(r=await _(e.credentialsFile,async()=>{const o=await readCredentials(e,!0);return o&&o.keychain===void 0&&await writeCredentials(e,o),o})),!r))return;const i=t(r);if(i)return i;const a=await authServer(e);return _(e.credentialsFile,async()=>{const o=await readCredentials(e,!0);if(!o)return;const d=t(o);if(d)return d;const u=o.device??E(),c=await S(await l(e,a.token_endpoint,{grant_type:"refresh_token",client_id:w,refresh_token:o.refreshToken,resource:e.url},void 0,await v(e,u)));if("error"in c)throw c.error==="invalid_grant"?(await forgetCredentials(e,o.refreshToken),new SignedOut("This computer is signed out of AllyHub.")):new Error(`Renewing the sign-in: AllyHub answered ${c.error}.`);const s={...o,refreshToken:c.refresh_token??o.refreshToken,access:D(c),device:u};return await writeCredentials(e,s),{token:s.access?.token??c.access_token,expiresAt:s.access?.expiresAt??"",credentials:s}})}export async function signOut(e,n){await forgetCredentials(e,n.refreshToken);const t=await authServer(e),r=await M(e,t.revocation_endpoint,n.refreshToken);if(await r.body?.cancel(),!r.ok&&r.status!==400)throw new Error(`Signing out: AllyHub answered ${String(r.status)}.`)}export async function chooseOrganization(e,n){await _(e.credentialsFile,async()=>{const t=await readCredentials(e,!0);if(!t)throw G();await writeCredentials(e,{...t,account:{...t.account,organization:n}})})}
2
+ import{randomBytes as T}from"node:crypto";import{chmod as C,mkdir as m,readFile as b,rename as P,rm as h,stat as O,writeFile as z}from"node:fs/promises";import{dirname as x}from"node:path";import*as y from"zod";import{ACCOUNT_PATH as I,AccountSchema as j,AuthServerSchema as N,CLIENT_ID as w,CredentialsFileSchema as $,DeviceAuthorizationSchema as R,METADATA_PATH as J,OAuthErrorSchema as L,SCOPES as U,TokenResponseSchema as B}from"@allyhub/protocol";import{deviceHeaders as W,newDeviceId as E}from"./device.js";import{notSignedIn as G}from"./errors.js";export class SignedOut extends Error{}const K=6e4,p={waitMs:15e3,staleMs:3e4,stepMs:50},g=new Map;export function authServer(e){let n=g.get(e.url);return n||(n=(async()=>{const t=await e.fetch(`${e.url}${J}`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(!t.ok)throw new Error(`AllyHub's sign-in metadata answered ${String(t.status)}.`);return N.parse(await t.json())})(),n.catch(()=>g.delete(e.url)),g.set(e.url,n)),n}const V=y.object({revision:y.string().min(1),refreshToken:y.string().min(1),access:$.shape.access}),k=new Map;async function q(e,n,t){const r=k.get(e.credentialsFile);if(!t&&r?.revision===n)return r;if(e.keychain)try{const i=await e.keychain.get(),a=V.safeParse(i===void 0?void 0:JSON.parse(i));return!a.success||a.data.revision!==n?void 0:(k.set(e.credentialsFile,a.data),a.data)}catch{return}}export async function readCredentials(e,n=!1){for(let t=0;t<3;t+=1){let r;try{const a=$.safeParse(JSON.parse(await b(e.credentialsFile,"utf8")));if(!a.success||a.data.url!==e.url)return;r=a.data}catch{return}if(r.keychain===void 0)return r.refreshToken===void 0?void 0:{...r,refreshToken:r.refreshToken};const i=await q(e,r.keychain,n||t>0);if(i){const{access:a,refreshToken:o}=i;return{...r,refreshToken:o,...a?{access:a}:{}}}await new Promise(a=>setTimeout(a,p.stepMs))}}export async function writeCredentials(e,n){const{refreshToken:t,access:r,...i}=n,a={version:i.version,url:i.url,issuer:i.issuer,account:i.account,since:i.since,...i.device===void 0?{}:{device:i.device}};let o={...a,refreshToken:t,...r?{access:r}:{}};if(e.keychain){const f={revision:T(9).toString("base64url"),refreshToken:t,...r?{access:r}:{}},A=JSON.stringify(f);try{if(await e.keychain.set(A),await e.keychain.get()!==A)throw new Error(`${e.keychain.name} did not keep the sign-in.`);k.set(e.credentialsFile,f),o={...a,keychain:f.revision}}catch{}}const d=e.credentialsFile,u=`${JSON.stringify(o,null,2)}
3
+ `,c=await O(d).catch(()=>{});if(c!==void 0&&(c.mode&511)===384&&await b(d,"utf8").catch(()=>{})===u)return;await m(x(d),{recursive:!0,mode:448});const s=`${d}.${T(6).toString("hex")}.tmp`;try{await z(s,u,{mode:384}),await C(s,384),await P(s,d)}finally{await h(s,{force:!0})}}export async function forgetCredentials(e,n){if(n!==void 0){const t=await readCredentials(e,!0);if(t!==void 0&&t.refreshToken!==n)return}await h(e.credentialsFile,{force:!0}),k.delete(e.credentialsFile),await e.keychain?.delete().catch(()=>{})}async function _(e,n){const t=`${e}.lock`;await m(x(e),{recursive:!0,mode:448});const r=Date.now()+p.waitMs;for(;;)try{await m(t);break}catch{const i=await O(t).catch(()=>{});if(i&&Date.now()-i.mtimeMs>p.staleMs){await h(t,{recursive:!0,force:!0});continue}if(Date.now()>r)throw new Error("Another AllyHub program holds the sign-in's lock.");await new Promise(a=>setTimeout(a,p.stepMs))}try{return await n()}finally{await h(t,{recursive:!0,force:!0})}}async function l(e,n,t,r,i={}){return e.fetch(n,{method:"POST",redirect:"error",headers:{...i,"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t).toString(),signal:r??AbortSignal.timeout(3e4)})}async function v(e){const n=await e.json().catch(()=>({}));if(e.ok)return B.parse(n);const t=L.safeParse(n);return{error:t.success?t.data.error:`http_${String(e.status)}`}}const D=e=>({token:e.access_token,expiresAt:new Date(Date.now()+e.expires_in*1e3).toISOString()});export async function accountOf(e,n){const t=await e.fetch(`${e.url}${I}`,{redirect:"error",headers:{authorization:`Bearer ${n}`,accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(t.status===401)throw new SignedOut("This computer is signed out of AllyHub.");if(!t.ok)throw new Error(`Reading the account: AllyHub answered ${String(t.status)}.`);const r=await t.json();return j.parse({id:r.id,email:r.email,...r.name?{name:r.name}:{},...r.organization?{organization:r.organization}:{}})}const Q=e=>e.client??"AllyHub",S=(e,n)=>W(Q(e),n),F=async e=>(await readCredentials(e).catch(()=>{}))?.device??E();async function H(e,n,t){if(n.refresh_token===void 0)throw new Error("AllyHub gave no refresh token.");const r=await authServer(e),i={version:1,url:e.url,issuer:r.issuer,account:await accountOf(e,n.access_token),refreshToken:n.refresh_token,access:D(n),since:new Date().toISOString(),device:t},a=await readCredentials(e).catch(()=>{});return await writeCredentials(e,i),a!==void 0&&a.device===void 0&&a.refreshToken!==i.refreshToken&&await M(e,r.revocation_endpoint,a.refreshToken).then(o=>o.body?.cancel()).catch(()=>{}),i}const M=(e,n,t)=>l(e,n,{token:t,token_type_hint:"refresh_token",client_id:w});export async function signInWithCode(e,n){const t=await authServer(e),r=await F(e),i=await v(await l(e,t.token_endpoint,{grant_type:"authorization_code",client_id:w,code:n.code,redirect_uri:n.redirectUri,code_verifier:n.codeVerifier,resource:e.url},void 0,await S(e,r)));if("error"in i)throw new Error(`Signing in: AllyHub refused the code (${i.error}).`);return H(e,i,r)}export async function signInWithDevice(e,n,t){const r=await authServer(e),i=await l(e,r.device_authorization_endpoint,{client_id:w,scope:U,resource:e.url});if(!i.ok)throw new Error(`Asking for a device's code: AllyHub answered ${String(i.status)}.`);const a=R.parse(await i.json()),o=await F(e),d=await S(e,o);n(a);let u=(a.interval??5)*1e3;const c=Date.now()+a.expires_in*1e3;for(;Date.now()<c;){if(await new Promise(f=>setTimeout(f,u)),t?.aborted===!0)throw new Error("Signing in was stopped.");const s=await v(await l(e,r.token_endpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:w,device_code:a.device_code,resource:e.url},void 0,d));if(!("error"in s))return H(e,s,o);if(s.error!=="authorization_pending"){if(s.error==="slow_down"){u+=5e3;continue}throw new Error(s.error==="access_denied"?"The sign-in was turned down.":`Signing in: AllyHub refused (${s.error}).`)}}throw new Error("The device's code ran out before it was entered.")}export async function accessOf(e,n={}){const t=o=>o?.access!==void 0&&o.access.token!==n.refused&&Date.parse(o.access.expiresAt)-K>Date.now()?{token:o.access.token,expiresAt:o.access.expiresAt,credentials:o}:void 0;let r=await readCredentials(e);if(!r||(e.keychain&&r.keychain===void 0&&(r=await _(e.credentialsFile,async()=>{const o=await readCredentials(e,!0);return o&&o.keychain===void 0&&await writeCredentials(e,o),o})),!r))return;const i=t(r);if(i)return i;const a=await authServer(e);return _(e.credentialsFile,async()=>{const o=await readCredentials(e,!0);if(!o)return;const d=t(o);if(d)return d;const u=o.device??E(),c=await v(await l(e,a.token_endpoint,{grant_type:"refresh_token",client_id:w,refresh_token:o.refreshToken,resource:e.url},void 0,await S(e,u)));if("error"in c)throw c.error==="invalid_grant"?(await forgetCredentials(e,o.refreshToken),new SignedOut("This computer is signed out of AllyHub.")):new Error(`Renewing the sign-in: AllyHub answered ${c.error}.`);const s={...o,refreshToken:c.refresh_token??o.refreshToken,access:D(c),device:u};return await writeCredentials(e,s),{token:s.access?.token??c.access_token,expiresAt:s.access?.expiresAt??"",credentials:s}})}export async function signOut(e,n){await forgetCredentials(e,n.refreshToken);const t=await authServer(e),r=await M(e,t.revocation_endpoint,n.refreshToken);if(await r.body?.cancel(),!r.ok&&r.status!==400)throw new Error(`Signing out: AllyHub answered ${String(r.status)}.`)}export async function chooseOrganization(e,n){await _(e.credentialsFile,async()=>{const t=await readCredentials(e,!0);if(!t)throw G();await writeCredentials(e,{...t,account:{...t.account,organization:n}})})}
@@ -7,6 +7,8 @@ export interface Computer {
7
7
  export declare function thisComputer(): Promise<Computer>;
8
8
  /** A new sign-in's id (DEVICE_HEADER). */
9
9
  export declare const newDeviceId: () => string;
10
+ /** The program and the system as a User-Agent (RFC 9110 §10.1.5): `AllyHub-Studio/0.9.1 (macOS 26.1; arm64)`. */
11
+ export declare function userAgent(client: string): Promise<string>;
10
12
  /** What a token request says of the computer, for the sign-in `device`, from the program `client` ("AllyHub-Studio/0.9.1"). */
11
13
  export declare function deviceHeaders(client: string, device: string): Promise<Record<string, string>>;
12
14
  //# sourceMappingURL=device.d.ts.map
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{execFile as u}from"node:child_process";import{randomBytes as l}from"node:crypto";import{arch as p,hostname as d,platform as s,release as r}from"node:os";import{DEVICE_HEADER as w,DEVICE_NAME_HEADER as f}from"@allyhub/protocol";const a=(e,t)=>new Promise(n=>{u(e,t,{timeout:2e3},(m,c)=>{const o=c.trim();n(m===null&&o!==""?o:void 0)})});let i;export function thisComputer(){return i??=(async()=>{const e=d().replace(/\.local$/u,"");switch(s()){case"darwin":{const[t,n]=await Promise.all([a("/usr/sbin/scutil",["--get","ComputerName"]),a("/usr/bin/sw_vers",["-productVersion"])]);return{name:t??e,os:`macOS ${n??r()}`}}case"win32":return{name:e,os:`Windows ${r()}`};case"linux":return{name:e,os:`Linux ${r()}`};default:return{name:e,os:`${s()} ${r()}`}}})(),i}export const newDeviceId=()=>l(18).toString("base64url");export async function deviceHeaders(e,t){const n=await thisComputer();return{"user-agent":`${e} (${n.os}; ${p()})`,[w]:t,[f]:encodeURIComponent(n.name)}}
2
+ import{execFile as m}from"node:child_process";import{randomBytes as l}from"node:crypto";import{arch as p,hostname as w,platform as s,release as r}from"node:os";import{DEVICE_HEADER as d,DEVICE_NAME_HEADER as f}from"@allyhub/protocol";const a=(e,t)=>new Promise(n=>{m(e,t,{timeout:2e3},(c,u)=>{const o=u.trim();n(c===null&&o!==""?o:void 0)})});let i;export function thisComputer(){return i??=(async()=>{const e=w().replace(/\.local$/u,"");switch(s()){case"darwin":{const[t,n]=await Promise.all([a("/usr/sbin/scutil",["--get","ComputerName"]),a("/usr/bin/sw_vers",["-productVersion"])]);return{name:t??e,os:`macOS ${n??r()}`}}case"win32":return{name:e,os:`Windows ${r()}`};case"linux":return{name:e,os:`Linux ${r()}`};default:return{name:e,os:`${s()} ${r()}`}}})(),i}export const newDeviceId=()=>l(18).toString("base64url");export async function userAgent(e){const t=await thisComputer();return`${e} (${t.os}; ${p()})`}export async function deviceHeaders(e,t){const n=await thisComputer();return{"user-agent":await userAgent(e),[d]:t,[f]:encodeURIComponent(n.name)}}
@@ -32,7 +32,7 @@ export declare function readGen(file: string): Promise<GenFile | undefined>;
32
32
  /**
33
33
  * The file a name stands for. A name with an extension is that file; one
34
34
  * without takes the result's extension, so before the call it is found by
35
- * its record (`<name>.<ext>.gen.json`), else any `<name>.<ext>`.
35
+ * its record (`<name>.<ext>.provenance`), else any `<name>.<ext>`.
36
36
  */
37
37
  export declare function namedFile(name: string): Promise<string | undefined>;
38
38
  /** The words of a voice tool's output (`words`: text, start and end in seconds); undefined when it returned none. */
@@ -11,6 +11,12 @@ export declare const SIGN_IN_WAIT_MS: number;
11
11
  export interface SignInHint {
12
12
  with?: "google" | undefined;
13
13
  email?: string | undefined;
14
+ /**
15
+ * The sign-in is the desktop app's, and its link opens it (the
16
+ * protocol's DESKTOP_OPEN): the page the browser lands on offers to
17
+ * bring the app forward.
18
+ */
19
+ desktop?: boolean | undefined;
14
20
  }
15
21
  /** Opens an address in this computer's browser; BROWSER=none opens nothing. */
16
22
  export declare function openBrowser(url: string, env: Readonly<Record<string, string | undefined>>): void;
@@ -23,10 +29,12 @@ export declare function signIn(cloud: Cloud, onUrl: (url: string) => void, timeo
23
29
  * address it does not know): the link's destination is this sign-in's
24
30
  * authorization, so following it in a browser on this computer signs that
25
31
  * browser in and sends the code straight back, with no page to fill in.
26
- * `onSent` is told once the link is on its way; then it waits for the
27
- * browser.
32
+ * Asked for at AllyHub's route for a program's sign-in link (the
33
+ * protocol's SIGN_IN_LINK_PATH), as the program it is. `onSent` is told
34
+ * once the link is on its way; then it waits for the browser. `hint` says
35
+ * whether the sign-in is the desktop app's.
28
36
  */
29
- export declare function signInByEmail(cloud: Cloud, email: string, onSent: () => void, timeoutMs?: number): Promise<Account>;
37
+ export declare function signInByEmail(cloud: Cloud, email: string, onSent: () => void, timeoutMs?: number, hint?: Pick<SignInHint, "desktop">): Promise<Account>;
30
38
  /** Signs in with a device's code (RFC 8628): `show` is given the code and where to enter it; it waits until the person has. */
31
39
  export declare function signInDevice(cloud: Cloud, show: (device: DeviceAuthorization) => void, signal?: AbortSignal): Promise<Account>;
32
40
  /**
@@ -1,4 +1,4 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{spawn as k}from"node:child_process";import{mkdtemp as j,open as E,readFile as u,rename as O,rm as m,writeFile as T}from"node:fs/promises";import{tmpdir as b}from"node:os";import{join as c}from"node:path";import{fileURLToPath as N}from"node:url";import{CLIENT_ID as R,EXIT as g,SCOPES as L}from"@allyhub/protocol";import{accessOf as P,authServer as v,SignedOut as $,signInWithCode as D,signInWithDevice as W}from"./credentials.js";import{nodeCommand as C}from"@allyhub/runtimes/node";import{CloudError as f,unreachable as w}from"./errors.js";import{LoopbackError as J,startLoopback as p}from"./loopback.js";import{pkcePair as A,randomState as B}from"./pkce.js";const F="idp_hint";export const SIGN_IN_WAIT_MS=5*6e4;const M=3e4;function h(){return{state:B(),...A()}}async function y(t,i,o,n={}){const e=await v(t),r=new URLSearchParams({response_type:"code",client_id:R,redirect_uri:o,scope:L,state:i.state,code_challenge:i.challenge,code_challenge_method:"S256",resource:t.url});return n.with!==void 0&&r.set(F,n.with),n.email!==void 0&&r.set("login_hint",n.email),`${e.authorization_endpoint}?${r.toString()}`}export function openBrowser(t,i){if(i.BROWSER==="none")return;const[o,n]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{const e=k(o,n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}export async function signedInAs(t){try{return(await P(t.config))?.credentials.account}catch(i){if(i instanceof $)return;throw w(t.url,i)}}const S=t=>new f(t instanceof J?t.code:"sign-in-failed",t instanceof Error?t.message:String(t),{exit:g.auth,hint:"Run allyhub auth login again."});async function I(t,i,o){let n;try{n=await o.result}catch(r){throw S(r)}let e;try{e=(await D(t,{code:n,codeVerifier:i.verifier,redirectUri:o.redirectUri})).account}catch(r){const a=S(r);throw await o.finish(a),a}return await o.finish(),e}const _=t=>`${t.url}/signed-in`;export async function signIn(t,i,o=SIGN_IN_WAIT_MS,n={}){const e=h(),r=await p({state:e.state,timeoutMs:o,landing:_(t.config)});try{i(await y(t.config,e,r.redirectUri,n))}catch(a){throw await r.close(),w(t.url,a)}return I(t.config,e,r)}export async function signInByEmail(t,i,o,n=SIGN_IN_WAIT_MS){const e=t.config,r=h(),a=await p({state:r.state,timeoutMs:n,landing:_(e)});try{const s=await y(e,r,a.redirectUri),d=await e.fetch(`${e.url}/api/auth/sign-in/magic-link`,{method:"POST",headers:{"content-type":"application/json",origin:e.url},body:JSON.stringify({email:i,callbackURL:s})});if(!d.ok)throw new f("sign-in-failed",`AllyHub did not send the link (${String(d.status)}): ${(await d.text()).slice(0,300)}`,{exit:g.auth,status:d.status});await d.body?.cancel()}catch(s){throw await a.close(),s instanceof f?s:w(t.url,s)}return o(),I(e,r,a)}export async function signInDevice(t,i,o){try{return(await W(t.config,i,o)).account}catch(n){throw S(n)}}const z=N(new URL("./signin-worker.js",import.meta.url));export async function signInInBackground(t,i,o=SIGN_IN_WAIT_MS){const n=h(),e=await j(c(b(),"allyhub-sign-in-"));await T(c(e,"flow.json"),JSON.stringify({flow:n,timeoutMs:o}),{mode:384});const r=await E(c(e,"worker.log"),"w"),a=k(C(i),[z,e],{detached:!0,stdio:["ignore","ignore",r.fd],env:{...i}});await r.close();const s={exited:!1};a.once("exit",()=>{s.exited=!0}),a.unref();const d=Date.now()+M;for(;Date.now()<d;)try{const l=JSON.parse(await u(c(e,"ready.json"),"utf8"));return await y(t.config,n,l.redirectUri)}catch(l){if(l instanceof Error&&!("code"in l))throw w(t.url,l);if(s.exited)break;await new Promise(U=>setTimeout(U,50))}const x=(await u(c(e,"worker.log"),"utf8").catch(()=>"")).trim().split(`
2
+ import{spawn as k}from"node:child_process";import{mkdtemp as j,open as E,readFile as m,rename as O,rm as g,writeFile as N}from"node:fs/promises";import{tmpdir as U}from"node:os";import{join as s}from"node:path";import{fileURLToPath as b}from"node:url";import{CLIENT_ID as P,EXIT as p,SCOPES as L,SIGN_IN_LINK_PATH as R,signedInAddress as v}from"@allyhub/protocol";import{accessOf as $,authServer as A,SignedOut as D,signInWithCode as W,signInWithDevice as C}from"./credentials.js";import{nodeCommand as J}from"@allyhub/runtimes/node";import{CloudError as l,unreachable as u}from"./errors.js";import{LoopbackError as B,startLoopback as h}from"./loopback.js";import{pkcePair as z,randomState as F}from"./pkce.js";const H="idp_hint";export const SIGN_IN_WAIT_MS=5*6e4;const M=3e4;function y(){return{state:F(),...z()}}async function I(t,e,o,r={}){const i=await A(t),n=new URLSearchParams({response_type:"code",client_id:P,redirect_uri:o,scope:L,state:e.state,code_challenge:e.challenge,code_challenge_method:"S256",resource:t.url});return r.with!==void 0&&n.set(H,r.with),r.email!==void 0&&n.set("login_hint",r.email),`${i.authorization_endpoint}?${n.toString()}`}export function openBrowser(t,e){if(e.BROWSER==="none")return;const[o,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{const i=k(o,r,{stdio:"ignore",detached:!0});i.on("error",()=>{}),i.unref()}catch{}}export async function signedInAs(t){try{return(await $(t.config))?.credentials.account}catch(e){if(e instanceof D)return;throw u(t.url,e)}}const S=t=>new l(t instanceof B?t.code:"sign-in-failed",t instanceof Error?t.message:String(t),{exit:p.auth,hint:"Run allyhub auth login again."});async function _(t,e,o){let r;try{r=await o.result}catch(n){throw S(n)}let i;try{i=(await W(t,{code:r,codeVerifier:e.verifier,redirectUri:o.redirectUri})).account}catch(n){const a=S(n);throw await o.finish(a),a}return await o.finish(),i}const x=(t,e={})=>v(t.url,{desktop:e.desktop});export async function signIn(t,e,o=SIGN_IN_WAIT_MS,r={}){const i=y(),n=await h({state:i.state,timeoutMs:o,landing:x(t.config,r)});try{e(await I(t.config,i,n.redirectUri,r))}catch(a){throw await n.close(),u(t.url,a)}return _(t.config,i,n)}export async function signInByEmail(t,e,o,r=SIGN_IN_WAIT_MS,i={}){const n=t.config,a=y(),f=await h({state:a.state,timeoutMs:r,landing:x(n,i)});try{const d={email:e,authorization:await I(n,a,f.redirectUri)},c=await n.fetch(`${n.url}${R}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(d)});if(!c.ok)throw new l("sign-in-failed",`AllyHub did not send the link (${String(c.status)}): ${(await c.text()).slice(0,300)}`,{exit:p.auth,status:c.status});await c.body?.cancel()}catch(d){throw await f.close(),d instanceof l?d:u(t.url,d)}return o(),_(n,a,f)}export async function signInDevice(t,e,o){try{return(await C(t.config,e,o)).account}catch(r){throw S(r)}}const G=b(new URL("./signin-worker.js",import.meta.url));export async function signInInBackground(t,e,o=SIGN_IN_WAIT_MS){const r=y(),i=await j(s(U(),"allyhub-sign-in-"));await N(s(i,"flow.json"),JSON.stringify({flow:r,timeoutMs:o}),{mode:384});const n=await E(s(i,"worker.log"),"w"),a=k(J(e),[G,i],{detached:!0,stdio:["ignore","ignore",n.fd],env:{...e}});await n.close();const f={exited:!1};a.once("exit",()=>{f.exited=!0}),a.unref();const d=Date.now()+M;for(;Date.now()<d;)try{const w=JSON.parse(await m(s(i,"ready.json"),"utf8"));return await I(t.config,r,w.redirectUri)}catch(w){if(w instanceof Error&&!("code"in w))throw u(t.url,w);if(f.exited)break;await new Promise(T=>setTimeout(T,50))}const c=(await m(s(i,"worker.log"),"utf8").catch(()=>"")).trim().split(`
3
3
  `).slice(-5).join(`
4
- `);throw await m(e,{recursive:!0,force:!0}),new f("sign-in-failed",x?`The sign-in listener did not start: ${x}`:"The sign-in listener did not start.",{exit:g.platform})}export async function serveSignIn(t,i){const{flow:o,timeoutMs:n}=JSON.parse(await u(c(i,"flow.json"),"utf8"));await m(c(i,"flow.json"),{force:!0});const e=await p({state:o.state,timeoutMs:n,landing:_(t)});await T(c(i,"ready.json.tmp"),JSON.stringify({redirectUri:e.redirectUri})),await O(c(i,"ready.json.tmp"),c(i,"ready.json"));try{await I(t,o,e)}finally{await new Promise(r=>setTimeout(r,200)),await m(i,{recursive:!0,force:!0})}}
4
+ `);throw await g(i,{recursive:!0,force:!0}),new l("sign-in-failed",c?`The sign-in listener did not start: ${c}`:"The sign-in listener did not start.",{exit:p.platform})}export async function serveSignIn(t,e){const{flow:o,timeoutMs:r}=JSON.parse(await m(s(e,"flow.json"),"utf8"));await g(s(e,"flow.json"),{force:!0});const i=await h({state:o.state,timeoutMs:r,landing:x(t)});await N(s(e,"ready.json.tmp"),JSON.stringify({redirectUri:i.redirectUri})),await O(s(e,"ready.json.tmp"),s(e,"ready.json"));try{await _(t,o,i)}finally{await new Promise(n=>setTimeout(n,200)),await g(e,{recursive:!0,force:!0})}}
@@ -2,7 +2,7 @@ import type { Cloud } from "./client.js";
2
2
  import { CloudError } from "./errors.js";
3
3
  /** The media types an upload is sent as, by extension: what media tools take. */
4
4
  export declare const UPLOAD_TYPES: Readonly<Record<string, string>>;
5
- /** A URL this computer got for a file is given again while it has this much time left. */
5
+ /** A URL this computer got for a file is given again while it has this much time left: an hour of the two AllyHub gives it, which keeps the file as long. */
6
6
  export declare const REUSE_LEFT_MS: number;
7
7
  /** How many files of a batch are sent at once. */
8
8
  export declare const UPLOAD_CONCURRENCY = 4;
@@ -1,3 +1,3 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{createHash as b}from"node:crypto";import{chmod as U,mkdir as F,readFile as x,realpath as S,stat as P,writeFile as C}from"node:fs/promises";import{basename as D,dirname as N,extname as _,isAbsolute as L,join as R,relative as A,resolve as g}from"node:path";import{EXIT as $,FILES_PATH as M,FILE_MAX_BYTES as O,FileContentResponseSchema as z,FileCreatedSchema as v,UploadedFileSchema as X,fileContentPath as q,fileDonePath as H}from"@allyhub/protocol";import{CloudError as p}from"./errors.js";export const UPLOAD_TYPES={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",mp3:"audio/mpeg",wav:"audio/wav",m4a:"audio/mp4",aac:"audio/aac",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm"},REUSE_LEFT_MS=7200*1e3;const K=720*60*60*1e3;export const UPLOAD_CONCURRENCY=4;const Y=Object.keys(UPLOAD_TYPES).map(e=>`.${e}`).join(", ");async function j(e){const t=(await e.key())?.account??"",i=b("sha256").update(`${e.url}
3
- ${t}`).digest("hex").slice(0,12);return R(e.config.cacheDir,`uploads-${i}.json`)}async function E(e){try{const t=JSON.parse(await x(e,"utf8"));return{files:t.files??{},urls:t.urls??{}}}catch{return{files:{},urls:{}}}}async function J(e,t){const i=Date.now();for(const[c,o]of Object.entries(t.urls))i-Date.parse(o.expiresAt??o.at)>K&&Reflect.deleteProperty(t.urls,c);await F(N(e),{recursive:!0}),await C(e,JSON.stringify(t),{mode:384}),await U(e,384)}export function urlExpiry(e){let t;try{t=new URL(e).searchParams}catch{return}const i=/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/u.exec(t.get("X-Amz-Date")??""),c=Number(t.get("X-Amz-Expires"));if(!i||!Number.isFinite(c)||c<=0)return;const[o,r,l,a,n,u]=i.slice(1).map(Number);return new Date(Date.UTC(o,r-1,l,a,n,u)+c*1e3).toISOString()}const T=async e=>await S(g(e)).catch(()=>g(e)),y=(e,t)=>{const i=A(e,t);return i.startsWith("..")||L(i)},w=(e,t)=>new p("bad-input",e,{exit:$.usage,...t===void 0?{}:{hint:t}});async function W(e,t){const i=g(t.base,e),c=()=>w(`${e} is not inside ${String(t.inside)}.`,"Upload a file of the project.");if(t.inside!==void 0&&y(g(t.inside),i))throw c();const o=await P(i).catch(()=>{});if(!o?.isFile())throw w(`There is no file ${i}.`,"A relative path is read from the folder it is run in.");const r=await S(i);if(t.inside!==void 0&&y(await T(t.inside),r))throw c();const l=_(r).slice(1).toLowerCase(),a=UPLOAD_TYPES[l];if(a===void 0)throw w(`${e} is a${l?` .${l}`:"n unnamed"} file; an upload is one of ${Y}.`,"Convert it first, for example with ffmpeg.");if(o.size>O)throw w(`${e} is ${String(o.size)} bytes; AllyHub keeps files of at most ${String(O)}.`,"Make it smaller first, for example with ffmpeg.");const n=await x(r);return{given:e,path:r,type:a,sha256:b("sha256").update(n).digest("hex"),bytes:n}}async function B(e,t,i){const c=new Array(e.length);let o=0;const r=async()=>{for(;o<e.length;){const l=o++;c[l]=await i(e[l])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},r)),c}async function k(e,t,i,c){const o=i.files[t.sha256];if(o&&!c)return{fileId:o.fileId,known:!0};const r={name:D(t.path),size:t.bytes.length,sha256:t.sha256,contentType:t.type},l=v.parse(await e.json(M,{method:"POST",body:r}));if(l.upload!==null){const n=await e.config.fetch(l.upload.url,{method:"PUT",headers:l.upload.headers,body:new Uint8Array(t.bytes),signal:AbortSignal.timeout(3e5)});if(!n.ok)throw new p("upload-failed",`Storage refused ${t.given}: ${String(n.status)} ${(await n.text()).slice(0,200)}`,{exit:$.platform})}const a=X.parse(await e.json(H(l.id),{method:"POST"}));return i.files[t.sha256]={fileId:a.id,path:t.path,bytes:t.bytes.length},{fileId:a.id,known:!1}}const I=async(e,t)=>z.parse(await e.json(q(t,"inline"))).url;export async function uploadFiles(e,t,i){if(t.length===0)throw w("Name at least one file to upload.");const c=[];for(const a of t)c.push(await W(a,{base:i.base,...i.inside===void 0?{}:{inside:i.inside}}));await e.requireKey();const o=await j(e),r=await E(o),l=await B(c,i.concurrency??UPLOAD_CONCURRENCY,async a=>{const n=(s,d,f,m,h)=>({ok:!0,file:a.given,path:a.path,fileId:s,url:d,...f===void 0?{}:{expiresAt:f},sha256:a.sha256,bytes:a.bytes.length,contentType:a.type,known:m,reused:h}),u=r.files[a.sha256];if(u){const s=Date.now(),d=Object.entries(r.urls).find(([,f])=>f.sha256===a.sha256&&f.expiresAt!==void 0&&Date.parse(f.expiresAt)-s>=REUSE_LEFT_MS);if(d)return u.path=a.path,n(u.fileId,d[0],d[1].expiresAt,!0,!0)}try{let s=await k(e,a,r,!1),d;try{d=await I(e,s.fileId)}catch(h){if(!s.known||!(h instanceof p)||h.code!=="api-error")throw h;s=await k(e,a,r,!0),d=await I(e,s.fileId)}const f=urlExpiry(d);r.urls[d]={sha256:a.sha256,...f===void 0?{}:{expiresAt:f},at:new Date().toISOString()};const m=r.files[a.sha256];return m&&(m.path=a.path),n(s.fileId,d,f,s.known,!1)}catch(s){if(!(s instanceof p)||s.code==="not-signed-in")throw s;return{ok:!1,file:a.given,error:new p(s.code==="api-error"?"upload-failed":s.code,`Uploading ${a.given} failed. ${s.message}`,{exit:s.exit,...s.hint?{hint:s.hint}:{}})}}});return await J(o,r),l}export async function withKnownUploads(e,t,i){const c=await E(await j(e)),o=await T(i),r=n=>y(o,n)?n:A(o,n),l=new Map;for(const[n,u]of Object.entries(c.urls)){const s=c.files[u.sha256];s&&l.set(n,{uploaded:r(s.path),sha256:u.sha256,bytes:s.bytes})}const a=n=>typeof n=="string"?l.get(n)??n:Array.isArray(n)?n.map(a):typeof n=="object"&&n!==null?Object.fromEntries(Object.entries(n).map(([u,s])=>[u,a(s)])):n;return a(t)}
2
+ import{createHash as b}from"node:crypto";import{chmod as U,mkdir as F,readFile as x,realpath as S,stat as P,writeFile as C}from"node:fs/promises";import{basename as D,dirname as N,extname as _,isAbsolute as L,join as R,relative as A,resolve as g}from"node:path";import{EXIT as $,FILES_PATH as M,FILE_MAX_BYTES as O,FileContentResponseSchema as z,FileCreatedSchema as v,UploadedFileSchema as X,fileContentPath as q,fileDonePath as H}from"@allyhub/protocol";import{CloudError as p}from"./errors.js";export const UPLOAD_TYPES={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",mp3:"audio/mpeg",wav:"audio/wav",m4a:"audio/mp4",aac:"audio/aac",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm"},REUSE_LEFT_MS=3600*1e3;const K=720*60*60*1e3;export const UPLOAD_CONCURRENCY=4;const Y=Object.keys(UPLOAD_TYPES).map(e=>`.${e}`).join(", ");async function j(e){const t=(await e.key())?.account??"",i=b("sha256").update(`${e.url}
3
+ ${t}`).digest("hex").slice(0,12);return R(e.config.cacheDir,`uploads-${i}.json`)}async function E(e){try{const t=JSON.parse(await x(e,"utf8"));return{files:t.files??{},urls:t.urls??{}}}catch{return{files:{},urls:{}}}}async function J(e,t){const i=Date.now();for(const[c,o]of Object.entries(t.urls))i-Date.parse(o.expiresAt??o.at)>K&&Reflect.deleteProperty(t.urls,c);await F(N(e),{recursive:!0}),await C(e,JSON.stringify(t),{mode:384}),await U(e,384)}export function urlExpiry(e){let t;try{t=new URL(e).searchParams}catch{return}const i=/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/u.exec(t.get("X-Amz-Date")??""),c=Number(t.get("X-Amz-Expires"));if(!i||!Number.isFinite(c)||c<=0)return;const[o,r,l,a,n,u]=i.slice(1).map(Number);return new Date(Date.UTC(o,r-1,l,a,n,u)+c*1e3).toISOString()}const T=async e=>await S(g(e)).catch(()=>g(e)),y=(e,t)=>{const i=A(e,t);return i.startsWith("..")||L(i)},w=(e,t)=>new p("bad-input",e,{exit:$.usage,...t===void 0?{}:{hint:t}});async function W(e,t){const i=g(t.base,e),c=()=>w(`${e} is not inside ${String(t.inside)}.`,"Upload a file of the project.");if(t.inside!==void 0&&y(g(t.inside),i))throw c();const o=await P(i).catch(()=>{});if(!o?.isFile())throw w(`There is no file ${i}.`,"A relative path is read from the folder it is run in.");const r=await S(i);if(t.inside!==void 0&&y(await T(t.inside),r))throw c();const l=_(r).slice(1).toLowerCase(),a=UPLOAD_TYPES[l];if(a===void 0)throw w(`${e} is a${l?` .${l}`:"n unnamed"} file; an upload is one of ${Y}.`,"Convert it first, for example with ffmpeg.");if(o.size>O)throw w(`${e} is ${String(o.size)} bytes; AllyHub keeps files of at most ${String(O)}.`,"Make it smaller first, for example with ffmpeg.");const n=await x(r);return{given:e,path:r,type:a,sha256:b("sha256").update(n).digest("hex"),bytes:n}}async function B(e,t,i){const c=new Array(e.length);let o=0;const r=async()=>{for(;o<e.length;){const l=o++;c[l]=await i(e[l])}};return await Promise.all(Array.from({length:Math.min(t,e.length)},r)),c}async function k(e,t,i,c){const o=i.files[t.sha256];if(o&&!c)return{fileId:o.fileId,known:!0};const r={name:D(t.path),size:t.bytes.length,sha256:t.sha256,contentType:t.type},l=v.parse(await e.json(M,{method:"POST",body:r}));if(l.upload!==null){const n=await e.config.fetch(l.upload.url,{method:"PUT",headers:l.upload.headers,body:new Uint8Array(t.bytes),signal:AbortSignal.timeout(3e5)});if(!n.ok)throw new p("upload-failed",`Storage refused ${t.given}: ${String(n.status)} ${(await n.text()).slice(0,200)}`,{exit:$.platform})}const a=X.parse(await e.json(H(l.id),{method:"POST"}));return i.files[t.sha256]={fileId:a.id,path:t.path,bytes:t.bytes.length},{fileId:a.id,known:!1}}const I=async(e,t)=>z.parse(await e.json(q(t,"inline"))).url;export async function uploadFiles(e,t,i){if(t.length===0)throw w("Name at least one file to upload.");const c=[];for(const a of t)c.push(await W(a,{base:i.base,...i.inside===void 0?{}:{inside:i.inside}}));await e.requireKey();const o=await j(e),r=await E(o),l=await B(c,i.concurrency??UPLOAD_CONCURRENCY,async a=>{const n=(s,d,f,m,h)=>({ok:!0,file:a.given,path:a.path,fileId:s,url:d,...f===void 0?{}:{expiresAt:f},sha256:a.sha256,bytes:a.bytes.length,contentType:a.type,known:m,reused:h}),u=r.files[a.sha256];if(u){const s=Date.now(),d=Object.entries(r.urls).find(([,f])=>f.sha256===a.sha256&&f.expiresAt!==void 0&&Date.parse(f.expiresAt)-s>=REUSE_LEFT_MS);if(d)return u.path=a.path,n(u.fileId,d[0],d[1].expiresAt,!0,!0)}try{let s=await k(e,a,r,!1),d;try{d=await I(e,s.fileId)}catch(h){if(!s.known||!(h instanceof p)||h.status!==404)throw h;s=await k(e,a,r,!0),d=await I(e,s.fileId)}const f=urlExpiry(d);r.urls[d]={sha256:a.sha256,...f===void 0?{}:{expiresAt:f},at:new Date().toISOString()};const m=r.files[a.sha256];return m&&(m.path=a.path),n(s.fileId,d,f,s.known,!1)}catch(s){if(!(s instanceof p)||s.code==="not-signed-in")throw s;return{ok:!1,file:a.given,error:new p(s.code==="api-error"?"upload-failed":s.code,`Uploading ${a.given} failed. ${s.message}`,{exit:s.exit,...s.hint?{hint:s.hint}:{}})}}});return await J(o,r),l}export async function withKnownUploads(e,t,i){const c=await E(await j(e)),o=await T(i),r=n=>y(o,n)?n:A(o,n),l=new Map;for(const[n,u]of Object.entries(c.urls)){const s=c.files[u.sha256];s&&l.set(n,{uploaded:r(s.path),sha256:u.sha256,bytes:s.bytes})}const a=n=>typeof n=="string"?l.get(n)??n:Array.isArray(n)?n.map(a):typeof n=="object"&&n!==null?Object.fromEntries(Object.entries(n).map(([u,s])=>[u,a(s)])):n;return a(t)}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/cloud",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/components",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
@@ -1,2 +1,2 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{rm as f}from"node:fs/promises";import{join as u}from"node:path";import{startBrowser as m}from"@allyhub/browser";import{kindBuildOf as w,mediaHref as v,nodeLending as b,projectItems as g,sourceOf as k,stageItem as S}from"@allyhub/build";import{CACHE_DIR as y}from"@allyhub/formats";import{CheckSession as D,ProjectError as R,pickTarget as E,parseCombo as O}from"@allyhub/project";import{RPC_ERROR as h,RpcError as c,SNAPSHOT_TREE as l}from"@allyhub/protocol";import{prepareStage as $,viewStage as C}from"@allyhub/stage";import{Routes as P}from"./routes.js";export function rpcErrorOf(o){return o instanceof R?new c(o.kind==="not-found"?h.notFound:h.invalid,o.hint?`${o.message} ${o.hint}`:o.message):o}export class Live{root;buildDir;revision=0;prep;last;lease;old=new Set;browserStarted;gpu;building=Promise.resolve();closed=!1;codes=new Map;kinds;routes;constructor(e,i){this.root=e,this.kinds=i.kinds,this.buildDir=u(e,y,"build",`dev-${String(process.pid)}`),this.gpu=i.gpu,this.routes=new P({root:e,kinds:i.kinds,buildDir:this.buildDir,revision:()=>this.revision,prepared:()=>this.prepared(),latest:()=>this.latest(),view:(t,s)=>C(e,t,s,i.kinds),recordInputs:(t,s,n)=>{i.recordInputs?.(t,s,n)}})}moved(e){this.revision=e,this.lease&&this.lease.revision!==e&&this.retire(this.lease)}prepared(){const e=this.revision;if(this.prep?.revision===e)return this.prep.promise;const i=this.building.then(()=>e===this.revision?this.build():void 0);this.building=i.catch(()=>{});const t=i.then(s=>s??this.prepared());return this.prep={revision:e,promise:t},t.catch(()=>{this.prep?.promise===t&&(this.prep=void 0)}),t}async build(){const e=await $(this.root,this.pieceDir,this.kinds);return this.last=e,e}async itemCode(e){const i=await this.item(e),t=i?await w(this.kinds.find(r=>r.id===i.kind))?.catch(()=>{}):void 0,s=t?.code?.bind(t);if(!i||!s)return{failed:!1};const n=this.codes.get(e),d=n?.revision===this.revision?n.promise:b(this.kinds,this.root).then(r=>s(i,{root:this.root,lend:r})).catch(()=>{});return this.codes.set(e,{revision:this.revision,promise:d}),await d??{failed:!0}}async item(e){const{items:i}=await g(this.root,this.kinds);return i.find(t=>t.id===e)}get pieceDir(){return u(this.buildDir,"stage")}latest(){return this.last}async target(e,i){const t=await this.prepared();try{const{piece:s,target:n}=E(t,e,i===void 0?void 0:[O(i)]);return{prepared:t,piece:s,combo:n.combo}}catch(s){throw rpcErrorOf(s)}}async componentHost(e,i){const t=await this.prepared(),s=t.docs.find(r=>r.place===e||r.file===e);if(s){if(s.components.length===0)throw new c(h.notFound,`${s.place} shows no component.`);const r=t.messages.locales[0];return{prepared:t,host:s,combo:r===void 0?{}:{lang:r}}}const{piece:n,combo:d}=await this.target(e,i);return{prepared:t,host:n,combo:d}}async source(e){const i=await this.prepared(),t=S(i,e);if(!t)throw new c(h.notFound,`No piece ${e}.`);const s=k(i,t),n={...s.media},d=(r,a)=>`${r}${v(a).slice(l.media.length)}`;return await Promise.all(Object.entries(n).map(async([r,a])=>{let p=a;a.kind==="video"&&a.matte===!0&&(p={...p,matteUrl:d(l.matte,r)}),n[r]=await this.routes.mediaOf(r,p)})),{...s,media:n}}browser(){return this.browserStarted??=m(this.gpu===void 0?{}:{gpu:this.gpu}),this.browserStarted}async withSession(e){this.refuseStopped();let i=this.lease;if(i?.revision!==this.revision){i&&this.retire(i);const t=await this.browser();if(this.refuseStopped(),i=this.lease,i?.revision!==this.revision){i&&this.retire(i);const s={revision:this.revision,session:this.prepared().then(n=>D.open({root:this.root,kinds:this.kinds,browser:t,prepared:n})),users:0,retired:!1};i=s,this.lease=s,s.session.catch(()=>{this.lease===s&&(this.lease=void 0)})}}i.users++;try{return await e(await i.session)}finally{i.users--,i.retired&&i.users===0&&this.end(i)}}refuseStopped(){if(this.closed)throw new c(h.unavailable,"allyhub dev is stopping.")}retire(e){e.retired=!0,this.lease===e&&(this.lease=void 0),this.old.add(e),e.users===0&&this.end(e)}end(e){return e.ended??=(async()=>{this.old.delete(e),await e.session.then(i=>i.close()).catch(()=>{})})(),e.ended}async close(){this.closed=!0;const e=[...this.old,...this.lease?[this.lease]:[]];this.lease&&this.retire(this.lease),await Promise.all(e.map(i=>this.end(i))),await this.browserStarted?.then(i=>i.close()).catch(()=>{}),await f(this.buildDir,{recursive:!0,force:!0})}}
2
+ import{rm as f}from"node:fs/promises";import{join as u}from"node:path";import{startBrowser as m}from"@allyhub/browser";import{kindBuildOf as w,mediaHref as b,nodeLending as v,projectItems as g,sourceOf as k,stageItem as S}from"@allyhub/build";import{CACHE_DIR as y}from"@allyhub/formats";import{CheckSession as D,ProjectError as R,pickTarget as E,parseCombo as O}from"@allyhub/project";import{RPC_ERROR as h,RpcError as c,SNAPSHOT_TREE as l}from"@allyhub/protocol";import{prepareStage as $,viewStage as C}from"@allyhub/stage";import{Routes as P}from"./routes.js";export function rpcErrorOf(o){return o instanceof R?new c(o.kind==="not-found"?h.notFound:h.invalid,o.hint?`${o.message} ${o.hint}`:o.message):o}export class Live{root;buildDir;revision=0;prep;last;lease;old=new Set;browserStarted;gpu;building=Promise.resolve();closed=!1;codes=new Map;kinds;routes;constructor(e,i){this.root=e,this.kinds=i.kinds,this.buildDir=u(e,y,"build",`dev-${String(process.pid)}`),this.gpu=i.gpu,this.routes=new P({root:e,kinds:i.kinds,buildDir:this.buildDir,revision:()=>this.revision,prepared:()=>this.prepared(),latest:()=>this.latest(),view:(t,s)=>C(e,t,s,i.kinds),recordInputs:(t,s,n)=>{i.recordInputs?.(t,s,n)}})}moved(e){this.revision=e,this.lease&&this.lease.revision!==e&&this.retire(this.lease)}prepared(){const e=this.revision;if(this.prep?.revision===e)return this.prep.promise;const i=this.building.then(()=>e===this.revision?this.build():void 0);this.building=i.catch(()=>{});const t=i.then(s=>s??this.prepared());return this.prep={revision:e,promise:t},t.catch(()=>{this.prep?.promise===t&&(this.prep=void 0)}),t}async build(){const e=await $(this.root,this.pieceDir,this.kinds);return this.last=e,e}async itemCode(e){const i=await this.item(e),t=i?await w(this.kinds.find(r=>r.id===i.kind))?.catch(()=>{}):void 0,s=t?.code?.bind(t);if(!i||!s)return{failed:!1};const n=this.codes.get(e),d=n?.revision===this.revision?n.promise:v(this.kinds,this.root).then(r=>s(i,{root:this.root,lend:r})).catch(()=>{});return this.codes.set(e,{revision:this.revision,promise:d}),await d??{failed:!0}}async item(e){const{items:i}=await g(this.root,this.kinds);return i.find(t=>t.id===e)}get pieceDir(){return u(this.buildDir,"stage")}latest(){return this.last}async target(e,i){const t=await this.prepared();try{const{piece:s,target:n}=E(t,e,i===void 0?void 0:[O(i)]);return{prepared:t,piece:s,combo:n.combo}}catch(s){throw rpcErrorOf(s)}}async componentHost(e,i){const t=await this.prepared(),s=t.docs.find(r=>r.place===e||r.file===e);if(s){if(s.components.length===0)throw new c(h.notFound,`${s.place} shows no component.`);const r=t.messages.locales[0];return{prepared:t,host:s,combo:r===void 0?{}:{lang:r}}}const{piece:n,combo:d}=await this.target(e,i);return{prepared:t,host:n,combo:d}}async source(e){const i=await this.prepared(),t=S(i,e);if(!t)throw new c(h.notFound,`No piece ${e}.`);const s=k(i,t),n={...s.media},d=(r,a)=>`${r}${b(a).slice(l.media.length)}`;return await Promise.all(Object.entries(n).map(async([r,a])=>{let p=a;a.kind==="video"&&a.matte===!0&&(p={...p,matteUrl:d(l.matte,r)}),n[r]=await this.routes.mediaOf(r,p)})),{...s,media:n}}browser(){return this.browserStarted??=m(this.gpu===void 0?{}:{gpu:this.gpu}),this.browserStarted}async withSession(e){this.refuseStopped();let i=this.lease;if(i?.revision!==this.revision){i&&this.retire(i);const t=await this.browser();if(this.refuseStopped(),i=this.lease,i?.revision!==this.revision){i&&this.retire(i);const s={revision:this.revision,session:this.prepared().then(n=>D.open({root:this.root,kinds:this.kinds,browser:t,prepared:n})),users:0,retired:!1};i=s,this.lease=s,s.session.catch(()=>{this.lease===s&&(this.lease=void 0)})}}i.users++;try{return await e(await i.session)}finally{i.users--,i.retired&&i.users===0&&this.end(i)}}refuseStopped(){if(this.closed)throw new c(h.unavailable,"allyhub dev is stopping.")}retire(e){e.retired=!0,this.lease===e&&(this.lease=void 0),this.old.add(e),e.users===0&&this.end(e)}end(e){return e.ended??=(async()=>{this.old.delete(e),await e.session.then(i=>i.close()).catch(()=>{})})(),e.ended}async close(){this.closed=!0;const e=[...this.old,...this.lease?[this.lease]:[]];this.lease&&this.retire(this.lease),await Promise.all(e.map(i=>this.end(i))),await this.browserStarted?.then(i=>i.close()).catch(()=>{}),await this.building,await f(this.buildDir,{recursive:!0,force:!0})}}
@@ -1,5 +1,5 @@
1
1
  /*! AllyHub. Copyright (c) 2026 AllyHub, Inc. All rights reserved. Use is subject to LICENSE.md. */
2
- import{randomBytes as F}from"node:crypto";import{readFile as z}from"node:fs/promises";import{createServer as D}from"node:http";import{join as J,resolve as C}from"node:path";import{getRequestListener as M}from"@hono/node-server";import{Hono as W}from"hono";import{WebSocketServer as G}from"ws";import{KeyedStore as K}from"@allyhub/project";import{CollaboratorStateSchema as Y,PRESENCE_PATH as Q,SNAPSHOT_TREE as $,TREE_PAGES as V,stageCsp as X}from"@allyhub/protocol";import{runtimeFile as Z}from"@allyhub/stage-page";import{pathProblem as ee}from"./paths.js";import{fileResponse as g}from"./respond.js";import{ProjectServer as te}from"./project.js";import{STILL_NAME as ne,inside as x,matteFile as re,sourceName as oe}from"./tree.js";export const RPC_PATH="/rpc",RAW_PATH="/files/raw/";const p={"access-control-allow-origin":"*"},T=/^[a-z][a-z0-9+.-]*:\/\/[a-z0-9.-]+(:\d{1,5})?$/u;export const PING_MS=3e4,ALLYHUB_FORWARDED="allyhub-forwarded";export function forwardedHost(n){const d=n[ALLYHUB_FORWARDED],y=(n.forwarded??(Array.isArray(d)?d[0]:d))?.split(",")[0]?.split(";").map(i=>i.trim().split("=")).find(([i])=>i?.toLowerCase()==="host")?.[1];if(y!==void 0)return y.replace(/^"(.*)"$/u,"$1");const u=n["x-forwarded-host"];return(Array.isArray(u)?u[0]:u)?.split(",")[0]?.trim()}export function frameSources(n){const d=["'self'","http://127.0.0.1:*","http://localhost:*"];if(n===void 0)return d;const a=new URL(n.replace("{port}","1")),y=new URL(n.replace("{port}","2"));if(a.port!==y.port)return[...d,`${a.protocol}//${a.hostname}:*`];const u=a.hostname.slice(a.hostname.indexOf(".")+1);return[...d,`${a.protocol}//*.${u}`]}export async function startDevServer(n){const d=C(n.root);if(n.embedder!==void 0&&!T.test(n.embedder))throw new Error(`Not an origin: ${n.embedder}`);if(n.publicOrigin!==void 0&&!T.test(n.publicOrigin.replace("{port}","1")))throw new Error(`Not an origin: ${n.publicOrigin}`);const a=n.token??F(18).toString("base64url"),u=`/s/${F(18).toString("base64url")}/`,i=await te.open({...n,root:d,...n.publicOrigin===void 0?{}:{reveal:!1}});let f=0;const P=()=>f===0?void 0:n.publicOrigin?.replace("{port}",String(f)),v=()=>{const e=P();return e===void 0?void 0:new URL(e).host},E=()=>{const e=v();return new Set([`127.0.0.1:${String(f)}`,`localhost:${String(f)}`,...e===void 0?[]:[e]])},R=e=>e===v()?P()??"":`http://${e}`,U=e=>R(e.req.header("host")??""),N=e=>{const t=v();t!==void 0&&forwardedHost(e.headers)===t&&(e.headers.host=t)},A=e=>e??`http://127.0.0.1:${String(f)}`;i.serving={file:(e,t)=>`${A(e)}${RAW_PATH}${t.split("/").map(encodeURIComponent).join("/")}?token=${encodeURIComponent(a)}`,tree:e=>`${A(e)}${u}`};const{routes:O}=i.live,b=new W,I=async e=>{if(!n.ui)return e.text("allyhub dev serves its editors here.",200);const t=await z(J(n.ui,"index.html"),"utf8").catch(()=>{});if(t===void 0)return e.text("The page's files are missing: build them first (pnpm --filter @allyhub/editor-web build).",500);const c=F(16).toString("base64");return e.html(t.replace(/<script/gu,`<script nonce="${c}"`).replace("</head>",`<meta name="allyhub-token" content="${a}"></head>`),200,{"content-security-policy":["default-src 'self'",`script-src 'self' 'nonce-${c}'`,"style-src 'self' 'unsafe-inline'","img-src 'self' data: blob:","media-src 'self' blob:","font-src 'self' data:",`connect-src 'self' ws://${e.req.header("host")??""}`,`frame-src ${frameSources(n.publicOrigin).join(" ")}`,`frame-ancestors ${n.embedder??"'none'"}`].join("; "),"cache-control":"no-store"})};b.get("/",I),b.post(Q,async e=>{if(e.req.header("authorization")!==`Bearer ${a}`)return e.text("forbidden",403);const t=Y.safeParse(await e.req.json().catch(()=>{}));return t.success?(i.presence.agent(t.data),e.body(null,204)):e.text(t.error.message,400)}),b.get(`${RAW_PATH}*`,async e=>{if(e.req.query("token")!==a)return e.text("forbidden",403);const t=decodeURIComponent(e.req.path.slice(RAW_PATH.length));if(ee(t)!==void 0)return e.text("forbidden",403);const c=x(d,t);return c?g(c,e.req.header("range"),{"x-content-type-options":"nosniff","content-security-policy":"sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'"}):e.text("forbidden",403)}),b.get(`${u}*`,async e=>{let t;try{t=decodeURIComponent(e.req.path.slice(u.length))}catch{return e.notFound()}const c=e.req.header("range"),m=U(e),l=t.slice(0,t.indexOf("/")+1),s=t.slice(l.length);switch(l){case $.runtime:{const r=Z(s);if(!r)return e.notFound();const o=Object.values(V).includes(t);return g(r,void 0,{...p,...o?{"content-security-policy":X(`${m}${u}`,[m,...n.embedder?[n.embedder]:[]],O.loads())}:{}})}case $.build:{const r=oe(s);if(r===void 0){const o=x(i.live.pieceDir,s);return o?g(o,void 0,p):e.notFound()}try{return e.json(await i.live.source(r),200,{...p,"cache-control":"no-store"})}catch(o){return e.json({error:{message:o instanceof Error?o.message:String(o)}},404,p)}}case $.media:{const o=Object.hasOwn(i.live.latest()?.media??{},s)||O.allowed(s)?x(d,s):void 0;return o?g(o,c,p):e.notFound()}case $.matte:{const r=re(d,i.live.latest()?.media[s]);return r?g(r,c,{...p,"content-type":"video/mp4"}):e.notFound()}case $.stills:return ne.test(s)?g(K.of(d,"stills").path(s),void 0,{...p,"cache-control":"public, max-age=31536000, immutable"}):e.notFound();default:try{const r=await O.route(l);if(!r)return await e.notFound();const o=new WeakSet,h=await r.route.serve({path:s,query:new URL(e.req.url).searchParams,file:async(_,q,B)=>{const j=x(_,q);if(!j)return;const k=await g(j,c,{...p,...B});return o.add(k),k}},r.context);return h?(!o.has(h)&&!h.headers.has("access-control-allow-origin")&&h.headers.set("access-control-allow-origin","*"),h):await e.notFound()}catch(r){return e.text(r instanceof Error?r.message:String(r),500,{...p})}}}),b.get("/*",async e=>{if(!n.ui)return e.notFound();const t=x(C(n.ui),decodeURIComponent(e.req.path.slice(1)));return t?g(t,void 0,{"cache-control":"public, max-age=3600"}):e.notFound()});const S=new G({noServer:!0,maxPayload:512*1024*1024});S.on("connection",(e,t)=>{const c=i.connect(r=>{e.readyState===e.OPEN&&e.send(JSON.stringify(r))},{origin:R(t.headers.host??"")});e.on("message",(r,o)=>{if(o||!Buffer.isBuffer(r))return;let h;try{h=JSON.parse(r.toString("utf8"))}catch{e.send(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Not JSON."}}));return}c.receive(h)});const m=n.pingMs??PING_MS;let l=!0;e.on("pong",()=>{l=!0});const s=m>0?setInterval(()=>{if(!l){e.terminate();return}l=!1,e.ping()},m):void 0;s?.unref(),e.on("close",()=>{clearInterval(s),c.close()})});const L=M(b.fetch),H=(e,t)=>{e.writeHead(403,{"content-type":"text/plain; charset=utf-8"}),e.end(t)},w=D((e,t)=>{if(N(e),!E().has(e.headers.host??"")){H(t,"forbidden host");return}L(e,t)});w.on("upgrade",(e,t,c)=>{const m=new URL(e.url??"/","http://x"),l=(r,o)=>{t.end(`HTTP/1.1 ${String(r)} ${o}\r
2
+ import{randomBytes as F}from"node:crypto";import{readFile as z}from"node:fs/promises";import{createServer as D}from"node:http";import{join as J,resolve as C}from"node:path";import{getRequestListener as M}from"@hono/node-server";import{Hono as W}from"hono";import{WebSocketServer as G}from"ws";import{KeyedStore as K}from"@allyhub/project";import{CollaboratorStateSchema as Y,PRESENCE_PATH as Q,SNAPSHOT_TREE as $,TREE_PAGES as V,stageCsp as X}from"@allyhub/protocol";import{runtimeFile as Z}from"@allyhub/stage-page";import{pathProblem as ee}from"./paths.js";import{fileResponse as g}from"./respond.js";import{ProjectServer as te}from"./project.js";import{STILL_NAME as ne,inside as x,matteFile as re,sourceName as oe}from"./tree.js";export const RPC_PATH="/rpc",RAW_PATH="/files/raw/";const p={"access-control-allow-origin":"*"},T=/^[a-z][a-z0-9+.-]*:\/\/[a-z0-9.-]+(:\d{1,5})?$/u;export const PING_MS=3e4,ALLYHUB_FORWARDED="allyhub-forwarded";export function forwardedHost(n){const d=n[ALLYHUB_FORWARDED],y=(n.forwarded??(Array.isArray(d)?d[0]:d))?.split(",")[0]?.split(";").map(i=>i.trim().split("=")).find(([i])=>i?.toLowerCase()==="host")?.[1];if(y!==void 0)return y.replace(/^"(.*)"$/u,"$1");const u=n["x-forwarded-host"];return(Array.isArray(u)?u[0]:u)?.split(",")[0]?.trim()}export function frameSources(n){const d=["'self'","http://127.0.0.1:*","http://localhost:*"];if(n===void 0)return d;const a=new URL(n.replace("{port}","1")),y=new URL(n.replace("{port}","2"));if(a.port!==y.port)return[...d,`${a.protocol}//${a.hostname}:*`];const u=a.hostname.slice(a.hostname.indexOf(".")+1);return[...d,`${a.protocol}//*.${u}`]}export async function startDevServer(n){const d=C(n.root);if(n.embedder!==void 0&&!T.test(n.embedder))throw new Error(`Not an origin: ${n.embedder}`);if(n.publicOrigin!==void 0&&!T.test(n.publicOrigin.replace("{port}","1")))throw new Error(`Not an origin: ${n.publicOrigin}`);const a=n.token??F(18).toString("base64url"),u=`/s/${F(18).toString("base64url")}/`,i=await te.open({...n,root:d,...n.publicOrigin===void 0?{}:{reveal:!1}});let f=0;const P=()=>f===0?void 0:n.publicOrigin?.replace("{port}",String(f)),v=()=>{const e=P();return e===void 0?void 0:new URL(e).host},E=()=>{const e=v();return new Set([`127.0.0.1:${String(f)}`,`localhost:${String(f)}`,...e===void 0?[]:[e]])},R=e=>e===v()?P()??"":`http://${e}`,U=e=>R(e.req.header("host")??""),N=e=>{const t=v();t!==void 0&&forwardedHost(e.headers)===t&&(e.headers.host=t)},A=e=>e??`http://127.0.0.1:${String(f)}`;i.serving={file:(e,t)=>`${A(e)}${RAW_PATH}${t.split("/").map(encodeURIComponent).join("/")}?token=${encodeURIComponent(a)}`,tree:e=>`${A(e)}${u}`};const{routes:O}=i.live,b=new W,I=async e=>{if(!n.ui)return e.text("allyhub dev serves its editors here.",200);const t=await z(J(n.ui,"index.html"),"utf8").catch(()=>{});if(t===void 0)return e.text("The page's files are missing: build them first (pnpm --filter @allyhub/editor-web build).",500);const c=F(16).toString("base64");return e.html(t.replace(/<script/gu,`<script nonce="${c}"`).replace("</head>",`<meta name="allyhub-token" content="${a}"></head>`),200,{"content-security-policy":["default-src 'self'",`script-src 'self' 'nonce-${c}'`,"style-src 'self' 'unsafe-inline'","img-src 'self' data: blob:","media-src 'self' blob:","font-src 'self' data:",`connect-src 'self' ws://${e.req.header("host")??""}`,`frame-src ${frameSources(n.publicOrigin).join(" ")}`,`frame-ancestors ${n.embedder??"'none'"}`].join("; "),"cache-control":"no-store"})};b.get("/",I),b.post(Q,async e=>{if(e.req.header("authorization")!==`Bearer ${a}`)return e.text("forbidden",403);const t=Y.safeParse(await e.req.json().catch(()=>{}));return t.success?(i.presence.agent(t.data),e.body(null,204)):e.text(t.error.message,400)}),b.get(`${RAW_PATH}*`,async e=>{if(e.req.query("token")!==a)return e.text("forbidden",403);const t=decodeURIComponent(e.req.path.slice(RAW_PATH.length));if(ee(t)!==void 0)return e.text("forbidden",403);const c=x(d,t);return c?g(c,e.req.header("range"),{"x-content-type-options":"nosniff","content-security-policy":"sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'"}):e.text("forbidden",403)}),b.get(`${u}*`,async e=>{let t;try{t=decodeURIComponent(e.req.path.slice(u.length))}catch{return e.notFound()}const c=e.req.header("range"),m=U(e),l=t.slice(0,t.indexOf("/")+1),s=t.slice(l.length);switch(l){case $.runtime:{const r=Z(s);if(!r)return e.notFound();const o=Object.values(V).includes(t);return g(r,void 0,{...p,...o?{"content-security-policy":X(`${m}${u}`,[m,...n.embedder?[n.embedder]:[],...n.framers??[]],O.loads())}:{}})}case $.build:{const r=oe(s);if(r===void 0){const o=x(i.live.pieceDir,s);return o?g(o,void 0,p):e.notFound()}try{return e.json(await i.live.source(r),200,{...p,"cache-control":"no-store"})}catch(o){return e.json({error:{message:o instanceof Error?o.message:String(o)}},404,p)}}case $.media:{const o=Object.hasOwn(i.live.latest()?.media??{},s)||O.allowed(s)?x(d,s):void 0;return o?g(o,c,p):e.notFound()}case $.matte:{const r=re(d,i.live.latest()?.media[s]);return r?g(r,c,{...p,"content-type":"video/mp4"}):e.notFound()}case $.stills:return ne.test(s)?g(K.of(d,"stills").path(s),void 0,{...p,"cache-control":"public, max-age=31536000, immutable"}):e.notFound();default:try{const r=await O.route(l);if(!r)return await e.notFound();const o=new WeakSet,h=await r.route.serve({path:s,query:new URL(e.req.url).searchParams,file:async(_,q,B)=>{const j=x(_,q);if(!j)return;const k=await g(j,c,{...p,...B});return o.add(k),k}},r.context);return h?(!o.has(h)&&!h.headers.has("access-control-allow-origin")&&h.headers.set("access-control-allow-origin","*"),h):await e.notFound()}catch(r){return e.text(r instanceof Error?r.message:String(r),500,{...p})}}}),b.get("/*",async e=>{if(!n.ui)return e.notFound();const t=x(C(n.ui),decodeURIComponent(e.req.path.slice(1)));return t?g(t,void 0,{"cache-control":"public, max-age=3600"}):e.notFound()});const S=new G({noServer:!0,maxPayload:512*1024*1024});S.on("connection",(e,t)=>{const c=i.connect(r=>{e.readyState===e.OPEN&&e.send(JSON.stringify(r))},{origin:R(t.headers.host??"")});e.on("message",(r,o)=>{if(o||!Buffer.isBuffer(r))return;let h;try{h=JSON.parse(r.toString("utf8"))}catch{e.send(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Not JSON."}}));return}c.receive(h)});const m=n.pingMs??PING_MS;let l=!0;e.on("pong",()=>{l=!0});const s=m>0?setInterval(()=>{if(!l){e.terminate();return}l=!1,e.ping()},m):void 0;s?.unref(),e.on("close",()=>{clearInterval(s),c.close()})});const L=M(b.fetch),H=(e,t)=>{e.writeHead(403,{"content-type":"text/plain; charset=utf-8"}),e.end(t)},w=D((e,t)=>{if(N(e),!E().has(e.headers.host??"")){H(t,"forbidden host");return}L(e,t)});w.on("upgrade",(e,t,c)=>{const m=new URL(e.url??"/","http://x"),l=(r,o)=>{t.end(`HTTP/1.1 ${String(r)} ${o}\r
3
3
  connection: close\r
4
4
  content-length: 0\r
5
5
  \r
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/dev-server",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/diagnostics",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/doc",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/doc-extension",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./cli": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/doc-print",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/export",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/extension-api",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allyhub/extension-host",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {