hyperframes 0.9.32 → 0.9.33

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 (256) hide show
  1. package/dist/{add-HYI4YJC5.js → add-GDXM36YQ.js} +13 -13
  2. package/dist/{agentPromptGenerator-JAQNBEUZ.js → agentPromptGenerator-KPNDH2EI.js} +7 -7
  3. package/dist/{animatedGifPrep-DVYRCZVR.js → animatedGifPrep-SAKETEZ2.js} +7 -7
  4. package/dist/api.js +39 -38
  5. package/dist/{asset-7FG3M3FQ.js → asset-KOJC72AQ.js} +2 -2
  6. package/dist/{assetCataloger-QDQZYHUC.js → assetCataloger-Q4ZFUI6G.js} +8 -8
  7. package/dist/{audio-R6ZG62DU.js → audio-XZBBXKQC.js} +25 -24
  8. package/dist/{auth-IPDYZXOG.js → auth-X45YSZGE.js} +4 -4
  9. package/dist/{autoUpdate-GAEDDZRN.js → autoUpdate-77XWQ564.js} +3 -3
  10. package/dist/{avatars-A45VFUZ4.js → avatars-D3D22TI2.js} +16 -15
  11. package/dist/{backgroundChecks-US74BS6V.js → backgroundChecks-2L2RWFJ3.js} +4 -4
  12. package/dist/backgroundChecksWorker.js +4 -4
  13. package/dist/{batchRender-VBSYVQA7.js → batchRender-O7J47H2Z.js} +3 -3
  14. package/dist/{beats-UPJ3KANG.js → beats-6RVVU56H.js} +11 -11
  15. package/dist/{benchmark-2RWYJGL2.js → benchmark-D5JRNAVQ.js} +10 -10
  16. package/dist/{billing-MD66MJTA.js → billing-WT4DGZII.js} +15 -14
  17. package/dist/{browser-JXCS62NX.js → browser-2OR737P4.js} +7 -7
  18. package/dist/{bundleWithLocalizedFonts-RAD7BNJF.js → bundleWithLocalizedFonts-VBET4RVR.js} +1 -1
  19. package/dist/{capture-DJ4WRP62.js → capture-23X2CK56.js} +44 -24
  20. package/dist/{capture-M6DT5WZT.js → capture-B34FTO6G.js} +3 -3
  21. package/dist/{captureCompositionFrame-IRXG7ZFU.js → captureCompositionFrame-TPZKEVKN.js} +15 -15
  22. package/dist/{catalog-GW45OWKU.js → catalog-ACHSYU5Z.js} +13 -13
  23. package/dist/{catch-up-YKJQ4IYC.js → catch-up-FGANS2BB.js} +8 -8
  24. package/dist/{check-7QTKMPGA.js → check-DXK4L5WP.js} +44 -44
  25. package/dist/{checkAudio-7WHUYGUZ.js → checkAudio-4ISYJED3.js} +15 -15
  26. package/dist/{checkBrowser-USAOWTAF.js → checkBrowser-5ECMULMP.js} +37 -37
  27. package/dist/{chunk-5VN7ZXJR.js → chunk-23354HMA.js} +1 -1
  28. package/dist/{chunk-GCJRV7LU.js → chunk-2I4DQZLQ.js} +1 -1
  29. package/dist/{chunk-WTO4DHBH.js → chunk-2KYLVWLO.js} +1 -1
  30. package/dist/{chunk-3R2X2VKB.js → chunk-2LMCARA5.js} +1 -1
  31. package/dist/{chunk-TVQNABOI.js → chunk-2QTGQGYA.js} +1 -1
  32. package/dist/{chunk-TLUDJLBN.js → chunk-2RBQLV6B.js} +1 -1
  33. package/dist/{chunk-EJPWGGPK.js → chunk-2TBW7UOF.js} +5150 -4985
  34. package/dist/{chunk-P5E3RHW3.js → chunk-3J32XVJ6.js} +1 -1
  35. package/dist/{chunk-LHFBKUVY.js → chunk-45ZQI734.js} +2 -2
  36. package/dist/{chunk-G7NKYELQ.js → chunk-4CHGNFCS.js} +4 -4
  37. package/dist/{chunk-34S7GYVK.js → chunk-4DLYTSWQ.js} +15 -8
  38. package/dist/{chunk-WAXPM7TK.js → chunk-4RPIEGL3.js} +2 -2
  39. package/dist/{chunk-SXOIG6VG.js → chunk-4US5QCXR.js} +231 -176
  40. package/dist/{chunk-XH6LGDIB.js → chunk-4WZU4FYS.js} +3 -3
  41. package/dist/{chunk-NNOAOQLT.js → chunk-5GYTBKZA.js} +2 -2
  42. package/dist/{chunk-K72X2YXR.js → chunk-5RVPI6QL.js} +4 -4
  43. package/dist/{chunk-M6FNCANA.js → chunk-6QEEF5RR.js} +1 -1
  44. package/dist/{chunk-MYFAVVA6.js → chunk-6RV2QY4K.js} +29 -29
  45. package/dist/{chunk-LXIEKLAC.js → chunk-6ZVUTYNB.js} +5 -5
  46. package/dist/{chunk-JMV63CNH.js → chunk-76KUCQXD.js} +1 -1
  47. package/dist/{chunk-GWSCUFGL.js → chunk-7LTXT7ME.js} +11 -9
  48. package/dist/{chunk-LBQQNNRC.js → chunk-7UUUV4PN.js} +1 -1
  49. package/dist/{chunk-6BI6URO2.js → chunk-A4VXOJZO.js} +4 -3
  50. package/dist/{chunk-2W4VQ3YZ.js → chunk-ADYMQM7T.js} +2 -2
  51. package/dist/{chunk-PXY3JZP2.js → chunk-AIC7T7CC.js} +2 -2
  52. package/dist/{chunk-KG3TONXU.js → chunk-B66UZ2YK.js} +9 -9
  53. package/dist/{chunk-7NDF2MO3.js → chunk-BAWGEGKD.js} +216 -344
  54. package/dist/{chunk-SIRYW7SY.js → chunk-BBL6STGK.js} +2 -2
  55. package/dist/{chunk-GTHRXU37.js → chunk-C2VZ7UPE.js} +18 -18
  56. package/dist/{chunk-I3QXWJ7V.js → chunk-CDI3CCAU.js} +5 -5
  57. package/dist/{chunk-C5JKRCSG.js → chunk-CHCMXYER.js} +1 -1
  58. package/dist/{chunk-4CSZZXL6.js → chunk-CHM3QYLF.js} +3 -3
  59. package/dist/{chunk-VB3JZKMN.js → chunk-CNJLBAKM.js} +29 -8
  60. package/dist/chunk-DDDSTRHU.js +3890 -0
  61. package/dist/{chunk-GJUL3PRV.js → chunk-DGC2RIQE.js} +3 -3
  62. package/dist/{chunk-LP7B3JLC.js → chunk-DMW5SSUN.js} +2 -1
  63. package/dist/{chunk-HXQDDCGY.js → chunk-DMZER7D5.js} +1 -1
  64. package/dist/{chunk-XPT4GC6X.js → chunk-ERJBWDPM.js} +6 -6
  65. package/dist/{chunk-NXSKZE3C.js → chunk-ETWXZQN5.js} +1 -1
  66. package/dist/{chunk-E5S4QMX7.js → chunk-EX533ULK.js} +1 -1
  67. package/dist/{chunk-3367VNGK.js → chunk-EX7WPDFA.js} +1 -1
  68. package/dist/{chunk-JHX76QFC.js → chunk-FRH3CPW5.js} +1 -1
  69. package/dist/{chunk-EXW2LV4K.js → chunk-G55YEL2L.js} +24 -24
  70. package/dist/{chunk-WLNQAJQC.js → chunk-GHLLC6LJ.js} +2 -2
  71. package/dist/{chunk-SFPIVVUE.js → chunk-HEXTAQYG.js} +1 -1
  72. package/dist/{chunk-ADP2GIBS.js → chunk-HMB3IAVP.js} +1 -1
  73. package/dist/{chunk-Z6X64P6C.js → chunk-HPKW6UVW.js} +6 -6
  74. package/dist/{chunk-BA3EQ2KL.js → chunk-I35B5RWZ.js} +3 -3
  75. package/dist/{chunk-2NMBD5AH.js → chunk-I3PA54IU.js} +1 -1
  76. package/dist/{chunk-AOQRVS63.js → chunk-IYLGUQFR.js} +7 -5
  77. package/dist/chunk-JCJJCYCP.js +392 -0
  78. package/dist/{chunk-G6JLFSII.js → chunk-JSVCF4A6.js} +4 -4
  79. package/dist/{chunk-WVRAFHJU.js → chunk-K2Z6OXEI.js} +33 -5
  80. package/dist/{chunk-YIE5FU73.js → chunk-KIAY63AB.js} +37 -3
  81. package/dist/{chunk-X6DWLN55.js → chunk-L6BFXQ6S.js} +7 -3
  82. package/dist/chunk-M3BJEZ7E.js +152 -0
  83. package/dist/{chunk-M6LAGO6O.js → chunk-MA35E5OY.js} +3 -3
  84. package/dist/{chunk-XB7HE2R5.js → chunk-MDBEAWP2.js} +3 -3
  85. package/dist/{chunk-3HT3UGF2.js → chunk-MDGNQWFN.js} +1 -1
  86. package/dist/{chunk-3YNJAXA5.js → chunk-MOR3H5FK.js} +1 -1
  87. package/dist/{chunk-5FFYMVRD.js → chunk-MP36L7OJ.js} +1 -1
  88. package/dist/{chunk-YCTWMO3G.js → chunk-MVIUSNPZ.js} +1 -1
  89. package/dist/{chunk-6SNGKC6B.js → chunk-N2C7WJDG.js} +1 -1
  90. package/dist/{chunk-3PHCFSPD.js → chunk-NQFIMBXS.js} +2 -2
  91. package/dist/{chunk-AZ2QJETV.js → chunk-O2T6ZTLN.js} +1 -1
  92. package/dist/{chunk-2T7EDEKE.js → chunk-O5CNNVRY.js} +7 -7
  93. package/dist/{chunk-5GXMZIQZ.js → chunk-OD7PLYYX.js} +7 -7
  94. package/dist/{chunk-TZH6HNZH.js → chunk-PNP2BO3U.js} +1 -1
  95. package/dist/{chunk-ZLDYDO64.js → chunk-QUUZ2BGC.js} +6 -4
  96. package/dist/{chunk-P7TCIUP2.js → chunk-QWM3NY2E.js} +3 -3
  97. package/dist/{chunk-Y3YHDU7T.js → chunk-R45WFVRA.js} +1 -1
  98. package/dist/{chunk-UWMOMAYI.js → chunk-RCB4SGTB.js} +2 -2
  99. package/dist/{chunk-W3HNLDK6.js → chunk-RGYOCAHC.js} +2 -2
  100. package/dist/{chunk-CMYUPVMI.js → chunk-ROXILOZ6.js} +2 -2
  101. package/dist/{chunk-EBG5RCPM.js → chunk-SIGASWB7.js} +4 -4
  102. package/dist/{chunk-KFXHBP2E.js → chunk-SOAQ3XXB.js} +1 -1
  103. package/dist/{chunk-LJMTEZOP.js → chunk-SUXEL7G4.js} +15 -15
  104. package/dist/{chunk-6MTSP2XE.js → chunk-SWPI27QV.js} +7 -7
  105. package/dist/{chunk-RCRUWNQ4.js → chunk-T3GSTIBS.js} +2 -2
  106. package/dist/{chunk-L72MPEM2.js → chunk-U77L3ZQZ.js} +1 -1
  107. package/dist/{chunk-6NNLDCX4.js → chunk-UE2WSWNA.js} +1 -1
  108. package/dist/{chunk-YMIEJZB6.js → chunk-VKZSAAXZ.js} +2 -2
  109. package/dist/chunk-VQJLTYEK.js +453 -0
  110. package/dist/{chunk-TTSLKH63.js → chunk-VZQXHYEI.js} +2 -2
  111. package/dist/{chunk-D7NNNL2K.js → chunk-W2FSQBUR.js} +17 -17
  112. package/dist/{chunk-AWT5FHTN.js → chunk-W5PW26KE.js} +1 -1
  113. package/dist/{chunk-KXOKZJBZ.js → chunk-WIMVXPYG.js} +12 -12
  114. package/dist/{chunk-KAG5KXNO.js → chunk-WYPRTHXQ.js} +1 -1
  115. package/dist/{chunk-YAZQBB2S.js → chunk-XDDBSGBD.js} +1 -1
  116. package/dist/{chunk-6RFCS4IU.js → chunk-XFXCI4IP.js} +7 -5
  117. package/dist/{chunk-2Z42EUHG.js → chunk-XQWWFIBR.js} +1 -1
  118. package/dist/{chunk-H7AJLEBR.js → chunk-XSHJ37U3.js} +3 -3
  119. package/dist/{chunk-HWMNSWEA.js → chunk-XUDJ5XSQ.js} +2 -2
  120. package/dist/{chunk-D6BV6TTI.js → chunk-XVVPEWNX.js} +1 -1
  121. package/dist/chunk-Y5DOT5NQ.js +57 -0
  122. package/dist/{chunk-HDCVU64B.js → chunk-YDG3OXH3.js} +3 -2
  123. package/dist/{chunk-H4C3P2KV.js → chunk-YNFHZ4RI.js} +2 -2
  124. package/dist/{chunk-PVSRPNIV.js → chunk-YSHUIQ3I.js} +2 -2
  125. package/dist/chunk-YTUPQTXA.js +560 -0
  126. package/dist/{chunk-262ADJJN.js → chunk-ZOAANTVI.js} +1 -1
  127. package/dist/{clean-MJBET4EN.js → clean-3IN64RHM.js} +21 -21
  128. package/dist/cli.js +68 -66
  129. package/dist/{cloud-WEDQYHZE.js → cloud-LBUZBUP6.js} +4 -4
  130. package/dist/{cloud-Z4Q76MLS.js → cloud-SVYXHFEG.js} +6 -5
  131. package/dist/{cloudrun-2KGSRAKA.js → cloudrun-PZOF2QGL.js} +5 -5
  132. package/dist/{compare-MJKWQOD7.js → compare-UOJ3LXQQ.js} +35 -35
  133. package/dist/{compiler-ETXRTUQC.js → compiler-5ZDHBKBQ.js} +6 -4
  134. package/dist/{component-PZGKEJ6L.js → component-EVIPLTTJ.js} +3 -3
  135. package/dist/{compositions-N3FEEWH7.js → compositions-R4GG5FBO.js} +13 -13
  136. package/dist/contract/LICENSE-Unicode.txt +39 -0
  137. package/dist/contract/path-policy.json +311 -0
  138. package/dist/contract/unicode-15.1.0.json +6179 -0
  139. package/dist/{curve-MWABBM7Q.js → curve-LR3PSRW3.js} +12 -12
  140. package/dist/{cuts-BQFSSNY7.js → cuts-DHCOBAFT.js} +13 -13
  141. package/dist/{delete-HPHGJABK.js → delete-MMGGU3QP.js} +9 -8
  142. package/dist/{deploy-JY2QOB5F.js → deploy-SKIGUTM2.js} +7 -7
  143. package/dist/{describeProject-S6AGYZWL.js → describeProject-L7HNTBPV.js} +8 -8
  144. package/dist/{destroy-AZK7J4IR.js → destroy-5HSMMDH7.js} +6 -6
  145. package/dist/{diff-XDNFCAU4.js → diff-KR7VKPYL.js} +40 -39
  146. package/dist/{dist-6EE3Y4M7.js → dist-3MFNUZSN.js} +2 -2
  147. package/dist/{dist-EYEYDD4F.js → dist-HK3AZNNL.js} +13 -13
  148. package/dist/{dist-TYGDYK56.js → dist-ZGYPFYOH.js} +2 -2
  149. package/dist/{doctor-6IRSMKZD.js → doctor-G7VGNSA5.js} +12 -12
  150. package/dist/{energy-VCJ2FJEF.js → energy-H7EEH6WO.js} +13 -13
  151. package/dist/{events-QQYBD7JM.js → events-5ATZCZTK.js} +4 -4
  152. package/dist/{events-DNTIMCUM.js → events-ASG27IXP.js} +15 -15
  153. package/dist/{events-M6A7BT3V.js → events-YD6N7OPQ.js} +7 -7
  154. package/dist/execute-OAS454OB.js +109 -0
  155. package/dist/{extract-X3IVXYHX.js → extract-645SENLA.js} +16 -16
  156. package/dist/{face-MZHXKBDB.js → face-WRT5XH4I.js} +14 -14
  157. package/dist/{feedback-TAMGYFUO.js → feedback-3LKLR5MV.js} +15 -14
  158. package/dist/{ffmpeg-XWPYYYB6.js → ffmpeg-PXKIZL2X.js} +7 -7
  159. package/dist/{figma-WMD7AR2S.js → figma-RIEVJJBW.js} +3 -3
  160. package/dist/fontLocalizeCli.js +12 -12
  161. package/dist/{frames-OU2UOLBU.js → frames-OTB3J5W3.js} +14 -14
  162. package/dist/{generate-6F6QEFXW.js → generate-IUKCZW2D.js} +27 -26
  163. package/dist/{get-VVDO7DXG.js → get-6WVQ7TBV.js} +9 -8
  164. package/dist/{gpuPolicy-CVNSHXHJ.js → gpuPolicy-HXSVAEU4.js} +7 -7
  165. package/dist/{grade-compare-O6LY2U73.js → grade-compare-TCAYHDEF.js} +37 -37
  166. package/dist/{heifImagePrep-J6TILZTM.js → heifImagePrep-GXIMK4HK.js} +8 -8
  167. package/dist/{help-XLSTTDHR.js → help-RGOL5EJD.js} +2 -1
  168. package/dist/{history-DBCCWBDG.js → history-XKPRGJGS.js} +10 -10
  169. package/dist/hyperframe.manifest.json +1 -1
  170. package/dist/hyperframe.runtime.iife.js +42 -42
  171. package/dist/hyperframes-player.global.js +1 -1
  172. package/dist/{info-E46BWAQ7.js → info-EYBBC42V.js} +15 -15
  173. package/dist/{init-23TG5W7S.js → init-F2FWPSMA.js} +29 -29
  174. package/dist/{ink-6UFSNJRW.js → ink-BWFERAAT.js} +13 -13
  175. package/dist/{inspect-RKI6XACH.js → inspect-74N7L3BW.js} +34 -34
  176. package/dist/{installer-JWPK75BR.js → installer-LOUR7G4R.js} +4 -4
  177. package/dist/{keyframes-J65V5A2G.js → keyframes-WB5PTKFE.js} +13 -11
  178. package/dist/{lambda-RZSXXBJU.js → lambda-JYCNXUKB.js} +12 -12
  179. package/dist/{layout-RJQUOYWB.js → layout-P52EVR24.js} +34 -34
  180. package/dist/{lint-4TUHKKA2.js → lint-SL55KAS2.js} +12 -12
  181. package/dist/{lintProject-R6RTBSCZ.js → lintProject-46WU53VC.js} +2 -2
  182. package/dist/{list-HOD2N4VS.js → list-LN6CQH52.js} +11 -10
  183. package/dist/{localPage-TC4NC3VL.js → localPage-L6OJU3UH.js} +7 -7
  184. package/dist/{login-NTOS3HKD.js → login-WTOAMDID.js} +8 -7
  185. package/dist/{logout-7SMEH7JL.js → logout-QGNBUJKS.js} +14 -5
  186. package/dist/{look-GC63E2I7.js → look-O6ESLJRP.js} +13 -13
  187. package/dist/{manager-FICBET24.js → manager-CMEZWENF.js} +8 -8
  188. package/dist/{measure-WTQCSQ55.js → measure-NEIXU53P.js} +11 -11
  189. package/dist/{media-treatment-KTZ6X2P2.js → media-treatment-6CAQG7MU.js} +15 -15
  190. package/dist/{media-use-K75FDXJ3.js → media-use-IXJFMKU7.js} +9 -7
  191. package/dist/{models-JKOA542M.js → models-TZALWUEY.js} +11 -11
  192. package/dist/{motionShot-A3TYKTQU.js → motionShot-OQYK6G6M.js} +20 -20
  193. package/dist/{normalize-audio-7JUM42YB.js → normalize-audio-43PJLOBY.js} +11 -11
  194. package/dist/oauth-SAVP2YM4.js +40 -0
  195. package/dist/{open-F6GI4TRA.js → open-EOX6QY4M.js} +13 -13
  196. package/dist/{parakeetRunner-6XIAKJLS.js → parakeetRunner-STHAXQAF.js} +13 -13
  197. package/dist/{pipeline-7P7LGGQG.js → pipeline-RRWZHFBQ.js} +10 -10
  198. package/dist/plan-JWUSMF4W.js +88 -0
  199. package/dist/{play-DYOZLKWX.js → play-TUKTST32.js} +25 -25
  200. package/dist/{preflight-VM4HSRBY.js → preflight-L42JKT6F.js} +8 -8
  201. package/dist/{present-IINIEZJC.js → present-Z7HRDXPV.js} +20 -20
  202. package/dist/{preview-NJO2UXWJ.js → preview-HGTIRAV3.js} +23 -23
  203. package/dist/{probe-LQQHFX5Q.js → probe-RXK44FY7.js} +13 -13
  204. package/dist/{producer-LH2SZHJ2.js → producer-KJ2RZDJ3.js} +1 -1
  205. package/dist/{projectConfig-BLACFLUW.js → projectConfig-K36NTJXP.js} +6 -6
  206. package/dist/{publication-NFF2BXIE.js → publication-OZWLT6K6.js} +2 -2
  207. package/dist/{publish-JST5Y4UR.js → publish-CRUTXNYM.js} +84 -24
  208. package/dist/{refresh-47T6Z2PK.js → refresh-6ONVQ3WV.js} +4 -3
  209. package/dist/{remove-background-WUBESLWN.js → remove-background-R37HZPCG.js} +11 -11
  210. package/dist/{render-R4VNR4E2.js → render-EZMKBT7V.js} +45 -44
  211. package/dist/{render-DA4V7CEE.js → render-SU2XTMJL.js} +5 -5
  212. package/dist/{render-4KWUUC5H.js → render-ZHCPCISN.js} +82 -948
  213. package/dist/{render-batch-JMPG4RLT.js → render-batch-YIUOEAAL.js} +5 -5
  214. package/dist/renderSetupWorker.js +2 -2
  215. package/dist/{resolver-PNIFIDIE.js → resolver-DLCKRKQR.js} +4 -4
  216. package/dist/{reverse-4NI7D2C3.js → reverse-4FAVXIER.js} +1 -1
  217. package/dist/{run-FWBIBLYE.js → run-H4GVEJVS.js} +5 -4
  218. package/dist/{screenshotCapture-KOLNFU7W.js → screenshotCapture-CQF5FYVI.js} +9 -9
  219. package/dist/service-XDQOULGD.js +68 -0
  220. package/dist/share-CUCQALE7.js +274 -0
  221. package/dist/{sherpa-W3BMN67E.js → sherpa-WZNRQUVC.js} +12 -12
  222. package/dist/skills/hyperframes-cli/SKILL.md +3 -3
  223. package/dist/skills/hyperframes-cli/references/preview-render.md +20 -0
  224. package/dist/{skills-KQQVUFGO.js → skills-J52DBZAK.js} +10 -10
  225. package/dist/{skillsUpdateCheck-VY5PS46S.js → skillsUpdateCheck-26DJHBTC.js} +4 -4
  226. package/dist/{snapshot-VIEJQAUB.js → snapshot-ZIRQFDA7.js} +50 -50
  227. package/dist/{src-MQU5F7GJ.js → src-7BGBN6SS.js} +11 -11
  228. package/dist/{src-HHPRCLEW.js → src-C3XYMTF4.js} +6 -6
  229. package/dist/{start-ZBNNVFMU.js → start-QG2XNMYN.js} +25 -24
  230. package/dist/{staticProjectServer-VPGZWJF4.js → staticProjectServer-TWMEFK3T.js} +18 -18
  231. package/dist/{status-RBZJYT7T.js → status-3UPA5WPI.js} +19 -17
  232. package/dist/studio/assets/{codec-Bz1jsLs8.js → codec-qz1-OXLj.js} +1 -1
  233. package/dist/studio/assets/{hyperframes-player-cdH5Sz_t.js → hyperframes-player-2eG1zFX5.js} +1 -1
  234. package/dist/studio/assets/{index-dsfjBidg.css → index-BJTCbv8z.css} +1 -1
  235. package/dist/studio/assets/{index-D1l7izdf.js → index-DDmhnfrS.js} +166 -166
  236. package/dist/studio/assets/{index-DFRbcd5J.js → index-DUveJ_YP.js} +1 -1
  237. package/dist/studio/assets/{pausedVideoDecoder-CgV8YB6S.js → pausedVideoDecoder-CoHTKUjM.js} +1 -1
  238. package/dist/studio/index.html +2 -2
  239. package/dist/{studio-api-EPZGLIWW.js → studio-api-Z42OO4JJ.js} +13 -13
  240. package/dist/{studioServer-YFQQ2ESJ.js → studioServer-SMN3RMVL.js} +437 -59
  241. package/dist/{sync-FRT55PVW.js → sync-ONTI2WSI.js} +13 -13
  242. package/dist/{telemetry-HAPPFR7P.js → telemetry-RRXALB5D.js} +7 -7
  243. package/dist/{templates-2IHYIWMA.js → templates-BHFOSD6F.js} +18 -17
  244. package/dist/{timeline-AY2F7BJF.js → timeline-Z5IHY5TN.js} +20 -20
  245. package/dist/{tokens-B3G257V3.js → tokens-MZVEPARM.js} +2 -2
  246. package/dist/{transcribe-RJCILGPA.js → transcribe-5IZS4BGW.js} +29 -28
  247. package/dist/{transcribe-EGQD32PT.js → transcribe-M5N3YZZU.js} +10 -10
  248. package/dist/{update-XTFIGQKW.js → update-EVPWBIKY.js} +11 -11
  249. package/dist/{updateCheck-M6YC52A4.js → updateCheck-2UUEF6TC.js} +5 -3
  250. package/dist/{upgrade-AKLIZKAO.js → upgrade-DK45FD4K.js} +4 -4
  251. package/dist/{urlDownloader-57A7Q7FC.js → urlDownloader-3MPHIDSA.js} +6 -6
  252. package/dist/{validate-YWSXJL54.js → validate-W27TQ367.js} +28 -28
  253. package/dist/{video-I5DDNK3Y.js → video-TI372QGV.js} +8 -8
  254. package/dist/{voices-IBMJU73H.js → voices-FZV4PGT6.js} +24 -23
  255. package/dist/warmCheck.js +44 -44
  256. package/package.json +2 -1
@@ -0,0 +1,3890 @@
1
+ import { createRequire as __hf_createRequire } from "node:module";
2
+ import { fileURLToPath as __hf_fileURLToPath } from "node:url";
3
+ import { dirname as __hf_dirname } from "node:path";
4
+ var require = __hf_createRequire(import.meta.url);
5
+ var __filename = __hf_fileURLToPath(import.meta.url);
6
+ var __dirname = __hf_dirname(__filename);
7
+ import {
8
+ resolveCredential
9
+ } from "./chunk-M3BJEZ7E.js";
10
+ import {
11
+ AuthClient,
12
+ apiBaseUrl,
13
+ refreshTokens
14
+ } from "./chunk-BAWGEGKD.js";
15
+ import {
16
+ resetTelemetryPostureCache,
17
+ trackEvent
18
+ } from "./chunk-YSHUIQ3I.js";
19
+ import {
20
+ AuthError,
21
+ ErrLoginChanged,
22
+ oauthEnvironment,
23
+ tokenEndpoint
24
+ } from "./chunk-DMW5SSUN.js";
25
+ import {
26
+ readConfigFresh
27
+ } from "./chunk-AWD2MWWL.js";
28
+ import {
29
+ CliUsageError
30
+ } from "./chunk-66W5IWLO.js";
31
+
32
+ // ../share/src/reviewClient.mjs
33
+ import { randomUUID } from "crypto";
34
+
35
+ // ../share/src/grantRefusal.mjs
36
+ var REASONS = /* @__PURE__ */ new Set(["revision_conflict", "grant_exists", "operation_result_revoked"]);
37
+ function rejectedGrantRequest(error) {
38
+ return error instanceof Error && "reason" in error && REASONS.has(String(error.reason));
39
+ }
40
+
41
+ // ../share/src/host.mjs
42
+ import { promisify } from "util";
43
+ import { execFile as nodeExecFile } from "child_process";
44
+
45
+ // ../share/src/signedInRequest.mjs
46
+ var AccountUnreachable = class extends Error {
47
+ constructor() {
48
+ super("the saved sign-in could not be renewed: HeyGen was unreachable");
49
+ this.name = "AccountUnreachable";
50
+ }
51
+ };
52
+ function signedInRequest({
53
+ access,
54
+ fetchImpl = fetch,
55
+ timeoutMs,
56
+ tag,
57
+ offline,
58
+ signedOut,
59
+ host: host2 = "heygen",
60
+ headers: always = {},
61
+ trace = (init) => init
62
+ }) {
63
+ const send = (signedIn, method, route, body, headers2, answers, label) => {
64
+ const init = {
65
+ method,
66
+ headers: {
67
+ // Never a caller's Authorization, in any case: fetch would join it to the bearer.
68
+ ...Object.fromEntries(
69
+ Object.entries({ ...always, ...headers2 }).filter(
70
+ ([name]) => name.toLowerCase() !== "authorization"
71
+ )
72
+ ),
73
+ authorization: `Bearer ${signedIn.token}`,
74
+ ...body === void 0 ? {} : { "content-type": "application/json" }
75
+ },
76
+ // A redirect would drop the bearer.
77
+ redirect: "error",
78
+ body: body === void 0 ? null : JSON.stringify(body),
79
+ signal: AbortSignal.timeout(timeoutMs)
80
+ };
81
+ return fetchImpl(`${signedIn[host2]}${route}`, answers ? trace(init, answers) : init).catch(
82
+ (error) => {
83
+ console.error(
84
+ `[${tag}] ${label} failed:`,
85
+ /** @type {Error} */
86
+ error.name
87
+ );
88
+ throw offline();
89
+ }
90
+ );
91
+ };
92
+ return async (method, route, body, headers2 = {}, answers = null, label = `${method} ${route}`) => {
93
+ let refused = "";
94
+ for (; ; ) {
95
+ const signedIn = await access(refused || void 0).catch((error) => {
96
+ throw error instanceof AccountUnreachable ? offline() : error;
97
+ });
98
+ if (!signedIn || signedIn.token === refused) throw signedOut();
99
+ const sending = typeof body === "function" ? await body() : body;
100
+ const reply = await send(signedIn, method, route, sending, headers2, answers, label);
101
+ if (reply.status !== 401 || refused)
102
+ return { reply, heygen: signedIn.heygen, owner: signedIn.owner ?? null };
103
+ refused = signedIn.token;
104
+ await reply.body?.cancel().catch(() => {
105
+ });
106
+ }
107
+ };
108
+ }
109
+
110
+ // ../share/src/host.mjs
111
+ var host = { execFile: nodeExecFile, signedInRequest };
112
+ var bindShareHost = (part) => void Object.assign(host, part);
113
+ var bound = (name) => {
114
+ const part = host[name];
115
+ if (part === void 0) throw new Error(`No host is bound to share projects (${name}).`);
116
+ return (
117
+ /** @type {ShareHost[K]} */
118
+ part
119
+ );
120
+ };
121
+ var normalize = (path4) => bound("normalize")(path4);
122
+ var signedInRequest2 = (deps) => bound("signedInRequest")(deps);
123
+ var latestExportFile = (dir) => bound("latestExportFile")(dir);
124
+ var reviewUploadOrigins = () => host.reviewUploadOrigins ?? (process.env.HYPERFRAMES_REVIEW_UPLOAD_ORIGINS ?? "").split(",").map((origin) => origin.trim());
125
+ var projectFingerprint = (dir) => bound("projectFingerprint")(dir);
126
+ var ffBinary = (name) => bound("ffBinary")(name);
127
+ var channelSite = () => bound("channelSite");
128
+ var signinSites = () => bound("signinSites");
129
+ var runFile = (file, args) => promisify(bound("execFile"))(file, args, { windowsHide: true });
130
+
131
+ // ../share/src/reviewOpenCalls.mjs
132
+ var REVIEWS = "/v1/hyperframes/reviews";
133
+ function shareOpenCalls(tokenCall) {
134
+ const share = (token) => `${REVIEWS}/${encodeURIComponent(token)}`;
135
+ const version = (token, id) => `${share(token)}/versions/${encodeURIComponent(id)}`;
136
+ return {
137
+ /** C1, for the requested version or the latest. @param {string} token @param {string | null} versionId
138
+ * @returns {Promise<import("./types/shareOpen.js").OpenSummaryDTO>} */
139
+ openSummary: (token, versionId) => tokenCall(
140
+ "GET reviews/\u2026/open",
141
+ "GET",
142
+ `${share(token)}/open${versionId ? `?${new URLSearchParams({ version_id: versionId })}` : ""}`
143
+ ),
144
+ /** C2: the snapshot's manifest and the first signed URLs (at most 500 files).
145
+ * @param {string} token @param {string} versionId @returns {Promise<import("./types/shareOpen.js").VersionFilesDTO>} */
146
+ versionFiles: (token, versionId) => tokenCall("GET reviews/\u2026/files", "GET", `${version(token, versionId)}/files`),
147
+ /** C2's refresh: URLs for `sha256s` (at most 500) of the same snapshot, by the token the last answer carried.
148
+ * @param {string} token @param {string} versionId @param {string} continuation @param {string[]} sha256s
149
+ * @returns {Promise<import("./types/shareOpen.js").FileUrlsDTO>} */
150
+ fileUrls: (token, versionId, continuation, sha256s) => tokenCall("POST reviews/\u2026/files", "POST", `${version(token, versionId)}/files`, {
151
+ continuation_token: continuation,
152
+ sha256s
153
+ }),
154
+ /** C3: a copy finished; the same handoff again is the same copy. The server answers 204 with no body.
155
+ * @param {string} token @param {string} versionId @param {string | null} handoffId @returns {Promise<null>} */
156
+ logCopy: (token, versionId, handoffId) => tokenCall("POST reviews/\u2026/copies", "POST", `${version(token, versionId)}/copies`, {
157
+ handoff_id: handoffId
158
+ })
159
+ };
160
+ }
161
+
162
+ // ../share/src/reviewClient.mjs
163
+ var TIMEOUT_MS = 3e4;
164
+ var PROJECTS = "/v1/hyperframes/review-projects";
165
+ var SPACES = "/v1/hyperframes/review-spaces";
166
+ var ReviewFailed = class extends Error {
167
+ /** @param {number} status @param {string} reason @param {number} [currentRevision] @param {number} [retryAfterMs]
168
+ * @param {import("./types/reviewWire.js").ErrorEnvelope["data"]} [details] */
169
+ constructor(status, reason, currentRevision, retryAfterMs, details) {
170
+ super(`review ${status} ${reason}`);
171
+ this.status = status;
172
+ this.reason = reason;
173
+ this.currentRevision = currentRevision;
174
+ this.retryAfterMs = retryAfterMs;
175
+ this.details = details;
176
+ }
177
+ };
178
+ async function dataOf(reply, what) {
179
+ if (reply.status === 204) return null;
180
+ const payload = await reply.json().catch(() => null);
181
+ if (reply.ok) return payload?.data ?? null;
182
+ const data = payload?.data;
183
+ throw responseFailure(reply, what, data);
184
+ }
185
+ function responseFailure(reply, what, data) {
186
+ if (process.env.HF_DEBUG_SHARE === "1")
187
+ console.error(`[review] ${what} refused:`, reply.status, data?.reason);
188
+ const retryAfter = Number(reply.headers.get("retry-after") ?? NaN);
189
+ return new ReviewFailed(
190
+ reply.status,
191
+ data?.reason ?? "",
192
+ data?.current_revision,
193
+ retryAfter >= 0 ? retryAfter * 1e3 : void 0,
194
+ data
195
+ );
196
+ }
197
+ var SHARING_REFUSALS = [401, 403, 404];
198
+ function reviewClient({ access, fetchImpl = fetch, signedInEmail = async () => null }) {
199
+ const request = signedInRequest2({
200
+ access,
201
+ fetchImpl,
202
+ timeoutMs: TIMEOUT_MS,
203
+ tag: "review",
204
+ offline: () => new ReviewFailed(0, "offline"),
205
+ signedOut: () => new ReviewFailed(401, "login_required")
206
+ });
207
+ const call = async (method, route, body, headers2 = {}, answers = null) => dataOf((await request(method, route, body, headers2, answers)).reply, `${method} ${route}`);
208
+ const tokenCall = async (what, method, route, body) => dataOf((await request(method, route, body, {}, null, what)).reply, what);
209
+ const project = (id) => `${PROJECTS}/${encodeURIComponent(id)}`;
210
+ return {
211
+ /** The signed-in account's email, null when unknown; the record keeps it as the project's owner. */
212
+ signedInEmail,
213
+ /** The spaces this account can share into, personal first.
214
+ * @returns {Promise<import("./types/reviewWire.js").SpaceDTO[]>} */
215
+ spaces: async () => {
216
+ const items = (await call("GET", SPACES))?.items;
217
+ if (!Array.isArray(items)) throw new ReviewFailed(502, "malformed_spaces");
218
+ return items;
219
+ },
220
+ /** The server's per-account flags on review-spaces, each on only for `true`: `hyperframes-review-version-sharing`
221
+ * and `hyperframes-review-share-files`. One read answers both.
222
+ * @returns {Promise<{ versionSharing: boolean, shareFiles: boolean }>} */
223
+ reviewFlags: async () => {
224
+ const data = await call("GET", SPACES, void 0, {}, SHARING_REFUSALS);
225
+ if (!Array.isArray(data?.items)) throw new ReviewFailed(502, "malformed_spaces");
226
+ return {
227
+ versionSharing: data?.version_sharing === true,
228
+ shareFiles: data?.share_files === true
229
+ };
230
+ },
231
+ /** Registers into `spaceId`; without one the server uses the caller's default space.
232
+ * @param {import("./types/reviewWire.js").RegisterProjectRequest} body @param {string | null} [spaceId]
233
+ * @returns {Promise<ProjectDTO>} */
234
+ register: (body, spaceId) => call("POST", PROJECTS, body, spaceId ? { "x-space-id": spaceId } : {}),
235
+ /** @param {string} id @returns {Promise<ShareDTO>} */
236
+ share: (id) => call("GET", `${project(id)}/share`),
237
+ /** @param {string} id @param {import("./types/reviewWire.js").UpdateProjectShareRequest} body
238
+ * @returns {Promise<ShareDTO>} */
239
+ updateShare: (id, body) => call("PATCH", `${project(id)}/share`, body),
240
+ /** @param {string} id @param {import("./types/reviewWire.js").ProjectOperationRequest} body @returns {Promise<ShareDTO>} */
241
+ linkOn: (id, body) => call("POST", `${project(id)}/share`, body),
242
+ /** @param {string} id @returns {Promise<null>} */
243
+ linkOff: (id) => call("DELETE", `${project(id)}/share`),
244
+ /** @param {string} id @returns {Promise<ProjectDTO>} */
245
+ project: (id) => call("GET", project(id)),
246
+ /** @param {string} id @returns {Promise<{frames: unknown[]}>} */
247
+ storyboard: (id) => call("GET", `/v1/hyperframes/projects/${encodeURIComponent(id)}/storyboard`),
248
+ /** @param {string} id @param {string} compositionId @returns {Promise<{composition_id: string}>} */
249
+ bindComposition: (id, compositionId) => call("PUT", `${project(id)}/composition`, { composition_id: compositionId }),
250
+ /** One page of the project's comments, every state. @param {string} id @param {URLSearchParams} query
251
+ * @returns {Promise<import("./types/reviewWire.js").FeedbackPage>} */
252
+ feedback: (id, query) => call("GET", `${project(id)}/feedback?${query}`),
253
+ /** A new version from a local MP4. A body factory runs after sign-in on each attempt.
254
+ * @param {string} id @param {ExportRequest | (() => Promise<ExportRequest>)} body @returns {Promise<ExportDTO>} */
255
+ createExport: (id, body) => call("POST", `${project(id)}/exports`, body),
256
+ /** @param {string} id @param {string} videoId @returns {Promise<ExportDTO>} */
257
+ readExport: (id, videoId) => call("GET", `${project(id)}/exports/${encodeURIComponent(videoId)}`),
258
+ /** The upload is in storage: start processing. @param {string} id @param {string} videoId
259
+ * @returns {Promise<ExportDTO>} */
260
+ completeExport: (id, videoId) => call("POST", `${project(id)}/exports/${encodeURIComponent(videoId)}/complete`),
261
+ /** Attaches the synced snapshot to a version that has none; the same one again is a no-op, another is refused
262
+ * with 409 `snapshot_already_attached`. @param {string} id @param {string} versionId
263
+ * @param {import("./types/reviewWire.js").SnapshotRef} snapshot @returns {Promise<unknown>} */
264
+ attachSnapshot: (id, versionId, snapshot) => call("PUT", `${project(id)}/versions/${encodeURIComponent(versionId)}/snapshot`, snapshot),
265
+ ...shareOpenCalls(tokenCall),
266
+ ...managementClient(call, project, access),
267
+ ...threadWrites(call, project)
268
+ };
269
+ }
270
+ function threadWrites(call, project) {
271
+ const thread = (id, rootId) => `${project(id)}/comments/${encodeURIComponent(rootId)}`;
272
+ return {
273
+ /** Accept, dismiss, reopen or resolve a thread. @param {string} id @param {string} rootId
274
+ * @param {{ action: import("./types/review.js").ReviewAction, expected_status_revision: number }} body */
275
+ setStatus: (id, rootId, body) => call("PATCH", `${thread(id, rootId)}/status`, body),
276
+ /** @param {string} id @param {string} rootId
277
+ * @param {{ client_operation_id: string, body: string, attachment_ids: string[] }} body */
278
+ reply: (id, rootId, body) => call("POST", `${thread(id, rootId)}/replies`, body)
279
+ };
280
+ }
281
+ function regrantOf(error, body) {
282
+ if (!(error instanceof ReviewFailed) || error.reason !== "revision_conflict") return null;
283
+ if (typeof error.currentRevision !== "number") return null;
284
+ const revision = error.currentRevision || null;
285
+ if (revision === body.expected_revision) return null;
286
+ return { ...body, client_operation_id: randomUUID(), expected_revision: revision };
287
+ }
288
+ function grantCalls(call, project, access) {
289
+ const sent = /* @__PURE__ */ new Map();
290
+ const revoked = /* @__PURE__ */ new Map();
291
+ const scopeOf = async (id) => {
292
+ const who = await access().catch(() => null);
293
+ return [who?.heygen ?? "", who?.owner ?? "", id].join("\n");
294
+ };
295
+ const settle = async (route, key, body) => {
296
+ try {
297
+ const answer = await call("POST", route, body);
298
+ sent.delete(key);
299
+ return answer;
300
+ } catch (error) {
301
+ if (rejectedGrantRequest(error)) sent.delete(key);
302
+ throw error;
303
+ }
304
+ };
305
+ const regranting = (route, key, body) => {
306
+ sent.set(key, { email: body.email, regrant: body });
307
+ return settle(route, key, body);
308
+ };
309
+ const forgetEarlierInvites = (scope, email) => {
310
+ for (const [other, kept] of sent)
311
+ if (other.startsWith(`${scope}
312
+ `) && kept.email === email) sent.delete(other);
313
+ };
314
+ return {
315
+ /** The project's live grants. @param {string} id
316
+ * @returns {Promise<{items: import("./types/reviewWire.js").AccessGrantDTO[]}>} */
317
+ grants: async (id) => {
318
+ const scope = await scopeOf(id);
319
+ const items = await everyGrant(call, `${project(id)}/access-grants`);
320
+ revoked.set(
321
+ scope,
322
+ new Map(
323
+ items.filter((grant2) => grant2.revoked_at).map((grant2) => [grant2.email, grant2.revision])
324
+ )
325
+ );
326
+ return { items: items.filter((grant2) => !grant2.revoked_at) };
327
+ },
328
+ /** @param {string} id @param {import("./types/reviewWire.js").CreateGrantRequest} body
329
+ * @returns {Promise<import("./types/reviewWire.js").AccessGrantDTO>} */
330
+ createGrant: async (id, body) => {
331
+ const route = `${project(id)}/access-grants`;
332
+ const scope = await scopeOf(id);
333
+ const key = `${scope}
334
+ ${body.client_operation_id}`;
335
+ const retained = sent.get(key);
336
+ if (retained) return settle(route, key, retained.regrant);
337
+ forgetEarlierInvites(scope, body.email);
338
+ const known = body.expected_revision === null ? revoked.get(scope)?.get(body.email) : void 0;
339
+ revoked.get(scope)?.delete(body.email);
340
+ const first = known === void 0 ? body : { ...body, client_operation_id: randomUUID(), expected_revision: known };
341
+ try {
342
+ return await (first === body ? call("POST", route, body) : regranting(route, key, first));
343
+ } catch (error) {
344
+ const regrant = regrantOf(error, first);
345
+ if (!regrant) throw error;
346
+ return regranting(route, key, regrant);
347
+ }
348
+ }
349
+ };
350
+ }
351
+ async function everyGrant(call, route) {
352
+ const items = [];
353
+ const cursors = /* @__PURE__ */ new Set();
354
+ let cursor = null;
355
+ do {
356
+ const query = new URLSearchParams({ include_revoked: "true", ...cursor ? { cursor } : {} });
357
+ const page = await call("GET", `${route}?${query}`);
358
+ items.push(...page.items);
359
+ cursor = page.next_cursor;
360
+ if (cursor && (cursors.has(cursor) || cursors.size >= 1e3))
361
+ throw new ReviewFailed(502, "malformed_grant_pagination");
362
+ cursors.add(cursor);
363
+ } while (cursor);
364
+ return items;
365
+ }
366
+ function managementClient(call, project, access) {
367
+ return {
368
+ /** @param {string} id @param {{ title: string, expected_title: string }} body
369
+ * @returns {Promise<{title: string}>} */
370
+ updateTitle: (id, body) => call("PATCH", project(id), body),
371
+ /** @param {string} spaceId @param {string | null} [cursor] @returns
372
+ * {Promise<import("./types/reviewWire.js").ManagedReviewPage>} */
373
+ listProjects: (spaceId, cursor = null) => call("GET", `${PROJECTS}?${new URLSearchParams(cursor ? { cursor } : {})}`, void 0, {
374
+ "x-space-id": spaceId
375
+ }),
376
+ /** @param {string} id @returns {Promise<null>} */
377
+ removeProject: (id) => call("DELETE", project(id)),
378
+ ...grantCalls(call, project, access),
379
+ /** @param {string} id @param {string} grantId @param {{role: import("./types/reviewWire.js").AccessGrantDTO["role"],
380
+ * expected_revision: number}} body @returns {Promise<import("./types/reviewWire.js").AccessGrantDTO>} */
381
+ updateGrant: (id, grantId, body) => call("PATCH", `${project(id)}/access-grants/${encodeURIComponent(grantId)}`, body),
382
+ /** @param {string} id @param {string} grantId @returns {Promise<null>} */
383
+ revokeGrant: (id, grantId) => call("DELETE", `${project(id)}/access-grants/${encodeURIComponent(grantId)}`)
384
+ };
385
+ }
386
+
387
+ // ../share/src/projectLock.mjs
388
+ import fs, {
389
+ lstat as lstat2,
390
+ mkdir as mkdir2,
391
+ open,
392
+ readdir,
393
+ readFile as readFile2,
394
+ realpath,
395
+ rmdir,
396
+ unlink,
397
+ writeFile as writeFile2
398
+ } from "fs/promises";
399
+ import { join as join2 } from "path";
400
+ import { hostname } from "os";
401
+ import { randomUUID as randomUUID3 } from "crypto";
402
+
403
+ // ../share/src/storage.mjs
404
+ import {
405
+ lstat,
406
+ mkdir,
407
+ readFile,
408
+ writeFile,
409
+ rename as renameFile,
410
+ rm as remove
411
+ } from "fs/promises";
412
+ import { basename, join, sep } from "path";
413
+ import { randomUUID as randomUUID2 } from "crypto";
414
+ var errorCode = (error) => error instanceof Error && "code" in error ? error.code : void 0;
415
+ async function retryBusy(run2) {
416
+ const waits = [10, 25, 50, 100, 200];
417
+ for (let attempt = 0; ; attempt++) {
418
+ try {
419
+ return await run2();
420
+ } catch (error) {
421
+ const delay = waits[attempt];
422
+ if (process.platform !== "win32" || !["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"].includes(String(errorCode(error))) || delay === void 0)
423
+ throw error;
424
+ await new Promise((resolve) => setTimeout(resolve, delay));
425
+ }
426
+ }
427
+ }
428
+ var rename = (from, to) => retryBusy(() => renameFile(from, to));
429
+ var rm = (path4, options) => retryBusy(() => remove(path4, options));
430
+ async function mkdirInside(root, rel) {
431
+ let dir = root;
432
+ for (const part of rel.split(sep).filter(Boolean)) {
433
+ if (part === ".." || part === ".") throw new Error("Invalid metadata directory.");
434
+ dir = join(dir, part);
435
+ await mkdir(dir).catch((error) => {
436
+ if (errorCode(error) !== "EEXIST") throw error;
437
+ });
438
+ if (!(await lstat(dir)).isDirectory())
439
+ throw new Error("The destination must be a real folder, not a link.");
440
+ }
441
+ return dir;
442
+ }
443
+ var queued = /* @__PURE__ */ new Map();
444
+ function writeJsonAtomic(path4, data) {
445
+ const text = JSON.stringify(data, null, 2);
446
+ const save = (queued.get(path4) ?? Promise.resolve()).then(async () => {
447
+ const temp = `${path4}.${randomUUID2()}.tmp`;
448
+ try {
449
+ await writeFile(temp, text, { mode: 384 });
450
+ await rename(temp, path4);
451
+ } finally {
452
+ await rm(temp, { force: true });
453
+ }
454
+ });
455
+ const settled = save.catch(() => {
456
+ });
457
+ queued.set(path4, settled);
458
+ void settled.then(() => queued.get(path4) === settled && queued.delete(path4));
459
+ return save;
460
+ }
461
+ var SharingStateError = class extends Error {
462
+ /** @param {string} path @param {unknown} [cause] */
463
+ constructor(path4, cause) {
464
+ super(
465
+ `Sharing state in .hyperframes/${basename(path4)} could not be read. Restore this file from a backup, or contact support to reconnect the existing share. Keep the file; deleting it can lose recovery state or create a duplicate share.`,
466
+ { cause }
467
+ );
468
+ this.name = "SharingStateError";
469
+ }
470
+ };
471
+ async function readJsonOr(path4, fallback) {
472
+ try {
473
+ return JSON.parse(await readFile(path4, "utf8"));
474
+ } catch (error) {
475
+ if (errorCode(error) !== "ENOENT") throw new SharingStateError(path4, error);
476
+ return (
477
+ /** @type {Record<string, unknown> | Exclude<T, object>} */
478
+ fallback
479
+ );
480
+ }
481
+ }
482
+ var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
483
+ var isSavedId = (value) => typeof value === "string" && value.trim() !== "";
484
+ var isNullableSavedId = (value) => value === null || isSavedId(value);
485
+ var isOptionalSavedId = (value) => value === void 0 || isNullableSavedId(value);
486
+ var isOptionalBoolean = (value) => value === void 0 || typeof value === "boolean";
487
+ async function readJsonRecord(path4) {
488
+ const value = await readJsonOr(path4, void 0);
489
+ if (value === void 0) return null;
490
+ if (!isJsonObject(value)) throw new SharingStateError(path4);
491
+ return value;
492
+ }
493
+
494
+ // ../share/src/projectLock.mjs
495
+ var ShareBusyError = class extends Error {
496
+ /** @param {string} path */
497
+ constructor(path4) {
498
+ super("Another process is sharing this project. Wait for it to finish, then retry.");
499
+ this.name = "ShareBusyError";
500
+ this.reason = "review_operation_busy";
501
+ this.lockPath = path4;
502
+ }
503
+ };
504
+ function isOwner(value) {
505
+ return isJsonObject(value) && typeof value.token === "string" && /^[a-f0-9-]{36}$/.test(value.token) && typeof value.pid === "number" && Number.isInteger(value.pid) && value.pid > 0 && typeof value.hostname === "string";
506
+ }
507
+ async function ownerAt(path4) {
508
+ try {
509
+ const value = JSON.parse(await readFile2(path4, "utf8"));
510
+ return isOwner(value) ? value : null;
511
+ } catch (error) {
512
+ if (missing(error) || errorCode(error) === "EISDIR" || error instanceof SyntaxError)
513
+ return null;
514
+ throw error;
515
+ }
516
+ }
517
+ function isDead(owner) {
518
+ if (owner.hostname !== hostname()) return false;
519
+ try {
520
+ process.kill(owner.pid, 0);
521
+ return false;
522
+ } catch (error) {
523
+ return errorCode(error) === "ESRCH";
524
+ }
525
+ }
526
+ function missing(error) {
527
+ return errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR";
528
+ }
529
+ function lockAt(path4) {
530
+ return lstat2(path4).catch((error) => {
531
+ if (missing(error)) return null;
532
+ throw error;
533
+ });
534
+ }
535
+ async function reapFile(path4) {
536
+ const old = await ownerAt(path4);
537
+ if (!old || !isDead(old)) return;
538
+ const claim2 = `${path4}.reap-${old.token}`;
539
+ const guard = await open(claim2, "wx", 384).catch((error) => {
540
+ if (errorCode(error) === "EEXIST") return null;
541
+ throw error;
542
+ });
543
+ if (!guard) return;
544
+ try {
545
+ if ((await ownerAt(path4))?.token === old.token) await unlink(path4);
546
+ } finally {
547
+ await guard.close();
548
+ await unlink(claim2);
549
+ }
550
+ }
551
+ async function removeEmptyDirectory(path4) {
552
+ await rmdir(path4).catch((error) => {
553
+ if (!missing(error) && !["ENOTEMPTY", "EEXIST"].includes(String(errorCode(error)))) throw error;
554
+ });
555
+ }
556
+ async function releaseDirectory(path4, marker) {
557
+ await unlink(join2(path4, marker)).catch((error) => {
558
+ if (!missing(error)) throw error;
559
+ });
560
+ await removeEmptyDirectory(path4);
561
+ }
562
+ async function reapDirectory(path4) {
563
+ const entries = await readdir(path4, { withFileTypes: true }).catch((error) => {
564
+ if (missing(error)) return [];
565
+ throw error;
566
+ });
567
+ if (entries.length === 0) return removeEmptyDirectory(path4);
568
+ const [entry] = entries;
569
+ if (entries.length !== 1 || !entry?.isFile()) return;
570
+ const owner = await ownerAt(join2(path4, entry.name));
571
+ if (owner && entry.name === `${owner.token}.json` && isDead(owner))
572
+ await releaseDirectory(path4, entry.name);
573
+ }
574
+ async function reap(path4) {
575
+ const stat2 = await lockAt(path4);
576
+ if (stat2?.isFile()) return reapFile(path4);
577
+ if (stat2?.isDirectory()) return reapDirectory(path4);
578
+ }
579
+ async function claim(draft, marker, lock, deadline) {
580
+ try {
581
+ await fs.link(join2(draft, marker), lock);
582
+ return "file";
583
+ } catch (error) {
584
+ if (errorCode(error) === "EEXIST") return null;
585
+ if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EINVAL", "EISDIR", "EACCES"].includes(
586
+ String(errorCode(error))
587
+ ))
588
+ throw error;
589
+ }
590
+ return claimDirectory(draft, lock, deadline);
591
+ }
592
+ async function claimDirectory(draft, lock, deadline) {
593
+ try {
594
+ await fs.rename(draft, lock);
595
+ return "directory";
596
+ } catch (error) {
597
+ const code = String(errorCode(error));
598
+ if (["EEXIST", "ENOTEMPTY", "ENOTDIR", "EISDIR"].includes(code)) return null;
599
+ if (["EPERM", "EACCES", "EBUSY"].includes(code)) {
600
+ if (await lockAt(lock)) return null;
601
+ if (process.platform === "win32" && Date.now() < deadline) return null;
602
+ }
603
+ throw error;
604
+ }
605
+ }
606
+ async function withProjectShareLock(projectPath, lane, run2, { timeoutMs = 3e4, signal } = {}) {
607
+ const root = await realpath(projectPath);
608
+ const folder = await mkdirInside(root, ".hyperframes");
609
+ const lock = join2(
610
+ folder,
611
+ lane === "operation" ? "share-operation.lock" : lane === "review" ? "review.lock" : lane === "source" ? "share-source.lock" : "review-export.lock"
612
+ );
613
+ const owner = { token: randomUUID3(), pid: process.pid, hostname: hostname() };
614
+ const draft = `${lock}.${owner.token}.tmp`;
615
+ const marker = `${owner.token}.json`;
616
+ await mkdir2(draft, { mode: 448 });
617
+ const deadline = Date.now() + timeoutMs;
618
+ let held = null;
619
+ try {
620
+ await writeFile2(join2(draft, marker), JSON.stringify(owner), { flag: "wx", mode: 384 });
621
+ while (!held) {
622
+ signal?.throwIfAborted();
623
+ held = await claim(draft, marker, lock, deadline);
624
+ if (held) break;
625
+ await reap(lock);
626
+ if (Date.now() >= deadline) throw new ShareBusyError(lock);
627
+ await new Promise((resolve) => setTimeout(resolve, 25));
628
+ }
629
+ signal?.throwIfAborted();
630
+ return await run2();
631
+ } finally {
632
+ try {
633
+ if (held === "directory") await releaseDirectory(lock, marker);
634
+ if (held === "file" && (await ownerAt(lock))?.token === owner.token) await unlink(lock);
635
+ } finally {
636
+ await releaseDirectory(draft, marker);
637
+ }
638
+ }
639
+ }
640
+
641
+ // ../share/src/reviewAudience.mjs
642
+ function firstReviewAudience(entitlements, chosen) {
643
+ if (entitlements === void 0) return chosen ?? "team";
644
+ if (!entitlements) throw new ReviewFailed(503, "review_entitlement_unavailable");
645
+ const audience = chosen ?? (entitlements.allowed_collaborative_access_modes.includes("team") ? "team" : null);
646
+ if (!audience)
647
+ throw new ReviewFailed(402, "review_public_consent_required", void 0, void 0, {
648
+ reason: "review_public_consent_required",
649
+ workspace_id: entitlements.workspace_id
650
+ });
651
+ if (audience !== "private" && !entitlements.allowed_collaborative_access_modes.includes(audience))
652
+ throw new ReviewFailed(402, "review_subscription_required", void 0, void 0, {
653
+ reason: "review_subscription_required",
654
+ workspace_id: entitlements.workspace_id,
655
+ requested_feature: audience
656
+ });
657
+ return audience;
658
+ }
659
+
660
+ // ../share/src/reviewShare.mjs
661
+ import { randomUUID as randomUUID4 } from "crypto";
662
+ import path from "path";
663
+ var chosenSite = null;
664
+ var site = () => chosenSite ?? channelSite();
665
+ var setReviewSite = (now) => {
666
+ chosenSite = now;
667
+ };
668
+ var recordPath = (projectPath, at = site()) => path.join(
669
+ projectPath,
670
+ ".hyperframes",
671
+ at === channelSite() ? "review.json" : `review-${new URL(at).host}.json`
672
+ );
673
+ function isRegistration(value) {
674
+ return isJsonObject(value) && isSavedId(value.studio_project_id) && isSavedId(value.client_operation_id) && typeof value.title === "string";
675
+ }
676
+ var isSavedIdentity = (record) => isSavedId(record.studioProjectId) && isOptionalSavedId(record.spaceId) && isOptionalSavedId(record.projectId) && isOptionalBoolean(record.opened) && isOptionalBoolean(record.removed) && (!record.opened || isSavedId(record.projectId));
677
+ function savedRegistration(value, studioProjectId, file) {
678
+ if (value == null) return void 0;
679
+ if (!isRegistration(value) || value.studio_project_id !== studioProjectId)
680
+ throw new SharingStateError(file);
681
+ return value;
682
+ }
683
+ async function readRecord(projectPath, at = site()) {
684
+ const file = recordPath(projectPath, at);
685
+ const record = await readJsonRecord(file);
686
+ if (!record) return null;
687
+ const { site: madeOn = channelSite() } = record;
688
+ if (madeOn !== at || !isSavedIdentity(record)) throw new SharingStateError(file);
689
+ return {
690
+ studioProjectId: record.studioProjectId,
691
+ spaceId: record.spaceId ?? null,
692
+ projectId: record.projectId ?? null,
693
+ opened: record.opened === true,
694
+ removed: record.removed === true,
695
+ registration: savedRegistration(record.registration, record.studioProjectId, file),
696
+ site: madeOn,
697
+ ownerEmail: typeof record.ownerEmail === "string" ? record.ownerEmail : null
698
+ };
699
+ }
700
+ var backendName = (at) => at === channelSite() ? "Production" : "Dev";
701
+ async function sharedElsewhere(projectPath) {
702
+ for (const other of signinSites()) {
703
+ const record = other === site() ? null : await readRecord(projectPath, other);
704
+ if (record?.opened && record.projectId)
705
+ return new ReviewFailed(409, `other_backend:${backendName(other)}`);
706
+ }
707
+ return null;
708
+ }
709
+ var spaceRefOf = (space) => ({
710
+ id: space.space_id,
711
+ name: space.name,
712
+ kind: space.kind,
713
+ ...typeof space.has_other_members === "boolean" && { hasOtherMembers: space.has_other_members }
714
+ });
715
+ var statusOf = (share) => ({
716
+ projectId: share.project_id,
717
+ url: share.revoked ? null : share.review_url,
718
+ access: share.access_mode,
719
+ role: share.default_role,
720
+ commentsOn: share.comments_enabled,
721
+ space: share.space ? spaceRefOf(share.space) : null,
722
+ elsewhere: false,
723
+ entitlements: share.review_entitlements,
724
+ ...share.sharing_state && { sharingState: share.sharing_state },
725
+ held: share.moderation_hold === true,
726
+ ...takenDown(share) && { takedown: { page: share.authenticated_review_url } }
727
+ });
728
+ var takenDown = (share) => share.moderation_hold_kind === "takedown";
729
+ var listSpaces = (client) => client.spaces().catch((error) => {
730
+ if (error instanceof ReviewFailed && error.status === 404) return [];
731
+ throw error;
732
+ });
733
+ function signedInSpace(spaces) {
734
+ const creatable = spaces.filter((space) => space.can_create_review);
735
+ return spaces.find((space) => space.bound) ?? (creatable.length === 1 ? creatable[0] : null);
736
+ }
737
+ async function shown(client, share) {
738
+ const bound2 = (await listSpaces(client).catch(() => [])).find((space) => space.bound);
739
+ const elsewhere = Boolean(bound2 && share.space && share.space.space_id !== bound2.space_id);
740
+ return { ...statusOf(share), elsewhere };
741
+ }
742
+ var ownerRefusal = (client, projectPath) => async (error) => {
743
+ if (!(error instanceof ReviewFailed)) throw error;
744
+ if (error.reason === "permission_denied") {
745
+ const [record, now] = await Promise.all([
746
+ projectPath ? readRecord(projectPath) : null,
747
+ client.signedInEmail()
748
+ ]);
749
+ const owner = record?.ownerEmail;
750
+ const other = owner && now && owner.toLowerCase() !== now.toLowerCase();
751
+ throw new ReviewFailed(403, other ? OWNER_SIGNED_OUT + owner : "no_access");
752
+ }
753
+ throw error.status === 404 ? new ReviewFailed(404, "another_account") : error;
754
+ };
755
+ var OWNER_SIGNED_OUT = "owner_signed_out:";
756
+ var ownerOf = (reason) => reason.startsWith(OWNER_SIGNED_OUT) ? reason.slice(OWNER_SIGNED_OUT.length) : null;
757
+ function projectLine() {
758
+ const queues = /* @__PURE__ */ new Map();
759
+ const inTurn2 = (projectPath, run2) => {
760
+ const key = normalize(projectPath);
761
+ const next = (queues.get(key) ?? Promise.resolve()).then(run2, run2);
762
+ const settled = next.catch(() => {
763
+ });
764
+ queues.set(key, settled);
765
+ void settled.then(() => queues.get(key) === settled && queues.delete(key));
766
+ return next;
767
+ };
768
+ return {
769
+ inTurn: inTurn2,
770
+ busy: (projectPath) => queues.has(normalize(projectPath))
771
+ };
772
+ }
773
+ var metadataLine = projectLine().inTurn;
774
+ var oneAtATime = (projectPath, run2) => metadataLine(projectPath, () => withProjectShareLock(projectPath, "review", run2));
775
+ async function changeShare(client, id, share, change) {
776
+ for (let read = share, retried = false; ; retried = true) {
777
+ const body = {
778
+ access_mode: read.access_mode,
779
+ default_role: read.default_role,
780
+ comments_enabled: read.comments_enabled,
781
+ ...change,
782
+ expected_revision: read.revision
783
+ };
784
+ if (body.access_mode !== "team" && body.default_role === "editor")
785
+ body.default_role = "commenter";
786
+ try {
787
+ return await client.updateShare(id, body);
788
+ } catch (error) {
789
+ const stale = error instanceof ReviewFailed && error.reason === "revision_conflict";
790
+ if (retried || !stale) throw error;
791
+ read = await client.share(id);
792
+ }
793
+ }
794
+ }
795
+ async function sharedId(projectPath, _client) {
796
+ const record = await readRecord(projectPath);
797
+ if (record?.removed) throw new ReviewFailed(410, "review_project_removed");
798
+ if (!record?.opened || !record.projectId)
799
+ throw await sharedElsewhere(projectPath) ?? new ReviewFailed(404, "not_shared");
800
+ return record.projectId;
801
+ }
802
+ async function reviewProjectId(projectPath) {
803
+ const record = await readRecord(projectPath);
804
+ return !record?.removed && record?.opened && record.projectId ? record.projectId : null;
805
+ }
806
+ var reviewRecord = (projectPath) => readRecord(projectPath);
807
+ var reviewSwitchPath = (projectPath) => recordPath(projectPath).replace(/\.json$/, ".switch.json");
808
+ async function readReviewSwitch(dir) {
809
+ const file = reviewSwitchPath(dir);
810
+ const change = await readJsonRecord(file);
811
+ if (!change) return null;
812
+ if (!isSavedId(change.from) || !isSavedId(change.spaceId) || typeof change.space !== "string" || !isNullableSavedId(change.projectId) || change.id !== void 0 && !isSavedId(change.id) || !isOptionalBoolean(change.opened) || !isOptionalBoolean(change.paused) || change.opened && !isSavedId(change.projectId) || !isRegistration(change.body)) {
813
+ throw new SharingStateError(file);
814
+ }
815
+ return (
816
+ /** @type {import("./reviewSwitch.mjs").Switch} */
817
+ change
818
+ );
819
+ }
820
+ var rebound = /* @__PURE__ */ new Set();
821
+ var announceRebound = (projectPath) => {
822
+ for (const listener of rebound) listener(normalize(projectPath));
823
+ };
824
+ var readShare = (client, id, projectPath) => client.share(id).catch(ownerRefusal(client, projectPath));
825
+ async function reviewStatus({ projectPath, client }) {
826
+ const record = await readRecord(projectPath);
827
+ if (record?.removed) throw new ReviewFailed(410, "review_project_removed");
828
+ if (!record?.opened || !record.projectId) {
829
+ const held = await takenDownFirst(client, record);
830
+ if (held) return held;
831
+ const elsewhere = await sharedElsewhere(projectPath);
832
+ if (elsewhere) throw elsewhere;
833
+ return null;
834
+ }
835
+ try {
836
+ return shown(client, await readShare(client, record.projectId, projectPath));
837
+ } catch (error) {
838
+ if (error instanceof ReviewFailed && error.reason === "review_project_removed")
839
+ await markReviewRemoved(projectPath, record.projectId);
840
+ throw error;
841
+ }
842
+ }
843
+ async function takenDownFirst(client, record) {
844
+ if (!record?.projectId) return null;
845
+ const share = await readShare(client, record.projectId).catch((error) => {
846
+ if (error instanceof ReviewFailed && error.reason === "review_project_removed") throw error;
847
+ return null;
848
+ });
849
+ return share && takenDown(share) ? shown(client, share) : null;
850
+ }
851
+ async function recordToShare(client, projectPath, spaceId) {
852
+ const record = await readRecord(projectPath);
853
+ if (record?.removed) throw new ReviewFailed(410, "review_project_removed");
854
+ if (record?.projectId) return record;
855
+ const space = await registrationSpace(client, spaceId, record);
856
+ if (record && space === record.spaceId) return record;
857
+ const fresh = {
858
+ studioProjectId: record?.studioProjectId ?? randomUUID4(),
859
+ spaceId: space,
860
+ projectId: null,
861
+ opened: false,
862
+ site: site(),
863
+ ownerEmail: null
864
+ };
865
+ await mkdirInside(projectPath, ".hyperframes");
866
+ await writeJsonAtomic(recordPath(projectPath), fresh);
867
+ return fresh;
868
+ }
869
+ async function registrationSpace(client, requested, record) {
870
+ return requested ?? record?.spaceId ?? signedInSpace(await listSpaces(client))?.space_id ?? null;
871
+ }
872
+ async function registerOnce(client, projectPath, record, title) {
873
+ const body = record.registration ?? {
874
+ studio_project_id: record.studioProjectId,
875
+ title: title.slice(0, 255),
876
+ client_operation_id: randomUUID4()
877
+ };
878
+ await writeJsonAtomic(recordPath(projectPath), { ...record, registration: body });
879
+ try {
880
+ return (await client.register(body, record.spaceId)).project_id;
881
+ } catch (error) {
882
+ if (!(error instanceof ReviewFailed) || error.reason !== "space_forbidden") throw error;
883
+ await writeJsonAtomic(recordPath(projectPath), { ...record, spaceId: null });
884
+ throw await spaceRefusal(client, record.spaceId, error);
885
+ }
886
+ }
887
+ async function spaceRefusal(client, refused, error) {
888
+ const here = signedInSpace(await listSpaces(client).catch(() => []));
889
+ const changed = Boolean(refused && here && here.space_id !== refused);
890
+ return changed ? error : new ReviewFailed(403, "workspace_cannot_share");
891
+ }
892
+ var shareForReview = ({
893
+ projectPath,
894
+ title,
895
+ client,
896
+ spaceId = null,
897
+ audience,
898
+ beforeOpen
899
+ }) => oneAtATime(projectPath, async () => {
900
+ const read = await recordToShare(client, projectPath, spaceId);
901
+ const id = read.projectId ?? await registerOnce(client, projectPath, read, title);
902
+ const record = read.projectId ? read : { ...read, projectId: id, ownerEmail: await client.signedInEmail() };
903
+ if (!read.projectId) await writeJsonAtomic(recordPath(projectPath), record);
904
+ const share = await readShare(client, id, projectPath);
905
+ if (takenDown(share)) return shown(client, share);
906
+ if (!record.opened || share.revoked) await beforeOpen?.(id);
907
+ return openLink(client, projectPath, record, id, share, audience).then(
908
+ (opened) => shown(client, opened),
909
+ heldInstead(client, id)
910
+ );
911
+ });
912
+ async function openLink(client, projectPath, record, id, share, audience) {
913
+ if (share.revoked)
914
+ share = await client.linkOn(id, {
915
+ expected_link_generation: share.link_generation,
916
+ client_operation_id: randomUUID4()
917
+ });
918
+ if (!record.opened) {
919
+ share = await applyFirstAudience(client, id, share, audience);
920
+ await writeJsonAtomic(recordPath(projectPath), { ...record, projectId: id, opened: true });
921
+ }
922
+ return share;
923
+ }
924
+ async function applyFirstAudience(client, id, share, audience) {
925
+ const chosen = audience !== void 0 || share.access_mode === "private" ? firstReviewAudience(share.review_entitlements, audience) : share.access_mode;
926
+ if (share.access_mode !== chosen)
927
+ share = await changeShare(client, id, share, { access_mode: chosen });
928
+ return share;
929
+ }
930
+ var heldInstead = (client, id) => async (error) => {
931
+ if (!(error instanceof ReviewFailed) || error.reason !== "moderation_hold") throw error;
932
+ return shown(client, await readShare(client, id));
933
+ };
934
+ var setReviewAccess = ({ projectPath, client, change }) => oneAtATime(projectPath, async () => {
935
+ const id = await sharedId(projectPath, client);
936
+ const share = await readShare(client, id, projectPath);
937
+ const picked = "access" in change ? { access_mode: change.access } : { default_role: change.role };
938
+ return shown(client, await changeShare(client, id, share, picked));
939
+ });
940
+ var turnOffReviewLink = ({ projectPath, client }) => oneAtATime(projectPath, async () => {
941
+ const id = await sharedId(projectPath, client);
942
+ await client.linkOff(id).catch(ownerRefusal(client, projectPath));
943
+ return shown(client, await readShare(client, id, projectPath));
944
+ });
945
+ var SENTENCES = {
946
+ review_project_limit_reached: "This workspace has used its five review projects. Remove a review project or upgrade HyperFrames to create more.",
947
+ review_subscription_required: "Restricted sharing requires a HyperFrames subscription.",
948
+ review_public_consent_required: "Choose Share with anyone who has the link to continue.",
949
+ review_entitlement_unavailable: "Couldn't confirm sharing availability. Try again.",
950
+ review_project_changed: "This project\u2019s review changed. Reopen sharing and try again.",
951
+ review_project_removed: "This review project was removed. Share again to create a new link and discussion.",
952
+ moderation_hold: "This review was taken down for a policy violation, so it can't be shared.",
953
+ not_public: "Only a link anyone can open has a guest view. Open the review page instead.",
954
+ another_account: "This link was made by another HeyGen account, or was deleted. Sign in with the account that shared it.",
955
+ no_access: "This account can't open this project's review page. Sign in with the account that shared it, or ask to be added back to its workspace.",
956
+ workspace_cannot_share: "This workspace can't create review pages.",
957
+ space_forbidden: "Your workspace changed. Share again to use the workspace you're signed into.",
958
+ project_bound_to_other_owner: "Someone else in your workspace already shares this project. Duplicate it to share your own copy.",
959
+ feature_unavailable: "Review pages aren't available for your account yet."
960
+ };
961
+ function reviewSentence(error, fallback = "Couldn't share this project. Try again.") {
962
+ if (error instanceof SharingStateError) return error.message;
963
+ if (!(error instanceof ReviewFailed)) return fallback;
964
+ if (error.status === 0) return "Couldn't reach HeyGen. Check your connection and try again.";
965
+ if (error.status === 401) return "Your sign-in has expired. Sign in again, then share.";
966
+ if (error.reason.startsWith("other_backend:")) {
967
+ const name = error.reason.slice("other_backend:".length);
968
+ return `This review was shared on ${name}. Switch to ${name} to open it, or share again here.`;
969
+ }
970
+ const owner = ownerOf(error.reason);
971
+ if (owner) return `This review belongs to ${owner}. Switch to that account to manage it.`;
972
+ if (Object.hasOwn(SENTENCES, error.reason))
973
+ return SENTENCES[
974
+ /** @type {keyof typeof SENTENCES} */
975
+ error.reason
976
+ ];
977
+ if (error.status === 403) return "This account can't share this project for review yet.";
978
+ if (error.status === 429 || error.status === 503)
979
+ return "Sharing is busy right now. Try again in a moment.";
980
+ return fallback;
981
+ }
982
+ var markReviewRemoved = (projectPath, projectId) => oneAtATime(projectPath, () => retainRemovedRecord(projectPath, projectId));
983
+ async function retainRemovedRecord(projectPath, projectId) {
984
+ const record = await readRecord(projectPath);
985
+ const journal2 = await readReviewSwitch(projectPath);
986
+ if (journal2?.from === projectId || journal2?.projectId === projectId)
987
+ await rename(
988
+ reviewSwitchPath(projectPath),
989
+ reviewSwitchPath(projectPath).replace(/\.json$/, `.removed-${Date.now()}.json`)
990
+ );
991
+ if (record?.projectId !== projectId) return;
992
+ await writeJsonAtomic(recordPath(projectPath), { ...record, removed: true });
993
+ announceRebound(projectPath);
994
+ }
995
+
996
+ // ../share/src/reviewExport.mjs
997
+ import { randomUUID as randomUUID5 } from "crypto";
998
+ import { stat } from "fs/promises";
999
+ import path2 from "path";
1000
+
1001
+ // ../share/src/fromReview.mjs
1002
+ async function readFromReview(host2, dir) {
1003
+ const since = host2.now();
1004
+ try {
1005
+ const value = await host2.read(dir);
1006
+ return { since, ...value && { value } };
1007
+ } catch (error) {
1008
+ console.error("[share] review mark not read:", error);
1009
+ return { since };
1010
+ }
1011
+ }
1012
+ async function sharedFromReview(host2, dir, since) {
1013
+ if (!host2 || since === void 0) return;
1014
+ try {
1015
+ await host2.published(dir, since);
1016
+ } catch (error) {
1017
+ console.error("[share] review mark not cleared:", error);
1018
+ }
1019
+ }
1020
+
1021
+ // ../share/src/reviewUpload.mjs
1022
+ import { createHash } from "crypto";
1023
+ import { createReadStream } from "fs";
1024
+ function fileSha256Base64(file) {
1025
+ return new Promise((resolve, reject) => {
1026
+ const hash = createHash("sha256");
1027
+ createReadStream(file).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve(hash.digest("base64")));
1028
+ });
1029
+ }
1030
+ function trustedUploadUrl(url) {
1031
+ if (!URL.canParse(url)) return null;
1032
+ const target = new URL(url);
1033
+ const loopback = target.protocol === "http:" && target.hostname === "127.0.0.1";
1034
+ if (target.protocol !== "https:" && !loopback || target.username || target.password || target.hash || !reviewUploadOrigins().includes(target.origin))
1035
+ return null;
1036
+ return target;
1037
+ }
1038
+ async function putFile(upload2, file, size, onSent, { stallMs = 6e4, fetchImpl = fetch } = {}) {
1039
+ const target = trustedUploadUrl(upload2.put_url);
1040
+ if (!target) return "refused";
1041
+ const stall = new AbortController();
1042
+ let timer;
1043
+ const arm = () => (clearTimeout(timer), timer = setTimeout(() => stall.abort(), stallMs));
1044
+ let sent = 0;
1045
+ const stream = createReadStream(file);
1046
+ const chunks = stream[Symbol.asyncIterator]();
1047
+ const body = new ReadableStream(
1048
+ {
1049
+ async pull(controller) {
1050
+ const { value, done } = await chunks.next();
1051
+ if (done) return controller.close();
1052
+ sent += value.length;
1053
+ arm();
1054
+ onSent(sent);
1055
+ controller.enqueue(value);
1056
+ },
1057
+ cancel: () => void chunks.return?.()
1058
+ },
1059
+ { highWaterMark: 0 }
1060
+ );
1061
+ arm();
1062
+ try {
1063
+ const request = {
1064
+ method: "PUT",
1065
+ headers: { ...upload2.headers, "content-length": String(size) },
1066
+ body,
1067
+ duplex: "half",
1068
+ redirect: "manual",
1069
+ signal: stall.signal
1070
+ };
1071
+ const reply = await fetchImpl(target, request);
1072
+ return await outcomeOf(reply);
1073
+ } catch (error) {
1074
+ console.error(
1075
+ "[review] upload failed:",
1076
+ /** @type {Error} */
1077
+ error.name
1078
+ );
1079
+ return "offline";
1080
+ } finally {
1081
+ clearTimeout(timer);
1082
+ stream.destroy();
1083
+ }
1084
+ }
1085
+ async function outcomeOf(reply) {
1086
+ if (reply.status < 300) return await reply.body?.cancel(), "sent";
1087
+ const text = await reply.text().catch(() => "");
1088
+ return reply.status === 403 && /expired/i.test(text) ? "expired" : "refused";
1089
+ }
1090
+
1091
+ // ../share/src/reviewVersionSentences.mjs
1092
+ var HELD_FOR_REVIEW = "Almost ready. Someone at HyperFrames needs to take a look first. This can take up to a day.";
1093
+ var SAID = {
1094
+ export_too_large: "This video is over 2 GB, the most a review page takes. Export a smaller one.",
1095
+ export_too_long: "This video is over 30 minutes, the most a review page takes. Export a shorter one.",
1096
+ export_hourly_limit: (error) => `You've added the most versions for this hour. Try again ${laterIn(error.retryAfterMs, "in an hour")}.`,
1097
+ export_daily_limit: (error) => `You've added the most versions for today. Try again ${laterIn(error.retryAfterMs, "tomorrow")}.`,
1098
+ content_rejected: "This video can't be shared.",
1099
+ export_blocked: "Adding videos to review pages isn't available for this account.",
1100
+ feature_unavailable: "Review pages aren't available for your account yet.",
1101
+ permission_denied: "This account can't add videos to this review page yet.",
1102
+ upload_expired: "The upload took too long. Try again.",
1103
+ storage_refused: "HyperFrames couldn't store the upload. Try again.",
1104
+ still_checking: "HyperFrames is still checking the video. People with the link can watch once it's ready; open Share to look again.",
1105
+ held_for_review: HELD_FOR_REVIEW
1106
+ };
1107
+ function versionSentence(error, fallback = "Couldn't add this version. Try again.") {
1108
+ if (!(error instanceof ReviewFailed)) return fallback;
1109
+ const said2 = SAID[error.reason];
1110
+ if (said2) return typeof said2 === "function" ? said2(error) : said2;
1111
+ if (error.status === 0) return "Couldn't reach HeyGen. Check your connection and try again.";
1112
+ if (error.status === 401) return "Your sign-in has expired. Sign in again, then add the version.";
1113
+ if (error.status === 200)
1114
+ return "HyperFrames couldn't process this video. Export it again, then try again.";
1115
+ return fallback;
1116
+ }
1117
+ function laterIn(ms, unknown) {
1118
+ if (!ms) return unknown;
1119
+ const minutes = Math.ceil(ms / 6e4);
1120
+ if (minutes < 60) return `in ${minutes} minute${minutes === 1 ? "" : "s"}`;
1121
+ const hours = Math.round(minutes / 60);
1122
+ return `in about ${hours} hour${hours === 1 ? "" : "s"}`;
1123
+ }
1124
+
1125
+ // ../share/src/reviewExport.mjs
1126
+ var POLL_MS = 2e3;
1127
+ var SLOW_AFTER_MS = 2 * 6e4;
1128
+ var LATE_AFTER_MS = 15 * 6e4;
1129
+ var SLOW_POLL_MS = 3e4;
1130
+ var FINAL = /* @__PURE__ */ new Set(["export_blocked", "content_rejected", "feature_unavailable"]);
1131
+ var TOO_BIG = /* @__PURE__ */ new Set(["export_too_large", "export_too_long"]);
1132
+ var UNCONFIRMED_VERSION = "Couldn't confirm whether the previous version was created. Check the review page. To add a new version, change the export settings and export again.";
1133
+ var MAX_WAIT_MS = 5 * 6e4;
1134
+ var WATCH_MS = 15 * 6e4;
1135
+ var HELD_WATCH_MS = 24 * 60 * 6e4;
1136
+ var MAX_BYTES = 2 * 1024 ** 3;
1137
+ var MAX_SECONDS = 30 * 60;
1138
+ var run$ = runFile;
1139
+ var statePath = (dir) => path2.join(dir, ".hyperframes", "review-export.json");
1140
+ async function probeVideo(file) {
1141
+ try {
1142
+ const args = [
1143
+ "-v",
1144
+ "error",
1145
+ "-select_streams",
1146
+ "v:0",
1147
+ "-show_entries",
1148
+ "stream=width,height:format=duration",
1149
+ "-of",
1150
+ "json",
1151
+ "--",
1152
+ file
1153
+ ];
1154
+ const { stdout } = await run$(ffBinary("ffprobe"), args);
1155
+ return factsOf(stdout);
1156
+ } catch {
1157
+ return null;
1158
+ }
1159
+ }
1160
+ function factsOf(stdout) {
1161
+ const facts = JSON.parse(stdout);
1162
+ const { width, height } = facts.streams?.[0] ?? {};
1163
+ const duration = Number.parseFloat(facts.format?.duration);
1164
+ return width > 0 && height > 0 && duration > 0 ? { duration, width, height } : null;
1165
+ }
1166
+ var isSavedUpload = (upload2) => isJsonObject(upload2) && Number.isSafeInteger(upload2.size_bytes) && isSavedId(upload2.checksum_sha256) && upload2.content_type === "video/mp4";
1167
+ var isOptionalSnapshot = (snapshot) => snapshot === void 0 || isJsonObject(snapshot) && isSavedId(snapshot.space_id) && isSavedId(snapshot.composition_id) && isSavedId(snapshot.snapshot_id);
1168
+ var isSavedExportSource = (body) => body.source_revision_id === null && (body.source_fingerprint == null || typeof body.source_fingerprint === "string") && isOptionalSnapshot(body.snapshot);
1169
+ function isSavedExportBody(body) {
1170
+ if (!isJsonObject(body)) return false;
1171
+ return isSavedId(body.client_operation_id) && typeof body.title_snapshot === "string" && [body.coordinate_width, body.coordinate_height, body.duration_seconds].every(Number.isFinite) && isJsonObject(body.render_settings) && isSavedUpload(body.local_upload) && isSavedExportSource(body);
1172
+ }
1173
+ var isPending = (value) => isJsonObject(value) && isSavedExportBody(value.body) && isNullableSavedId(value.videoId) && isOptionalSavedId(value.projectId) && (value.checkingSince === void 0 || Number.isFinite(value.checkingSince)) && isOptionalBoolean(value.snapshotRefused) && isOptionalBoolean(value.unanswered) && isOptionalReviewSent(value.reviewSent);
1174
+ var isOptionalReviewSent = (sent) => sent === void 0 || isJsonObject(sent) && Number.isFinite(sent.since) && (sent.value === void 0 || sent.value === "yes" || sent.value === "no");
1175
+ function isLast(value) {
1176
+ return isJsonObject(value) && (value.fingerprint === void 0 || typeof value.fingerprint === "string") && isSavedId(value.versionId) && isSavedId(value.exportedAt) && isSavedId(value.projectId) && isLastMetadata(value);
1177
+ }
1178
+ function isLastMetadata(value) {
1179
+ return isOptionalBoolean(value.files) && isOptionalSnapshot(value.snapshot) && (value.checksum === void 0 || isSavedId(value.checksum));
1180
+ }
1181
+ var isExportState = (saved) => ("pending" in saved || "last" in saved) && (saved.pending == null || isPending(saved.pending)) && (saved.last == null || isLast(saved.last));
1182
+ var isSavedFailure = (value) => isJsonObject(value) && isSavedId(value.projectId) && typeof value.exportKey === "string" && typeof value.sentence === "string" && typeof value.final === "boolean" && typeof value.exportHelps === "boolean" && isOptionalBoolean(value.held);
1183
+ async function readState(dir) {
1184
+ const file = statePath(dir);
1185
+ const saved = await readJsonRecord(file);
1186
+ if (!saved) return { pending: null, last: null };
1187
+ if (!isExportState(saved)) throw new SharingStateError(file);
1188
+ const { last, pending } = saved;
1189
+ return {
1190
+ pending: pending ?? null,
1191
+ failure: isSavedFailure(saved.failure) ? saved.failure : null,
1192
+ last: typeof last?.fingerprint === "string" ? { ...last, fingerprint: last.fingerprint } : null
1193
+ };
1194
+ }
1195
+ async function writeState(dir, state) {
1196
+ await mkdirInside(dir, ".hyperframes");
1197
+ await writeJsonAtomic(statePath(dir), state);
1198
+ }
1199
+ function said(error, refusedReplay = false) {
1200
+ const sentence = versionSentence(error, refusedReplay ? UNCONFIRMED_VERSION : void 0);
1201
+ const exportHelps = sentence === UNCONFIRMED_VERSION || error instanceof ReviewFailed && TOO_BIG.has(error.reason);
1202
+ return {
1203
+ sentence,
1204
+ final: exportHelps || error instanceof ReviewFailed && FINAL.has(error.reason),
1205
+ exportHelps,
1206
+ ...error instanceof ReviewFailed && error.reason === "held_for_review" && { held: true }
1207
+ };
1208
+ }
1209
+ var local = (sentence) => ({ sentence, final: false, exportHelps: false });
1210
+ var inFlight = /* @__PURE__ */ new Map();
1211
+ var wakers = /* @__PURE__ */ new Map();
1212
+ var woken = /* @__PURE__ */ new Set();
1213
+ var failures = /* @__PURE__ */ new Map();
1214
+ var exportKeyOf = (dir) => {
1215
+ const latest = latestExportFile(dir);
1216
+ return latest ? `${latest.id}
1217
+ ${latest.path}
1218
+ ${latest.fingerprint ?? ""}` : "";
1219
+ };
1220
+ function sourceOf(dir, now) {
1221
+ const latest = latestExportFile(dir);
1222
+ if (!latest) return "none";
1223
+ if (!/\.mp4$/i.test(latest.path)) return "not-mp4";
1224
+ return latest.fingerprint === now ? "ready" : "stale";
1225
+ }
1226
+ async function reviewVersion(projectPath, server = {}) {
1227
+ const [state, now, projectId] = await Promise.all([
1228
+ readState(projectPath),
1229
+ projectFingerprint(projectPath),
1230
+ reviewProjectId(projectPath)
1231
+ ]);
1232
+ const key = normalize(projectPath);
1233
+ const last = state.last?.projectId === projectId ? state.last : null;
1234
+ const onServer = server.latestReadyVersionId === void 0 || server.latestReadyVersionId === last?.versionId;
1235
+ const savedFailure = state.failure?.projectId === projectId ? state.failure : null;
1236
+ const failed = savedFailure ?? failures.get(key);
1237
+ return {
1238
+ last: last ? { exportedAt: last.exportedAt, current: last.fingerprint === now && onServer } : null,
1239
+ source: sourceOf(projectPath, now),
1240
+ exporting: inFlight.get(key) ?? null,
1241
+ ...failed?.exportKey === exportKeyOf(projectPath) ? {
1242
+ failure: failed.sentence,
1243
+ retryable: !failed.final,
1244
+ exportHelps: failed.exportHelps,
1245
+ ...failed.held && { held: true }
1246
+ } : { failure: null }
1247
+ };
1248
+ }
1249
+ async function exportSource(dir, title, probe, filesForExport, requireSource) {
1250
+ const latest = latestExportFile(dir);
1251
+ if (!latest || sourceOf(dir, await projectFingerprint(dir)) !== "ready")
1252
+ return { failure: local("Export an MP4 of the project as it is now first.") };
1253
+ const { size } = await stat(latest.path);
1254
+ if (size > MAX_BYTES) return { failure: said(new ReviewFailed(400, "export_too_large")) };
1255
+ const facts = await probe(latest.path);
1256
+ if (!facts) return { failure: local("Couldn't read this video. Export it again.") };
1257
+ if (facts.duration > MAX_SECONDS)
1258
+ return { failure: said(new ReviewFailed(400, "export_too_long")) };
1259
+ const body = {
1260
+ client_operation_id: `export-${randomUUID5()}`,
1261
+ title_snapshot: title.slice(0, 255),
1262
+ coordinate_width: facts.width,
1263
+ coordinate_height: facts.height,
1264
+ duration_seconds: facts.duration,
1265
+ render_settings: {},
1266
+ source_revision_id: null,
1267
+ // The project as rendered, which is what the version shows; never "now".
1268
+ source_fingerprint: latest.fingerprint ?? null,
1269
+ local_upload: {
1270
+ size_bytes: size,
1271
+ checksum_sha256: await fileSha256Base64(latest.path),
1272
+ content_type: "video/mp4"
1273
+ }
1274
+ };
1275
+ const snapshot = await sourceSnapshot(
1276
+ dir,
1277
+ body.source_fingerprint,
1278
+ filesForExport,
1279
+ requireSource
1280
+ );
1281
+ if (missingRequiredSource(requireSource, snapshot))
1282
+ return {
1283
+ failure: local(
1284
+ "Source changed after preparation. Retry sharing, or choose video-only explicitly."
1285
+ )
1286
+ };
1287
+ if (snapshot) body.snapshot = snapshot;
1288
+ return { file: latest.path, body };
1289
+ }
1290
+ var missingRequiredSource = (required, snapshot) => required && !snapshot;
1291
+ async function sourceSnapshot(dir, rendered, filesForExport, requireSource) {
1292
+ return filesForExport(dir, rendered).catch((error) => {
1293
+ if (requireSource) throw error;
1294
+ console.error("[review files] could not read source; adding video only:", error);
1295
+ return null;
1296
+ });
1297
+ }
1298
+ var sameSnapshot = (a, b) => a?.space_id === b?.space_id && a?.composition_id === b?.composition_id && a?.snapshot_id === b?.snapshot_id;
1299
+ function bodyToSend(state, fresh, projectId) {
1300
+ const pending = state.pending;
1301
+ if (pending && sameRender(pending, fresh, projectId) && reusableSnapshot(pending, fresh))
1302
+ return pending;
1303
+ return { body: fresh, videoId: null, projectId };
1304
+ }
1305
+ function sameRender(pending, fresh, projectId) {
1306
+ return (pending.projectId ?? projectId) === projectId && (pending.body.source_fingerprint ?? null) === fresh.source_fingerprint && pending.body.local_upload.checksum_sha256 === fresh.local_upload.checksum_sha256;
1307
+ }
1308
+ function reusableSnapshot(pending, fresh) {
1309
+ if (pending.videoId || pending.snapshotRefused || pending.unanswered) return true;
1310
+ return sameSnapshot(pending.body.snapshot, fresh.snapshot);
1311
+ }
1312
+ var unanswered = (error) => !(error instanceof ReviewFailed) || error.status === 0 || error.status === 408 || error.status >= 500;
1313
+ async function createdExport(r, id, pending, kept) {
1314
+ if (pending.videoId) return { dto: await r.client.readExport(id, pending.videoId), pending };
1315
+ try {
1316
+ return await sendCreate(r, id, pending, kept);
1317
+ } catch (error) {
1318
+ const refused = error instanceof ReviewFailed && error.reason === "snapshot_mismatch";
1319
+ if (!refused || !pending.body.snapshot || pending.unanswered || r.requireSource) throw error;
1320
+ console.error("[review] snapshot refused; the version goes up without files:", error);
1321
+ const body = { ...pending.body, client_operation_id: `export-${randomUUID5()}` };
1322
+ delete body.snapshot;
1323
+ const next = { ...pending, body, snapshotRefused: true };
1324
+ await kept(next);
1325
+ return sendCreate(r, id, next, kept);
1326
+ }
1327
+ }
1328
+ async function sendCreate(r, id, pending, kept) {
1329
+ const host2 = r.fromReview;
1330
+ const { from_review: _, ...body } = pending.body;
1331
+ const replay = pending.unanswered;
1332
+ const beforeSend = (reviewSent) => kept({ ...pending, unanswered: true, reviewSent });
1333
+ let mark;
1334
+ try {
1335
+ if (!host2 && !replay) await beforeSend();
1336
+ const dto = await r.client.createExport(
1337
+ id,
1338
+ host2 ? async () => {
1339
+ mark = await readFromReview(host2, r.projectPath);
1340
+ if (!replay) await beforeSend({ since: mark.since });
1341
+ return { ...body, ...mark.value && { from_review: mark.value } };
1342
+ } : pending.body
1343
+ );
1344
+ const reviewSent = replay ? cleanupOnly(pending.reviewSent) : mark;
1345
+ return { dto, pending: { ...pending, unanswered: false, reviewSent } };
1346
+ } catch (error) {
1347
+ if (!replay && !unanswered(error)) await kept(pending);
1348
+ throw error;
1349
+ }
1350
+ }
1351
+ var cleanupOnly = (mark) => mark && { since: mark.since };
1352
+ function uploadReporter(size, report) {
1353
+ let shown2 = -1;
1354
+ return (sent) => {
1355
+ const percent = Math.floor(sent / Math.max(size, 1) * 100);
1356
+ if (percent !== shown2) {
1357
+ shown2 = percent;
1358
+ report({ step: "uploading", sent, total: size });
1359
+ }
1360
+ };
1361
+ }
1362
+ async function upload(r, id, created, file, size, report) {
1363
+ let current = created;
1364
+ for (let tries = 0; current.status === "upload_pending" && current.upload && tries < 2; tries++) {
1365
+ const sent = await r.put(current.upload, file, size, uploadReporter(size, report));
1366
+ if (sent === "offline") throw new ReviewFailed(0, "offline");
1367
+ if (sent === "refused") throw new ReviewFailed(502, "storage_refused");
1368
+ if (sent === "sent") return r.client.completeExport(id, current.video_id);
1369
+ current = await r.client.readExport(id, current.video_id);
1370
+ }
1371
+ if (current.status === "upload_pending") throw new ReviewFailed(410, "upload_expired");
1372
+ return current;
1373
+ }
1374
+ var going = (dto) => dto.status === "processing" || dto.status === "screening";
1375
+ var screeningWatch = (current) => {
1376
+ if (current.screening_state === "held") return HELD_WATCH_MS;
1377
+ return current.screening_state ? 2 * LATE_AFTER_MS : 0;
1378
+ };
1379
+ async function watch(r, id, current, size, report, clock) {
1380
+ let until = r.now() + WATCH_MS;
1381
+ let { since } = clock;
1382
+ let checkingSince = Infinity;
1383
+ while (going(current)) {
1384
+ if (current.status === "screening") {
1385
+ checkingSince = Math.min(checkingSince, r.now());
1386
+ if (since === null) await clock.keep(since = r.now());
1387
+ until = Math.max(until, since + screeningWatch(current));
1388
+ }
1389
+ const progress = progressOf(
1390
+ current,
1391
+ size,
1392
+ r.now() - (since ?? Infinity),
1393
+ r.now() - checkingSince
1394
+ );
1395
+ report(progress);
1396
+ if (r.now() >= until || !r.open()) return current;
1397
+ current = await poll(r, id, current, until, progress.slow ? SLOW_POLL_MS : POLL_MS);
1398
+ }
1399
+ return current;
1400
+ }
1401
+ function progressOf(current, size, sinceUpload, sinceChecking) {
1402
+ const checking = current.status === "screening";
1403
+ const screening = checking ? current.screening_state : null;
1404
+ const late = screening === "checking" && sinceUpload >= LATE_AFTER_MS;
1405
+ const progress = {
1406
+ step: checking ? "checking" : "processing",
1407
+ sent: size,
1408
+ total: size,
1409
+ slow: screening === "held" || sinceChecking >= SLOW_AFTER_MS
1410
+ };
1411
+ if (screening) progress.screening = screening;
1412
+ if (late) progress.late = true;
1413
+ return progress;
1414
+ }
1415
+ async function checkingClock(r, kept, completedNow, keep) {
1416
+ if (kept === null && completedNow) await keep(kept = r.now());
1417
+ return { since: kept, keep };
1418
+ }
1419
+ var stillGoing = (done) => said(
1420
+ new ReviewFailed(
1421
+ 202,
1422
+ done.status === "screening" && done.screening_state === "held" ? "held_for_review" : "still_checking"
1423
+ )
1424
+ );
1425
+ var transient = (error) => error instanceof ReviewFailed && (error.status === 0 || error.status === 429 || error.status >= 500);
1426
+ async function poll(r, id, current, until, every) {
1427
+ const key = normalize(r.projectPath);
1428
+ for (let wait = every; ; ) {
1429
+ if (!woken.delete(key))
1430
+ await new Promise((done) => {
1431
+ wakers.set(key, () => done(void 0));
1432
+ void r.sleep(wait).then(done);
1433
+ });
1434
+ wakers.delete(key);
1435
+ try {
1436
+ return await r.client.readExport(id, current.video_id);
1437
+ } catch (error) {
1438
+ if (!transient(error) || r.now() >= until) throw error;
1439
+ if (!r.open()) return current;
1440
+ wait = Math.min(
1441
+ MAX_WAIT_MS,
1442
+ Math.max(
1443
+ every,
1444
+ /** @type {ReviewFailed} */
1445
+ error.retryAfterMs ?? 0
1446
+ )
1447
+ );
1448
+ }
1449
+ }
1450
+ }
1451
+ var permanentRefusal = (error) => error instanceof ReviewFailed && error.status >= 400 && error.status < 500 && ![401, 408, 429].includes(error.status);
1452
+ async function finish(dir, state, pending, id, done, fromReview) {
1453
+ const ready = done.status === "ready";
1454
+ const last = readyRecord(pending, id, done);
1455
+ const failure = ready ? null : said(new ReviewFailed(200, done.error?.reason ?? ""));
1456
+ await writeState(dir, {
1457
+ pending: null,
1458
+ last: ready ? last : state.last,
1459
+ ...failure && {
1460
+ failure: { ...failure, projectId: id, exportKey: await failedExportKey(dir, pending) }
1461
+ }
1462
+ });
1463
+ if (ready) await sharedFromReview(fromReview, dir, pending.reviewSent?.since);
1464
+ return failure;
1465
+ }
1466
+ async function failedExportKey(dir, pending) {
1467
+ if (typeof pending.renderKey === "string") return pending.renderKey;
1468
+ const latest = latestExportFile(dir);
1469
+ if (!latest) return "";
1470
+ const checksum = latest.fingerprint === pending.body.source_fingerprint ? await fileSha256Base64(latest.path).catch(() => null) : null;
1471
+ return checksum === pending.body.local_upload.checksum_sha256 ? exportKeyOf(dir) : `pending:${pending.body.client_operation_id}`;
1472
+ }
1473
+ async function run(r, report) {
1474
+ report({ step: "preparing", sent: 0, total: 0 });
1475
+ const state = await readState(r.projectPath);
1476
+ const source = await exportSource(
1477
+ r.projectPath,
1478
+ r.title,
1479
+ r.probe,
1480
+ r.omitSource ? noSource : r.filesForExport,
1481
+ r.requireSource
1482
+ );
1483
+ if ("failure" in source) return source.failure ?? null;
1484
+ const id = r.projectId ?? await reviewProjectId(r.projectPath);
1485
+ if (!id) return local("Share the project first, then add a version.");
1486
+ if (sameSourceMode(r, state.last, source.body.snapshot) && await alreadyUploaded(r.client, id, state, source.body))
1487
+ return null;
1488
+ return sendVersion(r, report, source, id, state);
1489
+ }
1490
+ var noSource = async () => null;
1491
+ function sameSourceMode(r, last, snapshot) {
1492
+ if (r.requireSource) return sameSnapshot(last?.snapshot, snapshot);
1493
+ if (r.omitSource) return last?.files !== true;
1494
+ return true;
1495
+ }
1496
+ async function alreadyUploaded(client, id, state, body) {
1497
+ const last = state.last;
1498
+ if (state.pending || state.failure?.projectId === id || !last || last.projectId !== id)
1499
+ return false;
1500
+ if (last.fingerprint !== body.source_fingerprint || last.checksum !== body.local_upload.checksum_sha256)
1501
+ return false;
1502
+ return (await client.project(id)).latest_ready_version_id === last.versionId;
1503
+ }
1504
+ async function sendVersion(r, report, source, id, state) {
1505
+ const first = state.last?.projectId !== id;
1506
+ let pending = bindRenderKey(bodyToSend(state, source.body, id), r.projectPath);
1507
+ const sourceConflict = pendingSourceConflict(r, pending, source.body);
1508
+ if (sourceConflict) return local(sourceConflict);
1509
+ await writeState(r.projectPath, state = { ...state, pending, failure: null });
1510
+ try {
1511
+ const answer = await createdExport(
1512
+ r,
1513
+ id,
1514
+ pending,
1515
+ (next) => writeState(r.projectPath, state = { ...state, pending: next })
1516
+ );
1517
+ const created = answer.dto;
1518
+ pending = answer.pending;
1519
+ await writeState(
1520
+ r.projectPath,
1521
+ state = { ...state, pending: { ...pending, videoId: created.video_id } }
1522
+ );
1523
+ const size = pending.body.local_upload.size_bytes;
1524
+ const uploaded = await upload(r, id, created, source.file, size, report);
1525
+ if (uploaded.status !== "failed") await r.onUploaded();
1526
+ const clock = await checkingClock(
1527
+ r,
1528
+ state.pending?.checkingSince ?? null,
1529
+ created.status === "upload_pending" && going(uploaded),
1530
+ async (since) => {
1531
+ const kept = { ...pending, videoId: created.video_id, checkingSince: since };
1532
+ await writeState(r.projectPath, state = { ...state, pending: kept });
1533
+ }
1534
+ );
1535
+ const done = await watch(r, id, uploaded, size, report, clock);
1536
+ return finishRun(r, state, pending, id, done, first);
1537
+ } catch (error) {
1538
+ return failedSend(r.projectPath, state, pending, id, error);
1539
+ }
1540
+ }
1541
+ async function failedSend(dir, state, pending, id, error) {
1542
+ const refused = permanentRefusal(error);
1543
+ const unansweredCreate = state.pending?.unanswered === true && state.pending.videoId === null;
1544
+ const failure = said(error, refused && unansweredCreate);
1545
+ await writeState(dir, {
1546
+ ...state,
1547
+ pending: refused && !unansweredCreate ? null : state.pending,
1548
+ failure: { ...failure, projectId: id, exportKey: await failedExportKey(dir, pending) }
1549
+ });
1550
+ return failure;
1551
+ }
1552
+ function pendingSourceConflict(r, pending, fresh) {
1553
+ if (r.requireSource && !pending.body.snapshot)
1554
+ return "A pending video-only upload must finish before attaching source. Retry with --video-only, then share source again.";
1555
+ if (r.omitSource && pending.body.snapshot)
1556
+ return "A pending upload includes source. Check its status or retry with source before creating a video-only version.";
1557
+ if (r.requireSource && !sameSnapshot(pending.body.snapshot, fresh.snapshot))
1558
+ return "A pending upload includes a different source snapshot. Check its status before sharing again.";
1559
+ return null;
1560
+ }
1561
+ async function finishRun(r, state, pending, id, done, first) {
1562
+ if (going(done)) return r.allowPending ? null : stillGoing(done);
1563
+ const failed = await finish(r.projectPath, state, pending, id, done, r.fromReview);
1564
+ if (!failed) {
1565
+ const fromReview = pending.reviewSent?.value;
1566
+ r.onAdded({ files: Boolean(pending.body.snapshot), first, ...fromReview && { fromReview } });
1567
+ }
1568
+ return failed;
1569
+ }
1570
+ async function addVersion(request) {
1571
+ let uploaded = false;
1572
+ const r = {
1573
+ put: putFile,
1574
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
1575
+ probe: probeVideo,
1576
+ // Read through Date each time, so a walk can move main's clock under a run.
1577
+ now: () => Date.now(),
1578
+ onProgress: () => {
1579
+ },
1580
+ open: () => true,
1581
+ allowPending: false,
1582
+ filesForExport: noSource,
1583
+ fromReview: null,
1584
+ requireSource: false,
1585
+ omitSource: false,
1586
+ onAdded: () => {
1587
+ },
1588
+ ...request,
1589
+ projectId: request.projectId ?? null,
1590
+ onUploaded: async () => {
1591
+ uploaded = true;
1592
+ await request.onUploaded?.();
1593
+ }
1594
+ };
1595
+ const key = normalize(r.projectPath);
1596
+ if (inFlight.has(key)) return null;
1597
+ failures.delete(key);
1598
+ const report = (progress) => (inFlight.set(key, progress), r.onProgress(progress));
1599
+ try {
1600
+ report({ step: "preparing", sent: 0, total: 0 });
1601
+ const failure = await withProjectShareLock(r.projectPath, "export", () => run(r, report));
1602
+ const kept = failure && (uploaded || !request.projectId);
1603
+ if (kept) failures.set(key, { ...failure, exportKey: exportKeyOf(r.projectPath) });
1604
+ return failure?.sentence ?? null;
1605
+ } catch (error) {
1606
+ const sentence = error instanceof SharingStateError ? error.message : "Couldn't add this version. Try again.";
1607
+ failures.set(key, {
1608
+ sentence,
1609
+ final: false,
1610
+ exportHelps: false,
1611
+ exportKey: exportKeyOf(r.projectPath)
1612
+ });
1613
+ return sentence;
1614
+ } finally {
1615
+ inFlight.delete(key);
1616
+ woken.delete(key);
1617
+ r.onProgress(null);
1618
+ }
1619
+ }
1620
+ async function whenExportIdle(dir, run2) {
1621
+ try {
1622
+ await withProjectShareLock(dir, "export", run2, { timeoutMs: 0 });
1623
+ } catch (error) {
1624
+ if (!(error instanceof ShareBusyError)) throw error;
1625
+ }
1626
+ }
1627
+ async function refreshReviewExport(projectPath, client, fromReview = null) {
1628
+ await whenExportIdle(projectPath, () => settleSavedExport(projectPath, client, fromReview));
1629
+ }
1630
+ async function settleSavedExport(dir, client, fromReview) {
1631
+ const state = await readState(dir);
1632
+ const pending = state.pending;
1633
+ const id = await reviewProjectId(dir);
1634
+ if (!pending?.videoId || !id || pending.projectId !== id) return;
1635
+ const done = await client.readExport(id, pending.videoId);
1636
+ if (done.status === "upload_pending" || going(done)) return;
1637
+ const failure = await finish(dir, state, pending, id, done, fromReview);
1638
+ const key = normalize(dir);
1639
+ if (failure) failures.set(key, { ...failure, exportKey: exportKeyOf(dir) });
1640
+ else failures.delete(key);
1641
+ }
1642
+ async function versionOnPage(dir) {
1643
+ const [state, projectId] = await Promise.all([readState(dir), reviewProjectId(dir)]);
1644
+ if (inFlight.has(normalize(dir))) return null;
1645
+ return state.last?.projectId === projectId ? state.last : null;
1646
+ }
1647
+ async function pendingReviewExport(projectPath) {
1648
+ const { pending } = await readState(projectPath);
1649
+ if (!pending) return null;
1650
+ return {
1651
+ projectId: pending.projectId ?? null,
1652
+ videoId: pending.videoId,
1653
+ operationId: pending.body.client_operation_id,
1654
+ fingerprint: pending.body.source_fingerprint ?? null,
1655
+ checksum: pending.body.local_upload.checksum_sha256
1656
+ };
1657
+ }
1658
+ function readyRecord(pending, id, done) {
1659
+ return {
1660
+ fingerprint: pending.body.source_fingerprint ?? "",
1661
+ versionId: done.version_id,
1662
+ exportedAt: done.exported_at,
1663
+ projectId: id,
1664
+ files: Boolean(pending.body.snapshot),
1665
+ ...pending.body.snapshot && { snapshot: pending.body.snapshot },
1666
+ checksum: pending.body.local_upload.checksum_sha256
1667
+ };
1668
+ }
1669
+ function bindRenderKey(pending, dir) {
1670
+ return typeof pending.renderKey === "string" ? pending : { ...pending, renderKey: exportKeyOf(dir) };
1671
+ }
1672
+
1673
+ // ../share/src/reviewSwitch.mjs
1674
+ import { createHash as createHash2, randomUUID as randomUUID6 } from "crypto";
1675
+ var journal = projectLine();
1676
+ var inTurn = journal.inTurn;
1677
+
1678
+ // ../share/src/sourceIgnore.mjs
1679
+ import { constants } from "fs";
1680
+ import { lstat as lstat3, open as open2 } from "fs/promises";
1681
+ import { join as join3 } from "path";
1682
+ var SourceIgnoreError = class extends Error {
1683
+ code = "invalid_source_ignore";
1684
+ };
1685
+ var scratch = (path4) => /(?:^|\/)[^/]+\.(?:log|swp)$/.test(path4);
1686
+ async function readSourceIgnore(root) {
1687
+ const file = join3(root, ".hyperframesignore");
1688
+ const invalid = () => new SourceIgnoreError(
1689
+ ".hyperframesignore must be a regular file inside the project, smaller than 64 KiB."
1690
+ );
1691
+ const handle = await open2(
1692
+ file,
1693
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
1694
+ ).catch(async (error) => {
1695
+ if (error.code !== "ENOENT") throw invalid();
1696
+ const named = await lstat3(file).catch((missing2) => {
1697
+ if (missing2.code === "ENOENT") return null;
1698
+ throw invalid();
1699
+ });
1700
+ if (named) throw invalid();
1701
+ return null;
1702
+ });
1703
+ if (!handle) return scratch;
1704
+ let text;
1705
+ try {
1706
+ const [stat2, named] = await Promise.all([handle.stat(), lstat3(file)]);
1707
+ if (!stat2.isFile() || stat2.size >= 65536 || !named.isFile() || stat2.ino !== named.ino || stat2.dev !== named.dev)
1708
+ throw invalid();
1709
+ const buffer = Buffer.alloc(65536);
1710
+ let length = 0;
1711
+ while (length < buffer.length) {
1712
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
1713
+ if (!bytesRead) break;
1714
+ length += bytesRead;
1715
+ }
1716
+ if (length === buffer.length) throw invalid();
1717
+ text = buffer.subarray(0, length).toString("utf8");
1718
+ } finally {
1719
+ await handle.close();
1720
+ }
1721
+ const paths = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
1722
+ const entries = paths.map(ignorePattern);
1723
+ return (path4) => scratch(path4) || entries.some((entry) => entry.test(path4));
1724
+ }
1725
+ function ignorePattern(entry) {
1726
+ const path4 = entry.replace(/\/$/, "");
1727
+ const invalid = () => new SourceIgnoreError(
1728
+ ".hyperframesignore accepts project-relative paths or patterns with one * wildcard. Negation, traversal, and excluding index.html are not supported."
1729
+ );
1730
+ if (!validPatternPath(path4)) throw invalid();
1731
+ const escaped2 = path4.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*");
1732
+ const prefix = path4.includes("*") && !path4.includes("/") ? "(?:^|/)" : "^";
1733
+ const pattern = new RegExp(`${prefix}${escaped2}(?:/|$)`);
1734
+ if (pattern.test("index.html")) throw invalid();
1735
+ return pattern;
1736
+ }
1737
+ function validPatternPath(path4) {
1738
+ return !/[\\?![\]:]/.test(path4) && !path4.includes("\0") && !path4.split("/").some((part) => !part || part === "." || part === "..") && path4.split("*").length <= 2;
1739
+ }
1740
+
1741
+ // ../share/src/projectSnapshot.mjs
1742
+ import fs2 from "fs/promises";
1743
+ import { constants as constants2 } from "fs";
1744
+ import path3 from "path";
1745
+ import { createHash as createHash3 } from "crypto";
1746
+
1747
+ // ../share/src/appOwnedPaths.mjs
1748
+ var pathParts = (path4) => path4.split(/[\\/]/);
1749
+ var APP_OWNED_DIRS = [
1750
+ ".thumbnails",
1751
+ ".hyperframes",
1752
+ ".claude",
1753
+ "renders",
1754
+ ".transcode-cache",
1755
+ ".waveform-cache"
1756
+ ];
1757
+ var isAppOwned = (relativePath) => APP_OWNED_DIRS.includes(
1758
+ /** @type {string} */
1759
+ pathParts(relativePath)[0]
1760
+ );
1761
+ function isOutsideFilm(relativePath) {
1762
+ const parts = pathParts(relativePath);
1763
+ return isAppOwned(relativePath) || parts.some((part) => part.startsWith(".") || part === "node_modules") || /(?:~|\.swp|\.tmp|\.part)$/.test(parts.at(-1) ?? "");
1764
+ }
1765
+
1766
+ // ../share/src/projectSnapshot.mjs
1767
+ var HF_ID_ATTRIBUTE = /\sdata-hf-id\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/g;
1768
+ var sha256 = (data) => createHash3("sha256").update(data).digest("hex");
1769
+ function contentKey(html) {
1770
+ return sha256(html.replace(HF_ID_ATTRIBUTE, ""));
1771
+ }
1772
+ async function snapshotKey(full, byContent) {
1773
+ const resolved = await fs2.realpath(full).catch(() => null);
1774
+ if (!resolved) return void 0;
1775
+ const handle = await fs2.open(resolved, constants2.O_RDONLY | constants2.O_NOFOLLOW).catch(() => null);
1776
+ if (!handle) return void 0;
1777
+ try {
1778
+ const stat2 = await handle.stat();
1779
+ if (!stat2.isFile()) return void 0;
1780
+ if (full.endsWith(".html")) return contentKey(await handle.readFile("utf8"));
1781
+ if (byContent) return await hashFile(handle);
1782
+ return `${stat2.mtimeMs}:${stat2.size}`;
1783
+ } catch {
1784
+ return void 0;
1785
+ } finally {
1786
+ await handle.close();
1787
+ }
1788
+ }
1789
+ async function hashFile(handle) {
1790
+ const hash = createHash3("sha256");
1791
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk);
1792
+ return hash.digest("hex");
1793
+ }
1794
+ async function entryKind(entry, full, followSymlinks) {
1795
+ if (!entry.isSymbolicLink()) return entry;
1796
+ return followSymlinks ? fs2.stat(full).catch(() => null) : null;
1797
+ }
1798
+ async function snapshotProject(dir, { byContent = false, followSymlinks = false } = {}) {
1799
+ const result = /* @__PURE__ */ new Map();
1800
+ const ignored = await readSourceIgnore(dir);
1801
+ async function walk(current, ancestors) {
1802
+ const real = await fs2.realpath(current).catch(() => null);
1803
+ if (!real || ancestors.has(real)) return;
1804
+ const parents = /* @__PURE__ */ new Set([...ancestors, real]);
1805
+ let entries;
1806
+ try {
1807
+ entries = await fs2.readdir(current, { withFileTypes: true });
1808
+ } catch {
1809
+ return;
1810
+ }
1811
+ for (const entry of entries) {
1812
+ const full = path3.join(current, entry.name);
1813
+ if (excludedFromSnapshot(dir, full, ignored)) continue;
1814
+ const kind = await entryKind(entry, full, followSymlinks);
1815
+ if (kind?.isDirectory()) await walk(full, parents);
1816
+ else if (kind?.isFile()) {
1817
+ const key = await snapshotKey(full, byContent);
1818
+ if (key !== void 0) result.set(path3.relative(dir, full), key);
1819
+ }
1820
+ }
1821
+ }
1822
+ await walk(dir, /* @__PURE__ */ new Set());
1823
+ return result;
1824
+ }
1825
+ function snapshotFingerprint(snapshot) {
1826
+ const files = [...snapshot].sort(([a], [b]) => a < b ? -1 : 1);
1827
+ return createHash3("sha256").update(JSON.stringify(files)).digest("hex");
1828
+ }
1829
+ var projectFingerprint2 = async (projectPath, options) => snapshotFingerprint(await snapshotProject(projectPath, { ...options, followSymlinks: true }));
1830
+ function excludedFromSnapshot(dir, full, ignored) {
1831
+ const relative = path3.relative(dir, full);
1832
+ return isOutsideFilm(relative) || ignored(relative.split(path3.sep).join("/"));
1833
+ }
1834
+
1835
+ // ../share/src/shareSources.mjs
1836
+ import { realpath as realpath4 } from "fs/promises";
1837
+ import { randomUUID as randomUUID8 } from "crypto";
1838
+ import { basename as basename2 } from "path";
1839
+
1840
+ // ../share/src/sources/capture.mjs
1841
+ import { createHash as createHash5 } from "crypto";
1842
+ import { constants as constants3 } from "fs";
1843
+ import { lstat as lstat4, open as open3, readdir as readdir2, realpath as realpath2 } from "fs/promises";
1844
+ import { dirname, join as join5 } from "path";
1845
+
1846
+ // ../share/src/sources/manifest.mjs
1847
+ import { createHash as createHash4 } from "crypto";
1848
+
1849
+ // ../share/src/sources/contract.mjs
1850
+ import { existsSync, readFileSync } from "fs";
1851
+ import { brotliDecompressSync } from "zlib";
1852
+ function readContract(name) {
1853
+ const packed = new URL(`./contract/${name}.br`, import.meta.url);
1854
+ const text = existsSync(packed) ? brotliDecompressSync(readFileSync(packed)).toString("utf8") : readFileSync(new URL(`./contract/${name}`, import.meta.url), "utf8");
1855
+ return JSON.parse(text);
1856
+ }
1857
+
1858
+ // ../share/src/sources/unicode.mjs
1859
+ var UNICODE_VERSION = "15.1.0";
1860
+ var HANGUL_BASE = 44032;
1861
+ var HANGUL_COUNT = 11172;
1862
+ var L_BASE = 4352;
1863
+ var V_BASE = 4449;
1864
+ var T_BASE = 4519;
1865
+ var L_COUNT = 19;
1866
+ var V_COUNT = 21;
1867
+ var T_COUNT = 28;
1868
+ var N_COUNT = V_COUNT * T_COUNT;
1869
+ function tablesOf(raw) {
1870
+ if (raw.unicode_version !== UNICODE_VERSION)
1871
+ throw new Error(`unicode table is ${raw.unicode_version}, expected ${UNICODE_VERSION}`);
1872
+ const hex = (code) => Number.parseInt(code, 16);
1873
+ const casefold = new Map(Object.entries(raw.casefold).map(([code, to]) => [hex(code), to]));
1874
+ const combining = new Map(Object.entries(raw.combining).map(([code, cc]) => [hex(code), cc]));
1875
+ const direct = new Map(Object.entries(raw.decomposition).map(([code, seq]) => [hex(code), seq]));
1876
+ const expand = (code) => direct.get(code)?.flatMap(expand) ?? [code];
1877
+ const decomposition = new Map([...direct.keys()].map((code) => [code, expand(code)]));
1878
+ const composition = new Map(
1879
+ Object.entries(raw.composition).map(([pair, composite]) => {
1880
+ const [first = "", second = ""] = pair.split(",");
1881
+ return [`${hex(first)},${hex(second)}`, composite];
1882
+ })
1883
+ );
1884
+ const starts = raw.assigned_ranges.map(([start]) => start);
1885
+ const ends = raw.assigned_ranges.map(([, end]) => end);
1886
+ return { casefold, combining, decomposition, composition, starts, ends };
1887
+ }
1888
+ var loaded = null;
1889
+ var tables = () => loaded ??= tablesOf(readContract("unicode-15.1.0.json"));
1890
+ var classOf = (code) => tables().combining.get(code) ?? 0;
1891
+ function decompose(code) {
1892
+ const syllable = code - HANGUL_BASE;
1893
+ if (syllable >= 0 && syllable < HANGUL_COUNT) {
1894
+ const trailing = syllable % T_COUNT;
1895
+ const leading = [
1896
+ L_BASE + Math.floor(syllable / N_COUNT),
1897
+ V_BASE + Math.floor(syllable % N_COUNT / T_COUNT)
1898
+ ];
1899
+ return trailing ? [...leading, T_BASE + trailing] : leading;
1900
+ }
1901
+ return tables().decomposition.get(code) ?? [code];
1902
+ }
1903
+ function composePair(first, second) {
1904
+ if (first >= L_BASE && first < L_BASE + L_COUNT && second >= V_BASE && second < V_BASE + V_COUNT)
1905
+ return HANGUL_BASE + ((first - L_BASE) * V_COUNT + second - V_BASE) * T_COUNT;
1906
+ return composeSyllable(first, second) ?? tables().composition.get(`${first},${second}`);
1907
+ }
1908
+ function composeSyllable(first, second) {
1909
+ if (first >= HANGUL_BASE && first < HANGUL_BASE + HANGUL_COUNT && (first - HANGUL_BASE) % T_COUNT === 0 && second > T_BASE && second < T_BASE + T_COUNT)
1910
+ return first + second - T_BASE;
1911
+ }
1912
+ function orderedCodes(value) {
1913
+ const ordered = [];
1914
+ for (const char of value) {
1915
+ for (const code of decompose(char.codePointAt(0) ?? 0)) {
1916
+ const current = classOf(code);
1917
+ let position = ordered.length;
1918
+ while (current && position && classOf(ordered[position - 1] ?? 0) > current) position--;
1919
+ ordered.splice(position, 0, code);
1920
+ }
1921
+ }
1922
+ return ordered;
1923
+ }
1924
+ function composed(ordered) {
1925
+ const result = [];
1926
+ let starter = 0;
1927
+ let lastClass = 0;
1928
+ for (const code of ordered) {
1929
+ const current = classOf(code);
1930
+ const head = result[starter];
1931
+ const composite = head === void 0 ? void 0 : composePair(head, code);
1932
+ if (composite !== void 0 && (lastClass < current || lastClass === 0)) {
1933
+ result[starter] = composite;
1934
+ continue;
1935
+ }
1936
+ if (current === 0) starter = result.length;
1937
+ result.push(code);
1938
+ lastClass = current;
1939
+ }
1940
+ return String.fromCodePoint(...result);
1941
+ }
1942
+ var ASCII = new RegExp("^\\p{ASCII}*$", "u");
1943
+ var nfc = (value) => ASCII.test(value) ? value : composed(orderedCodes(value));
1944
+ function fullCasefold(value) {
1945
+ if (ASCII.test(value)) return value.toLowerCase();
1946
+ let folded = "";
1947
+ for (const char of value) folded += tables().casefold.get(char.codePointAt(0) ?? 0) ?? char;
1948
+ return folded;
1949
+ }
1950
+ function allAssigned(value) {
1951
+ const { starts, ends } = tables();
1952
+ for (const char of value) {
1953
+ const code = char.codePointAt(0) ?? 0;
1954
+ let low = 0;
1955
+ let high = starts.length;
1956
+ while (low < high) {
1957
+ const middle = low + high >>> 1;
1958
+ if ((starts[middle] ?? Infinity) <= code) low = middle + 1;
1959
+ else high = middle;
1960
+ }
1961
+ if (low === 0 || code > (ends[low - 1] ?? -1)) return false;
1962
+ }
1963
+ return true;
1964
+ }
1965
+ var KEYS_KEPT = 16384;
1966
+ var keys = /* @__PURE__ */ new Map();
1967
+ function comparisonKey(value) {
1968
+ const known = keys.get(value);
1969
+ if (known !== void 0) return known;
1970
+ const key = nfc(fullCasefold(nfc(value)));
1971
+ if (keys.size >= KEYS_KEPT) keys.clear();
1972
+ keys.set(value, key);
1973
+ return key;
1974
+ }
1975
+
1976
+ // ../share/src/sources/pathPolicy.mjs
1977
+ var PATH_POLICY_VERSION = "portable-source-v4";
1978
+ var PathViolation = class extends Error {
1979
+ /** @param {string} code @param {string} path @param {string} [rule] */
1980
+ constructor(code, path4, rule) {
1981
+ super(`${code}: ${JSON.stringify(path4)}${rule ? ` (${rule})` : ""}`);
1982
+ this.name = "PathViolation";
1983
+ this.code = code;
1984
+ this.path = path4;
1985
+ this.rule = rule ?? null;
1986
+ }
1987
+ };
1988
+ var ASCII2 = new RegExp("^\\p{ASCII}*$", "u");
1989
+ var whole = (pattern) => new RegExp(`^(?:${pattern})$`, "su");
1990
+ var escaped = (text) => text.replace(/[\\\]^-]/g, "\\$&");
1991
+ function compile(document) {
1992
+ if (document.policy_version !== PATH_POLICY_VERSION)
1993
+ throw new Error(`path policy is ${document.policy_version}, expected ${PATH_POLICY_VERSION}`);
1994
+ if (document.unicode.version !== UNICODE_VERSION)
1995
+ throw new Error(
1996
+ `path policy pins Unicode ${document.unicode.version}, the table is ${UNICODE_VERSION}`
1997
+ );
1998
+ if (document.rules.at(-1)?.regex !== ".+")
1999
+ throw new Error("path policy must end with a catch-all rule, so every path is classified");
2000
+ for (const rule of document.rules)
2001
+ if (rule.server_action === "allow" !== (rule.client_action === "include"))
2002
+ throw new Error(`path rule ${rule.id}: the server allows exactly what clients include`);
2003
+ const limits = document.path;
2004
+ return {
2005
+ limits,
2006
+ invalidCharacter: new RegExp(
2007
+ `[\\x00-\\x1f\\x7f-\\x9f\\ud800-\\udfff${escaped(limits.forbidden_characters)}]`,
2008
+ "u"
2009
+ ),
2010
+ reservedSegment: whole(limits.reserved_segment_regex),
2011
+ canonicalRoots: new Map(
2012
+ limits.canonical_spelling_roots.map((root) => [comparisonKey(root), root])
2013
+ ),
2014
+ rules: document.rules.map((rule) => ({ rule, pattern: whole(rule.regex) })),
2015
+ storedRules: document.rules.map((rule) => ({
2016
+ rule,
2017
+ pattern: whole(
2018
+ rule.id === "agent-client-state" ? document.stored_manifest.legacy_agent_state_regex : rule.regex
2019
+ )
2020
+ })),
2021
+ prefilter: new Set(document.client_prefilter.names),
2022
+ symlinkPrefixes: document.client_symlinks.skip_prefixes
2023
+ };
2024
+ }
2025
+ var compiled = null;
2026
+ var policy = () => compiled ??= compile(readContract("path-policy.json"));
2027
+ var foldedPath = (path4) => path4.split("/").map(comparisonKey).join("/");
2028
+ function classifyPath(path4) {
2029
+ const folded = foldedPath(path4);
2030
+ const found = policy().rules.find(({ pattern }) => pattern.test(folded));
2031
+ if (!found) throw new Error("the path policy's catch-all rule did not match");
2032
+ return found.rule;
2033
+ }
2034
+ function checkSpelling(path4) {
2035
+ const { limits, invalidCharacter } = policy();
2036
+ if (!path4) throw new PathViolation("path_empty", path4);
2037
+ if (invalidCharacter.test(path4)) throw new PathViolation("path_invalid_character", path4);
2038
+ if (!ASCII2.test(path4) && !allAssigned(path4))
2039
+ throw new PathViolation("path_unassigned_code_point", path4);
2040
+ if (nfc(path4) !== path4) throw new PathViolation("path_not_nfc", path4);
2041
+ if (Buffer.byteLength(path4, "utf8") > limits.max_path_bytes)
2042
+ throw new PathViolation("path_too_long", path4);
2043
+ if (path4.startsWith("/")) throw new PathViolation("path_not_relative", path4);
2044
+ return checkSegments(path4, limits);
2045
+ }
2046
+ function checkSegments(path4, limits) {
2047
+ const segments = path4.split("/");
2048
+ if (segments.some((segment) => !segment)) throw new PathViolation("path_empty_segment", path4);
2049
+ if (segments.some((segment) => segment === "." || segment === ".."))
2050
+ throw new PathViolation("path_dot_segment", path4);
2051
+ if (segments.some((segment) => Buffer.byteLength(segment, "utf8") > limits.max_segment_bytes))
2052
+ throw new PathViolation("segment_too_long", path4);
2053
+ if (segments.some((segment) => segment.endsWith(".") || segment.endsWith(" ")))
2054
+ throw new PathViolation("segment_trailing_dot_or_space", path4);
2055
+ return segments;
2056
+ }
2057
+ function validatePath(path4, stored = false) {
2058
+ const segments = checkSpelling(path4);
2059
+ const keys2 = segments.map(comparisonKey);
2060
+ const { reservedSegment, canonicalRoots } = policy();
2061
+ const rules = stored ? policy().storedRules : policy().rules;
2062
+ if (keys2.some((key) => reservedSegment.test(key))) throw new PathViolation("reserved_name", path4);
2063
+ const root = canonicalRoots.get(keys2[0] ?? "");
2064
+ if (root !== void 0 && segments[0] !== root)
2065
+ throw new PathViolation("reserved_path_alias", path4);
2066
+ const folded = keys2.join("/");
2067
+ const found = rules.find(({ pattern }) => pattern.test(folded));
2068
+ if (!found) throw new Error("the path policy's catch-all rule did not match");
2069
+ if (found.rule.server_action === "reject")
2070
+ throw new PathViolation("excluded_path", path4, found.rule.id);
2071
+ if (!found.pattern.test(path4))
2072
+ throw new PathViolation("reserved_path_alias", path4, found.rule.id);
2073
+ return path4;
2074
+ }
2075
+ function checkInventoryPaths(paths) {
2076
+ const seen = { spellingByKey: /* @__PURE__ */ new Map(), fileKeys: /* @__PURE__ */ new Set(), directoryKeys: /* @__PURE__ */ new Set() };
2077
+ for (const path4 of paths) {
2078
+ const segments = path4.split("/");
2079
+ const keys2 = segments.map(comparisonKey);
2080
+ for (let depth = 1; depth <= segments.length; depth++)
2081
+ notePrefix(seen, path4, {
2082
+ prefix: segments.slice(0, depth).join("/"),
2083
+ key: keys2.slice(0, depth).join("/"),
2084
+ isFile: depth === segments.length
2085
+ });
2086
+ }
2087
+ }
2088
+ function notePrefix(seen, path4, { prefix, key, isFile }) {
2089
+ const spelling = seen.spellingByKey.get(key) ?? prefix;
2090
+ seen.spellingByKey.set(key, spelling);
2091
+ if (isFile && seen.fileKeys.has(key))
2092
+ throw new PathViolation(spelling === prefix ? "duplicate_path" : "path_collision", path4);
2093
+ if (spelling !== prefix) throw new PathViolation("path_collision", path4);
2094
+ if (isFile ? seen.directoryKeys.has(key) : seen.fileKeys.has(key))
2095
+ throw new PathViolation("file_directory_collision", path4);
2096
+ (isFile ? seen.fileKeys : seen.directoryKeys).add(key);
2097
+ }
2098
+ var prefiltered = (name) => policy().prefilter.has(name);
2099
+ var skippedSymlink = (path4) => policy().symlinkPrefixes.some((prefix) => foldedPath(path4).startsWith(prefix));
2100
+ function literalPrefix(regex) {
2101
+ let text = "";
2102
+ for (let i = 0; i < regex.length; i++) {
2103
+ const char = regex[i] ?? "";
2104
+ if (char === "\\" && /[./-]/.test(regex[i + 1] ?? "")) text += regex[++i];
2105
+ else if (/[\w/-]/.test(char)) text += char;
2106
+ else break;
2107
+ }
2108
+ return text;
2109
+ }
2110
+ function excludedFolder(dir) {
2111
+ const folded = foldedPath(dir);
2112
+ const at = policy().rules.findIndex(
2113
+ ({ pattern, rule }) => rule.client_action !== "include" && pattern.test(folded) && pattern.test(`${folded}/x`)
2114
+ );
2115
+ if (at < 0) return false;
2116
+ return policy().rules.slice(0, at).every(({ rule }) => {
2117
+ if (rule.client_action !== "include") return true;
2118
+ const prefix = literalPrefix(rule.regex);
2119
+ return !(prefix.startsWith(`${folded}/`) || `${folded}/`.startsWith(prefix));
2120
+ });
2121
+ }
2122
+
2123
+ // ../share/src/sources/manifest.mjs
2124
+ var FORMAT_VERSION = 1;
2125
+ var ENTRYPOINT = "index.html";
2126
+ var MAX_SAFE_SIZE = Number.MAX_SAFE_INTEGER;
2127
+ var SHA256 = /^[0-9a-f]{64}$/;
2128
+ var ManifestInvalid = class extends Error {
2129
+ /** @param {Violation[]} violations */
2130
+ constructor(violations) {
2131
+ super(violations.map((violation) => violation.code).join(", "));
2132
+ this.name = "ManifestInvalid";
2133
+ this.violations = violations;
2134
+ this.code = violations[0]?.code ?? "invalid_schema";
2135
+ }
2136
+ };
2137
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2138
+ var violationOf = (error) => {
2139
+ if (!(error instanceof PathViolation)) throw error;
2140
+ return { code: error.code, path: error.path, ...error.rule ? { rule: error.rule } : {} };
2141
+ };
2142
+ function unknownFields(value, fields, out) {
2143
+ for (const key of Object.keys(value))
2144
+ if (!fields.includes(key)) out.push({ code: "invalid_schema" });
2145
+ }
2146
+ function fileOf(raw, out, stored) {
2147
+ if (!isObject(raw)) return out.push({ code: "invalid_schema" }), null;
2148
+ const before = out.length;
2149
+ const { path: path4, sha256: sha2562, size } = raw;
2150
+ if (typeof path4 !== "string") out.push({ code: "invalid_schema" });
2151
+ else {
2152
+ try {
2153
+ validatePath(path4, stored);
2154
+ } catch (error) {
2155
+ out.push(violationOf(error));
2156
+ }
2157
+ }
2158
+ checkBlob(sha2562, size, out);
2159
+ unknownFields(raw, ["path", "sha256", "size"], out);
2160
+ return out.length === before ? { path: String(path4), sha256: String(sha2562), size: Number(size) } : null;
2161
+ }
2162
+ function checkBlob(sha2562, size, out) {
2163
+ if (typeof sha2562 !== "string") out.push({ code: "invalid_schema" });
2164
+ else if (!SHA256.test(sha2562)) out.push({ code: "invalid_sha256" });
2165
+ if (typeof size !== "number" || !Number.isInteger(size)) out.push({ code: "invalid_schema" });
2166
+ else if (size < 0 || size > MAX_SAFE_SIZE) out.push({ code: "invalid_size" });
2167
+ }
2168
+ var byUtf8 = (a, b) => Buffer.compare(Buffer.from(a.path, "utf8"), Buffer.from(b.path, "utf8"));
2169
+ function canonicalInventory(files, out) {
2170
+ const ordered = [...files].sort(byUtf8);
2171
+ const sizeByDigest = /* @__PURE__ */ new Map();
2172
+ for (const file of ordered) {
2173
+ const size = sizeByDigest.get(file.sha256) ?? file.size;
2174
+ sizeByDigest.set(file.sha256, size);
2175
+ if (size !== file.size)
2176
+ return out.push({ code: "inconsistent_digest_size", path: file.path }), null;
2177
+ }
2178
+ try {
2179
+ checkInventoryPaths(ordered.map((file) => file.path));
2180
+ } catch (error) {
2181
+ return out.push(violationOf(error)), null;
2182
+ }
2183
+ return ordered;
2184
+ }
2185
+ function filesOf(raw, out, stored) {
2186
+ if (!Array.isArray(raw)) return out.push({ code: "invalid_schema" }), null;
2187
+ const before = out.length;
2188
+ const files = raw.map((item) => fileOf(item, out, stored));
2189
+ if (out.length !== before) return null;
2190
+ return canonicalInventory(
2191
+ /** @type {ManifestFile[]} */
2192
+ files,
2193
+ out
2194
+ );
2195
+ }
2196
+ function canonicalBytes(document) {
2197
+ const files = document.files.map(
2198
+ ({ path: path4, sha256: sha2562, size }) => `{"path":${JSON.stringify(path4)},"sha256":${JSON.stringify(sha2562)},"size":${size}}`
2199
+ ).join(",");
2200
+ const text = `{"entrypoint":${JSON.stringify(document.entrypoint)},"files":[${files}],"format_version":${document.format_version}}`;
2201
+ return Buffer.from(text, "utf8");
2202
+ }
2203
+ function parseManifest(raw, stored = false) {
2204
+ if (!isObject(raw)) throw new ManifestInvalid([{ code: "invalid_schema" }]);
2205
+ const out = [];
2206
+ const { format_version: version, entrypoint } = raw;
2207
+ if (!("format_version" in raw) || typeof version !== "number" || !Number.isInteger(version))
2208
+ out.push({ code: "invalid_schema" });
2209
+ else if (version !== FORMAT_VERSION) out.push({ code: "unsupported_format_version" });
2210
+ if (typeof entrypoint !== "string") out.push({ code: "invalid_schema" });
2211
+ else if (entrypoint !== ENTRYPOINT) out.push({ code: "invalid_entrypoint" });
2212
+ const files = filesOf(raw.files, out, stored);
2213
+ unknownFields(raw, ["format_version", "entrypoint", "files"], out);
2214
+ if (out.length) throw new ManifestInvalid(out);
2215
+ const ordered = (
2216
+ /** @type {ManifestFile[]} */
2217
+ files
2218
+ );
2219
+ if (!ordered.some((file) => file.path === ENTRYPOINT))
2220
+ throw new ManifestInvalid([{ code: "entrypoint_not_listed" }]);
2221
+ const document = { format_version: FORMAT_VERSION, entrypoint: ENTRYPOINT, files: ordered };
2222
+ const canonical = canonicalBytes(document);
2223
+ return { document, canonical, sha256: createHash4("sha256").update(canonical).digest("hex") };
2224
+ }
2225
+ var parseStoredManifest = (raw) => parseManifest(raw, true);
2226
+
2227
+ // ../share/src/sources/limits.mjs
2228
+ var MIB = 1024 * 1024;
2229
+ var GIB = 1024 * MIB;
2230
+ var V1_LIMITS = Object.freeze({
2231
+ maxFiles: 1e4,
2232
+ maxFileBytes: 5 * GIB,
2233
+ maxProjectBytes: 10 * GIB,
2234
+ maxManifestBytes: 8 * MIB
2235
+ });
2236
+ var NAMED = 10;
2237
+ var measure = (files, manifestBytes2) => ({
2238
+ fileCount: files.length,
2239
+ largestFileBytes: files.reduce((most, file) => Math.max(most, file.size), 0),
2240
+ projectBytes: files.reduce((sum, file) => sum + file.size, 0),
2241
+ manifestBytes: manifestBytes2
2242
+ });
2243
+ function overLimit(files, manifestBytes2, limits = V1_LIMITS) {
2244
+ const size = measure(files, manifestBytes2);
2245
+ const checks = [
2246
+ ["file_count", size.fileCount, limits.maxFiles],
2247
+ ["file_size", size.largestFileBytes, limits.maxFileBytes],
2248
+ ["project_size", size.projectBytes, limits.maxProjectBytes],
2249
+ ["manifest_size", size.manifestBytes, limits.maxManifestBytes]
2250
+ ];
2251
+ const broken = checks.find(([, actual, maximum]) => actual > maximum);
2252
+ if (!broken) return null;
2253
+ const biggest = [...files].sort((a, b) => b.size - a.size || (a.path < b.path ? -1 : 1)).slice(0, NAMED).map(({ path: path4, size: bytes }) => ({ path: path4, size: bytes }));
2254
+ return { limit: broken[0], actual: broken[1], maximum: broken[2], biggest };
2255
+ }
2256
+
2257
+ // ../share/src/sources/projectState.mjs
2258
+ import { readFile as readFile3 } from "fs/promises";
2259
+ import { join as join4 } from "path";
2260
+ async function readRenderOutputs(root) {
2261
+ const raw = await readFile3(join4(root, ".hyperframes", "render-outputs.json"), "utf8").catch(
2262
+ () => null
2263
+ );
2264
+ let record = null;
2265
+ try {
2266
+ record = raw === null ? null : JSON.parse(raw);
2267
+ } catch {
2268
+ record = null;
2269
+ }
2270
+ const paths = record?.version === 1 && Array.isArray(record.paths) ? record.paths.filter((path4) => typeof path4 === "string").map((path4) => path4.replace(/\\/g, "/")) : [];
2271
+ const listed = new Set(paths);
2272
+ return (rel) => listed.has(rel) || paths.some((path4) => rel.startsWith(`${path4}/`));
2273
+ }
2274
+ function alive(pid) {
2275
+ try {
2276
+ process.kill(pid, 0);
2277
+ return true;
2278
+ } catch (error) {
2279
+ return (
2280
+ /** @type {NodeJS.ErrnoException} */
2281
+ error.code === "EPERM"
2282
+ );
2283
+ }
2284
+ }
2285
+ async function settledState(root) {
2286
+ const dir = join4(root, ".hyperframes");
2287
+ const turn = await readFile3(join4(dir, "history-turn.json")).then(
2288
+ () => true,
2289
+ () => false
2290
+ );
2291
+ const lock = await readFile3(join4(dir, "project.lock"), "utf8").catch(() => null);
2292
+ let holder = null;
2293
+ try {
2294
+ holder = lock === null ? null : JSON.parse(lock);
2295
+ } catch {
2296
+ holder = null;
2297
+ }
2298
+ const locked = lock !== null && (typeof holder?.pid !== "number" || alive(holder.pid));
2299
+ return { agentTurnOpen: turn, projectLocked: locked };
2300
+ }
2301
+
2302
+ // ../share/src/sources/capture.mjs
2303
+ var INLINE_HASH_BYTES = 4 * 1024 * 1024;
2304
+ var HASHING_AT_ONCE = 4;
2305
+ async function visit(root, rel, entry, walk, dirs) {
2306
+ if (entry.isDirectory()) {
2307
+ if (!excludedFolder(rel)) dirs.push(rel);
2308
+ return;
2309
+ }
2310
+ const action = classifyPath(rel).client_action;
2311
+ if (action === "exclude") return;
2312
+ if (action === "wait_then_exclude") return void walk.waiting.push(rel);
2313
+ if (entry.isSymbolicLink()) {
2314
+ if (skippedSymlink(rel)) walk.skippedLinks.push(rel);
2315
+ else walk.problems.push({ path: rel, problem: "symlink" });
2316
+ return;
2317
+ }
2318
+ if (!entry.isFile()) return void walk.problems.push({ path: rel, problem: "special-file" });
2319
+ await visitFile(root, rel, walk);
2320
+ }
2321
+ async function visitFile(root, rel, walk) {
2322
+ try {
2323
+ validatePath(rel);
2324
+ } catch (error) {
2325
+ if (!(error instanceof PathViolation)) throw error;
2326
+ return void walk.problems.push({ path: rel, problem: "invalid-name", code: error.code });
2327
+ }
2328
+ const full = join5(root, rel);
2329
+ try {
2330
+ const { size, mtimeMs, ino, dev } = await lstat4(full);
2331
+ walk.files.push({ path: rel, full, size, mtimeMs, ino, dev });
2332
+ } catch {
2333
+ walk.problems.push({ path: rel, problem: "unreadable" });
2334
+ }
2335
+ }
2336
+ var FolderMoved = class extends Error {
2337
+ };
2338
+ async function listFolder(root, dir) {
2339
+ const full = join5(root, dir);
2340
+ const before = await lstat4(full);
2341
+ if (!before.isDirectory()) throw new FolderMoved();
2342
+ const entries = await readdir2(full, { withFileTypes: true });
2343
+ const after = await lstat4(full);
2344
+ if (!after.isDirectory() || after.ino !== before.ino || after.dev !== before.dev)
2345
+ throw new FolderMoved();
2346
+ return entries;
2347
+ }
2348
+ async function walkProject(root, renderOutput) {
2349
+ const walk = { files: [], problems: [], waiting: [], skippedLinks: [] };
2350
+ const ignored = await readSourceIgnore(root);
2351
+ const dirs = [""];
2352
+ for (let dir = dirs.pop(); dir !== void 0; dir = dirs.pop()) {
2353
+ let entries;
2354
+ try {
2355
+ entries = await listFolder(root, dir);
2356
+ } catch (error) {
2357
+ const changed = error instanceof FolderMoved;
2358
+ walk.problems.push({ path: dir, problem: changed ? "changed" : "unreadable" });
2359
+ continue;
2360
+ }
2361
+ for (const entry of entries) {
2362
+ const rel = dir ? `${dir}/${entry.name}` : entry.name;
2363
+ if (prefiltered(entry.name) || renderOutput(rel) || ignored(rel)) continue;
2364
+ await visit(root, rel, entry, walk, dirs);
2365
+ }
2366
+ }
2367
+ return walk;
2368
+ }
2369
+ var manifestBytes = (files) => canonicalBytes({
2370
+ format_version: 1,
2371
+ entrypoint: ENTRYPOINT,
2372
+ files: files.map(({ path: path4, size }) => ({ path: path4, sha256: "0".repeat(64), size }))
2373
+ }).length;
2374
+ var SETTLED_MS = 2e3;
2375
+ function hashMemo(now = Date.now) {
2376
+ const known = /* @__PURE__ */ new Map();
2377
+ return {
2378
+ /** @param {Found} file */
2379
+ get: (file) => {
2380
+ const kept = known.get(file.full);
2381
+ const same = kept?.size === file.size && kept.mtimeMs === file.mtimeMs && kept.ino === file.ino;
2382
+ return same ? kept.sha256 : null;
2383
+ },
2384
+ /** @param {Found} file @param {string} sha256 */
2385
+ set: (file, sha2562) => {
2386
+ if (now() - file.mtimeMs > SETTLED_MS) known.set(file.full, { ...file, sha256: sha2562 });
2387
+ }
2388
+ };
2389
+ }
2390
+ async function openListed(root, file, resolve = realpath2) {
2391
+ const handle = await open3(file.full, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0)).catch(
2392
+ (error) => {
2393
+ if (error.code === "ELOOP" || error.code === "EMLINK") return null;
2394
+ throw error;
2395
+ }
2396
+ );
2397
+ if (!handle) return null;
2398
+ try {
2399
+ const opened = await handle.stat();
2400
+ const same = opened.isFile() && opened.ino === file.ino && opened.dev === file.dev && opened.size === file.size && await resolve(dirname(file.full)) === join5(root, dirname(file.path));
2401
+ if (same) return handle;
2402
+ } catch (error) {
2403
+ await handle.close();
2404
+ throw error;
2405
+ }
2406
+ await handle.close();
2407
+ return null;
2408
+ }
2409
+ async function hashListedFile(root, file, resolve = realpath2) {
2410
+ const handle = await openListed(root, file, resolve);
2411
+ if (!handle) return null;
2412
+ try {
2413
+ const sha2562 = file.size <= INLINE_HASH_BYTES ? await handle.readFile().then(
2414
+ (bytes) => bytes.length === file.size ? createHash5("sha256").update(bytes).digest("hex") : null
2415
+ ) : await hashHandle(handle);
2416
+ const after = await handle.stat();
2417
+ return after.size === file.size && after.mtimeMs === file.mtimeMs ? sha2562 : null;
2418
+ } finally {
2419
+ await handle.close();
2420
+ }
2421
+ }
2422
+ async function hashAll(root, files, memo) {
2423
+ const hashed = [];
2424
+ const problems = [];
2425
+ const queue = [...files];
2426
+ const worker = async () => {
2427
+ for (let file = queue.shift(); file; file = queue.shift()) {
2428
+ const sha2562 = memo.get(file) ?? await hashListedFile(root, file).catch(() => void 0);
2429
+ if (sha2562 === void 0) problems.push({ path: file.path, problem: "unreadable" });
2430
+ else if (sha2562 === null) problems.push({ path: file.path, problem: "changed" });
2431
+ else {
2432
+ memo.set(file, sha2562);
2433
+ hashed.push({ path: file.path, sha256: sha2562, size: file.size });
2434
+ }
2435
+ }
2436
+ };
2437
+ await Promise.all(Array.from({ length: HASHING_AT_ONCE }, worker));
2438
+ return { hashed, problems };
2439
+ }
2440
+ function inventoryProblems(files) {
2441
+ if (!files.some((file) => file.path === ENTRYPOINT))
2442
+ return [{ path: ENTRYPOINT, problem: "no-entrypoint" }];
2443
+ try {
2444
+ checkInventoryPaths(files.map((file) => file.path));
2445
+ return [];
2446
+ } catch (error) {
2447
+ if (!(error instanceof PathViolation)) throw error;
2448
+ return [{ path: error.path, problem: "invalid-name", code: error.code }];
2449
+ }
2450
+ }
2451
+ async function captureProject(root, { memo = hashMemo(), limits = V1_LIMITS } = {}) {
2452
+ const renderOutput = await readRenderOutputs(root);
2453
+ const walk = await walkProject(root, renderOutput);
2454
+ const problems = walk.problems.length ? walk.problems : inventoryProblems(walk.files);
2455
+ if (problems.length) return { at: "problems", problems };
2456
+ const over = overLimit(walk.files, manifestBytes(walk.files), limits);
2457
+ if (over) return { at: "too-big", over };
2458
+ const { hashed, problems: unhashed } = await hashAll(await realpath2(root), walk.files, memo);
2459
+ if (unhashed.length) return { at: "problems", problems: unhashed };
2460
+ try {
2461
+ const manifest = parseManifest({ format_version: 1, entrypoint: ENTRYPOINT, files: hashed });
2462
+ const settled = await settledState(root);
2463
+ return {
2464
+ at: "captured",
2465
+ manifest,
2466
+ settled,
2467
+ waiting: walk.waiting,
2468
+ skippedLinks: walk.skippedLinks
2469
+ };
2470
+ } catch (error) {
2471
+ if (!(error instanceof ManifestInvalid)) throw error;
2472
+ const first = error.violations[0];
2473
+ return {
2474
+ at: "problems",
2475
+ problems: [{ path: first?.path ?? "", problem: "invalid-name", code: error.code }]
2476
+ };
2477
+ }
2478
+ }
2479
+ async function hashHandle(handle) {
2480
+ const hash = createHash5("sha256");
2481
+ for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk);
2482
+ return hash.digest("hex");
2483
+ }
2484
+
2485
+ // ../share/src/sources/errors.mjs
2486
+ var KIND_BY_CODE = {
2487
+ hyperframes_composition_sync_not_enabled: "not-enabled",
2488
+ hf_subscription_required: "plan-required",
2489
+ hyperframes_composition_sync_limit_reached: "limit-reached",
2490
+ byok_not_supported: "byok",
2491
+ resource_access_denied: "no-write-role",
2492
+ forbidden: "forbidden",
2493
+ hyperframes_composition_not_found: "composition-not-found",
2494
+ resource_not_found: "not-found",
2495
+ hyperframes_composition_upload_too_large: "too-large",
2496
+ hyperframes_composition_upload_reference_invalid: "reference-invalid",
2497
+ hyperframes_composition_upload_not_pending: "upload-not-pending",
2498
+ hyperframes_composition_active_uploads_exceeded: "active-uploads-exceeded",
2499
+ hyperframes_composition_upload_file_not_writable: "file-not-writable",
2500
+ conflict: "idempotency-key-reused",
2501
+ request_in_progress: "request-in-progress",
2502
+ hyperframes_composition_snapshot_not_downloadable: "snapshot-not-downloadable",
2503
+ hyperframes_composition_conflict_not_open: "conflict-not-open",
2504
+ hyperframes_composition_download_expired: "download-expired",
2505
+ invalid_parameter: "invalid-parameter",
2506
+ rate_limit_exceeded: "rate-limited",
2507
+ service_unavailable: "unavailable"
2508
+ };
2509
+ var SyncApiError = class extends Error {
2510
+ /** @param {SyncErrorKind} kind @param {{ status?: number, code?: string | null, param?: string | null,
2511
+ * requestId?: string | null, retryAfterMs?: number | null, detail?: string }} [about] */
2512
+ constructor(kind, about = {}) {
2513
+ super(`composition sync: ${kind}${about.code ? ` (${about.code})` : ""}`);
2514
+ this.name = "SyncApiError";
2515
+ this.kind = kind;
2516
+ this.status = about.status ?? 0;
2517
+ this.code = about.code ?? null;
2518
+ this.param = about.param ?? null;
2519
+ this.requestId = about.requestId ?? null;
2520
+ this.retryAfterMs = about.retryAfterMs ?? null;
2521
+ this.detail = about.detail ?? null;
2522
+ }
2523
+ };
2524
+ function kindOfStatus(status) {
2525
+ if (status === 404) return "not-found";
2526
+ if (status === 429) return "rate-limited";
2527
+ if (status === 503) return "unavailable";
2528
+ if (status >= 500) return "server-error";
2529
+ return "refused";
2530
+ }
2531
+ async function refusalOf(reply) {
2532
+ const payload = await reply.json().catch(() => null);
2533
+ const error = payload?.error;
2534
+ const code = typeof error?.code === "string" ? error.code : null;
2535
+ const seconds = Number(reply.headers.get("retry-after") ?? Number.NaN);
2536
+ return new SyncApiError(code && KIND_BY_CODE[code] || kindOfStatus(reply.status), {
2537
+ status: reply.status,
2538
+ code,
2539
+ param: typeof error?.param === "string" ? error.param : null,
2540
+ requestId: typeof error?.request_id === "string" ? error.request_id : reply.headers.get("x-heygen-request-id"),
2541
+ retryAfterMs: seconds >= 0 ? seconds * 1e3 : null,
2542
+ ...typeof error?.message === "string" ? { detail: error.message } : {}
2543
+ });
2544
+ }
2545
+
2546
+ // ../share/src/sources/wire.mjs
2547
+ var malformed = (field) => new SyncApiError("malformed", { detail: `missing or mistyped ${field}` });
2548
+ function objectOf(value, field) {
2549
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw malformed(field);
2550
+ return (
2551
+ /** @type {Record<string, unknown>} */
2552
+ value
2553
+ );
2554
+ }
2555
+ var str = (o, key) => {
2556
+ const value = o[key];
2557
+ if (typeof value !== "string") throw malformed(key);
2558
+ return value;
2559
+ };
2560
+ var optStr = (o, key) => o[key] === void 0 || o[key] === null ? null : str(o, key);
2561
+ var int = (o, key) => {
2562
+ const value = o[key];
2563
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw malformed(key);
2564
+ return value;
2565
+ };
2566
+ var list = (o, key) => {
2567
+ const value = o[key] ?? [];
2568
+ if (!Array.isArray(value)) throw malformed(key);
2569
+ return value;
2570
+ };
2571
+ var headers = (o, key) => {
2572
+ const value = objectOf(o[key] ?? {}, key);
2573
+ return Object.fromEntries(Object.keys(value).map((name) => [name, str(value, name)]));
2574
+ };
2575
+ var oneOf = (o, key, allowed) => {
2576
+ const value = str(o, key);
2577
+ if (!allowed.includes(
2578
+ /** @type {T} */
2579
+ value
2580
+ )) throw malformed(key);
2581
+ return (
2582
+ /** @type {T} */
2583
+ value
2584
+ );
2585
+ };
2586
+ function compositionOf(raw) {
2587
+ const o = objectOf(raw, "composition");
2588
+ return {
2589
+ id: str(o, "id"),
2590
+ spaceId: str(o, "space_id"),
2591
+ title: str(o, "title"),
2592
+ createdBy: str(o, "created_by"),
2593
+ latestSnapshotId: optStr(o, "latest_snapshot_id"),
2594
+ createdAt: str(o, "created_at"),
2595
+ updatedAt: str(o, "updated_at")
2596
+ };
2597
+ }
2598
+ function snapshotManifestOf(raw, sha2562) {
2599
+ const o = objectOf(raw, "manifest");
2600
+ try {
2601
+ const manifest = parseStoredManifest(o.document);
2602
+ if (manifest.sha256 !== sha2562) throw malformed("manifest.document (sha256)");
2603
+ return manifest;
2604
+ } catch (error) {
2605
+ if (error instanceof ManifestInvalid) throw malformed(`manifest.document (${error.code})`);
2606
+ throw error;
2607
+ }
2608
+ }
2609
+ function snapshotOf(raw) {
2610
+ const o = objectOf(raw, "snapshot");
2611
+ const manifestSha256 = str(o, "manifest_sha256");
2612
+ const state = optStr(o, "conflict_state");
2613
+ if (state !== null && !["open", "resolved", "discarded"].includes(state))
2614
+ throw malformed("conflict_state");
2615
+ return {
2616
+ id: str(o, "id"),
2617
+ compositionId: str(o, "composition_id"),
2618
+ baseSnapshotId: optStr(o, "base_snapshot_id"),
2619
+ publicationOutcome: oneOf(
2620
+ o,
2621
+ "publication_outcome",
2622
+ /** @type {const} */
2623
+ ["published", "conflict_saved"]
2624
+ ),
2625
+ conflictedWithSnapshotId: optStr(o, "conflicted_with_snapshot_id"),
2626
+ conflictState: (
2627
+ /** @type {Snapshot["conflictState"]} */
2628
+ state
2629
+ ),
2630
+ resolvedBySnapshotId: optStr(o, "resolved_by_snapshot_id"),
2631
+ createdBy: str(o, "created_by"),
2632
+ createdByName: optStr(o, "created_by_name"),
2633
+ clientType: str(o, "client_type"),
2634
+ summary: optStr(o, "summary"),
2635
+ summarySource: str(o, "summary_source"),
2636
+ manifestSha256,
2637
+ createdAt: str(o, "created_at"),
2638
+ manifest: o.manifest === void 0 ? null : snapshotManifestOf(o.manifest, manifestSha256)
2639
+ };
2640
+ }
2641
+ var UPLOAD_STATUSES = (
2642
+ /** @type {const} */
2643
+ [
2644
+ "pending",
2645
+ "verifying",
2646
+ "completed",
2647
+ "failed",
2648
+ "expired"
2649
+ ]
2650
+ );
2651
+ function uploadOf(raw) {
2652
+ const o = objectOf(raw, "upload");
2653
+ const result = o.result === void 0 || o.result === null ? null : objectOf(o.result, "result");
2654
+ return {
2655
+ uploadId: str(o, "upload_id"),
2656
+ compositionId: str(o, "composition_id"),
2657
+ snapshotId: str(o, "snapshot_id"),
2658
+ status: oneOf(o, "status", UPLOAD_STATUSES),
2659
+ errorCode: optStr(o, "error_code"),
2660
+ baseSnapshotId: optStr(o, "base_snapshot_id"),
2661
+ resolvesConflictSnapshotIds: list(o, "resolves_conflict_snapshot_ids").map((id) => {
2662
+ if (typeof id !== "string") throw malformed("resolves_conflict_snapshot_ids");
2663
+ return id;
2664
+ }),
2665
+ manifestSha256: str(o, "manifest_sha256"),
2666
+ uploadDeadline: str(o, "upload_deadline"),
2667
+ verificationDeadline: optStr(o, "verification_deadline"),
2668
+ completedAt: optStr(o, "completed_at"),
2669
+ result: result && {
2670
+ snapshotId: str(result, "snapshot_id"),
2671
+ publicationOutcome: oneOf(
2672
+ result,
2673
+ "publication_outcome",
2674
+ /** @type {const} */
2675
+ ["published", "conflict_saved"]
2676
+ ),
2677
+ conflictedWithSnapshotId: optStr(result, "conflicted_with_snapshot_id")
2678
+ }
2679
+ };
2680
+ }
2681
+ var blobsOf = (raw, field) => list(objectOf(raw, field), field).map((item) => {
2682
+ const blob = objectOf(item, field);
2683
+ return { sha256: str(blob, "sha256"), size: int(blob, "size") };
2684
+ });
2685
+ var beginOf = (raw, created) => ({
2686
+ ...uploadOf(raw),
2687
+ present: blobsOf(raw, "present"),
2688
+ needed: blobsOf(raw, "needed"),
2689
+ created
2690
+ });
2691
+ var grantsOf = (raw) => list(objectOf(raw, "grants"), "files").map((item) => {
2692
+ const o = objectOf(item, "files");
2693
+ return {
2694
+ sha256: str(o, "sha256"),
2695
+ size: int(o, "size"),
2696
+ expiresAt: str(o, "expires_at"),
2697
+ url: optStr(o, "url"),
2698
+ headers: headers(o, "headers"),
2699
+ multipartUploadId: optStr(o, "multipart_upload_id"),
2700
+ parts: list(o, "parts").map((part) => {
2701
+ const p = objectOf(part, "parts");
2702
+ return {
2703
+ partNumber: int(p, "part_number"),
2704
+ length: int(p, "length"),
2705
+ url: str(p, "url"),
2706
+ headers: headers(p, "headers")
2707
+ };
2708
+ })
2709
+ };
2710
+ });
2711
+ function syncLimitsOf(raw) {
2712
+ const o = objectOf(raw, "limits answer");
2713
+ const limits = objectOf(o.limits, "limits");
2714
+ if (typeof o.sync_allowed !== "boolean") throw malformed("sync_allowed");
2715
+ return {
2716
+ at: "read",
2717
+ syncAllowed: o.sync_allowed,
2718
+ maxCompositions: int(limits, "max_compositions"),
2719
+ compositions: int(objectOf(o.usage, "usage"), "compositions"),
2720
+ push: {
2721
+ maxFiles: int(limits, "max_files"),
2722
+ maxFileBytes: int(limits, "max_file_bytes"),
2723
+ maxProjectBytes: int(limits, "max_project_bytes"),
2724
+ maxManifestBytes: int(limits, "max_manifest_bytes")
2725
+ }
2726
+ };
2727
+ }
2728
+
2729
+ // ../share/src/sources/api.mjs
2730
+ function sourceApi({ access, fetchImpl = fetch }) {
2731
+ const request = signedInRequest({
2732
+ access,
2733
+ fetchImpl,
2734
+ timeoutMs: 12e4,
2735
+ tag: "share-source",
2736
+ host: "heygenApi",
2737
+ offline: () => new SyncApiError("offline"),
2738
+ signedOut: () => new SyncApiError("signed-out")
2739
+ });
2740
+ const send = async (method, route, body, headers2) => {
2741
+ const { reply } = await request(method, route, body, headers2);
2742
+ if (!reply.ok) throw await refusalOf(reply);
2743
+ return objectOf(await reply.json(), "envelope").data;
2744
+ };
2745
+ const path4 = (space, composition) => `/v3/hyperframes/workspaces/${encodeURIComponent(space)}/compositions/${encodeURIComponent(composition)}`;
2746
+ return {
2747
+ /** @param {string} space */
2748
+ limits: async (space) => syncLimitsOf(
2749
+ await send(
2750
+ "GET",
2751
+ `/v3/hyperframes/workspaces/${encodeURIComponent(space)}/composition-sync/limits`
2752
+ )
2753
+ ),
2754
+ /** @param {string} space @param {string} composition @param {string} title */
2755
+ create: async (space, composition, title) => compositionOf(await send("PUT", path4(space, composition), { title })),
2756
+ /** @param {string} space @param {string} composition @param {string} snapshot */
2757
+ snapshot: async (space, composition, snapshot) => snapshotOf(
2758
+ await send(
2759
+ "GET",
2760
+ `${path4(space, composition)}/snapshots/${encodeURIComponent(snapshot)}?include=manifest`
2761
+ )
2762
+ ),
2763
+ /** @param {string} space @param {string} composition @param {import("./types.js").BeginRequest} body */
2764
+ begin: async (space, composition, body) => beginOf(
2765
+ await send(
2766
+ "POST",
2767
+ `${path4(space, composition)}/uploads`,
2768
+ {
2769
+ base_snapshot_id: body.baseSnapshotId,
2770
+ resolves_conflict_snapshot_ids: [],
2771
+ client_type: "cli",
2772
+ manifest_sha256: body.manifest.sha256,
2773
+ manifest: body.manifest.document
2774
+ },
2775
+ { "Idempotency-Key": body.idempotencyKey }
2776
+ ),
2777
+ false
2778
+ ),
2779
+ /** @param {string} space @param {string} composition @param {string} upload @param {import("./types.js").GrantRequest[]} files */
2780
+ uploadUrls: async (space, composition, upload2, files) => grantsOf(
2781
+ await send(
2782
+ "POST",
2783
+ `${path4(space, composition)}/uploads/${encodeURIComponent(upload2)}/upload-urls`,
2784
+ {
2785
+ files: files.map((file) => ({
2786
+ sha256: file.sha256,
2787
+ ...file.multipartUploadId && { multipart_upload_id: file.multipartUploadId },
2788
+ ...file.parts && {
2789
+ parts: file.parts.map((part) => ({
2790
+ part_number: part.partNumber,
2791
+ sha256: part.sha256
2792
+ }))
2793
+ }
2794
+ }))
2795
+ }
2796
+ )
2797
+ ),
2798
+ /** @param {string} space @param {string} composition @param {string} upload */
2799
+ status: async (space, composition, upload2) => uploadOf(
2800
+ await send("GET", `${path4(space, composition)}/uploads/${encodeURIComponent(upload2)}`)
2801
+ ),
2802
+ /** @param {string} space @param {string} composition @param {string} upload */
2803
+ cancel: async (space, composition, upload2) => uploadOf(
2804
+ await send(
2805
+ "POST",
2806
+ `${path4(space, composition)}/uploads/${encodeURIComponent(upload2)}/cancel`
2807
+ )
2808
+ ),
2809
+ /** @param {string} space @param {string} composition @param {string} upload */
2810
+ submit: async (space, composition, upload2) => uploadOf(
2811
+ await send(
2812
+ "POST",
2813
+ `${path4(space, composition)}/uploads/${encodeURIComponent(upload2)}/verification`
2814
+ )
2815
+ )
2816
+ };
2817
+ }
2818
+
2819
+ // ../share/src/sources/store.mjs
2820
+ import { createHash as createHash6 } from "crypto";
2821
+ import { constants as constants4 } from "fs";
2822
+ import { lstat as lstat5, open as open4 } from "fs/promises";
2823
+ import { join as join6 } from "path";
2824
+ var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2825
+ function bindingOf(raw, key) {
2826
+ if (!object(raw) || raw.version !== 1 || raw.backend !== key.backend || raw.account !== key.account || raw.projectPath !== key.projectPath || typeof raw.compositionId !== "string" || typeof raw.ownerSpaceId !== "string")
2827
+ throw new Error(
2828
+ "Source binding belongs to another account, backend or project. Reset explicitly before sharing this copy."
2829
+ );
2830
+ checkSnapshots(raw);
2831
+ return (
2832
+ /** @type {import("./types.js").Binding} */
2833
+ /** @type {unknown} */
2834
+ raw
2835
+ );
2836
+ }
2837
+ function checkSnapshots(raw) {
2838
+ if (raw.base !== null && (!object(raw.base) || typeof raw.base.snapshotId !== "string" || parseStoredManifest(raw.base.manifest).sha256 !== raw.base.manifestSha256))
2839
+ throw new Error("Invalid source base snapshot.");
2840
+ if (raw.inflight !== null && (!object(raw.inflight) || typeof raw.inflight.idempotencyKey !== "string" || parseStoredManifest(raw.inflight.manifest).sha256 !== raw.inflight.manifestSha256))
2841
+ throw new Error("Invalid pending source upload.");
2842
+ }
2843
+ function createProjectShareSourceStore() {
2844
+ const location = async (key) => {
2845
+ const dir = await mkdirInside(key.projectPath, ".hyperframes");
2846
+ const environment = createHash6("sha256").update(key.backend).digest("hex").slice(0, 16);
2847
+ return join6(dir, `share-sync.${environment}.json`);
2848
+ };
2849
+ return {
2850
+ read: async (key) => {
2851
+ const file = await location(key);
2852
+ const handle = await open4(file, constants4.O_RDONLY | constants4.O_NOFOLLOW).catch((error) => {
2853
+ if (errorCode(error) === "ENOENT") return null;
2854
+ throw error;
2855
+ });
2856
+ if (!handle) return null;
2857
+ try {
2858
+ if (!(await handle.stat()).isFile())
2859
+ throw new Error("Source binding must be a regular file.");
2860
+ return bindingOf(JSON.parse(await handle.readFile("utf8")), key);
2861
+ } finally {
2862
+ await handle.close();
2863
+ }
2864
+ },
2865
+ write: async (binding) => {
2866
+ const file = await location(binding);
2867
+ const held = await lstat5(file).catch((error) => {
2868
+ if (errorCode(error) === "ENOENT") return null;
2869
+ throw error;
2870
+ });
2871
+ if (held && !held.isFile()) throw new Error("Source binding must be a regular file.");
2872
+ await writeJsonAtomic(file, binding);
2873
+ }
2874
+ };
2875
+ }
2876
+
2877
+ // ../share/src/sources/transfer.mjs
2878
+ import { createHash as createHash7 } from "crypto";
2879
+ import { constants as constants5, createReadStream as createReadStream2 } from "fs";
2880
+ import { open as open5, realpath as realpath3 } from "fs/promises";
2881
+ import { dirname as dirname2 } from "path";
2882
+ import { setTimeout as sleep } from "timers/promises";
2883
+ var TransferError = class extends Error {
2884
+ /** @param {"expired" | "exists" | "changed" | "unreadable" | "corrupt" | "transient" | "refused"} kind
2885
+ * @param {{ status?: number, path?: string }} [about] */
2886
+ constructor(kind, about = {}) {
2887
+ super(`composition sync transfer: ${kind}${about.status ? ` (${about.status})` : ""}`);
2888
+ this.name = "TransferError";
2889
+ this.kind = kind;
2890
+ this.status = about.status ?? 0;
2891
+ this.path = about.path ?? null;
2892
+ }
2893
+ };
2894
+ var isAbort = (error) => error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
2895
+ var realWait = (ms, signal) => sleep(ms, void 0, { signal });
2896
+ function refusalOf2(status) {
2897
+ if (status === 403) return new TransferError("expired", { status });
2898
+ if (status === 412) return new TransferError("exists", { status });
2899
+ if (status === 429 || status >= 500) return new TransferError("transient", { status });
2900
+ return new TransferError("refused", { status });
2901
+ }
2902
+ async function openSource(file) {
2903
+ const handle = await open5(file, constants5.O_RDONLY | constants5.O_NOFOLLOW);
2904
+ try {
2905
+ const stat2 = await handle.stat();
2906
+ if (!stat2.isFile() || await realpath3(dirname2(file)) !== dirname2(file))
2907
+ throw new TransferError("unreadable", { path: file });
2908
+ return handle;
2909
+ } catch (error) {
2910
+ await handle.close();
2911
+ throw error;
2912
+ }
2913
+ }
2914
+ async function hashedBody(file, start, length, onBytes) {
2915
+ const handle = await openSource(file);
2916
+ const hash = createHash7("sha256");
2917
+ const seen = { bytes: 0, ended: false, readError: (
2918
+ /** @type {unknown} */
2919
+ null
2920
+ ) };
2921
+ const chunks = length === 0 ? null : handle.createReadStream({ start, end: start + length - 1, autoClose: false })[Symbol.asyncIterator]();
2922
+ const body = new ReadableStream(
2923
+ {
2924
+ async pull(controller) {
2925
+ if (!chunks) return controller.close();
2926
+ try {
2927
+ const { value, done } = await chunks.next();
2928
+ if (done) return seen.ended = true, controller.close();
2929
+ hash.update(value);
2930
+ seen.bytes += value.length;
2931
+ onBytes(value.length);
2932
+ controller.enqueue(value);
2933
+ } catch (error) {
2934
+ seen.readError = error;
2935
+ controller.error(error);
2936
+ }
2937
+ },
2938
+ cancel: () => void chunks?.return?.()
2939
+ },
2940
+ { highWaterMark: 0 }
2941
+ );
2942
+ return { body, seen, digest: () => hash.digest("hex"), close: () => handle.close() };
2943
+ }
2944
+ function fileProblem({ seen, digest }, { length, sha256: sha2562, path: path4 }) {
2945
+ if (seen.readError) return new TransferError("unreadable", { path: path4 });
2946
+ const short = seen.ended && seen.bytes < length;
2947
+ if (short || seen.bytes === length && digest() !== sha2562)
2948
+ return new TransferError("changed", { path: path4 });
2949
+ return null;
2950
+ }
2951
+ async function putRange(put) {
2952
+ const { fetchImpl, url, headers: headers2, file, start, length, signal } = put;
2953
+ const target = trustedUploadUrl(url);
2954
+ if (!target) throw new TransferError("refused", { path: put.path });
2955
+ signal.throwIfAborted();
2956
+ const stall = new AbortController();
2957
+ const sent = await hashedBody(file, start, length, (bytes) => {
2958
+ timer.refresh();
2959
+ put.onBytes?.(bytes);
2960
+ });
2961
+ const timer = setTimeout(() => stall.abort(), put.stallMs ?? 6e4);
2962
+ const init = {
2963
+ method: "PUT",
2964
+ headers: headers2,
2965
+ body: sent.body,
2966
+ duplex: "half",
2967
+ redirect: "error",
2968
+ signal: AbortSignal.any([signal, stall.signal])
2969
+ };
2970
+ let reply;
2971
+ try {
2972
+ reply = await fetchImpl(
2973
+ target.href,
2974
+ /** @type {RequestInit} */
2975
+ init
2976
+ );
2977
+ } catch (error) {
2978
+ signal.throwIfAborted();
2979
+ if (!stall.signal.aborted && isAbort(error)) throw error;
2980
+ throw fileProblem(sent, put) ?? new TransferError("transient", { path: put.path });
2981
+ } finally {
2982
+ clearTimeout(timer);
2983
+ await sent.close();
2984
+ }
2985
+ await reply.body?.cancel().catch(() => {
2986
+ });
2987
+ const problem = fileProblem(sent, put);
2988
+ if (problem) throw problem;
2989
+ if (!reply.ok) throw refusalOf2(reply.status);
2990
+ }
2991
+ async function partDigests(file, size, partBytes, signal) {
2992
+ const whole2 = createHash7("sha256");
2993
+ const parts = [];
2994
+ let part = createHash7("sha256");
2995
+ let inPart = 0;
2996
+ for await (const chunk of createReadStream2(file, { highWaterMark: 1 << 20, signal })) {
2997
+ whole2.update(chunk);
2998
+ for (let at = 0; at < chunk.length; ) {
2999
+ const take = Math.min(partBytes - inPart, chunk.length - at);
3000
+ part.update(chunk.subarray(at, at + take));
3001
+ inPart += take;
3002
+ at += take;
3003
+ if (inPart === partBytes) {
3004
+ parts.push(part.digest("hex"));
3005
+ part = createHash7("sha256");
3006
+ inPart = 0;
3007
+ }
3008
+ }
3009
+ }
3010
+ if (inPart > 0 || parts.length === 0) parts.push(part.digest("hex"));
3011
+ return {
3012
+ parts,
3013
+ whole: whole2.digest("hex"),
3014
+ complete: parts.length === Math.ceil(size / partBytes)
3015
+ };
3016
+ }
3017
+ async function eachLimit(items, limit, work) {
3018
+ let next = 0;
3019
+ const failure = { failed: false, error: (
3020
+ /** @type {unknown} */
3021
+ null
3022
+ ) };
3023
+ const worker = async () => {
3024
+ while (!failure.failed && next < items.length) {
3025
+ const item = (
3026
+ /** @type {T} */
3027
+ items[next++]
3028
+ );
3029
+ try {
3030
+ await work(item);
3031
+ } catch (error) {
3032
+ if (!failure.failed) Object.assign(failure, { failed: true, error });
3033
+ }
3034
+ }
3035
+ };
3036
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
3037
+ if (failure.failed) throw failure.error;
3038
+ }
3039
+ var backoffMs = (attempt, askedMs = null, baseMs = 1e3, maxMs = 3e4) => askedMs ?? Math.min(maxMs, baseMs * 2 ** (attempt - 1));
3040
+
3041
+ // ../share/src/sources/upload.mjs
3042
+ import { randomUUID as randomUUID7 } from "crypto";
3043
+ import { join as join7 } from "path";
3044
+
3045
+ // ../share/src/sources/uploadFiles.mjs
3046
+ import { lstat as lstat6 } from "fs/promises";
3047
+ var PART_BYTES = 64 * 1024 * 1024;
3048
+ var GRANT_FILES = 100;
3049
+ var PARTS_PER_GRANT = 8;
3050
+ var AT_ONCE = 4;
3051
+ var ATTEMPTS = 5;
3052
+ var URL_MARGIN_MS = 6e4;
3053
+ var NotWritable = class extends Error {
3054
+ constructor() {
3055
+ super("composition sync: a file's multipart upload can no longer take parts");
3056
+ this.name = "NotWritable";
3057
+ }
3058
+ };
3059
+ async function againAfter(job, error, attempt) {
3060
+ if (attempt >= ATTEMPTS || isAbort(error)) return false;
3061
+ const transient2 = error instanceof TransferError && (error.kind === "transient" || error.kind === "corrupt") || error instanceof SyncApiError && ["offline", "unavailable", "server-error", "rate-limited"].includes(error.kind);
3062
+ if (!transient2) return false;
3063
+ const asked = error instanceof SyncApiError ? error.retryAfterMs : null;
3064
+ await job.wait(backoffMs(attempt, asked), job.signal);
3065
+ return true;
3066
+ }
3067
+ var wrongPinnedId = (error, asked) => error instanceof SyncApiError && error.kind === "invalid-parameter" && (error.param ?? "").endsWith("multipart_upload_id") && asked.some((file) => file.multipartUploadId);
3068
+ async function grant(job, files) {
3069
+ let asked = files;
3070
+ for (let attempt = 1; ; attempt++) {
3071
+ try {
3072
+ return await job.api.uploadUrls(job.space, job.composition, job.uploadId, asked);
3073
+ } catch (error) {
3074
+ if (error instanceof SyncApiError && error.kind === "file-not-writable")
3075
+ throw new NotWritable();
3076
+ if (wrongPinnedId(error, asked))
3077
+ asked = asked.map(({ multipartUploadId: _dropped, ...file }) => file);
3078
+ else if (!await againAfter(job, error, attempt)) throw error;
3079
+ }
3080
+ }
3081
+ }
3082
+ function localFile(job, sha2562) {
3083
+ const file = job.local.get(sha2562);
3084
+ if (!file) throw new Error(`composition sync: needed file ${sha2562} is not in the capture`);
3085
+ return file;
3086
+ }
3087
+ async function attemptPut(job, held, { file, ...range }) {
3088
+ let sent = 0;
3089
+ try {
3090
+ await putRange({
3091
+ fetchImpl: job.fetchImpl,
3092
+ url: held.url,
3093
+ headers: held.headers,
3094
+ file: file.full,
3095
+ path: file.path,
3096
+ ...range,
3097
+ signal: job.signal,
3098
+ onBytes: (count) => (sent += count, job.onBytes(count))
3099
+ });
3100
+ return "done";
3101
+ } catch (error) {
3102
+ job.onBytes(-sent);
3103
+ if (!(error instanceof TransferError)) return { failed: error };
3104
+ if (error.kind === "exists") return job.onBytes(range.length), "done";
3105
+ return error.kind === "expired" ? "expired" : { failed: error };
3106
+ }
3107
+ }
3108
+ async function putWithGrant(job, given, fresh, bytes) {
3109
+ const usable = (signed) => signed && Date.parse(signed.expiresAt) - job.now() >= URL_MARGIN_MS ? signed : null;
3110
+ let held = usable(given);
3111
+ for (let attempt = 1; ; attempt++) {
3112
+ held ??= await fresh();
3113
+ const outcome = await attemptPut(job, held, bytes);
3114
+ if (outcome === "done") return;
3115
+ if (outcome === "expired" && attempt < ATTEMPTS) held = null;
3116
+ else {
3117
+ const failed = outcome === "expired" ? new TransferError("expired") : outcome.failed;
3118
+ if (!await againAfter(job, failed, attempt)) throw failed;
3119
+ }
3120
+ }
3121
+ }
3122
+ function singleUrl(held) {
3123
+ if (!held?.url) throw new Error("composition sync: a single-PUT grant came without its URL");
3124
+ return { url: held.url, headers: held.headers, expiresAt: held.expiresAt };
3125
+ }
3126
+ async function sendSmall(job, blobs) {
3127
+ for (let at = 0; at < blobs.length; at += GRANT_FILES) {
3128
+ const batch = blobs.slice(at, at + GRANT_FILES);
3129
+ const grants = await grant(
3130
+ job,
3131
+ batch.map((blob) => ({ sha256: blob.sha256 }))
3132
+ );
3133
+ const bySha = new Map(grants.map((one) => [one.sha256, one]));
3134
+ await eachLimit(batch, AT_ONCE, async (blob) => {
3135
+ const given = bySha.has(blob.sha256) ? singleUrl(bySha.get(blob.sha256)) : null;
3136
+ const fresh = async () => singleUrl((await grant(job, [{ sha256: blob.sha256 }]))[0]);
3137
+ const bytes = {
3138
+ file: localFile(job, blob.sha256),
3139
+ start: 0,
3140
+ length: blob.size,
3141
+ sha256: blob.sha256
3142
+ };
3143
+ await putWithGrant(job, given, fresh, bytes);
3144
+ (job.inflight.sent ??= []).push(blob.sha256);
3145
+ job.persist();
3146
+ job.onFile();
3147
+ });
3148
+ }
3149
+ }
3150
+ async function partGrants(job, blob, parts) {
3151
+ const pinned = job.inflight.multipart?.[blob.sha256];
3152
+ const [held] = await grant(job, [
3153
+ {
3154
+ sha256: blob.sha256,
3155
+ ...pinned && { multipartUploadId: pinned.uploadId },
3156
+ parts: parts.map((part) => ({ partNumber: part.number, sha256: part.sha256 }))
3157
+ }
3158
+ ]);
3159
+ if (!held?.multipartUploadId)
3160
+ throw new Error("composition sync: a multipart grant came without its upload id");
3161
+ if (pinned && pinned.uploadId !== held.multipartUploadId) throw new NotWritable();
3162
+ if (!pinned) {
3163
+ job.inflight.multipart = {
3164
+ ...job.inflight.multipart,
3165
+ [blob.sha256]: { uploadId: held.multipartUploadId, partsDone: [] }
3166
+ };
3167
+ job.persist();
3168
+ }
3169
+ return { expiresAt: held.expiresAt, parts: held.parts };
3170
+ }
3171
+ async function partsToSend(job, blob) {
3172
+ const file = localFile(job, blob.sha256);
3173
+ const digests = await partDigests(file.full, blob.size, PART_BYTES, job.signal).catch((error) => {
3174
+ if (isAbort(error)) throw error;
3175
+ throw new TransferError("unreadable", { path: file.path });
3176
+ });
3177
+ if (digests.whole !== blob.sha256 || !digests.complete)
3178
+ throw new TransferError("changed", { path: file.path });
3179
+ const done = new Set(job.inflight.multipart?.[blob.sha256]?.partsDone ?? []);
3180
+ return digests.parts.map((sha2562, index) => ({
3181
+ number: index + 1,
3182
+ sha256: sha2562,
3183
+ start: index * PART_BYTES,
3184
+ length: Math.min(PART_BYTES, blob.size - index * PART_BYTES)
3185
+ })).filter((part) => !done.has(part.number));
3186
+ }
3187
+ async function sendLarge(job, blob) {
3188
+ const file = localFile(job, blob.sha256);
3189
+ const before = await lstat6(file.full);
3190
+ const parts = await partsToSend(job, blob);
3191
+ job.onBytes(blob.size - parts.reduce((sum, part) => sum + part.length, 0));
3192
+ for (let at = 0; at < parts.length; at += PARTS_PER_GRANT) {
3193
+ const batch = parts.slice(at, at + PARTS_PER_GRANT);
3194
+ const granted = await partGrants(job, blob, batch);
3195
+ const byNumber = new Map(granted.parts.map((part) => [part.partNumber, part]));
3196
+ await eachLimit(batch, AT_ONCE, async (part) => {
3197
+ const signed = byNumber.get(part.number);
3198
+ const given = signed ? { url: signed.url, headers: signed.headers, expiresAt: granted.expiresAt } : null;
3199
+ const fresh = async () => {
3200
+ const again = await partGrants(job, blob, [part]);
3201
+ const one = again.parts[0];
3202
+ if (!one) throw new Error("composition sync: a part grant came without its part");
3203
+ return { url: one.url, headers: one.headers, expiresAt: again.expiresAt };
3204
+ };
3205
+ await putWithGrant(job, given, fresh, { file, ...part });
3206
+ job.inflight.multipart?.[blob.sha256]?.partsDone.push(part.number);
3207
+ job.persist();
3208
+ });
3209
+ }
3210
+ const after = await lstat6(file.full).catch(() => null);
3211
+ if (!after || after.size !== before.size || after.mtimeMs !== before.mtimeMs)
3212
+ throw new TransferError("changed", { path: file.path });
3213
+ (job.inflight.sent ??= []).push(blob.sha256);
3214
+ job.persist();
3215
+ job.onFile();
3216
+ }
3217
+ async function uploadNeeded(job) {
3218
+ const sent = new Set(job.inflight.sent ?? []);
3219
+ const waiting = job.needed.filter((blob) => !sent.has(blob.sha256));
3220
+ for (const blob of job.needed.filter((one) => sent.has(one.sha256))) {
3221
+ job.onBytes(blob.size);
3222
+ job.onFile();
3223
+ }
3224
+ await sendSmall(
3225
+ job,
3226
+ waiting.filter((blob) => blob.size <= PART_BYTES)
3227
+ );
3228
+ for (const blob of waiting.filter((one) => one.size > PART_BYTES)) await sendLarge(job, blob);
3229
+ }
3230
+
3231
+ // ../share/src/sources/upload.mjs
3232
+ async function begin(run2) {
3233
+ const { binding, manifest, api, store } = run2;
3234
+ if (!binding.inflight) {
3235
+ binding.inflight = {
3236
+ idempotencyKey: randomUUID7(),
3237
+ baseSnapshotId: binding.base?.snapshotId ?? null,
3238
+ resolvesConflictSnapshotIds: [],
3239
+ summary: null,
3240
+ manifest: manifest.document,
3241
+ manifestSha256: manifest.sha256,
3242
+ uploadId: null,
3243
+ snapshotId: null,
3244
+ uploadDeadline: null,
3245
+ verificationDeadline: null,
3246
+ begunAt: Date.now(),
3247
+ sent: [],
3248
+ multipart: {}
3249
+ };
3250
+ await store.write(binding);
3251
+ }
3252
+ const inflight = binding.inflight;
3253
+ const receipt = await api.begin(binding.ownerSpaceId, binding.compositionId, {
3254
+ ...inflight,
3255
+ manifest
3256
+ });
3257
+ assertReceipt(binding, receipt);
3258
+ Object.assign(inflight, {
3259
+ uploadId: receipt.uploadId,
3260
+ snapshotId: receipt.snapshotId,
3261
+ uploadDeadline: receipt.uploadDeadline,
3262
+ verificationDeadline: receipt.verificationDeadline
3263
+ });
3264
+ await store.write(binding);
3265
+ return receipt;
3266
+ }
3267
+ async function sendFiles(run2, receipt) {
3268
+ const { binding, manifest, store } = run2;
3269
+ if (!binding.inflight) throw new Error("Missing source upload intent.");
3270
+ const local2 = new Map(
3271
+ manifest.document.files.map((file) => [
3272
+ file.sha256,
3273
+ { path: file.path, full: join7(binding.projectPath, file.path) }
3274
+ ])
3275
+ );
3276
+ const known = new Map(manifest.document.files.map((file) => [file.sha256, file.size]));
3277
+ for (const blob of receipt.needed)
3278
+ if (known.get(blob.sha256) !== blob.size)
3279
+ throw new Error("Upload requested an unknown source file.");
3280
+ let persisted = Promise.resolve();
3281
+ await uploadNeeded({
3282
+ api: run2.api,
3283
+ space: binding.ownerSpaceId,
3284
+ composition: binding.compositionId,
3285
+ uploadId: receipt.uploadId,
3286
+ inflight: binding.inflight,
3287
+ local: local2,
3288
+ needed: receipt.needed,
3289
+ fetchImpl: run2.fetchImpl,
3290
+ wait: run2.wait,
3291
+ signal: run2.signal,
3292
+ now: Date.now,
3293
+ persist: () => {
3294
+ persisted = persisted.then(() => store.write(binding));
3295
+ },
3296
+ onBytes: run2.onProgress,
3297
+ onFile: () => {
3298
+ }
3299
+ }).finally(() => persisted);
3300
+ return run2.api.submit(binding.ownerSpaceId, binding.compositionId, receipt.uploadId);
3301
+ }
3302
+ function assertReceipt(binding, receipt) {
3303
+ const saved = binding.inflight;
3304
+ if (!saved || receipt.manifestSha256 !== saved.manifestSha256)
3305
+ throw new Error("Source upload receipt does not match the captured project.");
3306
+ if (receipt.compositionId !== binding.compositionId)
3307
+ throw new Error("Source upload receipt does not match the composition.");
3308
+ if (saved.uploadId !== null && receipt.uploadId !== saved.uploadId)
3309
+ throw new Error("Source upload receipt identity changed.");
3310
+ if (saved.snapshotId !== null && receipt.snapshotId !== saved.snapshotId)
3311
+ throw new Error("Source snapshot identity changed.");
3312
+ }
3313
+ async function storePublished({ binding, store }, receipt) {
3314
+ const saved = binding.inflight;
3315
+ const result = receipt.result;
3316
+ if (!saved || !result || result.snapshotId !== receipt.snapshotId)
3317
+ throw new Error("Source snapshot identity changed.");
3318
+ binding.base = {
3319
+ snapshotId: result.snapshotId,
3320
+ manifest: saved.manifest,
3321
+ manifestSha256: saved.manifestSha256
3322
+ };
3323
+ await clearIntent({ binding, store });
3324
+ }
3325
+ async function clearIntent({ binding, store }) {
3326
+ binding.inflight = null;
3327
+ await store.write(binding);
3328
+ }
3329
+ async function cancelPending({ binding, api }, receipt) {
3330
+ const { ownerSpaceId, compositionId } = binding;
3331
+ try {
3332
+ return await api.cancel(ownerSpaceId, compositionId, receipt.uploadId);
3333
+ } catch (error) {
3334
+ if (!(error instanceof SyncApiError) || error.kind !== "upload-not-pending") throw error;
3335
+ return api.status(ownerSpaceId, compositionId, receipt.uploadId);
3336
+ }
3337
+ }
3338
+ async function recoverSourceUpload(job) {
3339
+ const { binding, api } = job;
3340
+ const saved = binding.inflight;
3341
+ if (!saved) return null;
3342
+ const manifest = parseStoredManifest(saved.manifest);
3343
+ if (manifest.sha256 !== saved.manifestSha256)
3344
+ throw new Error("Saved source upload manifest does not match its checksum.");
3345
+ let receipt = saved.uploadId ? await api.status(binding.ownerSpaceId, binding.compositionId, saved.uploadId) : await begin({ ...job, manifest });
3346
+ assertReceipt(binding, receipt);
3347
+ if (receipt.status === "pending") receipt = await cancelPending(job, receipt);
3348
+ assertReceipt(binding, receipt);
3349
+ return recoverReceipt(job, receipt);
3350
+ }
3351
+ async function recoverReceipt(job, receipt) {
3352
+ if (receipt.status === "completed") {
3353
+ if (receipt.result?.publicationOutcome !== "published")
3354
+ return { at: (
3355
+ /** @type {const} */
3356
+ "unavailable"
3357
+ ), reason: "source_conflict" };
3358
+ await storePublished(job, receipt);
3359
+ } else if (terminalFailure(receipt)) await clearIntent(job);
3360
+ else return { at: (
3361
+ /** @type {const} */
3362
+ "unavailable"
3363
+ ), reason: "source_verification_pending" };
3364
+ return null;
3365
+ }
3366
+ var terminalFailure = (receipt) => receipt.status === "failed" || receipt.status === "expired";
3367
+ async function uploadSource(run2) {
3368
+ const receipt = await begin(run2);
3369
+ let status;
3370
+ try {
3371
+ status = receipt.status === "pending" ? await sendFiles(run2, receipt) : receipt;
3372
+ } catch (error) {
3373
+ if (!(error instanceof NotWritable)) throw error;
3374
+ return await recoverSourceUpload(run2) ?? {
3375
+ at: "unavailable",
3376
+ reason: "source_upload_not_writable"
3377
+ };
3378
+ }
3379
+ const deadline = Date.now() + run2.timeoutMs;
3380
+ while (status.status === "verifying") {
3381
+ run2.signal.throwIfAborted();
3382
+ if (Date.now() >= deadline) return { at: "unavailable", reason: "source_verification_pending" };
3383
+ await run2.wait(1e3, run2.signal);
3384
+ status = await run2.api.status(
3385
+ run2.binding.ownerSpaceId,
3386
+ run2.binding.compositionId,
3387
+ receipt.uploadId
3388
+ );
3389
+ }
3390
+ assertReceipt(run2.binding, status);
3391
+ if (status.status !== "completed" || !status.result) {
3392
+ if (terminalFailure(status)) await clearIntent(run2);
3393
+ return { at: "unavailable", reason: status.errorCode ?? `source_upload_${status.status}` };
3394
+ }
3395
+ if (status.result.publicationOutcome !== "published")
3396
+ return { at: "unavailable", reason: "source_conflict" };
3397
+ await storePublished(run2, status);
3398
+ return {
3399
+ at: "ready",
3400
+ snapshot: {
3401
+ space_id: run2.binding.ownerSpaceId,
3402
+ composition_id: run2.binding.compositionId,
3403
+ snapshot_id: status.snapshotId
3404
+ }
3405
+ };
3406
+ }
3407
+
3408
+ // ../share/src/shareSources.mjs
3409
+ var unavailable = (reason) => ({ at: "unavailable", reason });
3410
+ async function shareSourceFingerprint(projectPath) {
3411
+ const capture = await captureProject(await realpath4(projectPath));
3412
+ return capture.at === "captured" && !captureRefusal(capture) ? capture.manifest.sha256 : null;
3413
+ }
3414
+ function bindingRefusal(binding, space) {
3415
+ if (binding.ownerSpaceId !== space) return "source_other_workspace";
3416
+ if (binding.sharedFrom) return "source_owned_by_someone_else";
3417
+ if (binding.gettingFromCloud || binding.duplicate) return "source_operation_in_progress";
3418
+ return null;
3419
+ }
3420
+ function captureRefusal(capture) {
3421
+ if (capture.at === "too-big") return `source_${capture.over.limit}_exceeded`;
3422
+ if (capture.at === "problems") return `source_${capture.problems[0]?.problem ?? "invalid"}`;
3423
+ if (capture.settled.agentTurnOpen || capture.settled.projectLocked || capture.waiting.length)
3424
+ return "source_edit_in_progress";
3425
+ return null;
3426
+ }
3427
+ function shareSources(options) {
3428
+ const store = options.store ?? createProjectShareSourceStore();
3429
+ const fingerprint = options.fingerprint ?? projectFingerprint2;
3430
+ const signal = options.signal ?? new AbortController().signal;
3431
+ const prepared = /* @__PURE__ */ new Map();
3432
+ const prepare = async (projectPath, rendered) => {
3433
+ const root = await realpath4(projectPath);
3434
+ prepared.delete(root);
3435
+ if (!enabled(options)) return unavailable("source_disabled");
3436
+ if (!rendered || await fingerprint(root) !== rendered)
3437
+ return unavailable("source_render_changed");
3438
+ return withProjectShareLock(
3439
+ root,
3440
+ "source",
3441
+ async () => {
3442
+ const signed = await options.access();
3443
+ if (!signed?.owner) return unavailable("source_signed_out");
3444
+ const key = { backend: signed.heygenApi, account: signed.owner, projectPath: root };
3445
+ const guardedAccess = async (refused2) => {
3446
+ const next = await options.access(refused2);
3447
+ if (!next || next.owner !== key.account || next.heygenApi !== key.backend)
3448
+ throw new Error("Source account or backend changed while sharing.");
3449
+ return next;
3450
+ };
3451
+ const api = options.api ?? sourceApi({ access: guardedAccess, fetchImpl: options.fetchImpl });
3452
+ const { own, existing, binding } = await selectBinding(key, options, store);
3453
+ const refused = bindingRefusal(binding, options.spaceId);
3454
+ if (refused) return unavailable(refused);
3455
+ const result = await prepareBinding({
3456
+ binding,
3457
+ own: Boolean(own),
3458
+ external: Boolean(existing),
3459
+ api,
3460
+ store,
3461
+ options,
3462
+ signal,
3463
+ fingerprint,
3464
+ rendered
3465
+ });
3466
+ const manifest = result.manifest;
3467
+ await guardedAccess(void 0);
3468
+ if (result.at !== "ready" || !manifest) return result;
3469
+ if (!await stillMatches(root, rendered, manifest.sha256, fingerprint))
3470
+ return unavailable("source_render_changed");
3471
+ prepared.set(root, {
3472
+ rendered,
3473
+ digest: manifest.sha256,
3474
+ snapshot: result.snapshot,
3475
+ account: key.account,
3476
+ backend: key.backend
3477
+ });
3478
+ return { at: "ready", snapshot: result.snapshot };
3479
+ },
3480
+ { signal }
3481
+ );
3482
+ };
3483
+ const filesForExport = async (projectPath, rendered) => {
3484
+ const root = await realpath4(projectPath);
3485
+ const held = prepared.get(root);
3486
+ const signed = await options.access();
3487
+ if (!held || !rendered || held.rendered !== rendered || !sameOwner(signed, held) || !enabled(options))
3488
+ return null;
3489
+ return await stillMatches(root, rendered, held.digest, fingerprint) ? held.snapshot : null;
3490
+ };
3491
+ return { prepare, filesForExport };
3492
+ }
3493
+ var enabled = (options) => options.enabled?.() ?? true;
3494
+ var sameOwner = (signed, held) => signed?.owner === held.account && signed?.heygenApi === held.backend;
3495
+ async function prepareBinding(job) {
3496
+ const { binding, api, fingerprint, rendered } = job;
3497
+ const limits = await api.limits(binding.ownerSpaceId);
3498
+ if (!limits.syncAllowed) return unavailable("source_plan_required");
3499
+ const capture = await captureProject(binding.projectPath, { limits: limits.push });
3500
+ const bad = captureRefusal(capture);
3501
+ if (bad) return unavailable(bad);
3502
+ if (capture.at !== "captured") return unavailable("source_invalid");
3503
+ if (await fingerprint(binding.projectPath) !== rendered)
3504
+ return unavailable("source_render_changed");
3505
+ const result = await snapshotFor(job, capture.manifest, limits);
3506
+ return { ...result, manifest: capture.manifest };
3507
+ }
3508
+ async function snapshotFor(job, manifest, limits) {
3509
+ const { binding, api, store, options, signal } = job;
3510
+ const blocked = await recoverEarlierCapture(job, manifest.sha256);
3511
+ if (blocked) return blocked;
3512
+ if (binding.base?.manifestSha256 === manifest.sha256 && !binding.inflight)
3513
+ return reuseSnapshot(api, binding, manifest.sha256);
3514
+ if (job.external) return unavailable("source_sync_required");
3515
+ if (!job.own && limits.compositions >= limits.maxCompositions)
3516
+ return unavailable("source_composition_limit");
3517
+ await store.write(binding);
3518
+ binding.composition = await api.create(
3519
+ binding.ownerSpaceId,
3520
+ binding.compositionId,
3521
+ basename2(binding.projectPath)
3522
+ );
3523
+ await store.write(binding);
3524
+ return uploadSource({ binding, manifest, api, store, signal, ...uploadOptions(options) });
3525
+ }
3526
+ function recoverEarlierCapture({ external, binding, api, store }, digest) {
3527
+ const inflight = binding.inflight;
3528
+ if (external || !inflight || inflight.manifestSha256 === digest) return null;
3529
+ return recoverSourceUpload({ binding, api, store });
3530
+ }
3531
+ function uploadOptions(options) {
3532
+ return {
3533
+ fetchImpl: options.fetchImpl ?? fetch,
3534
+ wait: options.wait ?? realWait,
3535
+ timeoutMs: options.verificationTimeoutMs ?? 12e4,
3536
+ onProgress: options.onProgress ?? (() => {
3537
+ })
3538
+ };
3539
+ }
3540
+ async function selectBinding(key, options, store) {
3541
+ const own = await store.read(key);
3542
+ const existing = own ? null : await options.existingBinding?.(key);
3543
+ return { own, existing, binding: own ?? existing ?? newBinding(key, options.spaceId) };
3544
+ }
3545
+ function newBinding(key, space) {
3546
+ return {
3547
+ ...key,
3548
+ version: 1,
3549
+ compositionId: randomUUID8(),
3550
+ ownerSpaceId: space,
3551
+ boundAt: Date.now(),
3552
+ composition: null,
3553
+ etag: null,
3554
+ base: null,
3555
+ inflight: null
3556
+ };
3557
+ }
3558
+ async function reuseSnapshot(api, binding, digest) {
3559
+ if (!binding.base) return unavailable("source_sync_required");
3560
+ const remote = await api.snapshot(
3561
+ binding.ownerSpaceId,
3562
+ binding.compositionId,
3563
+ binding.base.snapshotId
3564
+ );
3565
+ if (remote.id !== binding.base.snapshotId || remote.compositionId !== binding.compositionId || remote.manifestSha256 !== digest || remote.manifest?.sha256 !== digest || remote.publicationOutcome !== "published")
3566
+ return unavailable("source_snapshot_mismatch");
3567
+ return {
3568
+ at: "ready",
3569
+ snapshot: {
3570
+ space_id: binding.ownerSpaceId,
3571
+ composition_id: binding.compositionId,
3572
+ snapshot_id: remote.id
3573
+ }
3574
+ };
3575
+ }
3576
+ async function stillMatches(root, rendered, digest, fingerprint) {
3577
+ if (await fingerprint(root) !== rendered) return false;
3578
+ const capture = await captureProject(root);
3579
+ return !captureRefusal(capture) && capture.at === "captured" && capture.manifest.sha256 === digest && await fingerprint(root) === rendered;
3580
+ }
3581
+
3582
+ // src/share/render.ts
3583
+ import { randomUUID as randomUUID9 } from "crypto";
3584
+ import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync } from "fs";
3585
+ import { mkdir as mkdir3, writeFile as writeFile3, rename as rename2, rm as rm2 } from "fs/promises";
3586
+ import { join as join8 } from "path";
3587
+ var shareContentFingerprint = shareSourceFingerprint;
3588
+ function latestShareRender(dir) {
3589
+ try {
3590
+ const value = JSON.parse(
3591
+ readFileSync2(join8(dir, ".hyperframes", "share-render.json"), "utf8")
3592
+ );
3593
+ if (!value || typeof value !== "object" || !("path" in value) || !("id" in value) || !("fingerprint" in value))
3594
+ return null;
3595
+ if (typeof value.path !== "string" || typeof value.id !== "string" || typeof value.fingerprint !== "string" || !/^[a-f0-9-]{36}$/.test(value.id))
3596
+ return null;
3597
+ const expected = join8(realpathSync(dir), ".hyperframes", "share-renders", `${value.id}.mp4`);
3598
+ if (value.path !== expected || !existsSync2(expected) || realpathSync(expected) !== expected)
3599
+ return null;
3600
+ const contentFingerprint = "contentFingerprint" in value && typeof value.contentFingerprint === "string" ? value.contentFingerprint : void 0;
3601
+ return {
3602
+ path: expected,
3603
+ id: value.id,
3604
+ fingerprint: value.fingerprint,
3605
+ ...contentFingerprint && { contentFingerprint }
3606
+ };
3607
+ } catch {
3608
+ return null;
3609
+ }
3610
+ }
3611
+ async function prepareShareRender(dir) {
3612
+ const [before, content] = await Promise.all([
3613
+ projectFingerprint2(dir),
3614
+ shareContentFingerprint(dir)
3615
+ ]);
3616
+ const previous = latestShareRender(dir);
3617
+ if (content && previous?.fingerprint === before && previous.contentFingerprint === content)
3618
+ return;
3619
+ const stateFolder = join8(dir, ".hyperframes");
3620
+ if (existsSync2(stateFolder) && realpathSync(stateFolder) !== stateFolder)
3621
+ throw new Error("Sharing state must stay inside this project, without symlinks.");
3622
+ await mkdir3(stateFolder, { recursive: true });
3623
+ const folder = join8(stateFolder, "share-renders");
3624
+ if (existsSync2(folder) && realpathSync(folder) !== folder)
3625
+ throw new Error("Sharing state must stay inside this project, without symlinks.");
3626
+ await mkdir3(folder, { recursive: true });
3627
+ if (realpathSync(folder) !== folder)
3628
+ throw new Error("Sharing state must stay inside this project, without symlinks.");
3629
+ const id = randomUUID9();
3630
+ const output = join8(folder, `${id}.mp4`);
3631
+ const [{ createRenderPlan }, { executeRenderPlan }, render] = await Promise.all([
3632
+ import("./plan-JWUSMF4W.js"),
3633
+ import("./execute-OAS454OB.js"),
3634
+ import("./render-ZHCPCISN.js")
3635
+ ]);
3636
+ const target = join8(stateFolder, "share-render.json");
3637
+ const temporary = `${target}.${id}.tmp`;
3638
+ try {
3639
+ const plan = createRenderPlan({ dir, output, format: "mp4", quiet: true, strict: true });
3640
+ await executeRenderPlan(plan, {
3641
+ renderLocal: (project, output2, options, cancellation) => render.renderLocal(
3642
+ project,
3643
+ output2,
3644
+ { ...options, embedded: true, exitAfterComplete: false },
3645
+ cancellation
3646
+ ),
3647
+ renderDocker: async () => {
3648
+ throw new Error("Share renders locally.");
3649
+ },
3650
+ checkResolution: render.checkRenderResolutionPreflight
3651
+ });
3652
+ if (!existsSync2(output))
3653
+ throw new Error("The render did not produce a video. Run hyperframes render to diagnose it.");
3654
+ const [after, afterContent] = await Promise.all([
3655
+ projectFingerprint2(dir),
3656
+ shareContentFingerprint(dir)
3657
+ ]);
3658
+ if (after !== before || afterContent !== content)
3659
+ throw new Error(
3660
+ "The project changed while rendering. Share again to capture the current project."
3661
+ );
3662
+ await writeFile3(
3663
+ temporary,
3664
+ JSON.stringify({ id, path: output, fingerprint: before, contentFingerprint: content })
3665
+ );
3666
+ await rename2(temporary, target);
3667
+ } catch (error) {
3668
+ await Promise.allSettled([rm2(output, { force: true }), rm2(temporary, { force: true })]);
3669
+ throw error;
3670
+ }
3671
+ }
3672
+
3673
+ // src/share/sources.ts
3674
+ var ShareSourceError = class extends Error {
3675
+ };
3676
+ var unavailablePlans = /* @__PURE__ */ new Set([
3677
+ "source_disabled",
3678
+ "source_plan_required",
3679
+ "source_composition_limit"
3680
+ ]);
3681
+ function uncheckedSource() {
3682
+ return { at: "not_checked" };
3683
+ }
3684
+ async function prepareCliShareSource(dir, access, spaceId, options) {
3685
+ if (options.includeSource !== true || options.videoOnly) return videoOnly("requested");
3686
+ if (!options.shareFiles) return videoOnly("source_disabled");
3687
+ if (!spaceId) throw new Error("The owning workspace could not be verified. Retry sharing.");
3688
+ try {
3689
+ const render = latestShareRender(dir);
3690
+ const source = shareSources({
3691
+ access,
3692
+ spaceId,
3693
+ fingerprint: async (path4) => render?.contentFingerprint === await shareContentFingerprint(path4) ? projectFingerprint2(path4) : null
3694
+ });
3695
+ const prepared = await source.prepare(dir, render?.fingerprint ?? null);
3696
+ if (prepared.at === "ready")
3697
+ return { source: prepared, filesForExport: source.filesForExport, requireSource: true };
3698
+ if (unavailablePlans.has(prepared.reason)) return videoOnly(prepared.reason);
3699
+ throw new Error(`Source could not be attached (${prepared.reason}).`);
3700
+ } catch (error) {
3701
+ const reason = error instanceof Error ? error.message : "Source upload failed.";
3702
+ throw new ShareSourceError(
3703
+ `${reason} Retry sharing, or use --video-only to share just the video.`,
3704
+ {
3705
+ cause: error
3706
+ }
3707
+ );
3708
+ }
3709
+ }
3710
+ function videoOnly(reason) {
3711
+ return { source: { at: "video_only", reason }, requireSource: false };
3712
+ }
3713
+
3714
+ // src/share/telemetry.ts
3715
+ import { randomUUID as randomUUID10 } from "crypto";
3716
+ var REASONS2 = /* @__PURE__ */ new Set([
3717
+ "feature_unavailable",
3718
+ "audience_required",
3719
+ "workspace_cannot_share",
3720
+ "workspace_mismatch",
3721
+ "manage_existing_audience",
3722
+ "review_project_limit_reached",
3723
+ "review_subscription_required",
3724
+ "review_entitlement_unavailable",
3725
+ "review_public_consent_required",
3726
+ "moderation_hold",
3727
+ "review_operation_busy",
3728
+ "not_shared",
3729
+ "offline",
3730
+ "signed_out"
3731
+ ]);
3732
+ function failureReason(error) {
3733
+ if (error instanceof AuthError) return "authentication";
3734
+ if (error instanceof CliUsageError && REASONS2.has(error.code)) return error.code;
3735
+ if (typeof error === "object" && error !== null && "reason" in error) {
3736
+ const reason = error.reason;
3737
+ if (typeof reason === "string" && REASONS2.has(reason)) return reason;
3738
+ }
3739
+ return "other";
3740
+ }
3741
+ function emit(event, properties) {
3742
+ try {
3743
+ readConfigFresh();
3744
+ resetTelemetryPostureCache();
3745
+ trackEvent(event, properties);
3746
+ } catch {
3747
+ }
3748
+ }
3749
+ function trackShareInteraction(input, surface = "cli") {
3750
+ if (input.event === "share_opened")
3751
+ emit(input.event, { client_surface: surface, link: input.link });
3752
+ else emit(input.event, { client_surface: surface, via: input.via });
3753
+ }
3754
+ function shareAttempt(action, surface) {
3755
+ const base = { client_surface: surface, action, attempt_id: randomUUID10() };
3756
+ let admitted = false;
3757
+ let recovery = false;
3758
+ const track = (event, extra = {}) => emit(event, { ...base, recovery, ...extra });
3759
+ const admit = () => {
3760
+ if (admitted) return;
3761
+ admitted = true;
3762
+ track("share_mutation_admitted");
3763
+ };
3764
+ track("share_mutation_attempted");
3765
+ return {
3766
+ authenticated: () => track("share_mutation_authenticated"),
3767
+ recover: (pending) => {
3768
+ recovery = pending;
3769
+ if (pending) track("share_recovery_attempted");
3770
+ },
3771
+ progress: (value) => {
3772
+ if (value && value.step !== "preparing") admit();
3773
+ },
3774
+ retrieved: () => track("share_existing_link_returned"),
3775
+ complete: (ready, added) => {
3776
+ if (!added)
3777
+ return track(ready ? "share_existing_link_returned" : "share_mutation_processing");
3778
+ admit();
3779
+ track("share_video_ready");
3780
+ },
3781
+ failed: (error) => track("share_mutation_failed", { reason: failureReason(error) })
3782
+ };
3783
+ }
3784
+ async function observeShareMutation(action, surface, run2) {
3785
+ const attempt = shareAttempt(action, surface);
3786
+ try {
3787
+ return await run2(attempt);
3788
+ } catch (error) {
3789
+ attempt.failed(error);
3790
+ throw error;
3791
+ }
3792
+ }
3793
+
3794
+ // src/share/auth.ts
3795
+ function shareSite() {
3796
+ return oauthEnvironment() === "dev" ? "https://dev.hyperframes.dev" : "https://hyperframes.dev";
3797
+ }
3798
+ function createShareAccess(pinIdentity = true) {
3799
+ let bound2;
3800
+ let identity;
3801
+ const userClient = new AuthClient();
3802
+ const access = async (refused, verifyIdentity = false) => {
3803
+ const credential = await shareCredential(refused);
3804
+ let account = identity;
3805
+ if (verifyIdentity || account?.token !== credential.access_token) {
3806
+ const user = await userClient.getCurrentUser(credential);
3807
+ if (!user.username) throw loginRequired();
3808
+ account = {
3809
+ token: credential.access_token,
3810
+ owner: user.username,
3811
+ email: user.email ?? null
3812
+ };
3813
+ }
3814
+ const key = JSON.stringify([account.owner, new URL(tokenEndpoint()).origin, apiBaseUrl()]);
3815
+ if (pinIdentity && bound2 !== void 0 && bound2 !== key) throw ErrLoginChanged();
3816
+ bound2 = key;
3817
+ identity = account;
3818
+ return {
3819
+ token: credential.access_token,
3820
+ heygen: new URL(tokenEndpoint()).origin,
3821
+ heygenApi: apiBaseUrl(),
3822
+ owner: account.owner
3823
+ };
3824
+ };
3825
+ return {
3826
+ access,
3827
+ signedInEmail: async () => {
3828
+ await access();
3829
+ return identity?.email ?? null;
3830
+ }
3831
+ };
3832
+ }
3833
+ function loginRequired() {
3834
+ return new AuthError(
3835
+ "UNAUTHENTICATED",
3836
+ "Sharing requires a signed-in HeyGen account.",
3837
+ "Run hyperframes auth login. API keys cannot own shared projects."
3838
+ );
3839
+ }
3840
+ async function shareCredential(refused) {
3841
+ let credential = await resolveCredential();
3842
+ if (credential.type !== "oauth") throw loginRequired();
3843
+ if (credential.refreshable || credential.access_token === refused) {
3844
+ if (!credential.refresh_token) throw loginRequired();
3845
+ await refreshTokens(credential.refresh_token);
3846
+ credential = await resolveCredential();
3847
+ if (credential.type !== "oauth") throw loginRequired();
3848
+ }
3849
+ if (credential.access_token === refused) throw loginRequired();
3850
+ return credential;
3851
+ }
3852
+
3853
+ export {
3854
+ rm,
3855
+ mkdirInside,
3856
+ writeJsonAtomic,
3857
+ readJsonRecord,
3858
+ withProjectShareLock,
3859
+ signedInRequest,
3860
+ bindShareHost,
3861
+ reviewUploadOrigins,
3862
+ ReviewFailed,
3863
+ reviewClient,
3864
+ setReviewSite,
3865
+ ownerOf,
3866
+ reviewRecord,
3867
+ reviewStatus,
3868
+ shareForReview,
3869
+ setReviewAccess,
3870
+ turnOffReviewLink,
3871
+ reviewSentence,
3872
+ fileSha256Base64,
3873
+ reviewVersion,
3874
+ addVersion,
3875
+ refreshReviewExport,
3876
+ versionOnPage,
3877
+ pendingReviewExport,
3878
+ SourceIgnoreError,
3879
+ projectFingerprint2 as projectFingerprint,
3880
+ shareContentFingerprint,
3881
+ latestShareRender,
3882
+ prepareShareRender,
3883
+ ShareSourceError,
3884
+ uncheckedSource,
3885
+ prepareCliShareSource,
3886
+ trackShareInteraction,
3887
+ observeShareMutation,
3888
+ shareSite,
3889
+ createShareAccess
3890
+ };