nolo-cli 0.149.0-alpha.1 → 0.151.0-alpha.2

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 (258) hide show
  1. package/{_executeModel-OW3H7ICR.js → _executeModel-XHAFJ2MM.js} +134 -91
  2. package/accountResolver-7RYB4D2P.js +300 -0
  3. package/action-SXJD5N5R.js +23 -0
  4. package/{addContentAction-B2DRF7P6.js → addContentAction-ZV774PHH.js} +20 -14
  5. package/{addDialogAgentAction-2P2FLTLD.js → addDialogAgentAction-A6SMKAGH.js} +26 -22
  6. package/{agentDeleteCommand-7IDWF6E3.js → agentDeleteCommand-DPUUS56Z.js} +181 -93
  7. package/{agentEmailCommands-A6XBQZBN.js → agentEmailCommands-V4P5EFLP.js} +132 -112
  8. package/{agentGrantCommands-M3XFO6EN.js → agentGrantCommands-HOJ3JBBQ.js} +3 -3
  9. package/agentListCommands-TWFLUYIZ.js +802 -0
  10. package/{agentMachineCommands-DQPUIMAC.js → agentMachineCommands-MELPAZZI.js} +58 -62
  11. package/{agentProviderCommands-YK2BIIXZ.js → agentProviderCommands-HL6MBLCL.js} +149 -2
  12. package/{agentPullCommand-HF4A42D4.js → agentPullCommand-FA43RBRU.js} +7 -7
  13. package/agentRecordCommands-FSWSSQIO.js +154 -0
  14. package/agentRunCommand-GDBJVOAT.js +183 -0
  15. package/{agentRunControl-2SKCR4SB.js → agentRunControl-IFM7IGMG.js} +10 -2
  16. package/{agentRuntimeLocal-AK2QVJHY.js → agentRuntimeLocal-KKSQJMTE.js} +47 -50
  17. package/{agentSlice-O4RUQUMT.js → agentSlice-YO2ZLJMD.js} +23 -16
  18. package/{appDeleteCommands-N3XEVVYC.js → appDeleteCommands-4PL4KYRN.js} +58 -59
  19. package/{appDeployCommands-AWFIXYVW.js → appDeployCommands-EEEXCEB6.js} +67 -63
  20. package/{appDeployStatusCommands-CZRON2FO.js → appDeployStatusCommands-35ZX7T66.js} +56 -56
  21. package/{appGetCommands-XQIUY4TD.js → appGetCommands-WFCHXJWF.js} +56 -56
  22. package/{appListCommands-NNG4H36Y.js → appListCommands-XY2U6DPF.js} +57 -59
  23. package/{authCommand-UBJ4EWYZ.js → authCommand-QYN47CQD.js} +371 -68
  24. package/{authCommands-H6WKKCRW.js → authCommands-77CHYBGF.js} +12 -9
  25. package/{builtinSkillRegistry-ZMF6YGNO.js → builtinSkillRegistry-TDQ6JB2E.js} +13 -11
  26. package/{chromeCommands-2N6MEWRU.js → chromeCommands-OBBNJCLS.js} +314 -13
  27. package/chromeOpsCommands-3Z34RKSE.js +472 -0
  28. package/{chunk-ALXHV7NK.js → chunk-2GGXHQIW.js} +43 -4
  29. package/{localRuntimeAuthority-5W6IJRAD.js → chunk-2IXDJNZI.js} +154 -75
  30. package/{chunk-IVZJWTDI.js → chunk-36OMEXXR.js} +89 -21
  31. package/{chunk-H6A6X4EK.js → chunk-3MZAGMYY.js} +16 -0
  32. package/chunk-3PVYUPXK.js +40 -0
  33. package/chunk-3SZA4U64.js +1192 -0
  34. package/{chunk-GNMAFAIS.js → chunk-44WXLHFI.js} +1 -1
  35. package/{chunk-AGGIDPCZ.js → chunk-4JH2UMJR.js} +6 -0
  36. package/chunk-4LCOCOR5.js +50 -0
  37. package/chunk-4YRTZIVN.js +871 -0
  38. package/chunk-556RW72X.js +14110 -0
  39. package/{chunk-N7J63Q6C.js → chunk-56GBUMO5.js} +10 -1
  40. package/{chunk-W7XHHYWM.js → chunk-5BHQICF2.js} +5 -1
  41. package/{chunk-XUWRURDF.js → chunk-5EBLANFT.js} +1 -1
  42. package/{chunk-3AH7LNUB.js → chunk-5EMSBTQ6.js} +33 -14
  43. package/{chunk-YRRASA5Q.js → chunk-5MM7NNO6.js} +113 -52
  44. package/chunk-5MMAK75Q.js +15 -0
  45. package/{chunk-M5PVFLD4.js → chunk-64K7WX26.js} +90 -21
  46. package/{chunk-AKG5W4LG.js → chunk-6CCFTVBP.js} +76 -221
  47. package/chunk-6MJNEXUU.js +614 -0
  48. package/{chunk-62IL3KQV.js → chunk-6MXDOUMH.js} +15 -3
  49. package/{chunk-QOKAKDPE.js → chunk-6Q7UTJKR.js} +6 -94
  50. package/chunk-6QDYSCPW.js +223 -0
  51. package/{chunk-HYZIYH2H.js → chunk-74RAWNQN.js} +56 -63
  52. package/chunk-7DPNBQSV.js +9 -0
  53. package/chunk-7MOXKPHC.js +119 -0
  54. package/{chunk-ZUEK6A6C.js → chunk-7XKL25PW.js} +1973 -754
  55. package/{chunk-IAESIMK7.js → chunk-A4MW3YZL.js} +10 -14
  56. package/chunk-AGIM7IMJ.js +147 -0
  57. package/{chunk-7CHC4W22.js → chunk-AIZE5TDM.js} +3 -3
  58. package/{chunk-YAQJJDC2.js → chunk-AOCM7HPT.js} +214 -51
  59. package/{chunk-5GVBDNTO.js → chunk-AU7AXHUL.js} +1 -1
  60. package/{chunk-4H22P2JV.js → chunk-AUIJZACN.js} +2073 -1275
  61. package/{chunk-CIF4X6ZM.js → chunk-AWVFQMOV.js} +25 -3
  62. package/{chunk-RYZINGPM.js → chunk-BPMPOFWP.js} +347 -235
  63. package/{chunk-YUNJN43V.js → chunk-BU2YQBV4.js} +215 -28
  64. package/{chunk-XPRWFQQK.js → chunk-CBHGZRCE.js} +38 -12
  65. package/{chunk-Y3PMXGLH.js → chunk-CHCS6XPJ.js} +365 -144
  66. package/chunk-CHOZJMJS.js +78 -0
  67. package/{chunk-GBRG75BQ.js → chunk-D2MDMY2M.js} +1 -0
  68. package/{chunk-3SV7RM24.js → chunk-D2QN6CTI.js} +117 -72
  69. package/{chunk-5TEEECZM.js → chunk-E2AKSW7L.js} +10 -7
  70. package/{chunk-RSEEDUMS.js → chunk-EDX5XSJM.js} +2 -2
  71. package/{chunk-ATLTFRYJ.js → chunk-ES633ZS5.js} +280 -98
  72. package/{chunk-QDSINZM3.js → chunk-EUGTFFO6.js} +2 -23
  73. package/{chunk-UNYJU5L6.js → chunk-EYLGAEB4.js} +5 -1
  74. package/{chunk-CU3QB4HW.js → chunk-EYWJT7A2.js} +12 -12
  75. package/{chunk-BNGW5ASC.js → chunk-EZVK3N5L.js} +66 -18
  76. package/{chunk-6FGTMQCL.js → chunk-F32Z66T4.js} +6 -10
  77. package/chunk-FJMRBOPO.js +11507 -0
  78. package/{chunk-ZOVKKMF6.js → chunk-FY4SDK2E.js} +1 -1
  79. package/chunk-G6OOUQWJ.js +417 -0
  80. package/{chunk-PQWU42UQ.js → chunk-GCKHQECX.js} +6 -6
  81. package/chunk-GKXCHNTE.js +15 -0
  82. package/{chunk-TXH4IWJL.js → chunk-GQN2WLAI.js} +20 -11
  83. package/{chunk-P6GMCCAT.js → chunk-GQV5KHJU.js} +78 -12
  84. package/{chunk-B2XUQXQX.js → chunk-HIQ4GF53.js} +191 -68
  85. package/{chunk-MST6R3E4.js → chunk-HKX3ULQB.js} +34 -22
  86. package/{chunk-GMZLP5DV.js → chunk-HNUWUO75.js} +30 -19
  87. package/{chunk-5UTFL4QJ.js → chunk-I2ZMGXXF.js} +10 -5
  88. package/chunk-I42VC5KR.js +15 -0
  89. package/{chunk-3BXNTXYI.js → chunk-I4SN4NUQ.js} +1199 -56
  90. package/chunk-IA7TRNNR.js +11 -0
  91. package/{chunk-WIWM4FE3.js → chunk-IJERIUXS.js} +55 -748
  92. package/{chunk-CPUFH46E.js → chunk-ILU2NPWY.js} +10 -10
  93. package/{chunk-SLLGJZDT.js → chunk-ISQL4V7C.js} +4 -4
  94. package/chunk-IT3ZZRJE.js +12 -0
  95. package/{chunk-TZZ2WRBL.js → chunk-IZ7OJB6K.js} +20 -16
  96. package/{chunk-DY7ANLKG.js → chunk-JKMLSTZK.js} +43 -12
  97. package/{chunk-6TPOEJMQ.js → chunk-JZX2XLKC.js} +64 -23
  98. package/{chunk-27ONFIEY.js → chunk-K2AER7RX.js} +19 -12
  99. package/{chunk-O2OWEFII.js → chunk-KFHQQ3NO.js} +1 -1
  100. package/{chunk-QXGPFY6J.js → chunk-LGN377P3.js} +27 -17
  101. package/{chunk-L36OWPP3.js → chunk-LIQJTQRN.js} +118 -139
  102. package/{chunk-UASIEDKM.js → chunk-LTRUTOHX.js} +36 -31
  103. package/{chunk-BFU6C242.js → chunk-NMFV26UG.js} +1 -1
  104. package/{chunk-5J3PYNUP.js → chunk-NYYFIKHI.js} +17 -3
  105. package/{chunk-6O4IK4V2.js → chunk-OFFL4DCR.js} +1 -1
  106. package/{chunk-B6SAMB33.js → chunk-OWYYDMGJ.js} +209 -9
  107. package/{chunk-KQHGZWSV.js → chunk-OXME3PEE.js} +1 -1
  108. package/{chunk-CTUQJVQM.js → chunk-P5QACQDK.js} +1 -1
  109. package/{chunk-DXHL7G2L.js → chunk-PCKVQXYV.js} +274 -93
  110. package/{chunk-4JMDLJAD.js → chunk-PJNFNEJE.js} +114 -37
  111. package/{chunk-Z4CSIXYP.js → chunk-PLSVXHSA.js} +3 -3
  112. package/{chunk-BIDGLJQ3.js → chunk-PLXDDGBK.js} +45 -8
  113. package/chunk-PWTNI4N7.js +47 -0
  114. package/chunk-QFEW2ULV.js +42 -0
  115. package/{chunk-RGNEEJ3Y.js → chunk-QLQ573SU.js} +35 -9
  116. package/chunk-QQ56R7KS.js +88 -0
  117. package/chunk-QYPE3TS3.js +43 -0
  118. package/{chunk-4DPP773Q.js → chunk-RSHPU4PD.js} +59 -11
  119. package/chunk-RVWMAFIT.js +134 -0
  120. package/{chunk-ESHYE7WU.js → chunk-S73EPYNC.js} +10 -7
  121. package/{chunk-UQNS32WZ.js → chunk-SCMHQUMK.js} +1 -1
  122. package/{chunk-HTVYCXBP.js → chunk-SMENBO3M.js} +354 -120
  123. package/{chunk-OMRJYNCI.js → chunk-SSFDFOVT.js} +26 -31
  124. package/chunk-SW4S4XYB.js +1794 -0
  125. package/{chunk-TB3MIBRC.js → chunk-T6X3D7NB.js} +572 -430
  126. package/chunk-TY3TIUJK.js +89 -0
  127. package/{chunk-X2QRZXZH.js → chunk-TYJ5XFEA.js} +4 -4
  128. package/{chunk-ALFH24P3.js → chunk-TYYRSFBG.js} +197 -155
  129. package/{chunk-7KVZ5LDQ.js → chunk-UBUH2TCC.js} +18 -4
  130. package/chunk-UEILX4EV.js +15 -0
  131. package/chunk-UHTDNB5Y.js +140 -0
  132. package/{chunk-YYLHWIW6.js → chunk-UKZX3NHN.js} +1 -1
  133. package/{chunk-OHOVNO7I.js → chunk-UOKFKFPO.js} +6 -3
  134. package/{chunk-XISEYOGH.js → chunk-USHQX6VT.js} +5 -5
  135. package/chunk-UUPR3TD7.js +53 -0
  136. package/{chunk-HDLLCBRF.js → chunk-VEA7H5FG.js} +2 -2
  137. package/chunk-VHGD6FHV.js +116 -0
  138. package/chunk-VIWDGTDA.js +8 -0
  139. package/{chunk-GOH6RW6F.js → chunk-VJXHL6MH.js} +34 -11
  140. package/{chunk-4XEYAFLY.js → chunk-VL5KOY2C.js} +623 -94
  141. package/{chunk-EADNWBAZ.js → chunk-VP3BINY7.js} +13 -0
  142. package/{chunk-EOARMOVD.js → chunk-W4S6OTSC.js} +6 -3
  143. package/chunk-WD4XYDYC.js +567 -0
  144. package/chunk-WJZOQR2J.js +151 -0
  145. package/{chunk-AUDNYVRC.js → chunk-XETG4RIX.js} +5 -5
  146. package/{chunk-MX574M24.js → chunk-XI7DGLUK.js} +4 -4
  147. package/{chunk-3L2WKC3W.js → chunk-XPWGOTBQ.js} +8 -1
  148. package/chunk-XRUSXPCQ.js +514 -0
  149. package/{chunk-I4OPU5TK.js → chunk-XS47QOFV.js} +273 -11
  150. package/{chunk-S5XGT6GB.js → chunk-XZNCX52W.js} +30 -9
  151. package/{chunk-ID7LNBWR.js → chunk-Y2DXOPSO.js} +1920 -644
  152. package/{chunk-5OA5HMTL.js → chunk-YLMMECCH.js} +1 -1
  153. package/{chunk-CFT5HBGW.js → chunk-YVLQXTUB.js} +448 -12
  154. package/chunk-YVPQATSC.js +709 -0
  155. package/{chunk-3DAVPNFT.js → chunk-Z7OJUX6S.js} +122 -107
  156. package/chunk-ZEZC7IIM.js +126 -0
  157. package/{chunk-ALGORS6Y.js → chunk-ZF6526IQ.js} +43 -8
  158. package/chunk-ZIWPQEFU.js +165 -0
  159. package/chunk-ZKZ5X2HS.js +7012 -0
  160. package/chunk-ZRAU6T47.js +56 -0
  161. package/{cliExecutor-AWYR3T33.js → cliExecutor-BWBF2MTI.js} +4 -3
  162. package/{clipboardy-BX4NMYHE.js → clipboardy-GCO3GT3I.js} +3 -8
  163. package/{commandRegistry-2KBOXZQC.js → commandRegistry-XN7C5GHO.js} +183 -107
  164. package/contentThunks-5L7YQI3S.js +84 -0
  165. package/{cooldownCommands-ZLEPIB4A.js → cooldownCommands-JFKTYS2D.js} +2 -2
  166. package/{createAgentAutomationAction-5UGTB26P.js → createAgentAutomationAction-QOPOLCRK.js} +53 -44
  167. package/createDialogAction-MZ66VY5Q.js +76 -0
  168. package/{createPageAction-CDLDKPRM.js → createPageAction-VQDJIXMY.js} +65 -54
  169. package/cursorProvider-YGGNMVWX.js +6123 -0
  170. package/{db-VQSAOWAO.js → db-2QOTXYGH.js} +11 -5
  171. package/{dbSlice-DQ32LYTJ.js → dbSlice-J37OGIXH.js} +19 -13
  172. package/{deleteFile-NX6QHCWZ.js → deleteFile-6JWDDRVP.js} +10 -6
  173. package/dialogCommands-YZLSJB6X.js +113 -0
  174. package/{dialogSlice-N3YB65G5.js → dialogSlice-6RODVYCK.js} +53 -39
  175. package/{docCreateCommands-ZSLGVBZT.js → docCreateCommands-JB2RRMRJ.js} +54 -57
  176. package/{docDeleteCommands-5N4GVZBG.js → docDeleteCommands-AQENULNM.js} +56 -58
  177. package/{docReadCommands-YJSAA7AV.js → docReadCommands-DYD25YLQ.js} +53 -56
  178. package/{docStore-E3CEOV5Q.js → docStore-ZZA3OPM5.js} +25 -16
  179. package/{docUpdateCommands-WEMLSW6W.js → docUpdateCommands-3GVS23QL.js} +54 -57
  180. package/{fetchMessages-67MEFPZR.js → fetchMessages-IIJWQ3HR.js} +5 -4
  181. package/{getPricing-NMMFT3YI.js → getPricing-FKK3F5EJ.js} +11 -9
  182. package/{handleSendMessageAction-DQAD5ERJ.js → handleSendMessageAction-DVG5U26T.js} +422 -118
  183. package/index.js +11 -7
  184. package/{lib-FRRS27KN.js → lib-4YTWAGY7.js} +581 -248
  185. package/{localDialogRead-EBRS242U.js → localDialogRead-FSOMOPDZ.js} +2 -2
  186. package/localRuntimeAdapter-HXRHFKRC.js +244 -0
  187. package/localRuntimeAuthority-JDAD7CB6.js +16 -0
  188. package/{localRuntimeDb-3LRMNLCM.js → localRuntimeDb-CVC62PM5.js} +1 -1
  189. package/{machineCommands-HAP75VSG.js → machineCommands-5KBF4RCC.js} +503 -161
  190. package/{machineInfo-66ZFUMLE.js → machineInfo-UKPTZO5Y.js} +2 -2
  191. package/machineWsRunDispatch-4OQDEDOR.js +169 -0
  192. package/{memberThunks-5ZXPR63F.js → memberThunks-66DH6ABQ.js} +25 -18
  193. package/{models-ZPU5EDF4.js → models-LAS4B2B5.js} +2 -2
  194. package/package.json +1 -1
  195. package/{providerPresetApply-DD6NGWW6.js → providerPresetApply-MY66I6NT.js} +10 -10
  196. package/{providerRegistry-XDRLMYGJ.js → providerRegistry-QOE2FT57.js} +13 -9
  197. package/{read-EPTJRAEF.js → read-DC4NUGN6.js} +12 -8
  198. package/{readDocTool-W4NDXNEX.js → readDocTool-NCJ5NT25.js} +1 -1
  199. package/{readlineWorkspace-7BC66QSX.js → readlineWorkspace-RIE62QVZ.js} +5022 -921
  200. package/{removeDialogAgentAction-OSYNZRX7.js → removeDialogAgentAction-E2H3OZU6.js} +29 -28
  201. package/{runAgentClientLoop-6E6UC3CE.js → runAgentClientLoop-KLUUXBZS.js} +154 -97
  202. package/{runtimeDoctorCommands-ID23PNNZ.js → runtimeDoctorCommands-GIOGC5SC.js} +17 -17
  203. package/secretCommands-ZXZRLR3R.js +700 -0
  204. package/setDialogExtraReferencesAction-SITRPMYU.js +37 -0
  205. package/{setPrimaryDialogAgentAction-WZ7KI3YA.js → setPrimaryDialogAgentAction-U7N45TGC.js} +30 -29
  206. package/{chunk-SONWNI3L.js → settingThunks-Y7SVJOMZ.js} +223 -928
  207. package/{skillDiscovery-ZBU76COE.js → skillDiscovery-QC35EQY4.js} +2 -2
  208. package/{slateUtils-RIZES3PV.js → slateUtils-NGV2NMKM.js} +1 -1
  209. package/{spaceCommands-UJOVU4XI.js → spaceCommands-ZR5BR3GX.js} +59 -59
  210. package/{streamAgentChatTurn-3UXPYFNX.js → streamAgentChatTurn-MN2SSPGA.js} +309 -165
  211. package/{switchDialogAgentAction-GMR7WN3P.js → switchDialogAgentAction-OMGBD3N2.js} +26 -22
  212. package/{tableCommands-G7RV3RU3.js → tableCommands-U3QDY4L6.js} +19 -17
  213. package/{toolApiClient-CVGWM4PN.js → toolApiClient-7WSJJJBV.js} +6 -5
  214. package/tools-W2MOLERY.js +124 -0
  215. package/tuiSummaryLlmCaller-BM3VSTBU.js +130 -0
  216. package/{updateCommands-4EHDLF5J.js → updateCommands-NQXAGFM7.js} +3 -3
  217. package/{updateDialogTitleAction-UPFV7TDT.js → updateDialogTitleAction-Z4JX6REN.js} +102 -57
  218. package/workloadLifecycle-36DXRZKU.js +320 -0
  219. package/action-GI44T4DR.js +0 -31
  220. package/agentListCommands-IW3GQVUP.js +0 -427
  221. package/agentRecordCommands-VCA76W6B.js +0 -134
  222. package/agentRunCommand-YNLDKVR7.js +0 -161
  223. package/browser-image-compression-MFDTD7K6.js +0 -1763
  224. package/chatQueueReduxAdapter-TJRMXMYA.js +0 -186
  225. package/chromeOpsCommands-IXRLN57H.js +0 -289
  226. package/chunk-36KZDDO5.js +0 -2415
  227. package/chunk-ACQD6YI2.js +0 -25363
  228. package/chunk-CQ3WA2NE.js +0 -299
  229. package/chunk-CYSYR67N.js +0 -93
  230. package/chunk-JBTJAPUF.js +0 -35
  231. package/chunk-K2CSUCHJ.js +0 -620
  232. package/chunk-LTRXGFMS.js +0 -83
  233. package/chunk-M76ECQRD.js +0 -13658
  234. package/chunk-MEYIRKDN.js +0 -8967
  235. package/chunk-OCZKATRC.js +0 -129
  236. package/chunk-OTGFTBLI.js +0 -13
  237. package/chunk-PUOC4YRO.js +0 -394
  238. package/chunk-PZZTFEKK.js +0 -34
  239. package/chunk-URMS4XY2.js +0 -10
  240. package/chunk-UV6VISQJ.js +0 -20
  241. package/chunk-VJVNU77E.js +0 -83
  242. package/chunk-XYJSY4KG.js +0 -13807
  243. package/chunk-Y5GCAMGP.js +0 -9
  244. package/chunk-YPREESF4.js +0 -225
  245. package/contentThunks-BDIQRZR6.js +0 -73
  246. package/createDialogAction-B7VGVEVU.js +0 -66
  247. package/dialogCommands-G7YBVAMC.js +0 -102
  248. package/levelLazyShim-GZBKODGI.js +0 -7
  249. package/machineWsRunDispatch-L32G7C4P.js +0 -149
  250. package/serverStoreFactory-YMXDF4NI.js +0 -20
  251. package/setDialogExtraReferencesAction-M32UYNCG.js +0 -30
  252. package/settingSlice-Q6EKL7EQ.js +0 -204
  253. package/syncMapping-N6RGXGBW.js +0 -437
  254. package/tools-MKYDMWA4.js +0 -111
  255. package/tuiSummaryLlmCaller-3YFNHCTW.js +0 -128
  256. package/{chunk-SV5IJK6K.js → chunk-NBTY7YJF.js} +3 -3
  257. package/{chunk-2SYTUTLI.js → chunk-YBNHPX4S.js} +3 -3
  258. package/{offlineMarxistsAgentCommand-HGXZV4XJ.js → offlineMarxistsAgentCommand-2QTHJCHV.js} +4 -4
package/chunk-36KZDDO5.js DELETED
@@ -1,2415 +0,0 @@
1
- import {
2
- getCurrentSpaceId,
3
- getCurrentSpaceIdRaw,
4
- updateCurrentSpaceIfMatch
5
- } from "./chunk-ZJ7UHBJS.js";
6
- import {
7
- deleteDialog,
8
- i18nBaseConfig,
9
- initReactI18next,
10
- instance,
11
- toast
12
- } from "./chunk-ACQD6YI2.js";
13
- import {
14
- require_date_fns
15
- } from "./chunk-M76ECQRD.js";
16
- import {
17
- require_react
18
- } from "./chunk-YDH3FDFQ.js";
19
- import {
20
- UNCATEGORIZED_ID,
21
- addContentAction,
22
- checkSpaceMembership,
23
- localSpaceAuthorityPatchStamp
24
- } from "./chunk-RSEEDUMS.js";
25
- import {
26
- createSpaceKey,
27
- normalizeSpaceId
28
- } from "./chunk-UAD2WT54.js";
29
- import {
30
- isSystemAdmin
31
- } from "./chunk-QDSINZM3.js";
32
- import {
33
- asRecordOrEmpty
34
- } from "./chunk-KX6YBIHG.js";
35
- import {
36
- patch,
37
- read,
38
- readAndWait,
39
- remove,
40
- resolveFileCategory,
41
- uploadFileAction,
42
- upsertSSREntity,
43
- write
44
- } from "./chunk-HYZIYH2H.js";
45
- import {
46
- SEPARATOR,
47
- asTrimmedNonEmptyStringArray,
48
- createKey,
49
- fileKey,
50
- isAgentKey,
51
- isPageKey,
52
- metaKey,
53
- rowKey,
54
- splitKey,
55
- ulid
56
- } from "./chunk-3AH7LNUB.js";
57
- import {
58
- asOptionalFiniteNumber
59
- } from "./chunk-WWC7I6TA.js";
60
- import {
61
- DEVICE_LOCAL_OWNER_ID,
62
- createAsyncThunk,
63
- getRuntimeServerContext,
64
- isDeviceLocalSpaceBody,
65
- resolveReplicationServers,
66
- scheduleDeleteReplication,
67
- scheduleWriteReplication
68
- } from "./chunk-WIWM4FE3.js";
69
- import {
70
- createClientLogger,
71
- isAbortError
72
- } from "./chunk-QOKAKDPE.js";
73
- import {
74
- selectIdentityUserId
75
- } from "./chunk-SEJ5OS6F.js";
76
- import {
77
- buildTombstoneRecord
78
- } from "./chunk-GBRG75BQ.js";
79
- import {
80
- isRecord
81
- } from "./chunk-KUG52IAP.js";
82
- import {
83
- extractUserId
84
- } from "./chunk-M2EJHDJP.js";
85
- import {
86
- asTrimmedString
87
- } from "./chunk-3EUW3WEO.js";
88
- import {
89
- asOptionalPositiveFiniteNumber
90
- } from "./chunk-U6VC4MU4.js";
91
- import {
92
- asOptionalTrimmedString
93
- } from "./chunk-G3SUCT4W.js";
94
- import {
95
- __toESM
96
- } from "./chunk-4VNS5WPM.js";
97
-
98
- // packages/render/table/tableStore.ts
99
- var import_react = __toESM(require_react(), 1);
100
- var import_date_fns2 = __toESM(require_date_fns(), 1);
101
- import { ulid as ulid3 } from "ulid";
102
-
103
- // packages/render/table/fetchAndCacheTableRows.ts
104
- var TABLE_ROWS_FETCH_TIMEOUT_MS = 5e3;
105
- var getRowTimestamp = (row) => {
106
- if (!row || typeof row !== "object") return 0;
107
- return asOptionalPositiveFiniteNumber(Date.parse(row.updatedAt ?? "")) ?? asOptionalPositiveFiniteNumber(Date.parse(row.createdAt ?? "")) ?? 0;
108
- };
109
- var shouldReplaceMergedRow = (nextRow, currentRow) => {
110
- const nextTs = getRowTimestamp(nextRow);
111
- const currentTs = getRowTimestamp(currentRow);
112
- if (nextTs !== currentTs) return nextTs > currentTs;
113
- return Boolean(nextRow?.deletedAt) && !currentRow?.deletedAt;
114
- };
115
- var mergeTableRows = (...rowLists) => {
116
- const merged = /* @__PURE__ */ new Map();
117
- for (const rowList of rowLists) {
118
- for (const row of rowList) {
119
- const dbKey = row?.dbKey;
120
- if (!dbKey) continue;
121
- const existing = merged.get(dbKey);
122
- if (!existing || shouldReplaceMergedRow(row, existing)) {
123
- merged.set(dbKey, row);
124
- }
125
- }
126
- }
127
- return Array.from(merged.values());
128
- };
129
- var TABLE_SYNC_ENVELOPE = "table-sync-v1";
130
- var getLatestTableMeta = (snapshots) => {
131
- let latestMeta = null;
132
- for (const snapshot of snapshots) {
133
- const tableMeta = snapshot.tableMeta;
134
- if (!tableMeta || typeof tableMeta !== "object") continue;
135
- if (!latestMeta || shouldReplaceMergedRow(tableMeta, latestMeta)) {
136
- latestMeta = tableMeta;
137
- }
138
- }
139
- return latestMeta;
140
- };
141
- var loadLocalTableRows = async (db, tenantId, tableId) => {
142
- if (!db || typeof db.iterator !== "function") {
143
- return [];
144
- }
145
- const rows = [];
146
- const { gte, lte } = rowKey.range(tenantId, tableId);
147
- try {
148
- for await (const [, value] of db.iterator({ gte, lte })) {
149
- if (value?.type === "table_row" /* TABLE_ROW */) {
150
- rows.push(value);
151
- }
152
- }
153
- } catch {
154
- return [];
155
- }
156
- return rows;
157
- };
158
- var fetchTableRowsFromServer = async (server, tenantId, tableId, headers, fetchImpl = fetch) => {
159
- const controller = new AbortController();
160
- const timeoutId = setTimeout(
161
- () => controller.abort(),
162
- TABLE_ROWS_FETCH_TIMEOUT_MS
163
- );
164
- try {
165
- const res = await fetchImpl(`${server}/rpc/listTableRows`, {
166
- method: "POST",
167
- headers,
168
- body: JSON.stringify({
169
- tenantId,
170
- tableId,
171
- includeDeleted: true,
172
- envelope: TABLE_SYNC_ENVELOPE
173
- }),
174
- signal: controller.signal
175
- });
176
- if (!res.ok) {
177
- let msg = `\u52A0\u8F7D\u8868 ${tableId} \u884C\u5931\u8D25\uFF08${res.status}\uFF09`;
178
- try {
179
- const err2 = await res.json();
180
- if (err2 && typeof err2.message === "string") {
181
- msg = err2.message;
182
- }
183
- } catch {
184
- }
185
- throw new Error(msg);
186
- }
187
- const data = await res.json();
188
- if (Array.isArray(data)) {
189
- return {
190
- rows: data,
191
- deletedRows: [],
192
- tableMeta: null,
193
- complete: false
194
- };
195
- }
196
- if (!data || typeof data !== "object" || !Array.isArray(data.rows)) {
197
- throw new Error("\u670D\u52A1\u5668\u8FD4\u56DE\u683C\u5F0F\u9519\u8BEF\uFF1A\u9884\u671F\u4E3A\u6570\u7EC4");
198
- }
199
- return {
200
- rows: data.rows,
201
- deletedRows: Array.isArray(data.deletedRows) ? data.deletedRows : [],
202
- tableMeta: data.tableMeta ?? null,
203
- complete: data.complete === true
204
- };
205
- } catch (err2) {
206
- if (isAbortError(err2)) {
207
- throw new Error(
208
- `\u52A0\u8F7D\u8868 ${tableId} \u884C\u8D85\u65F6\uFF1A${server} \u5728 ${TABLE_ROWS_FETCH_TIMEOUT_MS / 1e3}s \u5185\u65E0\u54CD\u5E94`
209
- );
210
- }
211
- throw err2;
212
- } finally {
213
- clearTimeout(timeoutId);
214
- }
215
- };
216
- var cacheMergedTableRows = async (db, mergedRows) => {
217
- if (!db) return;
218
- await Promise.all(
219
- mergedRows.map(async (mergedRow) => {
220
- if (!mergedRow?.dbKey) return;
221
- try {
222
- const localRow = await db.get(mergedRow.dbKey).catch(() => null);
223
- if (!localRow) {
224
- await db.put(mergedRow.dbKey, mergedRow);
225
- return;
226
- }
227
- const serverTs = new Date(
228
- mergedRow.updatedAt ?? mergedRow.createdAt ?? 0
229
- ).getTime();
230
- const localTs = new Date(
231
- localRow.updatedAt ?? localRow.createdAt ?? 0
232
- ).getTime();
233
- const shouldOverwrite = serverTs > localTs || serverTs === localTs && Boolean(mergedRow.deletedAt) && !Boolean(localRow.deletedAt);
234
- if (shouldOverwrite) {
235
- await db.put(mergedRow.dbKey, mergedRow);
236
- }
237
- } catch {
238
- }
239
- })
240
- );
241
- };
242
- var clearStaleLocalRows = async (db, localRows, authoritativeRows) => {
243
- if (!db || typeof db.del !== "function") return;
244
- const authoritativeKeys = new Set(
245
- authoritativeRows.map((row) => row?.dbKey).filter((dbKey) => typeof dbKey === "string" && dbKey.length > 0)
246
- );
247
- await Promise.all(
248
- localRows.map(async (row) => {
249
- const dbKey = row?.dbKey;
250
- if (typeof dbKey !== "string" || authoritativeKeys.has(dbKey)) return;
251
- try {
252
- await db.del(dbKey);
253
- } catch {
254
- }
255
- })
256
- );
257
- };
258
- var keepRemoteRowForPartialMerge = (row, localRowsByKey) => {
259
- const dbKey = row?.dbKey;
260
- if (typeof dbKey !== "string" || !dbKey) return false;
261
- const localRow = localRowsByKey.get(dbKey);
262
- if (!localRow) return true;
263
- const remoteDeleted = Boolean(row?.deletedAt);
264
- const localDeleted = Boolean(localRow?.deletedAt);
265
- return remoteDeleted === localDeleted;
266
- };
267
- var fetchAndCacheTableRows = async ({
268
- db,
269
- tenantId,
270
- tableId,
271
- token,
272
- remoteServers = [],
273
- fetchImpl = fetch
274
- }) => {
275
- const headers = {
276
- "Content-Type": "application/json"
277
- };
278
- if (token) {
279
- headers.Authorization = `Bearer ${token}`;
280
- }
281
- const localRows = await loadLocalTableRows(db, tenantId, tableId);
282
- const remoteResults = await Promise.allSettled(
283
- remoteServers.map(
284
- (server) => fetchTableRowsFromServer(server, tenantId, tableId, headers, fetchImpl)
285
- )
286
- );
287
- const fulfilledRemoteSnapshots = remoteResults.filter(
288
- (result) => result.status === "fulfilled"
289
- ).map((result) => result.value);
290
- if (fulfilledRemoteSnapshots.length === 0 && localRows.length === 0) {
291
- const firstFailure = remoteResults.find(
292
- (result) => result.status === "rejected"
293
- );
294
- throw new Error(firstFailure?.reason?.message || "\u52A0\u8F7D\u8868\u884C\u5931\u8D25");
295
- }
296
- const allRemoteSnapshotsComplete = remoteServers.length > 0 && remoteResults.length === remoteServers.length && fulfilledRemoteSnapshots.length === remoteServers.length && fulfilledRemoteSnapshots.every((snapshot) => snapshot.complete);
297
- const localRowsByKey = new Map(
298
- localRows.filter((row) => typeof row?.dbKey === "string" && row.dbKey.length > 0).map((row) => [row.dbKey, row])
299
- );
300
- const remoteRowLists = fulfilledRemoteSnapshots.map((snapshot) => {
301
- const snapshotRows = [...snapshot.rows, ...snapshot.deletedRows];
302
- return allRemoteSnapshotsComplete ? snapshotRows : snapshotRows.filter((row) => keepRemoteRowForPartialMerge(row, localRowsByKey));
303
- });
304
- const authoritativeRemoteRows = remoteRowLists.flat();
305
- const tableDeleted = allRemoteSnapshotsComplete && Boolean(getLatestTableMeta(fulfilledRemoteSnapshots)?.deletedAt);
306
- if (allRemoteSnapshotsComplete) {
307
- await clearStaleLocalRows(db, localRows, authoritativeRemoteRows);
308
- }
309
- const localRowsForMerge = allRemoteSnapshotsComplete ? localRows.filter(
310
- (row) => authoritativeRemoteRows.some((remoteRow) => remoteRow?.dbKey === row?.dbKey)
311
- ) : localRows;
312
- const mergedRows = mergeTableRows(localRowsForMerge, ...remoteRowLists);
313
- await cacheMergedTableRows(db, mergedRows);
314
- return tableDeleted ? [] : mergedRows.filter((row) => !row?.deletedAt);
315
- };
316
-
317
- // packages/render/table/tableColumnCore.ts
318
- var ok = (value) => ({ ok: true, value });
319
- var err = (error) => ({ ok: false, error });
320
- var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
321
- var buildMeta = (meta, columns, updatedAt) => ({
322
- meta: { ...meta, columns, updatedAt },
323
- metaChanges: { columns, updatedAt },
324
- noop: false
325
- });
326
- var reorderList = (list, from, to) => {
327
- const next = [...list];
328
- const [moved] = next.splice(from, 1);
329
- next.splice(to, 0, moved);
330
- return next;
331
- };
332
- function addColumnToMeta(meta, input, deps) {
333
- const { columnName } = input;
334
- if (!columnName.trim()) {
335
- return err("\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A");
336
- }
337
- if (meta.columns.some((c) => c.name === columnName)) {
338
- return err(`\u5B57\u6BB5 ${columnName} \u5DF2\u5B58\u5728`);
339
- }
340
- const newColumn = {
341
- id: deps.id,
342
- name: columnName,
343
- label: columnName
344
- };
345
- return ok(buildMeta(meta, [...meta.columns, newColumn], deps.nowIso));
346
- }
347
- function deleteColumnFromMeta(meta, rows, input, deps) {
348
- const { columnName } = input;
349
- const { nowIso } = deps;
350
- if (!meta.columns.some((c) => c.name === columnName)) {
351
- return err(`\u5B57\u6BB5 ${columnName} \u4E0D\u5B58\u5728`);
352
- }
353
- const newColumns = meta.columns.filter((c) => c.name !== columnName);
354
- const rowPatches = rows.filter((row) => hasOwn(row, columnName)).map((row) => ({
355
- dbKey: row.dbKey,
356
- changes: { [columnName]: null, updatedAt: nowIso }
357
- }));
358
- const newRows = rows.map((row) => {
359
- if (!hasOwn(row, columnName)) {
360
- return row;
361
- }
362
- const { [columnName]: _removed, ...rest } = row;
363
- return { ...rest, updatedAt: nowIso };
364
- });
365
- return ok({
366
- ...buildMeta(meta, newColumns, nowIso),
367
- rows: newRows,
368
- rowPatches
369
- });
370
- }
371
- function reorderColumnInMeta(meta, input, deps) {
372
- const { fromIndex, toIndex } = input;
373
- const columnCount = meta.columns.length;
374
- if (fromIndex < 0 || fromIndex >= columnCount || toIndex < 0 || toIndex >= columnCount) {
375
- return err("\u5217\u7D22\u5F15\u8D85\u51FA\u8303\u56F4");
376
- }
377
- if (fromIndex === toIndex) {
378
- return ok({
379
- meta,
380
- metaChanges: { columns: meta.columns, updatedAt: meta.updatedAt },
381
- noop: true
382
- });
383
- }
384
- return ok(
385
- buildMeta(meta, reorderList(meta.columns, fromIndex, toIndex), deps.nowIso)
386
- );
387
- }
388
- function renameColumnLabelInMeta(meta, input, deps) {
389
- const { columnId } = input;
390
- const label = input.label.trim();
391
- if (!label) {
392
- return err("\u5B57\u6BB5\u663E\u793A\u540D\u4E0D\u80FD\u4E3A\u7A7A");
393
- }
394
- if (!meta.columns.some((c) => c.id === columnId)) {
395
- return err("\u8981\u91CD\u547D\u540D\u7684\u5B57\u6BB5\u4E0D\u5B58\u5728");
396
- }
397
- const newColumns = meta.columns.map(
398
- (c) => c.id === columnId ? { ...c, label } : c
399
- );
400
- return ok(buildMeta(meta, newColumns, deps.nowIso));
401
- }
402
- function updateColumnWidthInMeta(meta, input, deps) {
403
- const { columnId, width } = input;
404
- if (!meta.columns.some((c) => c.id === columnId)) {
405
- return err("\u8981\u8C03\u6574\u5BBD\u5EA6\u7684\u5B57\u6BB5\u4E0D\u5B58\u5728");
406
- }
407
- const normalizedWidth = typeof width === "number" && width > 0 ? Math.round(width) : void 0;
408
- const newColumns = meta.columns.map(
409
- (c) => c.id === columnId ? { ...c, width: normalizedWidth } : c
410
- );
411
- return ok(buildMeta(meta, newColumns, deps.nowIso));
412
- }
413
- function addColumnOptionInMeta(meta, input, deps) {
414
- const { columnId } = input;
415
- const option = input.option.trim();
416
- if (!option) {
417
- return err("\u9009\u9879\u540D\u4E0D\u80FD\u4E3A\u7A7A");
418
- }
419
- const column = meta.columns.find((c) => c.id === columnId);
420
- if (!column) {
421
- return err("\u8981\u65B0\u589E\u9009\u9879\u7684\u5B57\u6BB5\u4E0D\u5B58\u5728");
422
- }
423
- if ((column.options ?? []).some((o) => o.trim() === option)) {
424
- return ok({
425
- meta,
426
- metaChanges: { columns: meta.columns, updatedAt: meta.updatedAt },
427
- noop: true
428
- });
429
- }
430
- const newColumns = meta.columns.map(
431
- (c) => c.id === columnId ? { ...c, options: [...c.options ?? [], option] } : c
432
- );
433
- return ok(buildMeta(meta, newColumns, deps.nowIso));
434
- }
435
-
436
- // packages/render/table/createTableAction.ts
437
- var import_date_fns = __toESM(require_date_fns(), 1);
438
- import { ulid as ulid2 } from "ulid";
439
-
440
- // packages/app/i18n/client.ts
441
- instance.use(initReactI18next).init({
442
- ...i18nBaseConfig,
443
- lng: "zh-CN" /* ZH_CN */,
444
- fallbackLng: {
445
- ["en" /* EN */]: ["en" /* EN */],
446
- ["zh-CN" /* ZH_CN */]: ["zh-CN" /* ZH_CN */, "en" /* EN */],
447
- ["zh-Hant" /* ZH_HANT */]: ["zh-Hant" /* ZH_HANT */, "zh-CN" /* ZH_CN */, "en" /* EN */],
448
- ["ja" /* JA */]: ["ja" /* JA */, "en" /* EN */],
449
- default: ["en" /* EN */]
450
- },
451
- compatibilityJSON: "v3"
452
- });
453
- var client_default = instance;
454
-
455
- // packages/render/table/createTableAction.ts
456
- var DEFAULT_COLUMNS = [
457
- {
458
- name: "title",
459
- label: "\u6807\u9898",
460
- type: "text",
461
- description: "\u8FD9\u4E00\u884C\u8BB0\u5F55\u7684\u4E3B\u9898\u6216\u540D\u79F0\u3002",
462
- isPrimary: true,
463
- required: true
464
- },
465
- {
466
- name: "note",
467
- label: "\u5907\u6CE8",
468
- type: "text",
469
- description: "\u5BF9\u8BE5\u6761\u76EE\u7684\u8865\u5145\u8BF4\u660E\u3002",
470
- required: false
471
- }
472
- ];
473
- var normalizeColumns = (inputColumns) => {
474
- const base = Array.isArray(inputColumns) ? inputColumns : [];
475
- const normalized = base.map((c) => {
476
- if (!c || typeof c.name !== "string") return null;
477
- const name = c.name.trim();
478
- if (!name) return null;
479
- const col = {
480
- id: asOptionalTrimmedString(c.id) ?? ulid2(),
481
- name
482
- };
483
- const label = asOptionalTrimmedString(c.label);
484
- if (label) col.label = label;
485
- if (typeof c.type === "string") {
486
- col.type = c.type;
487
- }
488
- const description = asOptionalTrimmedString(c.description);
489
- if (description) col.description = description;
490
- if (typeof c.isPrimary === "boolean") {
491
- col.isPrimary = c.isPrimary;
492
- }
493
- if (typeof c.required === "boolean") {
494
- col.required = c.required;
495
- }
496
- if (Array.isArray(c.options)) {
497
- const opts = asTrimmedNonEmptyStringArray(c.options);
498
- if (opts.length) {
499
- col.options = opts;
500
- }
501
- }
502
- return col;
503
- }).filter(Boolean);
504
- if (normalized.length > 0) {
505
- if (!normalized.some((c) => c.isPrimary)) {
506
- normalized[0].isPrimary = true;
507
- }
508
- return normalized;
509
- }
510
- return DEFAULT_COLUMNS.map((c) => ({
511
- ...c,
512
- id: ulid2()
513
- }));
514
- };
515
- var normalizeStringArray = (value) => {
516
- if (!Array.isArray(value)) return void 0;
517
- const items = [...new Set(asTrimmedNonEmptyStringArray(value))];
518
- return items.length ? items : void 0;
519
- };
520
- var normalizePublicIntake = (input) => {
521
- if (!isRecord(input)) return void 0;
522
- const allowedFields = normalizeStringArray(input.allowedFields) ?? [];
523
- if (input.enabled !== true) {
524
- return { enabled: false, allowedFields };
525
- }
526
- if (allowedFields.length === 0) {
527
- throw new Error("publicIntake.allowedFields \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5\u3002");
528
- }
529
- const slug = asOptionalTrimmedString(input.slug);
530
- const honeypotField = asOptionalTrimmedString(input.honeypotField);
531
- return {
532
- enabled: true,
533
- ...slug ? { slug } : {},
534
- ...normalizeStringArray(input.appIds) ? { appIds: normalizeStringArray(input.appIds) } : {},
535
- allowedFields,
536
- ...normalizeStringArray(input.requiredFields) ? { requiredFields: normalizeStringArray(input.requiredFields) } : {},
537
- ...honeypotField ? { honeypotField } : {}
538
- };
539
- };
540
- var createTableAction = async ({
541
- spaceId: customSpaceId,
542
- title: customTitle,
543
- purpose: customPurpose,
544
- description: customDescription,
545
- tags: customTags,
546
- publicIntake,
547
- categoryId,
548
- columns,
549
- withDefaultRows = true
550
- } = {}, { dispatch, getState }) => {
551
- const state3 = getState();
552
- const userId = selectIdentityUserId(state3);
553
- if (!userId) throw new Error("User ID not found.");
554
- const spaceId = customSpaceId ?? getCurrentSpaceId();
555
- const tableId = ulid2();
556
- const now = /* @__PURE__ */ new Date();
557
- const nowIso = (0, import_date_fns.formatISO)(now);
558
- const dbKey = metaKey(userId, tableId);
559
- const defaultTitle = client_default.t("space:newTable", {
560
- defaultValue: "\u65B0\u5EFA\u8868\u683C"
561
- });
562
- const title = asOptionalTrimmedString(customTitle) ?? defaultTitle;
563
- const purpose = asOptionalTrimmedString(customPurpose);
564
- const description = asOptionalTrimmedString(customDescription);
565
- const tags = Array.isArray(customTags) && customTags.length ? asTrimmedNonEmptyStringArray(customTags) : void 0;
566
- const finalPublicIntake = normalizePublicIntake(publicIntake);
567
- const finalColumns = normalizeColumns(columns);
568
- const tableMeta = {
569
- dbKey,
570
- tenantId: userId,
571
- tableId,
572
- spaceId: spaceId ?? null,
573
- displayName: title,
574
- purpose,
575
- description,
576
- tags,
577
- schemaVersion: 1,
578
- columns: finalColumns,
579
- views: [],
580
- // 后续可以在 UI 中新增视图
581
- triggers: [],
582
- // 后续可以在 UI/配置中新增触发器
583
- aiConfig: void 0,
584
- ...finalPublicIntake ? { publicIntake: finalPublicIntake } : {},
585
- createdAt: nowIso,
586
- updatedAt: nowIso,
587
- type: "table" /* TABLE */
588
- };
589
- await dispatch(
590
- write({
591
- data: tableMeta,
592
- customKey: dbKey
593
- })
594
- ).unwrap();
595
- if (withDefaultRows) {
596
- const defaultRows = [
597
- {
598
- title: "\u793A\u4F8B\u4E00",
599
- note: "\u4F60\u53EF\u4EE5\u5728\u8FD9\u91CC\u8BB0\u5F55\u4EFB\u4F55\u5185\u5BB9\uFF0C\u4F8B\u5982\u4EFB\u52A1\u3001\u60F3\u6CD5\u6216\u914D\u7F6E\u9879\u3002"
600
- },
601
- {
602
- title: "\u793A\u4F8B\u4E8C",
603
- note: "\u53CC\u51FB\u5355\u5143\u683C\u5F00\u59CB\u7F16\u8F91\uFF0C\u53F3\u4E0A\u89D2\u53EF\u4EE5\u6DFB\u52A0\u5B57\u6BB5\u548C\u884C\u3002"
604
- }
605
- ];
606
- await Promise.all(
607
- defaultRows.map(async (values) => {
608
- const { dbKey: rowKeyStr, rowId } = rowKey.create(userId, tableId);
609
- const row = {
610
- dbKey: rowKeyStr,
611
- tenantId: userId,
612
- tableId,
613
- rowId,
614
- createdAt: nowIso,
615
- updatedAt: nowIso,
616
- type: "table_row" /* TABLE_ROW */,
617
- ...values
618
- };
619
- await dispatch(
620
- write({
621
- data: row,
622
- customKey: rowKeyStr
623
- })
624
- ).unwrap();
625
- })
626
- );
627
- }
628
- if (spaceId) {
629
- await dispatch(
630
- addContentToSpace({
631
- spaceId,
632
- contentKey: dbKey,
633
- type: "table" /* TABLE */,
634
- title,
635
- categoryId
636
- })
637
- ).unwrap();
638
- }
639
- if (typeof window !== "undefined") {
640
- window.dispatchEvent(new Event("nolo-user-data-updated"));
641
- }
642
- return dbKey;
643
- };
644
-
645
- // packages/render/table/deleteTableAction.ts
646
- var parseMetaKey = (dbKey) => {
647
- const parts = dbKey.split(SEPARATOR);
648
- if (parts[0] !== "meta" || parts.length < 3) {
649
- throw new Error(`\u975E\u6CD5\u8868 key\uFF1A${dbKey}`);
650
- }
651
- const tenantId = parts[1];
652
- const tableId = parts.slice(2).join(SEPARATOR);
653
- return { tenantId, tableId };
654
- };
655
- var collectEntriesByPrefix = async (db, prefix) => {
656
- const entries = [];
657
- for await (const [key, value] of db.iterator({
658
- gte: prefix,
659
- lte: prefix + "\uFFFF"
660
- })) {
661
- entries.push([key, value]);
662
- }
663
- return entries;
664
- };
665
- var belongsToTable = (value, tenantId, tableId) => Boolean(
666
- value && typeof value === "object" && value.tenantId === tenantId && value.tableId === tableId
667
- );
668
- var indexValueReferencesRows = (value, rowDbKeys, rowIds) => {
669
- if (typeof value === "string") {
670
- return rowDbKeys.has(value) || rowIds.has(value);
671
- }
672
- if (!value || typeof value !== "object") return false;
673
- const candidate = value;
674
- return typeof candidate.dbKey === "string" && rowDbKeys.has(candidate.dbKey) || typeof candidate.rowDbKey === "string" && rowDbKeys.has(candidate.rowDbKey) || typeof candidate.rowId === "string" && rowIds.has(candidate.rowId);
675
- };
676
- var deleteTableAction = async ({ dbKey }, {
677
- dispatch,
678
- getState,
679
- extra
680
- }) => {
681
- const { db } = extra;
682
- const state3 = getState();
683
- const { currentServer, syncServers } = getRuntimeServerContext(state3);
684
- const { tenantId, tableId } = parseMetaKey(dbKey);
685
- const nowIso = (/* @__PURE__ */ new Date()).toISOString();
686
- const rowPrefix = createKey("row", tenantId, tableId, "");
687
- const rowEntries = (await collectEntriesByPrefix(db, rowPrefix)).filter(
688
- ([, value]) => belongsToTable(value, tenantId, tableId)
689
- );
690
- const rowDbKeys = new Set(rowEntries.map(([key]) => key));
691
- const rowIds = new Set(
692
- rowEntries.map(([, value]) => value.rowId).filter((rowId) => typeof rowId === "string")
693
- );
694
- const idxPrefix = createKey("idx", tenantId, tableId, "");
695
- const idxEntries = await collectEntriesByPrefix(db, idxPrefix);
696
- const idxKeys = idxEntries.filter(
697
- ([, value]) => belongsToTable(value, tenantId, tableId) || indexValueReferencesRows(value, rowDbKeys, rowIds)
698
- ).map(([key]) => key);
699
- const viewPrefix = createKey("view", tenantId, tableId, "");
700
- const viewEntries = await collectEntriesByPrefix(db, viewPrefix);
701
- const viewKeys = viewEntries.filter(([, value]) => belongsToTable(value, tenantId, tableId)).map(([key]) => key);
702
- const metaRecord = typeof db.get === "function" ? await db.get(dbKey).catch(() => null) : null;
703
- const keysToDelete = Array.from(
704
- /* @__PURE__ */ new Set([
705
- ...idxKeys,
706
- ...viewKeys
707
- ])
708
- );
709
- const putOps = [
710
- ...metaRecord && typeof metaRecord === "object" ? [
711
- {
712
- type: "put",
713
- key: dbKey,
714
- value: buildTombstoneRecord(metaRecord, nowIso)
715
- }
716
- ] : [],
717
- ...rowEntries.map(([key, value]) => ({
718
- type: "put",
719
- key,
720
- value: buildTombstoneRecord(value, nowIso)
721
- }))
722
- ];
723
- if (keysToDelete.length > 0 || putOps.length > 0) {
724
- const ops = [
725
- ...putOps,
726
- ...keysToDelete.map((key) => ({
727
- type: "del",
728
- key
729
- }))
730
- ];
731
- await db.batch(ops);
732
- }
733
- scheduleDeleteReplication({
734
- currentServer,
735
- syncServers,
736
- dbKey,
737
- deleteOptions: { type: "table" },
738
- state: state3
739
- });
740
- return dbKey;
741
- };
742
-
743
- // packages/render/table/tableStore.ts
744
- async function safeDispatch(dispatch, action) {
745
- if (!dispatch) return void 0;
746
- const res = await dispatch(action);
747
- if (res && typeof res.unwrap === "function") {
748
- return await res.unwrap();
749
- }
750
- return res?.payload ?? res;
751
- }
752
- var createInitialState = () => ({
753
- currentTable: null,
754
- isLoading: false,
755
- isInitialized: false,
756
- error: null,
757
- rows: [],
758
- focusContext: null
759
- });
760
- var listeners = /* @__PURE__ */ new Set();
761
- var version = 0;
762
- var state = createInitialState();
763
- var notify = () => {
764
- for (const listener of listeners) {
765
- try {
766
- listener();
767
- } catch {
768
- }
769
- }
770
- };
771
- var bump = () => {
772
- version += 1;
773
- notify();
774
- };
775
- var setState = (updater) => {
776
- state = typeof updater === "function" ? updater(state) : updater;
777
- bump();
778
- };
779
- function getTableState() {
780
- return state;
781
- }
782
- function createTableCommand(name, fn) {
783
- const command = (args) => {
784
- return async (dispatch, getState, extra) => {
785
- try {
786
- const payload = await fn(args, { dispatch, getState, extra });
787
- return {
788
- type: `${name}/fulfilled`,
789
- payload,
790
- meta: { arg: args },
791
- unwrap: async () => payload
792
- };
793
- } catch (err2) {
794
- const message = err2?.message || String(err2);
795
- return {
796
- type: `${name}/rejected`,
797
- payload: message,
798
- error: { message },
799
- unwrap: async () => {
800
- throw err2 instanceof Error ? err2 : new Error(message);
801
- }
802
- };
803
- }
804
- };
805
- };
806
- command.fulfilled = {
807
- type: `${name}/fulfilled`,
808
- match: (action) => action?.type === `${name}/fulfilled`
809
- };
810
- command.rejected = {
811
- type: `${name}/rejected`,
812
- match: (action) => action?.type === `${name}/rejected`
813
- };
814
- command.pending = {
815
- type: `${name}/pending`,
816
- match: (action) => action?.type === `${name}/pending`
817
- };
818
- command.run = (args, context = {}) => fn(args, context);
819
- return command;
820
- }
821
- var initTable = createTableCommand(
822
- "table/initTable",
823
- async (args, { dispatch } = {}) => {
824
- const { tenantId, tableId } = args;
825
- const dbKey = metaKey(tenantId, tableId);
826
- setState((s) => ({
827
- ...s,
828
- isLoading: true,
829
- error: null,
830
- isInitialized: false,
831
- currentTable: null,
832
- rows: []
833
- }));
834
- try {
835
- if (!dispatch) {
836
- throw new Error("dispatch is required to initialize table");
837
- }
838
- const readAction = await dispatch(readAndWait(dbKey));
839
- const isMatch = typeof readAndWait?.fulfilled?.match === "function" && readAndWait.fulfilled.match(readAction);
840
- const meta = isMatch && readAction.payload ? readAction.payload : readAction?.payload || readAction;
841
- if (meta && typeof meta === "object" && ("columns" in meta || "displayName" in meta || "tableId" in meta)) {
842
- setState((s) => ({
843
- ...s,
844
- isLoading: false,
845
- isInitialized: true,
846
- currentTable: meta,
847
- error: null
848
- }));
849
- return meta;
850
- }
851
- const msg = readAction.payload?.message || `\u65E0\u6CD5\u52A0\u8F7D\u8868 ${tableId}`;
852
- setState((s) => ({
853
- ...s,
854
- isLoading: false,
855
- isInitialized: true,
856
- currentTable: null,
857
- error: msg,
858
- rows: []
859
- }));
860
- throw new Error(msg);
861
- } catch (e) {
862
- const msg = e?.message || `\u521D\u59CB\u5316\u8868 ${tableId} \u65F6\u51FA\u9519`;
863
- setState((s) => ({
864
- ...s,
865
- isLoading: false,
866
- isInitialized: true,
867
- currentTable: null,
868
- error: msg,
869
- rows: []
870
- }));
871
- throw e;
872
- }
873
- }
874
- );
875
- var loadTableRows = createTableCommand(
876
- "table/loadTableRows",
877
- async (args, { getState, extra } = {}) => {
878
- const { tenantId, tableId } = args;
879
- const db = extra?.db;
880
- setState((s) => {
881
- if (s.currentTable && s.currentTable.tenantId === tenantId && s.currentTable.tableId === tableId) {
882
- return { ...s, error: null };
883
- }
884
- return s;
885
- });
886
- try {
887
- const stateObj = getState ? getState() : {};
888
- const { currentToken: token, remoteServers } = getRuntimeServerContext(stateObj);
889
- const rows = await fetchAndCacheTableRows({
890
- db,
891
- tenantId,
892
- tableId,
893
- token,
894
- remoteServers
895
- });
896
- setState((s) => {
897
- if (s.currentTable && s.currentTable.tenantId === tenantId && s.currentTable.tableId === tableId) {
898
- return { ...s, rows };
899
- }
900
- return s;
901
- });
902
- return rows;
903
- } catch (e) {
904
- const msg = e?.message || "\u52A0\u8F7D\u8868\u884C\u5931\u8D25";
905
- setState((s) => {
906
- if (s.currentTable && s.currentTable.tenantId === tenantId && s.currentTable.tableId === tableId) {
907
- return { ...s, error: msg, rows: [] };
908
- }
909
- return s;
910
- });
911
- throw e;
912
- }
913
- }
914
- );
915
- var addRow = createTableCommand(
916
- "table/addRow",
917
- async (args, { dispatch } = {}) => {
918
- const { tenantId, tableId, values } = args;
919
- setState((s) => {
920
- if (s.currentTable && s.currentTable.tenantId === tenantId && s.currentTable.tableId === tableId) {
921
- return { ...s, error: null };
922
- }
923
- return s;
924
- });
925
- try {
926
- const { dbKey, rowId } = rowKey.create(tenantId, tableId);
927
- const nowIso = (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date());
928
- const row = {
929
- dbKey,
930
- tenantId,
931
- tableId,
932
- rowId,
933
- createdAt: nowIso,
934
- updatedAt: nowIso,
935
- type: "table_row" /* TABLE_ROW */,
936
- ...values
937
- };
938
- if (dispatch) {
939
- await safeDispatch(
940
- dispatch,
941
- write({
942
- data: row,
943
- customKey: dbKey
944
- })
945
- );
946
- }
947
- setState((s) => {
948
- const meta = s.currentTable;
949
- if (meta && row?.tenantId === meta.tenantId && row?.tableId === meta.tableId) {
950
- return { ...s, rows: [...s.rows, row] };
951
- }
952
- return s;
953
- });
954
- return row;
955
- } catch (e) {
956
- const msg = e?.message || "\u65B0\u589E\u8868\u884C\u5931\u8D25";
957
- setState((s) => {
958
- if (s.currentTable && s.currentTable.tenantId === tenantId && s.currentTable.tableId === tableId) {
959
- return { ...s, error: msg };
960
- }
961
- return s;
962
- });
963
- throw e;
964
- }
965
- }
966
- );
967
- var deleteRow = createTableCommand(
968
- "table/deleteRow",
969
- async (dbKey, { dispatch, getState, extra } = {}) => {
970
- try {
971
- let row = state.rows.find((item) => item?.dbKey === dbKey);
972
- if (!row && extra?.db && typeof extra.db.get === "function") {
973
- try {
974
- row = await extra.db.get(dbKey);
975
- } catch {
976
- }
977
- }
978
- if (!row && dispatch) {
979
- try {
980
- const readAction = await safeDispatch(dispatch, readAndWait(dbKey));
981
- row = readAction?.payload || readAction;
982
- } catch {
983
- }
984
- }
985
- if (!row) {
986
- throw new Error(`\u5F53\u524D\u8868\u4E2D\u627E\u4E0D\u5230\u8981\u5220\u9664\u7684\u884C\uFF1A${dbKey}`);
987
- }
988
- const nowIso = (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date());
989
- const tombstoneRow = {
990
- ...row,
991
- deletedAt: nowIso,
992
- updatedAt: nowIso,
993
- type: "table_row" /* TABLE_ROW */
994
- };
995
- if (extra?.db && typeof extra.db.put === "function") {
996
- await extra.db.put(dbKey, tombstoneRow);
997
- }
998
- if (dispatch) {
999
- dispatch(upsertSSREntity(tombstoneRow));
1000
- }
1001
- const stateObj = getState ? getState() : {};
1002
- const { currentServer, syncServers } = getRuntimeServerContext(stateObj);
1003
- const servers = resolveReplicationServers(currentServer, syncServers);
1004
- scheduleWriteReplication(
1005
- servers,
1006
- {
1007
- data: tombstoneRow,
1008
- customKey: dbKey
1009
- },
1010
- stateObj
1011
- );
1012
- setState((s) => ({
1013
- ...s,
1014
- rows: s.rows.filter((r) => r.dbKey !== dbKey)
1015
- }));
1016
- return dbKey;
1017
- } catch (e) {
1018
- const msg = e?.message || "\u5220\u9664\u8868\u884C\u5931\u8D25";
1019
- setState((s) => ({ ...s, error: msg }));
1020
- throw e;
1021
- }
1022
- }
1023
- );
1024
- var createTable = createTableCommand(
1025
- "table/createTable",
1026
- async (args, context = {}) => {
1027
- return await createTableAction(args, context);
1028
- }
1029
- );
1030
- var deleteTable = createTableCommand(
1031
- "table/deleteTable",
1032
- async (args, context = {}) => {
1033
- setState((s) => ({ ...s, error: null }));
1034
- try {
1035
- const deletedKey = await deleteTableAction(args, context);
1036
- setState((s) => {
1037
- if (s.currentTable?.dbKey === deletedKey) {
1038
- return {
1039
- ...s,
1040
- currentTable: null,
1041
- rows: [],
1042
- isInitialized: false
1043
- };
1044
- }
1045
- return s;
1046
- });
1047
- return deletedKey;
1048
- } catch (e) {
1049
- const msg = e?.message || "\u5220\u9664\u8868\u65F6\u53D1\u751F\u672A\u77E5\u9519\u8BEF";
1050
- setState((s) => ({ ...s, error: msg }));
1051
- throw e;
1052
- }
1053
- }
1054
- );
1055
- var addColumn = createTableCommand(
1056
- "table/addColumn",
1057
- async (args, { dispatch } = {}) => {
1058
- const { tenantId, tableId, columnName } = args;
1059
- const meta = state.currentTable;
1060
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1061
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1062
- }
1063
- const result = addColumnToMeta(
1064
- meta,
1065
- { columnName },
1066
- { id: ulid3(), nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1067
- );
1068
- if (!result.ok) {
1069
- throw new Error(result.error);
1070
- }
1071
- setState((s) => ({ ...s, error: null }));
1072
- try {
1073
- if (dispatch) {
1074
- await safeDispatch(
1075
- dispatch,
1076
- patch({
1077
- dbKey: meta.dbKey,
1078
- changes: result.value.metaChanges
1079
- })
1080
- );
1081
- }
1082
- setState((s) => ({
1083
- ...s,
1084
- currentTable: result.value.meta,
1085
- isInitialized: true
1086
- }));
1087
- return result.value.meta;
1088
- } catch (e) {
1089
- const msg = e?.message || "\u6DFB\u52A0\u5B57\u6BB5\u5931\u8D25";
1090
- setState((s) => ({ ...s, error: msg }));
1091
- throw e;
1092
- }
1093
- }
1094
- );
1095
- var deleteColumn = createTableCommand(
1096
- "table/deleteColumn",
1097
- async (args, { dispatch } = {}) => {
1098
- const { tenantId, tableId, columnName } = args;
1099
- const meta = state.currentTable;
1100
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1101
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1102
- }
1103
- const result = deleteColumnFromMeta(
1104
- meta,
1105
- state.rows,
1106
- { columnName },
1107
- { nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1108
- );
1109
- if (!result.ok) {
1110
- throw new Error(result.error);
1111
- }
1112
- const { meta: nextMeta, metaChanges, rows: newRows, rowPatches } = result.value;
1113
- setState((s) => ({ ...s, error: null }));
1114
- try {
1115
- if (dispatch) {
1116
- await Promise.all(
1117
- rowPatches.map((p) => safeDispatch(dispatch, patch(p)))
1118
- );
1119
- await safeDispatch(
1120
- dispatch,
1121
- patch({ dbKey: meta.dbKey, changes: metaChanges })
1122
- );
1123
- }
1124
- setState((s) => ({
1125
- ...s,
1126
- currentTable: nextMeta,
1127
- rows: newRows,
1128
- isInitialized: true
1129
- }));
1130
- return { meta: nextMeta, rows: newRows };
1131
- } catch (e) {
1132
- const msg = e?.message || "\u5220\u9664\u5B57\u6BB5\u5931\u8D25";
1133
- setState((s) => ({ ...s, error: msg }));
1134
- throw e;
1135
- }
1136
- }
1137
- );
1138
- var reorderColumn = createTableCommand(
1139
- "table/reorderColumn",
1140
- async (args, { dispatch } = {}) => {
1141
- const { tenantId, tableId, fromIndex, toIndex } = args;
1142
- const meta = state.currentTable;
1143
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1144
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1145
- }
1146
- const result = reorderColumnInMeta(
1147
- meta,
1148
- { fromIndex, toIndex },
1149
- { nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1150
- );
1151
- if (!result.ok) {
1152
- throw new Error(result.error);
1153
- }
1154
- if (result.value.noop) {
1155
- return meta;
1156
- }
1157
- const { meta: nextMeta, metaChanges } = result.value;
1158
- setState((s) => ({ ...s, error: null }));
1159
- try {
1160
- if (dispatch) {
1161
- await safeDispatch(
1162
- dispatch,
1163
- patch({ dbKey: meta.dbKey, changes: metaChanges })
1164
- );
1165
- }
1166
- setState((s) => ({
1167
- ...s,
1168
- currentTable: nextMeta,
1169
- isInitialized: true
1170
- }));
1171
- return nextMeta;
1172
- } catch (e) {
1173
- const msg = e?.message || "\u8C03\u6574\u5217\u987A\u5E8F\u5931\u8D25";
1174
- setState((s) => ({ ...s, error: msg }));
1175
- throw e;
1176
- }
1177
- }
1178
- );
1179
- var renameColumnLabel = createTableCommand(
1180
- "table/renameColumnLabel",
1181
- async (args, { dispatch } = {}) => {
1182
- const { tenantId, tableId, columnId, newLabel } = args;
1183
- const meta = state.currentTable;
1184
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1185
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1186
- }
1187
- const result = renameColumnLabelInMeta(
1188
- meta,
1189
- { columnId, label: newLabel },
1190
- { nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1191
- );
1192
- if (!result.ok) {
1193
- throw new Error(result.error);
1194
- }
1195
- const { meta: nextMeta, metaChanges } = result.value;
1196
- setState((s) => ({ ...s, error: null }));
1197
- try {
1198
- if (dispatch) {
1199
- await safeDispatch(
1200
- dispatch,
1201
- patch({ dbKey: meta.dbKey, changes: metaChanges })
1202
- );
1203
- }
1204
- setState((s) => ({
1205
- ...s,
1206
- currentTable: nextMeta,
1207
- isInitialized: true
1208
- }));
1209
- return nextMeta;
1210
- } catch (e) {
1211
- const msg = e?.message || "\u91CD\u547D\u540D\u5B57\u6BB5\u663E\u793A\u540D\u5931\u8D25";
1212
- setState((s) => ({ ...s, error: msg }));
1213
- throw e;
1214
- }
1215
- }
1216
- );
1217
- var updateColumnWidth = createTableCommand(
1218
- "table/updateColumnWidth",
1219
- async (args, { dispatch } = {}) => {
1220
- const { tenantId, tableId, columnId, width } = args;
1221
- const meta = state.currentTable;
1222
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1223
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1224
- }
1225
- const result = updateColumnWidthInMeta(
1226
- meta,
1227
- { columnId, width },
1228
- { nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1229
- );
1230
- if (!result.ok) {
1231
- throw new Error(result.error);
1232
- }
1233
- const { meta: nextMeta, metaChanges } = result.value;
1234
- setState((s) => ({ ...s, error: null }));
1235
- try {
1236
- if (dispatch) {
1237
- await safeDispatch(
1238
- dispatch,
1239
- patch({ dbKey: meta.dbKey, changes: metaChanges })
1240
- );
1241
- }
1242
- setState((s) => ({
1243
- ...s,
1244
- currentTable: nextMeta,
1245
- isInitialized: true
1246
- }));
1247
- return nextMeta;
1248
- } catch (e) {
1249
- const msg = e?.message || "\u66F4\u65B0\u5B57\u6BB5\u5BBD\u5EA6\u5931\u8D25";
1250
- setState((s) => ({ ...s, error: msg }));
1251
- throw e;
1252
- }
1253
- }
1254
- );
1255
- var addColumnOption = createTableCommand(
1256
- "table/addColumnOption",
1257
- async (args, { dispatch } = {}) => {
1258
- const { tenantId, tableId, columnId, option } = args;
1259
- const meta = state.currentTable;
1260
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1261
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1262
- }
1263
- const result = addColumnOptionInMeta(
1264
- meta,
1265
- { columnId, option },
1266
- { nowIso: (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date()) }
1267
- );
1268
- if (!result.ok) {
1269
- throw new Error(result.error);
1270
- }
1271
- if (result.value.noop) {
1272
- return meta;
1273
- }
1274
- const { meta: nextMeta, metaChanges } = result.value;
1275
- setState((s) => ({ ...s, error: null }));
1276
- try {
1277
- if (dispatch) {
1278
- await safeDispatch(
1279
- dispatch,
1280
- patch({ dbKey: meta.dbKey, changes: metaChanges })
1281
- );
1282
- }
1283
- setState((s) => ({
1284
- ...s,
1285
- currentTable: nextMeta,
1286
- isInitialized: true
1287
- }));
1288
- return nextMeta;
1289
- } catch (e) {
1290
- const msg = e?.message || "\u65B0\u589E\u9009\u9879\u5931\u8D25";
1291
- setState((s) => ({ ...s, error: msg }));
1292
- throw e;
1293
- }
1294
- }
1295
- );
1296
- var renameTable = createTableCommand(
1297
- "table/renameTable",
1298
- async (args, { dispatch } = {}) => {
1299
- const { tenantId, tableId, newName } = args;
1300
- const trimmedName = newName.trim();
1301
- if (!trimmedName) {
1302
- throw new Error("\u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A");
1303
- }
1304
- const meta = state.currentTable;
1305
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1306
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1307
- }
1308
- const nowIso = (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date());
1309
- setState((s) => ({ ...s, error: null }));
1310
- try {
1311
- if (dispatch) {
1312
- await safeDispatch(
1313
- dispatch,
1314
- patch({
1315
- dbKey: meta.dbKey,
1316
- changes: {
1317
- displayName: trimmedName,
1318
- updatedAt: nowIso
1319
- }
1320
- })
1321
- );
1322
- }
1323
- const nextMeta = {
1324
- ...meta,
1325
- displayName: trimmedName,
1326
- updatedAt: nowIso
1327
- };
1328
- setState((s) => ({
1329
- ...s,
1330
- currentTable: nextMeta,
1331
- isInitialized: true
1332
- }));
1333
- return nextMeta;
1334
- } catch (e) {
1335
- const msg = e?.message || "\u91CD\u547D\u540D\u8868\u5931\u8D25";
1336
- setState((s) => ({ ...s, error: msg }));
1337
- throw e;
1338
- }
1339
- }
1340
- );
1341
- var updateTableIcon = createTableCommand(
1342
- "table/updateTableIcon",
1343
- async (args, { dispatch } = {}) => {
1344
- const { tenantId, tableId, icon } = args;
1345
- const meta = state.currentTable;
1346
- if (!meta || meta.tenantId !== tenantId || meta.tableId !== tableId) {
1347
- throw new Error("\u5F53\u524D\u6CA1\u6709\u52A0\u8F7D\u5BF9\u5E94\u7684\u8868\u5B9A\u4E49");
1348
- }
1349
- const nowIso = (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date());
1350
- setState((s) => ({ ...s, error: null }));
1351
- try {
1352
- if (dispatch) {
1353
- await safeDispatch(
1354
- dispatch,
1355
- patch({
1356
- dbKey: meta.dbKey,
1357
- changes: {
1358
- icon: icon ?? null,
1359
- updatedAt: nowIso
1360
- }
1361
- })
1362
- );
1363
- }
1364
- const nextMeta = {
1365
- ...meta,
1366
- icon: icon ?? null,
1367
- updatedAt: nowIso
1368
- };
1369
- setState((s) => ({
1370
- ...s,
1371
- currentTable: nextMeta
1372
- }));
1373
- return nextMeta;
1374
- } catch (e) {
1375
- const msg = e?.message || "\u66F4\u65B0\u8868\u683C\u56FE\u6807\u5931\u8D25";
1376
- setState((s) => ({ ...s, error: msg }));
1377
- throw e;
1378
- }
1379
- }
1380
- );
1381
- var updateCell = createTableCommand(
1382
- "table/updateCell",
1383
- async (args, { dispatch } = {}) => {
1384
- const { dbKey, columnName, value } = args;
1385
- setState((s) => ({ ...s, error: null }));
1386
- try {
1387
- const nowIso = (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date());
1388
- if (dispatch) {
1389
- await safeDispatch(
1390
- dispatch,
1391
- patch({
1392
- dbKey,
1393
- changes: {
1394
- [columnName]: value,
1395
- updatedAt: nowIso
1396
- }
1397
- })
1398
- );
1399
- }
1400
- setState((s) => ({
1401
- ...s,
1402
- rows: s.rows.map((r) => {
1403
- if (r.dbKey === dbKey) {
1404
- return {
1405
- ...r,
1406
- [columnName]: value,
1407
- updatedAt: nowIso
1408
- };
1409
- }
1410
- return r;
1411
- })
1412
- }));
1413
- return { dbKey, columnName, value, updatedAt: nowIso };
1414
- } catch (e) {
1415
- const msg = e?.message || "\u66F4\u65B0\u5355\u5143\u683C\u5931\u8D25";
1416
- setState((s) => ({ ...s, error: msg }));
1417
- throw e;
1418
- }
1419
- }
1420
- );
1421
-
1422
- // packages/create/space/content/deleteContentFromSpaceAction.ts
1423
- var nextSpaceUpdatedAt = (value) => {
1424
- const previousTimestamp = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) || 0 : 0;
1425
- const nextTimestamp = Math.max(Date.now(), previousTimestamp + 1);
1426
- return typeof value === "string" ? new Date(nextTimestamp).toISOString() : nextTimestamp;
1427
- };
1428
- var findContentReference = (spaceData, requestedContentKey) => {
1429
- const contents = spaceData.contents ?? {};
1430
- const directMatch = contents[requestedContentKey];
1431
- if (directMatch) {
1432
- return { entryKey: requestedContentKey, contentInfo: directMatch };
1433
- }
1434
- for (const [entryKey, item] of Object.entries(contents)) {
1435
- if (!item) continue;
1436
- if (item.contentKey === requestedContentKey) {
1437
- return { entryKey, contentInfo: item };
1438
- }
1439
- }
1440
- return null;
1441
- };
1442
- var ENTITY_DELETE_STRATEGIES = {
1443
- dialog: async (key, { dispatch }) => {
1444
- await dispatch(deleteDialog(key)).unwrap();
1445
- },
1446
- page: async (key, { dispatch, userId, sourceServerOrigin }) => {
1447
- const isOwnerByKey = extractUserId(key) === userId;
1448
- if (isOwnerByKey || isSystemAdmin(userId)) {
1449
- await dispatch(remove({ dbKey: key, preferredServerOrigin: sourceServerOrigin }));
1450
- }
1451
- },
1452
- table: async (key, { dispatch }) => {
1453
- await dispatch(deleteTable({ dbKey: key })).unwrap();
1454
- },
1455
- file: async (key, { thunkAPI }) => {
1456
- const { deleteFileAction } = await import("./deleteFile-NX6QHCWZ.js");
1457
- await deleteFileAction(key, thunkAPI);
1458
- },
1459
- image: async (key, { thunkAPI }) => {
1460
- const { deleteFileAction } = await import("./deleteFile-NX6QHCWZ.js");
1461
- await deleteFileAction(key, thunkAPI);
1462
- },
1463
- agent: async (key, { dispatch, userId, sourceServerOrigin }) => {
1464
- const parts = splitKey(key);
1465
- const isPublic = parts[1] === "pub";
1466
- const isOwnerByKey = parts[1] === userId;
1467
- if (!isPublic) {
1468
- if (isOwnerByKey || isSystemAdmin(userId)) {
1469
- await dispatch(remove({ dbKey: key, preferredServerOrigin: sourceServerOrigin }));
1470
- }
1471
- } else {
1472
- const agentData = await dispatch(read({
1473
- dbKey: key,
1474
- preferredServerOrigin: sourceServerOrigin
1475
- })).unwrap();
1476
- if (agentData) {
1477
- const isCreator = agentData.userId === userId;
1478
- const isAdmin = isSystemAdmin(userId);
1479
- if (isCreator || isAdmin) {
1480
- await dispatch(remove({ dbKey: key, preferredServerOrigin: sourceServerOrigin }));
1481
- }
1482
- }
1483
- }
1484
- }
1485
- };
1486
- var deleteContentFromSpaceAction = async (input, thunkAPI) => {
1487
- const { contentKey, sourceServerOrigin } = input;
1488
- const spaceId = normalizeSpaceId(input.spaceId);
1489
- const { dispatch, getState } = thunkAPI;
1490
- const accountUserId = selectIdentityUserId(getState());
1491
- const spaceKey = createSpaceKey.space(spaceId);
1492
- const spaceData = await dispatch(read({
1493
- dbKey: spaceKey,
1494
- preferredServerOrigin: sourceServerOrigin
1495
- })).unwrap();
1496
- if (!spaceData) throw new Error("\u7A7A\u95F4\u4E0D\u5B58\u5728");
1497
- checkSpaceMembership(spaceData, accountUserId);
1498
- const contentReference = findContentReference(spaceData, contentKey);
1499
- if (!contentReference) {
1500
- return { contentKey, spaceId, updatedSpaceData: spaceData };
1501
- }
1502
- const { entryKey, contentInfo } = contentReference;
1503
- const entityKey = String(contentInfo.contentKey || contentKey || entryKey);
1504
- const contentDeletes = {
1505
- [entryKey]: null
1506
- };
1507
- if (entityKey !== entryKey) {
1508
- contentDeletes[entityKey] = null;
1509
- }
1510
- const updatedSpaceData = await dispatch(
1511
- patch({
1512
- dbKey: spaceKey,
1513
- preferredServerOrigin: sourceServerOrigin,
1514
- changes: {
1515
- contents: contentDeletes,
1516
- updatedAt: nextSpaceUpdatedAt(spaceData.updatedAt),
1517
- ...localSpaceAuthorityPatchStamp(spaceData)
1518
- }
1519
- })
1520
- ).unwrap();
1521
- const userId = isDeviceLocalSpaceBody(spaceData) ? DEVICE_LOCAL_OWNER_ID : String(accountUserId ?? "");
1522
- let entityRemoveError = null;
1523
- const contentType = String(contentInfo.type || "").toLowerCase();
1524
- try {
1525
- const strategy = ENTITY_DELETE_STRATEGIES[contentType];
1526
- if (strategy) {
1527
- await strategy(entityKey, { dispatch, userId, thunkAPI, sourceServerOrigin });
1528
- } else if (isPageKey(entityKey)) {
1529
- await ENTITY_DELETE_STRATEGIES.page(entityKey, {
1530
- dispatch,
1531
- userId,
1532
- thunkAPI,
1533
- sourceServerOrigin
1534
- });
1535
- } else if (isAgentKey(entityKey)) {
1536
- await ENTITY_DELETE_STRATEGIES.agent(entityKey, {
1537
- dispatch,
1538
- userId,
1539
- thunkAPI,
1540
- sourceServerOrigin
1541
- });
1542
- }
1543
- } catch (err2) {
1544
- console.error(`[deleteContent] Failed to delete entity ${entityKey}:`, err2);
1545
- entityRemoveError = err2.message || "Unknown error";
1546
- }
1547
- return {
1548
- contentKey,
1549
- spaceId,
1550
- updatedSpaceData,
1551
- entityRemoveError
1552
- };
1553
- };
1554
-
1555
- // packages/create/space/content/moveContentAction.ts
1556
- var logger = createClientLogger("move-content");
1557
- var moveContentAction = async (input, thunkAPI) => {
1558
- const {
1559
- contentKey,
1560
- sourceSpaceId,
1561
- targetSpaceId,
1562
- targetCategoryId: rawTargetCategoryId
1563
- } = input;
1564
- const { dispatch, getState } = thunkAPI;
1565
- const state3 = getState();
1566
- const userId = selectIdentityUserId(state3);
1567
- const now = Date.now();
1568
- logger.info({ ...input, userId }, "Initiating moveContentAction");
1569
- if (sourceSpaceId === targetSpaceId) {
1570
- logger.error("Source and target space IDs are the same.");
1571
- throw new Error(
1572
- "\u6E90\u7A7A\u95F4\u548C\u76EE\u6807\u7A7A\u95F4\u4E0D\u80FD\u76F8\u540C\u3002\u5982\u9700\u4FEE\u6539\u5206\u7C7B\uFF0C\u8BF7\u4F7F\u7528\u66F4\u65B0\u5206\u7C7B\u64CD\u4F5C\u3002"
1573
- );
1574
- }
1575
- if (!contentKey || typeof contentKey !== "string" || contentKey.trim() === "") {
1576
- logger.error("Invalid contentKey provided.");
1577
- throw new Error("\u65E0\u6548\u7684\u5185\u5BB9 Key\u3002");
1578
- }
1579
- let sourceSpaceData = null;
1580
- let targetSpaceData = null;
1581
- let contentDataFromSource = null;
1582
- let finalSourceData = null;
1583
- let finalTargetData = null;
1584
- let overallError = void 0;
1585
- try {
1586
- const sourceSpaceKey = createSpaceKey.space(sourceSpaceId);
1587
- const targetSpaceKey = createSpaceKey.space(targetSpaceId);
1588
- logger.info(
1589
- { sourceSpaceKey, targetSpaceKey },
1590
- "Reading source and target space data."
1591
- );
1592
- const [sourceResult, targetResult] = await Promise.allSettled([
1593
- dispatch(read({
1594
- dbKey: sourceSpaceKey
1595
- })).unwrap(),
1596
- dispatch(read({
1597
- dbKey: targetSpaceKey
1598
- })).unwrap()
1599
- ]);
1600
- if (sourceResult.status === "rejected" || !sourceResult.value) {
1601
- const reason = sourceResult.status === "rejected" ? sourceResult.reason : "Data is null";
1602
- throw new Error(
1603
- `\u65E0\u6CD5\u52A0\u8F7D\u6E90\u7A7A\u95F4 (${sourceSpaceId}): ${reason?.message || reason}`
1604
- );
1605
- }
1606
- sourceSpaceData = sourceResult.value;
1607
- if (targetResult.status === "rejected" || !targetResult.value) {
1608
- const reason = targetResult.status === "rejected" ? targetResult.reason : "Data is null";
1609
- throw new Error(
1610
- `\u65E0\u6CD5\u52A0\u8F7D\u76EE\u6807\u7A7A\u95F4 (${targetSpaceId}): ${reason?.message || reason}`
1611
- );
1612
- }
1613
- targetSpaceData = targetResult.value;
1614
- logger.info("Checking permissions for source and target spaces.");
1615
- checkSpaceMembership(sourceSpaceData, userId);
1616
- checkSpaceMembership(targetSpaceData, userId);
1617
- if (!sourceSpaceData.contents || !sourceSpaceData.contents[contentKey]) {
1618
- logger.error(
1619
- { contentKey, sourceSpaceId },
1620
- "Content key not found in source space contents."
1621
- );
1622
- throw new Error(
1623
- `\u5185\u5BB9 (${contentKey}) \u4E0D\u5728\u6E90\u7A7A\u95F4 (${sourceSpaceId}) \u4E2D\u3002`
1624
- );
1625
- }
1626
- contentDataFromSource = sourceSpaceData.contents[contentKey];
1627
- if (targetSpaceData.contents && targetSpaceData.contents[contentKey]) {
1628
- logger.warn(
1629
- { contentKey, targetSpaceId },
1630
- "Content key already exists in target space. Overwriting."
1631
- );
1632
- }
1633
- let categoryIdForTargetStorage;
1634
- if (rawTargetCategoryId && rawTargetCategoryId !== "" && rawTargetCategoryId !== UNCATEGORIZED_ID) {
1635
- if (targetSpaceData.categories?.[rawTargetCategoryId]) {
1636
- categoryIdForTargetStorage = rawTargetCategoryId;
1637
- } else {
1638
- logger.warn(
1639
- `Target category ${rawTargetCategoryId} not found in target space ${targetSpaceId}. Content will be uncategorized.`
1640
- );
1641
- categoryIdForTargetStorage = void 0;
1642
- }
1643
- } else {
1644
- categoryIdForTargetStorage = void 0;
1645
- }
1646
- const contentReferenceForTarget = {
1647
- ...contentDataFromSource,
1648
- updatedAt: now
1649
- };
1650
- delete contentReferenceForTarget.categoryId;
1651
- if (categoryIdForTargetStorage !== void 0) {
1652
- contentReferenceForTarget.categoryId = categoryIdForTargetStorage;
1653
- }
1654
- const sourcePatchChanges = {
1655
- contents: {
1656
- [contentKey]: null
1657
- // 从源移除引用 (null value in patch typically means delete key)
1658
- },
1659
- updatedAt: now,
1660
- ...localSpaceAuthorityPatchStamp(sourceSpaceData)
1661
- };
1662
- const targetPatchChanges = {
1663
- contents: {
1664
- [contentKey]: contentReferenceForTarget
1665
- // 向目标添加(或覆盖)引用
1666
- },
1667
- updatedAt: now,
1668
- ...localSpaceAuthorityPatchStamp(targetSpaceData)
1669
- };
1670
- logger.info("Patching source and target space data.");
1671
- await Promise.all([
1672
- dispatch(
1673
- patch({ dbKey: sourceSpaceKey, changes: sourcePatchChanges })
1674
- ).unwrap(),
1675
- dispatch(
1676
- patch({ dbKey: targetSpaceKey, changes: targetPatchChanges })
1677
- ).unwrap()
1678
- ]);
1679
- logger.info("Successfully patched both source and target spaces.");
1680
- } catch (error) {
1681
- logger.error(
1682
- { error: error.message, stack: error.stack },
1683
- "Error during move content action execution."
1684
- );
1685
- overallError = error.message || "\u79FB\u52A8\u5185\u5BB9\u65F6\u53D1\u751F\u672A\u77E5\u9519\u8BEF";
1686
- } finally {
1687
- logger.info("Attempting to re-read final space data.");
1688
- const sourceSpaceKey = createSpaceKey.space(sourceSpaceId);
1689
- const targetSpaceKey = createSpaceKey.space(targetSpaceId);
1690
- const [finalSourceResult, finalTargetResult] = await Promise.allSettled([
1691
- dispatch(read({
1692
- dbKey: sourceSpaceKey
1693
- })).unwrap(),
1694
- dispatch(read({
1695
- dbKey: targetSpaceKey
1696
- })).unwrap()
1697
- ]);
1698
- if (finalSourceResult.status === "fulfilled") {
1699
- finalSourceData = finalSourceResult.value;
1700
- } else {
1701
- logger.error(
1702
- { sourceSpaceId, reason: finalSourceResult.reason },
1703
- "Failed to re-read final source space data."
1704
- );
1705
- }
1706
- if (finalTargetResult.status === "fulfilled") {
1707
- finalTargetData = finalTargetResult.value;
1708
- } else {
1709
- logger.error(
1710
- { targetSpaceId, reason: finalTargetResult.reason },
1711
- "Failed to re-read final target space data."
1712
- );
1713
- }
1714
- logger.info(
1715
- {
1716
- hasError: !!overallError,
1717
- sourceReadSuccess: !!finalSourceData,
1718
- targetReadSuccess: !!finalTargetData
1719
- },
1720
- "Move content action finished."
1721
- );
1722
- const result = {
1723
- sourceSpaceId,
1724
- updatedSourceSpaceData: finalSourceData,
1725
- targetSpaceId,
1726
- updatedTargetSpaceData: finalTargetData,
1727
- error: overallError
1728
- // 如果过程中有错误,则传递错误信息
1729
- };
1730
- return result;
1731
- }
1732
- };
1733
-
1734
- // packages/create/space/content/spaceContentPatch.ts
1735
- var notifyUserDataUpdated = () => {
1736
- if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof window.Event === "function") {
1737
- window.dispatchEvent(new window.Event("nolo-user-data-updated"));
1738
- }
1739
- };
1740
- var loadSpaceContentOrThrow = async (dispatch, spaceId, contentKey, sourceServerOrigin) => {
1741
- if (!contentKey || typeof contentKey !== "string" || contentKey.trim() === "") {
1742
- throw new Error("Invalid contentKey provided.");
1743
- }
1744
- const spaceKey = createSpaceKey.space(spaceId);
1745
- let spaceData = null;
1746
- try {
1747
- spaceData = await dispatch(
1748
- read({ dbKey: spaceKey, preferredServerOrigin: sourceServerOrigin })
1749
- ).unwrap();
1750
- } catch (readError) {
1751
- throw new Error(`\u65E0\u6CD5\u52A0\u8F7D\u7A7A\u95F4\u6570\u636E: ${spaceId}`);
1752
- }
1753
- if (!spaceData) {
1754
- throw new Error("Space not found");
1755
- }
1756
- const content = spaceData.contents?.[contentKey];
1757
- if (!content) {
1758
- throw new Error("Content not found in space");
1759
- }
1760
- return { spaceKey, spaceData, content };
1761
- };
1762
- var patchIndividualContentRecord = async (dispatch, contentKey, changes, sourceServerOrigin, failMessagePrefix) => {
1763
- let hasIndividualRecord = false;
1764
- try {
1765
- const existing = await dispatch(
1766
- read({ dbKey: contentKey, preferredServerOrigin: sourceServerOrigin })
1767
- ).unwrap();
1768
- hasIndividualRecord = Boolean(existing);
1769
- } catch {
1770
- hasIndividualRecord = false;
1771
- }
1772
- if (hasIndividualRecord) {
1773
- try {
1774
- await dispatch(
1775
- patch({
1776
- dbKey: contentKey,
1777
- changes,
1778
- preferredServerOrigin: sourceServerOrigin
1779
- })
1780
- ).unwrap();
1781
- notifyUserDataUpdated();
1782
- } catch (contentPatchError) {
1783
- throw new Error(
1784
- `${failMessagePrefix}: ${contentPatchError?.message || "\u672A\u77E5\u9519\u8BEF"}`
1785
- );
1786
- }
1787
- }
1788
- };
1789
-
1790
- // packages/create/space/content/updateContentTitleAction.ts
1791
- var buildContentRecordTitleChanges = (content, title, updatedAt) => {
1792
- const changes = { title, updatedAt };
1793
- if (content.type === "app") {
1794
- changes.name = title;
1795
- }
1796
- return changes;
1797
- };
1798
- var updateContentTitleAction = async (input, thunkAPI) => {
1799
- const { spaceId, contentKey, title, skillSummary, sourceServerOrigin } = input;
1800
- const { dispatch } = thunkAPI;
1801
- if (title === void 0 || title === null || typeof title !== "string") {
1802
- throw new Error("Invalid title provided.");
1803
- }
1804
- if (title.trim() === "") {
1805
- throw new Error("Title cannot be empty.");
1806
- }
1807
- const { spaceKey, spaceData, content } = await loadSpaceContentOrThrow(
1808
- dispatch,
1809
- spaceId,
1810
- contentKey,
1811
- sourceServerOrigin
1812
- );
1813
- const trimmedTitle = title.trim();
1814
- const now = (/* @__PURE__ */ new Date()).toISOString();
1815
- const changes = {
1816
- contents: {
1817
- [contentKey]: {
1818
- ...spaceData.contents[contentKey],
1819
- title: trimmedTitle,
1820
- updatedAt: now,
1821
- ...skillSummary !== void 0 ? { skillSummary } : {}
1822
- }
1823
- },
1824
- updatedAt: now
1825
- };
1826
- let updatedSpaceData;
1827
- try {
1828
- updatedSpaceData = await dispatch(
1829
- patch({
1830
- dbKey: spaceKey,
1831
- changes,
1832
- preferredServerOrigin: sourceServerOrigin
1833
- })
1834
- ).unwrap();
1835
- } catch (patchError) {
1836
- throw new Error(`\u66F4\u65B0\u5185\u5BB9\u6807\u9898\u5931\u8D25: ${patchError.message || "\u672A\u77E5\u9519\u8BEF"}`);
1837
- }
1838
- await patchIndividualContentRecord(
1839
- dispatch,
1840
- contentKey,
1841
- buildContentRecordTitleChanges(content, trimmedTitle, now),
1842
- sourceServerOrigin,
1843
- "\u6807\u9898\u5DF2\u5199\u5165\u7A7A\u95F4\uFF0C\u4F46\u540C\u6B65\u72EC\u7ACB\u8BB0\u5F55\u5931\u8D25"
1844
- );
1845
- if (contentKey.startsWith("meta-")) {
1846
- const parts = contentKey.split(SEPARATOR);
1847
- if (parts.length >= 3) {
1848
- const tableId = parts.slice(2).join(SEPARATOR);
1849
- const tenantId = parts[1];
1850
- try {
1851
- await dispatch(
1852
- renameTable({
1853
- tenantId,
1854
- tableId,
1855
- newName: trimmedTitle
1856
- })
1857
- ).unwrap();
1858
- } catch (tableError) {
1859
- console.error("Failed to sync title to TableMeta:", tableError);
1860
- }
1861
- }
1862
- }
1863
- return { spaceId, updatedSpaceData };
1864
- };
1865
-
1866
- // packages/create/space/content/updateContentPinnedAction.ts
1867
- var updateContentPinnedAction = async (input, thunkAPI) => {
1868
- const { spaceId, contentKey, pinned, sourceServerOrigin } = input;
1869
- const { dispatch } = thunkAPI;
1870
- if (typeof pinned !== "boolean") {
1871
- throw new Error("Invalid pinned value provided.");
1872
- }
1873
- if (!spaceId) {
1874
- if (!contentKey || typeof contentKey !== "string" || contentKey.trim() === "") {
1875
- throw new Error("Invalid contentKey provided.");
1876
- }
1877
- await patchIndividualContentRecord(
1878
- dispatch,
1879
- contentKey,
1880
- { pinned },
1881
- sourceServerOrigin,
1882
- "\u66F4\u65B0\u7F6E\u9876\u72B6\u6001\u5931\u8D25"
1883
- );
1884
- return { spaceId: null, updatedSpaceData: null };
1885
- }
1886
- const { spaceKey, spaceData } = await loadSpaceContentOrThrow(
1887
- dispatch,
1888
- spaceId,
1889
- contentKey,
1890
- sourceServerOrigin
1891
- );
1892
- const changes = {
1893
- contents: {
1894
- [contentKey]: { ...spaceData.contents[contentKey], pinned }
1895
- },
1896
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1897
- };
1898
- let updatedSpaceData;
1899
- try {
1900
- updatedSpaceData = await dispatch(
1901
- patch({ dbKey: spaceKey, changes, preferredServerOrigin: sourceServerOrigin })
1902
- ).unwrap();
1903
- } catch (patchError) {
1904
- throw new Error(`\u66F4\u65B0\u5185\u5BB9\u7F6E\u9876\u72B6\u6001\u5931\u8D25: ${patchError.message || "\u672A\u77E5\u9519\u8BEF"}`);
1905
- }
1906
- await patchIndividualContentRecord(
1907
- dispatch,
1908
- contentKey,
1909
- { pinned },
1910
- sourceServerOrigin,
1911
- "\u7F6E\u9876\u72B6\u6001\u5DF2\u5199\u5165\u7A7A\u95F4\uFF0C\u4F46\u540C\u6B65\u72EC\u7ACB\u8BB0\u5F55\u5931\u8D25"
1912
- );
1913
- return { spaceId, updatedSpaceData };
1914
- };
1915
-
1916
- // packages/create/space/content/updateContentCategoryAction.ts
1917
- var updateContentCategoryAction = async (input, thunkAPI) => {
1918
- const { spaceId, contentKey, categoryId: targetContainerId } = input;
1919
- const { dispatch, getState } = thunkAPI;
1920
- const state3 = getState();
1921
- const userId = selectIdentityUserId(state3);
1922
- if (!userId) {
1923
- throw new Error("User is not logged in.");
1924
- }
1925
- if (!contentKey || typeof contentKey !== "string" || contentKey.trim() === "") {
1926
- throw new Error("Invalid contentKey provided.");
1927
- }
1928
- if (typeof targetContainerId !== "string") {
1929
- throw new Error("Invalid target container ID provided (must be a string).");
1930
- }
1931
- const spaceKey = createSpaceKey.space(spaceId);
1932
- let spaceData = null;
1933
- try {
1934
- spaceData = await dispatch(read({
1935
- dbKey: spaceKey
1936
- })).unwrap();
1937
- } catch (readError) {
1938
- console.error(
1939
- `[updateContentCategoryAction] Failed to read space data for key ${spaceKey}:`,
1940
- readError
1941
- );
1942
- throw new Error(
1943
- `\u65E0\u6CD5\u52A0\u8F7D\u7A7A\u95F4\u6570\u636E: ${spaceId}, \u539F\u56E0: ${readError.message || "\u672A\u77E5\u9519\u8BEF"}`
1944
- );
1945
- }
1946
- if (!spaceData) {
1947
- throw new Error(`\u7A7A\u95F4\u4E0D\u5B58\u5728: ${spaceId}`);
1948
- }
1949
- try {
1950
- checkSpaceMembership(spaceData, userId);
1951
- } catch (permissionError) {
1952
- throw new Error(`\u6743\u9650\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u4FEE\u6539\u5185\u5BB9\u5206\u7C7B: ${permissionError.message}`);
1953
- }
1954
- const currentContent = spaceData.contents?.[contentKey];
1955
- if (!currentContent) {
1956
- console.warn(
1957
- `[updateContentCategoryAction] Content ${contentKey} not found in space ${spaceId}.`
1958
- );
1959
- throw new Error("Content not found");
1960
- }
1961
- if (targetContainerId !== UNCATEGORIZED_ID) {
1962
- if (!spaceData.categories[targetContainerId]) {
1963
- console.warn(
1964
- `[updateContentCategoryAction] Target category ${targetContainerId} not found or invalid in space ${spaceId}. Cannot move content.`
1965
- );
1966
- throw new Error("Target category not found or is invalid");
1967
- }
1968
- }
1969
- const now = Date.now();
1970
- const categoryIdValueForPatch = targetContainerId === UNCATEGORIZED_ID ? null : targetContainerId;
1971
- const currentCategoryId = currentContent.categoryId;
1972
- let needsUpdate = true;
1973
- if (categoryIdValueForPatch === null && currentCategoryId === void 0) {
1974
- needsUpdate = false;
1975
- } else if (categoryIdValueForPatch === currentCategoryId) {
1976
- needsUpdate = false;
1977
- }
1978
- let changes = null;
1979
- if (needsUpdate) {
1980
- changes = {
1981
- contents: {
1982
- // 使用动态键更新指定的 contentKey
1983
- [contentKey]: {
1984
- // --- 修改: 使用计算出的 categoryIdValueForPatch ---
1985
- categoryId: categoryIdValueForPatch,
1986
- // null 或 目标分类 ID
1987
- updatedAt: now
1988
- // 更新内容的 updatedAt
1989
- }
1990
- },
1991
- updatedAt: now
1992
- // 更新顶层的 updatedAt
1993
- };
1994
- } else {
1995
- console.log(
1996
- `[updateContentCategoryAction] No category change needed for ${contentKey}. Skipping patch.`
1997
- );
1998
- return { spaceId, updatedSpaceData: spaceData };
1999
- }
2000
- let updatedSpaceData;
2001
- try {
2002
- updatedSpaceData = await dispatch(
2003
- patch({ dbKey: spaceKey, changes })
2004
- // 使用非空断言,因为已检查
2005
- ).unwrap();
2006
- } catch (patchError) {
2007
- console.error(
2008
- `[updateContentCategoryAction] Failed to patch space data for key ${spaceKey}:`,
2009
- patchError
2010
- );
2011
- throw new Error(`\u66F4\u65B0\u5185\u5BB9\u5206\u7C7B\u5931\u8D25: ${patchError.message || "\u672A\u77E5\u9519\u8BEF"}`);
2012
- }
2013
- return { spaceId, updatedSpaceData };
2014
- };
2015
-
2016
- // packages/create/space/content/deleteMultipleContentAction.ts
2017
- var logger2 = createClientLogger("delete-multiple-content");
2018
- var deleteMultipleContentAction = async (input, thunkAPI) => {
2019
- const { contentKeys, spaceId } = input;
2020
- if (!contentKeys || contentKeys.length === 0) {
2021
- logger2.warn("deleteMultipleContentAction called with no contentKeys.");
2022
- return { spaceId, updatedSpaceData: null };
2023
- }
2024
- const { dispatch, getState } = thunkAPI;
2025
- const state3 = getState();
2026
- const userId = selectIdentityUserId(state3);
2027
- logger2.info(
2028
- { count: contentKeys.length, spaceId, userId },
2029
- "Initiating deleteMultipleContentAction"
2030
- );
2031
- const spaceKey = createSpaceKey.space(spaceId);
2032
- const spaceData = await dispatch(
2033
- read({
2034
- dbKey: spaceKey
2035
- })
2036
- ).unwrap();
2037
- if (!spaceData) {
2038
- logger2.error({ spaceKey }, "Space data not found for batch delete");
2039
- throw new Error("\u7A7A\u95F4\u4E0D\u5B58\u5728");
2040
- }
2041
- if (!userId || !spaceData.members.includes(userId)) {
2042
- logger2.warn({ userId, spaceId }, "Unauthorized attempt for batch delete");
2043
- throw new Error("\u65E0\u6743\u4FEE\u6539\u6B64\u7A7A\u95F4");
2044
- }
2045
- const changes = {
2046
- contents: contentKeys.reduce(
2047
- (acc, key) => {
2048
- acc[key] = null;
2049
- return acc;
2050
- },
2051
- {}
2052
- )
2053
- };
2054
- try {
2055
- await dispatch(patch({ dbKey: spaceKey, changes })).unwrap();
2056
- logger2.info(
2057
- { spaceKey, count: contentKeys.length },
2058
- "Successfully batched patch to remove content references"
2059
- );
2060
- } catch (patchError) {
2061
- logger2.error(
2062
- { error: patchError, spaceKey },
2063
- "Failed to batch patch space data. Aborting."
2064
- );
2065
- throw new Error(`\u66F4\u65B0\u7A7A\u95F4\u5F15\u7528\u5931\u8D25: ${patchError.message}`);
2066
- }
2067
- const removePromises = contentKeys.map(
2068
- (key) => dispatch(remove(key)).unwrap()
2069
- );
2070
- const results = await Promise.allSettled(removePromises);
2071
- results.forEach((result, index) => {
2072
- if (result.status === "fulfilled") {
2073
- logger2.info({ contentKey: contentKeys[index] }, "Entity removed");
2074
- } else {
2075
- logger2.error(
2076
- { contentKey: contentKeys[index], error: result.reason },
2077
- "Failed to remove an entity"
2078
- );
2079
- }
2080
- });
2081
- const finalSpaceData = await dispatch(
2082
- read({
2083
- dbKey: spaceKey
2084
- })
2085
- ).unwrap();
2086
- logger2.info({ spaceId }, "Finished batch delete and refetched space data.");
2087
- return {
2088
- spaceId,
2089
- updatedSpaceData: finalSpaceData
2090
- };
2091
- };
2092
-
2093
- // packages/create/space/content/uploadAndAddFileToSpaceAction.ts
2094
- var uploadAndAddFileToSpaceAction = async (payload, thunkAPI) => {
2095
- const { spaceId, file, categoryId } = payload;
2096
- const { dispatch, getState } = thunkAPI;
2097
- const state3 = getState();
2098
- const userId = selectIdentityUserId(state3);
2099
- if (!userId) {
2100
- console.warn("[uploadAndAddFileToSpace] Warning: No userId found in state. Uploading as anonymous/unknown might cause issues.");
2101
- }
2102
- try {
2103
- const id = ulid();
2104
- const dbKey = fileKey.single(userId || "unknown", id);
2105
- const contentType = "file" /* FILE */;
2106
- const fileCategory = resolveFileCategory({
2107
- mimeType: file.type,
2108
- fileName: file.name
2109
- });
2110
- const fileMetadata = await uploadFileAction(
2111
- { file, customKey: dbKey, userId },
2112
- thunkAPI
2113
- );
2114
- if (!fileMetadata) {
2115
- throw new Error("Upload failed, no metadata returned");
2116
- }
2117
- const contentKey = fileMetadata.dbKey || dbKey;
2118
- const title = file.name;
2119
- const result = await addContentAction({
2120
- spaceId,
2121
- contentKey,
2122
- title,
2123
- type: contentType,
2124
- fileCategory,
2125
- mimeType: file.type || void 0,
2126
- fileSize: asOptionalFiniteNumber(file.size),
2127
- originalName: file.name,
2128
- categoryId
2129
- }, thunkAPI);
2130
- await dispatch(
2131
- patch({
2132
- dbKey: contentKey,
2133
- changes: {
2134
- title,
2135
- spaceId,
2136
- fileCategory,
2137
- mimeType: file.type || void 0,
2138
- fileSize: asOptionalFiniteNumber(file.size),
2139
- originalName: file.name
2140
- }
2141
- })
2142
- ).unwrap();
2143
- if (typeof window !== "undefined") {
2144
- window.dispatchEvent(new Event("nolo-user-data-updated"));
2145
- }
2146
- return { ...result, contentKey, fileId: fileMetadata.id };
2147
- } catch (error) {
2148
- console.error("Upload and add file error:", error);
2149
- throw error;
2150
- }
2151
- };
2152
-
2153
- // packages/create/space/spaceCollapsedState.ts
2154
- var SPACE_COLLAPSE_STORAGE_PREFIX = "space-collapsed-categories:";
2155
- var normalizeCollapsedCategories = (value) => {
2156
- const entries = Object.entries(asRecordOrEmpty(value)).filter(
2157
- ([key, collapsed]) => typeof key === "string" && typeof collapsed === "boolean"
2158
- );
2159
- return Object.fromEntries(entries);
2160
- };
2161
- var storageKeyForSpace = (spaceId) => `${SPACE_COLLAPSE_STORAGE_PREFIX}${spaceId}`;
2162
- var readStoredCollapsedCategories = (spaceId, storage) => {
2163
- if (!spaceId || !storage) return {};
2164
- try {
2165
- const raw = storage.getItem(storageKeyForSpace(spaceId));
2166
- if (!raw) return { [UNCATEGORIZED_ID]: false };
2167
- return normalizeCollapsedCategories(JSON.parse(raw));
2168
- } catch (error) {
2169
- console.warn("[Space] \u8BFB\u53D6\u5206\u7C7B\u6298\u53E0\u72B6\u6001\u5931\u8D25:", error);
2170
- return {};
2171
- }
2172
- };
2173
- var writeStoredCollapsedCategories = (spaceId, collapsedCategories, storage) => {
2174
- if (!spaceId || !storage) return;
2175
- try {
2176
- storage.setItem(
2177
- storageKeyForSpace(spaceId),
2178
- JSON.stringify(normalizeCollapsedCategories(collapsedCategories))
2179
- );
2180
- } catch (error) {
2181
- console.warn("[Space] \u4FDD\u5B58\u5206\u7C7B\u6298\u53E0\u72B6\u6001\u5931\u8D25:", error);
2182
- }
2183
- };
2184
-
2185
- // packages/create/space/spaceUiStore.ts
2186
- var import_react2 = __toESM(require_react(), 1);
2187
- var DEFAULT_COLLAPSED_CATEGORIES = {
2188
- [UNCATEGORIZED_ID]: false
2189
- };
2190
- var FAVORITES_COLLAPSED_STORAGE_KEY = "nolo-sidebar-favorites-collapsed";
2191
- var readStoredFavoritesCollapsed = () => {
2192
- try {
2193
- if (typeof window === "undefined") return false;
2194
- return window.localStorage.getItem(FAVORITES_COLLAPSED_STORAGE_KEY) === "1";
2195
- } catch {
2196
- return false;
2197
- }
2198
- };
2199
- var createInitialState2 = () => ({
2200
- favoritesCollapsed: readStoredFavoritesCollapsed(),
2201
- collapsedCategories: {},
2202
- collapsedCategoriesSpaceId: null
2203
- });
2204
- var state2 = createInitialState2();
2205
- var listeners2 = /* @__PURE__ */ new Set();
2206
- var version2 = 0;
2207
- var notify2 = () => {
2208
- version2 += 1;
2209
- for (const listener of listeners2) {
2210
- try {
2211
- listener();
2212
- } catch {
2213
- }
2214
- }
2215
- };
2216
- function getCollapsedCategories() {
2217
- return state2.collapsedCategories;
2218
- }
2219
- function setCollapsedCategories(categories, spaceId) {
2220
- state2 = {
2221
- ...state2,
2222
- collapsedCategories: categories,
2223
- collapsedCategoriesSpaceId: spaceId
2224
- };
2225
- notify2();
2226
- }
2227
- function toggleCategoryCollapse(categoryId) {
2228
- const current = state2.collapsedCategories[categoryId] ?? (DEFAULT_COLLAPSED_CATEGORIES[categoryId] ?? true);
2229
- state2 = {
2230
- ...state2,
2231
- collapsedCategories: {
2232
- ...state2.collapsedCategories,
2233
- [categoryId]: !current
2234
- }
2235
- };
2236
- notify2();
2237
- }
2238
- function expandCategoryInCollapsed(categoryId, spaceId) {
2239
- if (!categoryId || categoryId === UNCATEGORIZED_ID) return;
2240
- state2 = {
2241
- ...state2,
2242
- collapsedCategories: {
2243
- ...state2.collapsedCategories,
2244
- [categoryId]: false
2245
- }
2246
- };
2247
- if (typeof window !== "undefined") {
2248
- writeStoredCollapsedCategories(
2249
- spaceId,
2250
- state2.collapsedCategories,
2251
- window.localStorage
2252
- );
2253
- }
2254
- notify2();
2255
- }
2256
-
2257
- // packages/create/space/content/contentThunks.ts
2258
- var syncCurrentSpaceIfNormalizedMatch = (spaceId, updatedSpaceData) => {
2259
- const normalizedSpaceId = normalizeSpaceId(spaceId);
2260
- const rawSpaceId = getCurrentSpaceIdRaw();
2261
- const normalizedCurrentSpaceId = rawSpaceId ? normalizeSpaceId(rawSpaceId) : null;
2262
- if (normalizedCurrentSpaceId === normalizedSpaceId && updatedSpaceData) {
2263
- updateCurrentSpaceIfMatch(spaceId, updatedSpaceData);
2264
- }
2265
- };
2266
- var addContentToSpace = createAsyncThunk(
2267
- "space/addContentToSpace",
2268
- async (input, thunkAPI) => {
2269
- const result = await addContentAction(input, thunkAPI);
2270
- const rawCategoryId = asTrimmedString(input.categoryId);
2271
- const expandCategoryId = rawCategoryId && rawCategoryId !== UNCATEGORIZED_ID ? rawCategoryId : null;
2272
- if (expandCategoryId) {
2273
- const collapsedCategories = {
2274
- ...getCollapsedCategories(),
2275
- [expandCategoryId]: false
2276
- };
2277
- if (typeof window !== "undefined") {
2278
- writeStoredCollapsedCategories(
2279
- result.spaceId,
2280
- collapsedCategories,
2281
- window.localStorage
2282
- );
2283
- }
2284
- expandCategoryInCollapsed(expandCategoryId, result.spaceId);
2285
- syncCurrentSpaceIfNormalizedMatch(
2286
- result.spaceId,
2287
- result.updatedSpaceData
2288
- );
2289
- return { ...result, expandCategoryId, collapsedCategories };
2290
- }
2291
- syncCurrentSpaceIfNormalizedMatch(result.spaceId, result.updatedSpaceData);
2292
- return { ...result, expandCategoryId: null };
2293
- }
2294
- );
2295
- var moveContentToSpace = createAsyncThunk(
2296
- "space/moveContentToSpace",
2297
- async (arg, thunkAPI) => {
2298
- const payload = await moveContentAction(arg, thunkAPI);
2299
- const {
2300
- sourceSpaceId,
2301
- updatedSourceSpaceData,
2302
- targetSpaceId,
2303
- updatedTargetSpaceData
2304
- } = payload;
2305
- if (getCurrentSpaceIdRaw() === sourceSpaceId && updatedSourceSpaceData) {
2306
- updateCurrentSpaceIfMatch(sourceSpaceId, updatedSourceSpaceData);
2307
- }
2308
- if (getCurrentSpaceIdRaw() === targetSpaceId && updatedTargetSpaceData) {
2309
- updateCurrentSpaceIfMatch(targetSpaceId, updatedTargetSpaceData);
2310
- }
2311
- return payload;
2312
- }
2313
- );
2314
- var deleteContentFromSpace = createAsyncThunk(
2315
- "space/deleteContentFromSpace",
2316
- async (arg, thunkAPI) => {
2317
- const payload = await deleteContentFromSpaceAction(arg, thunkAPI);
2318
- syncCurrentSpaceIfNormalizedMatch(
2319
- payload.spaceId,
2320
- payload.updatedSpaceData
2321
- );
2322
- return payload;
2323
- }
2324
- );
2325
- var deleteMultipleContent = createAsyncThunk(
2326
- "space/deleteMultipleContent",
2327
- async (arg, thunkAPI) => {
2328
- const payload = await deleteMultipleContentAction(arg, thunkAPI);
2329
- syncCurrentSpaceIfNormalizedMatch(
2330
- payload.spaceId,
2331
- payload.updatedSpaceData
2332
- );
2333
- return payload;
2334
- }
2335
- );
2336
- var uploadAndAddFileToSpace = createAsyncThunk(
2337
- "space/uploadAndAddFileToSpace",
2338
- async (arg, thunkAPI) => {
2339
- const payload = await uploadAndAddFileToSpaceAction(arg, thunkAPI);
2340
- if (getCurrentSpaceIdRaw() === payload.spaceId) {
2341
- updateCurrentSpaceIfMatch(payload.spaceId, payload.updatedSpaceData);
2342
- }
2343
- return payload;
2344
- }
2345
- );
2346
- var updateContentTitle = createAsyncThunk(
2347
- "space/updateContentTitle",
2348
- async (arg, thunkAPI) => {
2349
- try {
2350
- const payload = await updateContentTitleAction(arg, thunkAPI);
2351
- if (getCurrentSpaceIdRaw() === payload.spaceId) {
2352
- updateCurrentSpaceIfMatch(payload.spaceId, payload.updatedSpaceData);
2353
- }
2354
- return payload;
2355
- } catch (error) {
2356
- const message = error?.message || "\u6807\u9898\u4FDD\u5B58\u5931\u8D25";
2357
- if (!message.includes("\u65E0\u6CD5\u52A0\u8F7D\u7A7A\u95F4\u6570\u636E")) {
2358
- toast.error(message);
2359
- }
2360
- throw error;
2361
- }
2362
- }
2363
- );
2364
- var updateContentPinned = createAsyncThunk(
2365
- "space/updateContentPinned",
2366
- async (arg, thunkAPI) => {
2367
- try {
2368
- const payload = await updateContentPinnedAction(arg, thunkAPI);
2369
- if (payload.updatedSpaceData && payload.spaceId && getCurrentSpaceIdRaw() === payload.spaceId) {
2370
- updateCurrentSpaceIfMatch(payload.spaceId, payload.updatedSpaceData);
2371
- }
2372
- return payload;
2373
- } catch (error) {
2374
- toast.error(
2375
- error?.message || "\u7F6E\u9876\u72B6\u6001\u66F4\u65B0\u5931\u8D25"
2376
- );
2377
- throw error;
2378
- }
2379
- }
2380
- );
2381
- var updateContentCategory = createAsyncThunk(
2382
- "space/updateContentCategory",
2383
- async (arg, thunkAPI) => {
2384
- const payload = await updateContentCategoryAction(arg, thunkAPI);
2385
- if (getCurrentSpaceIdRaw() === payload.spaceId) {
2386
- updateCurrentSpaceIfMatch(payload.spaceId, payload.updatedSpaceData);
2387
- }
2388
- return payload;
2389
- }
2390
- );
2391
-
2392
- export {
2393
- fetchAndCacheTableRows,
2394
- client_default,
2395
- getTableState,
2396
- loadTableRows,
2397
- addRow,
2398
- createTable,
2399
- deleteTable,
2400
- readStoredCollapsedCategories,
2401
- writeStoredCollapsedCategories,
2402
- DEFAULT_COLLAPSED_CATEGORIES,
2403
- getCollapsedCategories,
2404
- setCollapsedCategories,
2405
- toggleCategoryCollapse,
2406
- expandCategoryInCollapsed,
2407
- addContentToSpace,
2408
- moveContentToSpace,
2409
- deleteContentFromSpace,
2410
- deleteMultipleContent,
2411
- uploadAndAddFileToSpace,
2412
- updateContentTitle,
2413
- updateContentPinned,
2414
- updateContentCategory
2415
- };