@heycys/gallery 0.1.1 → 0.1.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 (370) hide show
  1. package/THIRD-PARTY-NOTICES.md +1 -1
  2. package/browser/editor/components/columns/page.mjs +4 -4
  3. package/browser/editor/components/embed/index.mjs +2 -2
  4. package/browser/editor/components/flowchart/add.mjs +7 -6
  5. package/browser/editor/components/flowchart/page.mjs +1 -1
  6. package/browser/editor/components/icons.mjs +8 -0
  7. package/browser/editor/components/image/crop.mjs +6 -9
  8. package/browser/editor/components/installed/index.mjs +11 -4
  9. package/browser/editor/components/installed/page.mjs +27 -16
  10. package/browser/editor/components/installed/served.mjs +6 -5
  11. package/browser/editor/components/instances.mjs +18 -0
  12. package/browser/editor/components/list/page.mjs +3 -6
  13. package/browser/editor/components/registry.mjs +13 -4
  14. package/browser/editor/components/table/index.mjs +59 -2
  15. package/browser/editor/components/table/page.mjs +1 -1
  16. package/browser/editor/page/annotate/card.mjs +3 -6
  17. package/browser/editor/page/autosave.mjs +310 -37
  18. package/browser/editor/page/board/client.mjs +57 -0
  19. package/browser/editor/page/board/hint.mjs +145 -0
  20. package/browser/editor/page/board/history.mjs +119 -0
  21. package/browser/editor/page/board/index.mjs +970 -0
  22. package/browser/editor/page/board/settings.mjs +209 -0
  23. package/browser/editor/page/caret.mjs +1 -1
  24. package/browser/editor/page/changes/bar.mjs +6 -14
  25. package/browser/editor/page/changes/index.mjs +2 -2
  26. package/browser/editor/page/clipboard/import/html.mjs +29 -6
  27. package/browser/editor/page/clipboard/import/inline.mjs +32 -0
  28. package/browser/editor/page/clipboard/import/markdown.mjs +58 -13
  29. package/browser/editor/page/clipboard/import/read.mjs +6 -1
  30. package/browser/editor/page/clipboard/import/to-blocks.mjs +44 -12
  31. package/browser/editor/page/clipboard/import/yuque.mjs +622 -0
  32. package/browser/editor/page/clipboard/index.mjs +124 -13
  33. package/browser/editor/page/clipboard/own/blocks.mjs +11 -11
  34. package/browser/editor/page/clipboard/own/chart-keys.mjs +41 -28
  35. package/browser/editor/page/clipboard/own/selection.mjs +1 -1
  36. package/browser/editor/page/columns/index.mjs +48 -46
  37. package/browser/editor/page/commit.mjs +80 -22
  38. package/browser/editor/page/conflicts.mjs +7 -7
  39. package/browser/editor/page/core.mjs +31 -15
  40. package/browser/editor/page/custom-page.mjs +106 -0
  41. package/browser/editor/page/editor.mjs +51 -14
  42. package/browser/editor/page/emoji-picker/styles.mjs +7 -12
  43. package/browser/editor/page/emoji-picker/upload.mjs +2 -2
  44. package/browser/editor/page/handle/index.mjs +5 -8
  45. package/browser/editor/page/history.mjs +24 -4
  46. package/browser/editor/page/links/index.mjs +5 -3
  47. package/browser/editor/page/links/pages.mjs +27 -9
  48. package/browser/editor/page/look.mjs +54 -3
  49. package/browser/editor/page/margin.mjs +18 -3
  50. package/browser/editor/page/media-menu/index.mjs +6 -7
  51. package/browser/editor/page/menu.mjs +18 -7
  52. package/browser/editor/page/notices.mjs +2 -2
  53. package/browser/editor/page/page-objects.mjs +13 -2
  54. package/browser/editor/page/panel.mjs +4 -9
  55. package/browser/editor/page/present-links.mjs +11 -2
  56. package/browser/editor/page/resize/index.mjs +42 -29
  57. package/browser/editor/page/served.mjs +14 -0
  58. package/browser/editor/page/session.mjs +48 -4
  59. package/browser/editor/page/slash-menu/index.mjs +3 -3
  60. package/browser/editor/page/table/cells.mjs +102 -46
  61. package/browser/editor/page/table/icons.mjs +2 -0
  62. package/browser/editor/page/table/index.mjs +29 -10
  63. package/browser/editor/page/table/pictures.mjs +299 -0
  64. package/browser/editor/page/table/views.mjs +150 -0
  65. package/browser/editor/page/text-select/index.mjs +26 -12
  66. package/browser/editor/page/todo-writes.mjs +75 -0
  67. package/browser/editor/page/typing/index.mjs +53 -3
  68. package/browser/editor/page/ui.mjs +13 -0
  69. package/browser/shared/block-packs.mjs +404 -0
  70. package/browser/shared/board-places.mjs +224 -0
  71. package/browser/shared/card-size.mjs +59 -0
  72. package/browser/shared/colors.mjs +3 -2
  73. package/browser/shared/component-catalog.mjs +323 -46
  74. package/browser/shared/component-source.mjs +37 -0
  75. package/browser/shared/components/index.mjs +12 -3
  76. package/browser/shared/components/installed.mjs +35 -3
  77. package/browser/shared/components/page.mjs +18 -8
  78. package/browser/shared/components/state.mjs +5 -1
  79. package/browser/shared/document-look.mjs +10 -5
  80. package/browser/shared/drafts.mjs +432 -0
  81. package/browser/shared/extension-sidebar.mjs +126 -0
  82. package/browser/shared/extensions.mjs +79 -0
  83. package/browser/shared/file-table.mjs +101 -0
  84. package/browser/shared/i18n/en.mjs +307 -27
  85. package/browser/shared/json-layout.mjs +47 -0
  86. package/browser/shared/net-cache.mjs +133 -0
  87. package/browser/shared/net-keys.mjs +32 -0
  88. package/browser/shared/net-policy.mjs +177 -0
  89. package/browser/shared/outline-shape.mjs +128 -0
  90. package/browser/shared/outline.mjs +331 -67
  91. package/browser/shared/pack-manifest.mjs +77 -0
  92. package/browser/shared/page-address.mjs +6 -3
  93. package/browser/shared/page-cards.mjs +308 -0
  94. package/browser/shared/page-links.mjs +69 -6
  95. package/browser/shared/pages.mjs +388 -0
  96. package/browser/shared/paths.mjs +6 -0
  97. package/browser/shared/preview-server.mjs +3 -7
  98. package/browser/shared/session.mjs +8 -1
  99. package/browser/shared/shipped-blocks.mjs +299 -0
  100. package/browser/shared/table-chart.mjs +33 -1
  101. package/browser/shared/todos.mjs +83 -0
  102. package/browser/shared/user-directory.mjs +24 -0
  103. package/browser/shared/versions.mjs +14 -0
  104. package/browser/shared/web-links.mjs +134 -0
  105. package/browser/shared/workspace-columns.mjs +120 -0
  106. package/browser/shared/workspace-name.mjs +154 -0
  107. package/browser/shared/workspace-query.mjs +125 -0
  108. package/browser/shared/workspace-registry.mjs +272 -0
  109. package/browser/shared/workspace.mjs +171 -20
  110. package/dist/chunk-2NRBY6AJ.mjs +2 -0
  111. package/dist/chunk-32ZUEFZ7.mjs +2 -0
  112. package/dist/chunk-35NQ4PLQ.mjs +2 -0
  113. package/dist/chunk-3KJHLHUO.mjs +2 -0
  114. package/dist/chunk-3NJACR4W.mjs +2 -0
  115. package/dist/chunk-4AV456RQ.mjs +2 -0
  116. package/dist/chunk-4OZWXZE5.mjs +5 -0
  117. package/dist/chunk-5XYHDBJ5.mjs +2 -0
  118. package/dist/chunk-5ZJA7CXT.mjs +2 -0
  119. package/dist/chunk-6A53MZYZ.mjs +2 -0
  120. package/dist/chunk-6EXH3ORZ.mjs +166 -0
  121. package/dist/chunk-6EZ7FNIK.mjs +3 -0
  122. package/dist/{chunk-V5JTW2LH.mjs → chunk-6QBHU4DF.mjs} +1 -1
  123. package/dist/{chunk-Y6RLRPG3.mjs → chunk-6VTU6KEO.mjs} +1 -1
  124. package/dist/chunk-B4P2CM2J.mjs +3 -0
  125. package/dist/{chunk-FDLXYYG4.mjs → chunk-BPL64HGA.mjs} +1 -1
  126. package/dist/chunk-BVEFGE4B.mjs +2 -0
  127. package/dist/{chunk-LS4F7JUM.mjs → chunk-BZ5RAF7L.mjs} +1 -1
  128. package/dist/chunk-CRJEG7MT.mjs +2 -0
  129. package/dist/{chunk-LCTHTZIL.mjs → chunk-D4CKRD3V.mjs} +91 -91
  130. package/dist/chunk-D4EURAX4.mjs +4 -0
  131. package/dist/chunk-DQCE7TJY.mjs +5 -0
  132. package/dist/chunk-DR73Y2UJ.mjs +3 -0
  133. package/dist/{chunk-TMYZB6AV.mjs → chunk-EKNHM3P4.mjs} +1 -1
  134. package/dist/{chunk-GB5SOYQJ.mjs → chunk-ERLAIBOA.mjs} +2 -2
  135. package/dist/chunk-EURLTOTZ.mjs +4 -0
  136. package/dist/chunk-FJYN7RTH.mjs +4 -0
  137. package/dist/chunk-FWNRPMCJ.mjs +12 -0
  138. package/dist/chunk-FWW4CSAZ.mjs +2 -0
  139. package/dist/{chunk-2B5E4CDJ.mjs → chunk-GPIWQ4X4.mjs} +1 -1
  140. package/dist/chunk-GY3FAUVM.mjs +2 -0
  141. package/dist/chunk-HLYV7RIH.mjs +2 -0
  142. package/dist/chunk-HMYTM3GT.mjs +15 -0
  143. package/dist/chunk-IA4PSIMD.mjs +2 -0
  144. package/dist/chunk-JEUK3ZO7.mjs +2 -0
  145. package/dist/chunk-KTKHRC6H.mjs +2 -0
  146. package/dist/chunk-L7UP52JO.mjs +2 -0
  147. package/dist/{chunk-SYGN7GLU.mjs → chunk-MHW7ZKOU.mjs} +1 -1
  148. package/dist/chunk-N76HWBA3.mjs +10 -0
  149. package/dist/chunk-N7AZZLGT.mjs +548 -0
  150. package/dist/chunk-NAMN3RAF.mjs +2 -0
  151. package/dist/{chunk-5ZKJ3H4P.mjs → chunk-NFMCP2HI.mjs} +3 -3
  152. package/dist/chunk-NG375ILQ.mjs +2 -0
  153. package/dist/chunk-NVRNLK25.mjs +6 -0
  154. package/dist/chunk-NWFBE2YA.mjs +2 -0
  155. package/dist/chunk-NWR2LT5B.mjs +2 -0
  156. package/dist/chunk-OJKMINIU.mjs +20 -0
  157. package/dist/{chunk-4FS7Z7WR.mjs → chunk-OUUP3WKT.mjs} +1 -1
  158. package/dist/{chunk-BGGDRNYQ.mjs → chunk-OW5NWPOJ.mjs} +1 -1
  159. package/dist/chunk-PAREWQGB.mjs +4 -0
  160. package/dist/chunk-POQSE4C2.mjs +2 -0
  161. package/dist/chunk-PUOQ65NC.mjs +2 -0
  162. package/dist/{chunk-XNROSH2T.mjs → chunk-PVER7LSC.mjs} +2 -2
  163. package/dist/chunk-PZDLJJTJ.mjs +3 -0
  164. package/dist/chunk-Q47PLKIJ.mjs +15 -0
  165. package/dist/chunk-Q4UEPUWF.mjs +2 -0
  166. package/dist/chunk-QKXMPUXC.mjs +2 -0
  167. package/dist/chunk-QOUEFUCH.mjs +16 -0
  168. package/dist/chunk-RFDZXFJF.mjs +13 -0
  169. package/dist/chunk-RKPWLGZ3.mjs +4 -0
  170. package/dist/chunk-RMECZA2K.mjs +2 -0
  171. package/dist/{chunk-7DTINW6U.mjs → chunk-SQ6Y2ZMA.mjs} +2 -2
  172. package/dist/chunk-SX4LJYT6.mjs +8 -0
  173. package/dist/chunk-SXHBYZST.mjs +16 -0
  174. package/dist/chunk-TANZRINB.mjs +2 -0
  175. package/dist/chunk-TEZAWDSQ.mjs +2 -0
  176. package/dist/chunk-UBBRTJ2R.mjs +24 -0
  177. package/dist/chunk-UFNYFFKO.mjs +20 -0
  178. package/dist/chunk-UGWYKHBL.mjs +170 -0
  179. package/dist/chunk-UKSHDZZ6.mjs +2 -0
  180. package/dist/chunk-UNOYVIYR.mjs +2 -0
  181. package/dist/{chunk-E7LWZRXY.mjs → chunk-V6RIYQZZ.mjs} +1 -1
  182. package/dist/chunk-VJPFVNNW.mjs +15 -0
  183. package/dist/chunk-VS3ZMVGX.mjs +5 -0
  184. package/dist/chunk-VTKNEYT3.mjs +6 -0
  185. package/dist/chunk-VXACTLO3.mjs +3 -0
  186. package/dist/chunk-YI43RG4P.mjs +2 -0
  187. package/dist/chunk-YQGT4AB2.mjs +6 -0
  188. package/dist/chunk-ZB4H7ZN4.mjs +2 -0
  189. package/dist/{chunk-IVDLMMBD.mjs → chunk-ZHEHPMBK.mjs} +1 -1
  190. package/dist/chunk-ZTHICSSF.mjs +2 -0
  191. package/dist/chunk-ZUNVAXLH.mjs +2 -0
  192. package/dist/chunk-ZWPMCK7P.mjs +2 -0
  193. package/dist/cli.mjs +1 -1
  194. package/dist/server.mjs +1 -1
  195. package/dist/{chunk-U6KNPJPR.mjs → update-fetch.mjs} +1 -1
  196. package/dist/worker.mjs +1 -1
  197. package/kit/board.css +95 -0
  198. package/kit/board.js +250 -0
  199. package/kit/charts.js +5 -71
  200. package/kit/code.js +14 -14
  201. package/kit/report.css +255 -17
  202. package/kit/runtime.js +1600 -125
  203. package/kit/state.js +10 -1
  204. package/kit/tables.js +128 -43
  205. package/kit/ui.js +77 -35
  206. package/package.json +2 -1
  207. package/packs/gallery/card/component.json +14 -0
  208. package/packs/gallery/card/example.html +10 -0
  209. package/packs/gallery/card/preview.svg +1 -0
  210. package/packs/gallery/card/style.css +6 -0
  211. package/packs/gallery/card/template.html +6 -0
  212. package/packs/gallery/card/writing.md +14 -0
  213. package/packs/gallery/chart-card/component.json +15 -0
  214. package/packs/gallery/chart-card/example.html +14 -0
  215. package/packs/gallery/chart-card/kit.js +130 -0
  216. package/packs/gallery/chart-card/preview.svg +1 -0
  217. package/packs/gallery/chart-card/style.css +42 -0
  218. package/packs/gallery/chart-card/template.html +13 -0
  219. package/packs/gallery/chart-card/writing.md +20 -0
  220. package/packs/gallery/chart-view/component.json +20 -0
  221. package/packs/gallery/chart-view/example.html +13 -0
  222. package/packs/gallery/chart-view/kit.js +355 -0
  223. package/packs/gallery/chart-view/preview.svg +1 -0
  224. package/packs/gallery/chart-view/style.css +94 -0
  225. package/packs/gallery/chart-view/template.html +3 -0
  226. package/packs/gallery/chart-view/writing.md +22 -0
  227. package/packs/gallery/countdown/component.json +18 -0
  228. package/packs/gallery/countdown/example.html +3 -0
  229. package/packs/gallery/countdown/kit.js +156 -0
  230. package/packs/gallery/countdown/preview.svg +1 -0
  231. package/packs/gallery/countdown/style.css +130 -0
  232. package/packs/gallery/countdown/template.html +3 -0
  233. package/packs/gallery/countdown/writing.md +22 -0
  234. package/packs/gallery/habit/component.json +14 -0
  235. package/packs/gallery/habit/example.html +3 -0
  236. package/packs/gallery/habit/kit.js +295 -0
  237. package/packs/gallery/habit/preview.svg +1 -0
  238. package/packs/gallery/habit/style.css +246 -0
  239. package/packs/gallery/habit/template.html +3 -0
  240. package/packs/gallery/habit/writing.md +21 -0
  241. package/packs/gallery/heatmap/component.json +18 -0
  242. package/packs/gallery/heatmap/example.html +3 -0
  243. package/packs/gallery/heatmap/kit.js +351 -0
  244. package/packs/gallery/heatmap/preview.svg +1 -0
  245. package/packs/gallery/heatmap/style.css +201 -0
  246. package/packs/gallery/heatmap/template.html +3 -0
  247. package/packs/gallery/heatmap/writing.md +21 -0
  248. package/packs/gallery/kanban/component.json +18 -0
  249. package/packs/gallery/kanban/example.html +12 -0
  250. package/packs/gallery/kanban/kit.js +540 -0
  251. package/packs/gallery/kanban/preview.svg +1 -0
  252. package/packs/gallery/kanban/style.css +212 -0
  253. package/packs/gallery/kanban/template.html +3 -0
  254. package/packs/gallery/kanban/writing.md +20 -0
  255. package/packs/gallery/metric/component.json +22 -0
  256. package/packs/gallery/metric/example.html +15 -0
  257. package/packs/gallery/metric/kit.js +248 -0
  258. package/packs/gallery/metric/preview.svg +1 -0
  259. package/packs/gallery/metric/style.css +92 -0
  260. package/packs/gallery/metric/template.html +3 -0
  261. package/packs/gallery/metric/writing.md +23 -0
  262. package/packs/gallery/note/component.json +14 -0
  263. package/packs/gallery/note/example.html +3 -0
  264. package/packs/gallery/note/kit.js +102 -0
  265. package/packs/gallery/note/preview.svg +1 -0
  266. package/packs/gallery/note/style.css +76 -0
  267. package/packs/gallery/note/template.html +3 -0
  268. package/packs/gallery/note/writing.md +18 -0
  269. package/packs/gallery/pack.json +8 -0
  270. package/packs/gallery/recent/component.json +13 -0
  271. package/packs/gallery/recent/example.html +1 -0
  272. package/packs/gallery/recent/kit.js +238 -0
  273. package/packs/gallery/recent/preview.svg +1 -0
  274. package/packs/gallery/recent/style.css +158 -0
  275. package/packs/gallery/recent/template.html +1 -0
  276. package/packs/gallery/recent/writing.md +15 -0
  277. package/packs/gallery/static/component.json +13 -0
  278. package/packs/gallery/static/example.html +11 -0
  279. package/packs/gallery/static/preview.svg +1 -0
  280. package/packs/gallery/static/style.css +138 -0
  281. package/packs/gallery/static/template.html +1 -0
  282. package/packs/gallery/static/writing.md +18 -0
  283. package/packs/gallery/stats/component.json +13 -0
  284. package/packs/gallery/stats/example.html +1 -0
  285. package/packs/gallery/stats/kit.js +166 -0
  286. package/packs/gallery/stats/preview.svg +1 -0
  287. package/packs/gallery/stats/style.css +151 -0
  288. package/packs/gallery/stats/template.html +1 -0
  289. package/packs/gallery/stats/writing.md +11 -0
  290. package/packs/gallery/today/component.json +12 -0
  291. package/packs/gallery/today/example.html +1 -0
  292. package/packs/gallery/today/kit.js +185 -0
  293. package/packs/gallery/today/preview.svg +1 -0
  294. package/packs/gallery/today/style.css +120 -0
  295. package/packs/gallery/today/template.html +1 -0
  296. package/packs/gallery/today/writing.md +14 -0
  297. package/packs/gallery/todos/component.json +19 -0
  298. package/packs/gallery/todos/example.html +3 -0
  299. package/packs/gallery/todos/kit.js +342 -0
  300. package/packs/gallery/todos/preview.svg +1 -0
  301. package/packs/gallery/todos/style.css +267 -0
  302. package/packs/gallery/todos/template.html +3 -0
  303. package/packs/gallery/todos/writing.md +30 -0
  304. package/packs/gallery/weather/component.json +19 -0
  305. package/packs/gallery/weather/example.html +3 -0
  306. package/packs/gallery/weather/kit.js +312 -0
  307. package/packs/gallery/weather/preview.svg +1 -0
  308. package/packs/gallery/weather/style.css +258 -0
  309. package/packs/gallery/weather/template.html +3 -0
  310. package/packs/gallery/weather/writing.md +26 -0
  311. package/packs/gallery-soft/pack.json +8 -0
  312. package/release.json +12 -10
  313. package/sdk/doc-kit.d.ts +396 -5
  314. package/sdk/doc-state.d.ts +2 -0
  315. package/skill/SKILL.md +56 -23
  316. package/skill/references/block-script.md +140 -0
  317. package/skill/references/building-blocks.md +257 -0
  318. package/skill/references/extensions.md +59 -0
  319. package/skill/references/pages-and-data.md +221 -0
  320. package/skill/references/writing-html.md +6 -4
  321. package/skill/sdk/doc-kit.d.ts +396 -5
  322. package/skill/sdk/doc-state.d.ts +2 -0
  323. package/web/assets/index-BK2e_07w.js +13 -0
  324. package/web/assets/index-CWFI83mF.css +1 -0
  325. package/web/index.html +2 -2
  326. package/dist/chunk-3HIRPVLU.mjs +0 -2
  327. package/dist/chunk-5MHMDLZD.mjs +0 -4
  328. package/dist/chunk-64K7IPLO.mjs +0 -255
  329. package/dist/chunk-6QXGZM36.mjs +0 -8
  330. package/dist/chunk-6RGJOMJP.mjs +0 -16
  331. package/dist/chunk-AJ73XJF3.mjs +0 -2
  332. package/dist/chunk-AUZGSZJH.mjs +0 -13
  333. package/dist/chunk-BFE45AKL.mjs +0 -2
  334. package/dist/chunk-BXO2ZY5P.mjs +0 -2
  335. package/dist/chunk-CEH4MRCC.mjs +0 -2
  336. package/dist/chunk-CY2FNNAB.mjs +0 -16
  337. package/dist/chunk-DFUDV4LX.mjs +0 -2
  338. package/dist/chunk-DKXG4XDG.mjs +0 -2
  339. package/dist/chunk-EZQ34M3F.mjs +0 -124
  340. package/dist/chunk-EZY3WC6Z.mjs +0 -15
  341. package/dist/chunk-FUKQNOQS.mjs +0 -9
  342. package/dist/chunk-JPOSLGOC.mjs +0 -6
  343. package/dist/chunk-L3QKH4OK.mjs +0 -26
  344. package/dist/chunk-LAE5NQ4B.mjs +0 -2
  345. package/dist/chunk-LEF6DRCK.mjs +0 -59
  346. package/dist/chunk-NO5NJCHO.mjs +0 -2
  347. package/dist/chunk-NQPVAU63.mjs +0 -2
  348. package/dist/chunk-NSKUTQ5J.mjs +0 -5
  349. package/dist/chunk-O35FIXRB.mjs +0 -2
  350. package/dist/chunk-P2CAZPDP.mjs +0 -3
  351. package/dist/chunk-PL6GHLGD.mjs +0 -15
  352. package/dist/chunk-QJIR2BLP.mjs +0 -6
  353. package/dist/chunk-QUPLVPB2.mjs +0 -7
  354. package/dist/chunk-R7BNENLY.mjs +0 -4
  355. package/dist/chunk-S6O4UHLC.mjs +0 -2
  356. package/dist/chunk-SGJWQKEI.mjs +0 -2
  357. package/dist/chunk-TX6JH7TR.mjs +0 -2
  358. package/dist/chunk-TYK6VNAB.mjs +0 -10
  359. package/dist/chunk-UALRNVSE.mjs +0 -4
  360. package/dist/chunk-V3HXVQEM.mjs +0 -2
  361. package/dist/chunk-V5VXUJKG.mjs +0 -2
  362. package/dist/chunk-VBXMADMP.mjs +0 -2
  363. package/dist/chunk-VNV55RUA.mjs +0 -2
  364. package/dist/chunk-VPD2PS35.mjs +0 -2
  365. package/dist/chunk-W4VKN3GF.mjs +0 -7
  366. package/dist/chunk-W5BXXPDJ.mjs +0 -3
  367. package/dist/chunk-XUNHRCOG.mjs +0 -6
  368. package/skill/references/building-components.md +0 -367
  369. package/web/assets/index-Bh74DfsV.css +0 -1
  370. package/web/assets/index-UW0RyFFt.js +0 -13
@@ -1,8 +1,8 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{spawn as J}from"node:child_process";import P from"node:fs";import m from"node:fs/promises";import Q from"node:os";import k from"node:path";import{escapeMarkup as X}from"../browser/shared/escape.mjs";import{spawn as C}from"node:child_process";import{existsSync as H,readFileSync as M}from"node:fs";import w from"node:path";var V=e=>!["","0",void 0].includes(e),z=(e,r)=>(r.PATH??"").split(w.delimiter).some(t=>t&&H(w.join(t,e))),U=()=>{try{return process.platform==="linux"&&/microsoft/i.test(M("/proc/version","utf8"))}catch{return!1}};function K(e,{platform:r=process.platform,env:t=process.env,wsl:s=U()}={}){let n=encodeURI(e);return V(t.GALLERY_NO_BROWSER)?{skip:"GALLERY_NO_BROWSER is set"}:r==="win32"?{command:w.join(t.SystemRoot||t.windir||"C:\\Windows","System32","rundll32.exe"),args:["url.dll,FileProtocolHandler",n]}:r==="darwin"?{command:"open",args:[n]}:s?{command:"cmd.exe",args:["/c","start",'""',n.replace(/[&^]/g,"^$&")]}:!t.DISPLAY&&!t.WAYLAND_DISPLAY?{skip:"no display here (neither DISPLAY nor WAYLAND_DISPLAY is set)"}:z("xdg-open",t)?{command:"xdg-open",args:[n]}:{skip:"xdg-open is not installed"}}var q="Opened it in the default browser (if that is not Chrome or Edge, open the address there to edit).",T=e=>e.opened?q:`Not opened in a browser: ${e.why}.`;async function O(e,r){let t=K(e,r);return t.skip?{opened:!1,why:t.skip}:new Promise(s=>{let n;try{n=C(t.command,t.args,{detached:!0,stdio:"ignore",windowsHide:!0})}catch(o){return s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})}n.once("error",o=>s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})),n.once("spawn",()=>{n.unref(),s({opened:!0})})})}import{packageRoot as Z,previewLogFile as f,projectRoot as G,release as I,reportsDirectory as h}from"../browser/shared/paths.mjs";import{fullAddress as ee}from"../browser/shared/page-address.mjs";import{findPreviewServer as te,galleryVersion as F,portIsFree as re,previewServerFor as ne,readAnnouncement as oe}from"../browser/shared/preview-server.mjs";import{documentLinks as se}from"../browser/shared/reports.mjs";import{documentDirectory as ie,documentFiles as ae,layoutOf as ce}from"../browser/shared/workspace.mjs";var $="\u4EA4\u7ED9\u7528\u6237\uFF08\u73B0\u5728\u5C31\u628A\u8FD9\u4E2A\u5730\u5740\u7ED9\u7528\u6237\uFF1B\u7528 Chrome \u6216 Edge \u6253\u5F00\uFF09\uFF1A",le="Agent \u81EA\u7528\uFF08\u53EA\u6709\u6587\u6863\u9875\uFF0C\u4E0D\u4EA4\u7ED9\u7528\u6237\uFF09\uFF1A",de=e=>`send the user ${e} now, in a message of its own, before any other step; then `;function Ve(e,r){let t=e.at(-1)??"";return`Next: ${t.startsWith($)?de(t.slice($.length)):""}${r}`}async function ze(e,r){let t=e.at(-1)??"";return t.startsWith($)?r.has("--no-browser")?"Not opened in a browser (--no-browser).":T(await O(t.slice($.length))):null}var D="GALLERY_NO_PREVIEW",pe=e=>!["","0",void 0].includes(e),Ue=e=>e.has("--no-preview")||pe(process.env[D]),ue=4317,fe=20,me=(e=process.env)=>{let r=Number(e.GALLERY_PORT);return Number.isInteger(r)&&r>0&&r<65536?r:ue},we=6e4,he=5*1024*1024,$e=k.join(G,"node_modules","vite","bin","vite.js"),ye=k.join(Z,"dist","server.mjs"),ge=e=>new Promise(r=>setTimeout(r,e)),A={reportsDirectory:h},Y=ce(h),R=(e,r)=>`http://127.0.0.1:${e}/generated/${r}.html`,ve=(e,r)=>`${R(e,r)}?agent`,j=e=>`http://127.0.0.1:${e}/`,xe=(e,r)=>se().then(({links:t})=>t,()=>null).then(t=>ee(`http://127.0.0.1:${e}`,r,t));async function ke({first:e=me(),count:r=fe}={}){let t=Number((await m.readFile(Y.lastPortFile,"utf8").catch(()=>"")).trim()),s=Array.from({length:Math.max(0,r)},(n,o)=>e+o);return Number.isInteger(t)&&t>0&&t<65536?[t,...s.filter(n=>n!==t)]:s}async function Le(){return await m.mkdir(k.dirname(f),{recursive:!0}),await m.stat(f).then(r=>r.size,()=>0)>he&&await m.rename(f,`${f}.1`).catch(()=>{}),P.openSync(f,"a")}async function Se(e,r){if(!I){let{writeSharedAssets:p}=await import("./chunk-VNV55RUA.mjs");await p()}let t=await Le();P.writeSync(t,`
2
+ import{spawn as J}from"node:child_process";import P from"node:fs";import m from"node:fs/promises";import Q from"node:os";import k from"node:path";import{escapeMarkup as X}from"../browser/shared/escape.mjs";import{spawn as C}from"node:child_process";import{existsSync as H,readFileSync as M}from"node:fs";import w from"node:path";var V=e=>!["","0",void 0].includes(e),z=(e,r)=>(r.PATH??"").split(w.delimiter).some(t=>t&&H(w.join(t,e))),U=()=>{try{return process.platform==="linux"&&/microsoft/i.test(M("/proc/version","utf8"))}catch{return!1}};function K(e,{platform:r=process.platform,env:t=process.env,wsl:s=U()}={}){let n=encodeURI(e);return V(t.GALLERY_NO_BROWSER)?{skip:"GALLERY_NO_BROWSER is set"}:r==="win32"?{command:w.join(t.SystemRoot||t.windir||"C:\\Windows","System32","rundll32.exe"),args:["url.dll,FileProtocolHandler",n]}:r==="darwin"?{command:"open",args:[n]}:s?{command:"cmd.exe",args:["/c","start",'""',n.replace(/[&^]/g,"^$&")]}:!t.DISPLAY&&!t.WAYLAND_DISPLAY?{skip:"no display here (neither DISPLAY nor WAYLAND_DISPLAY is set)"}:z("xdg-open",t)?{command:"xdg-open",args:[n]}:{skip:"xdg-open is not installed"}}var q="Opened it in the default browser (if that is not Chrome or Edge, open the address there to edit).",T=e=>e.opened?q:`Not opened in a browser: ${e.why}.`;async function O(e,r){let t=K(e,r);return t.skip?{opened:!1,why:t.skip}:new Promise(s=>{let n;try{n=C(t.command,t.args,{detached:!0,stdio:"ignore",windowsHide:!0})}catch(o){return s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})}n.once("error",o=>s({opened:!1,why:`${w.basename(t.command)} did not start (${o.code??o.message})`})),n.once("spawn",()=>{n.unref(),s({opened:!0})})})}import{packageRoot as Z,previewLogFile as f,projectRoot as G,release as I,reportsDirectory as h}from"../browser/shared/paths.mjs";import{fullAddress as ee}from"../browser/shared/page-address.mjs";import{findPreviewServer as te,galleryVersion as F,portIsFree as re,previewServerFor as ne,readAnnouncement as oe}from"../browser/shared/preview-server.mjs";import{documentLinks as se}from"../browser/shared/reports.mjs";import{documentDirectory as ie,documentFiles as ae,layoutOf as ce}from"../browser/shared/workspace.mjs";var $="\u4EA4\u7ED9\u7528\u6237\uFF08\u73B0\u5728\u5C31\u628A\u8FD9\u4E2A\u5730\u5740\u7ED9\u7528\u6237\uFF1B\u7528 Chrome \u6216 Edge \u6253\u5F00\uFF09\uFF1A",le="Agent \u81EA\u7528\uFF08\u53EA\u6709\u6587\u6863\u9875\uFF0C\u4E0D\u4EA4\u7ED9\u7528\u6237\uFF09\uFF1A",de=e=>`send the user ${e} now, in a message of its own, before any other step; then `;function Ve(e,r){let t=e.at(-1)??"";return`Next: ${t.startsWith($)?de(t.slice($.length)):""}${r}`}async function ze(e,r){let t=e.at(-1)??"";return t.startsWith($)?r.has("--no-browser")?"Not opened in a browser (--no-browser).":T(await O(t.slice($.length))):null}var D="GALLERY_NO_PREVIEW",pe=e=>!["","0",void 0].includes(e),Ue=e=>e.has("--no-preview")||pe(process.env[D]),ue=4317,fe=20,me=(e=process.env)=>{let r=Number(e.GALLERY_PORT);return Number.isInteger(r)&&r>0&&r<65536?r:ue},we=6e4,he=5*1024*1024,$e=k.join(G,"node_modules","vite","bin","vite.js"),ye=k.join(Z,"dist","server.mjs"),ge=e=>new Promise(r=>setTimeout(r,e)),A={reportsDirectory:h},Y=ce(h),R=(e,r)=>`http://127.0.0.1:${e}/generated/${r}.html`,ve=(e,r)=>`${R(e,r)}?agent`,j=e=>`http://127.0.0.1:${e}/`,xe=(e,r)=>se().then(({links:t})=>t,()=>null).then(t=>ee(`http://127.0.0.1:${e}`,r,t));async function ke({first:e=me(),count:r=fe}={}){let t=Number((await m.readFile(Y.lastPortFile,"utf8").catch(()=>"")).trim()),s=Array.from({length:Math.max(0,r)},(n,o)=>e+o);return Number.isInteger(t)&&t>0&&t<65536?[t,...s.filter(n=>n!==t)]:s}async function Le(){return await m.mkdir(k.dirname(f),{recursive:!0}),await m.stat(f).then(r=>r.size,()=>0)>he&&await m.rename(f,`${f}.1`).catch(()=>{}),P.openSync(f,"a")}async function Se(e,r){if(!I){let{writeSharedAssets:p}=await import("./chunk-NG375ILQ.mjs");await p()}let t=await Le();P.writeSync(t,`
3
3
  [${new Date().toISOString()}] ${r}: Gallery ${F} on 127.0.0.1:${e} for ${h}
4
- `);let[s,n]=I?[[ye,"--port",String(e)],Q.homedir()]:[[$e,"--host","127.0.0.1","--port",String(e),"--strictPort"],G],o=J(process.execPath,s,{cwd:n,env:{...process.env,GALLERY_WORKSPACE:k.resolve(h),GALLERY_SERVER_KIND:"cli"},detached:!0,stdio:["ignore",t,t],windowsHide:!0});return P.closeSync(t),o.unref(),o}async function be({slug:e=null,command:r=`gallery open${e?` ${e}`:""}`,ports:t=null,starting:s=we,baseline:n=!1}={}){let o=()=>!0;if(e){let a=ae(ie(e,h)),c=await m.readFile(a.html,"utf8").catch(()=>null);if(c===null)return{ok:!1,reason:"missing",message:`No document "${e}": ${a.html} does not exist (gallery new ${e} "<\u6807\u9898>" makes one; gallery list lists those there are).`};n&&await import("./chunk-SGJWQKEI.mjs").then(({previewBaseline:x})=>x(e,c));let i=await m.readFile(a.json,"utf8").then(JSON.parse).catch(()=>({})),v=[/<title>([^<]*)<\/title>/i.exec(c)?.[1]?.trim(),typeof i.title=="string"?i.title.trim():""].filter(Boolean);o=x=>v.length===0||v.some(_=>x.includes(_)||x.includes(X(_)))}let p=t??await ke(),L=p.length?`${Math.min(...p)} to ${Math.max(...p)}`:"none",S=`gallery open${e?` ${e}`:""}`,E=async(a,c=[])=>{let i=await ne({...A,ports:p.slice(a),start:v=>Se(v,r)});return i.busy?.newer?{failed:{ok:!1,reason:"newer",message:`A newer Gallery (${i.busy.version}) serves this workspace (port ${i.busy.port}, pid ${i.busy.pid}) and gave no answer in 10s; this is Gallery ${F}. Update this one (npm i -g @heycys/gallery@latest), or run ${S} again in a while.`}}:i.busy?{failed:{ok:!1,reason:"busy",message:`This workspace's Gallery server (port ${i.busy.port}, pid ${i.busy.pid}) took the request and gave no answer in 10s: it is busy or stuck. Run ${S} again in a while, or stop that process first (gallery stop): a second server of this workspace is not started beside it.`}}:i.stuck?{failed:{ok:!1,reason:"stuck",message:`An older Gallery's server serves this workspace and did not stop: ${i.stuck.message}`}}:i.port===null?{failed:{ok:!1,reason:"ports",message:`No server of this workspace runs, and no port from ${L} is free to start one on: stop a server on one of them (or name another first port: GALLERY_PORT=<n>), then run ${S}.`}}:{...i,passed:[...c,...i.passed]}},u=await E(0);if(u.failed)return u.failed;let{port:l,started:d,passed:b,replaced:W}=u,y=u.running??null,N=Date.now()+s,g="",B=async()=>{if(e){let c=await fetch(`${R(l,e)}?present`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null),i=c?.ok?await c.text():"";return g=c?i?`HTTP ${c.status} without the title`:`HTTP ${c.status}`:"no answer",!!(i&&o(i))}let a=await fetch(`http://127.0.0.1:${l}/__gallery/workspace/info`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null);return g=a?`HTTP ${a.status}`:"no answer",!!a?.ok};for(;;await ge(300)){if(Date.now()>N)return{ok:!1,reason:"timeout",message:`${e?R(l,e):j(l)} did not answer${e?" with the document's title":""} in ${s/1e3}s (${g})${d?`; the server's output is in ${f}`:""}.`};if(d){let a=await te({...A,answering:!0});if(a&&a.pid!==d.pid){if(d.exitCode===null)try{process.kill(d.pid)}catch{}({port:l}=a),y={pid:a.pid,kind:(await oe(A))?.kind??"cli",version:null},d=null;continue}if(!a&&d.exitCode===null){g="the server started has not announced itself yet";continue}if(!a){if(!await re(l)){if(u=await E(p.indexOf(l)+1,[...b,`${l} (taken by another program while the server started)`]),u.failed)return u.failed;({port:l,started:d,passed:b}=u),y=u.running??null,N=Date.now()+s;continue}let c=await m.readFile(f,"utf8").catch(()=>"");return{ok:!1,reason:"stopped",message:`The Gallery server on port ${l} stopped (exit ${d.exitCode}). Its last words (${f}):
4
+ `);let[s,n]=I?[[ye,"--port",String(e)],Q.homedir()]:[[$e,"--host","127.0.0.1","--port",String(e),"--strictPort"],G],o=J(process.execPath,s,{cwd:n,env:{...process.env,GALLERY_WORKSPACE:k.resolve(h),GALLERY_SERVER_KIND:"cli"},detached:!0,stdio:["ignore",t,t],windowsHide:!0});return P.closeSync(t),o.unref(),o}async function be({slug:e=null,command:r=`gallery open${e?` ${e}`:""}`,ports:t=null,starting:s=we,baseline:n=!1}={}){let o=()=>!0;if(e){let a=ae(ie(e,h)),c=await m.readFile(a.html,"utf8").catch(()=>null);if(c===null)return{ok:!1,reason:"missing",message:`No document "${e}": ${a.html} does not exist (gallery new ${e} "<\u6807\u9898>" makes one; gallery list lists those there are).`};n&&await import("./chunk-3NJACR4W.mjs").then(({previewBaseline:x})=>x(e,c));let i=await m.readFile(a.json,"utf8").then(JSON.parse).catch(()=>({})),v=[/<title>([^<]*)<\/title>/i.exec(c)?.[1]?.trim(),typeof i.title=="string"?i.title.trim():""].filter(Boolean);o=x=>v.length===0||v.some(_=>x.includes(_)||x.includes(X(_)))}let p=t??await ke(),L=p.length?`${Math.min(...p)} to ${Math.max(...p)}`:"none",S=`gallery open${e?` ${e}`:""}`,E=async(a,c=[])=>{let i=await ne({...A,ports:p.slice(a),start:v=>Se(v,r)});return i.busy?.newer?{failed:{ok:!1,reason:"newer",message:`A newer Gallery (${i.busy.version}) serves this workspace (port ${i.busy.port}, pid ${i.busy.pid}) and gave no answer in 10s; this is Gallery ${F}. Update this one (npm i -g @heycys/gallery@latest), or run ${S} again in a while.`}}:i.busy?{failed:{ok:!1,reason:"busy",message:`This workspace's Gallery server (port ${i.busy.port}, pid ${i.busy.pid}) took the request and gave no answer in 10s: it is busy or stuck. Run ${S} again in a while, or stop that process first (gallery stop): a second server of this workspace is not started beside it.`}}:i.stuck?{failed:{ok:!1,reason:"stuck",message:`An older Gallery's server serves this workspace and did not stop: ${i.stuck.message}`}}:i.port===null?{failed:{ok:!1,reason:"ports",message:`No server of this workspace runs, and no port from ${L} is free to start one on: stop a server on one of them (or name another first port: GALLERY_PORT=<n>), then run ${S}.`}}:{...i,passed:[...c,...i.passed]}},u=await E(0);if(u.failed)return u.failed;let{port:l,started:d,passed:b,replaced:W}=u,y=u.running??null,N=Date.now()+s,g="",B=async()=>{if(e){let c=await fetch(`${R(l,e)}?present`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null),i=c?.ok?await c.text():"";return g=c?i?`HTTP ${c.status} without the title`:`HTTP ${c.status}`:"no answer",!!(i&&o(i))}let a=await fetch(`http://127.0.0.1:${l}/__gallery/workspace/info`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null);return g=a?`HTTP ${a.status}`:"no answer",!!a?.ok};for(;;await ge(300)){if(Date.now()>N)return{ok:!1,reason:"timeout",message:`${e?R(l,e):j(l)} did not answer${e?" with the document's title":""} in ${s/1e3}s (${g})${d?`; the server's output is in ${f}`:""}.`};if(d){let a=await te({...A,answering:!0});if(a&&a.pid!==d.pid){if(d.exitCode===null)try{process.kill(d.pid)}catch{}({port:l}=a),y={pid:a.pid,kind:(await oe(A))?.kind??"cli",version:null},d=null;continue}if(!a&&d.exitCode===null){g="the server started has not announced itself yet";continue}if(!a){if(!await re(l)){if(u=await E(p.indexOf(l)+1,[...b,`${l} (taken by another program while the server started)`]),u.failed)return u.failed;({port:l,started:d,passed:b}=u),y=u.running??null,N=Date.now()+s;continue}let c=await m.readFile(f,"utf8").catch(()=>"");return{ok:!1,reason:"stopped",message:`The Gallery server on port ${l} stopped (exit ${d.exitCode}). Its last words (${f}):
5
5
  ${c.split(`
6
6
  `).slice(-15).join(`
7
7
  `)}`}}}if(await B())break}return await m.writeFile(Y.lastPortFile,`${l}
8
- `).catch(()=>{}),{ok:!0,port:l,pid:d?.pid??y?.pid??null,kind:y?.kind??"cli",started:!!d,replaced:W??null,passed:b}}var Ae=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`;function Pe({port:e,pid:r,kind:t,started:s,replaced:n,passed:o=[]}){let p=[`pid ${r}`,...t==="dev"?["npm run dev's"]:[],...s?[`started now${o.length?`, after passing over ${Ae(o)}`:""}`]:[],...n?[`it replaced Gallery ${n.version??"an older version"}'s server, pid ${n.pid}`]:[]],L=s?`; its log: ${f}`:"";return`This workspace's Gallery server runs on port ${e} (${p.join(", ")}${L}). This command is done; the server runs on after it (nothing to wait for or keep running).`}async function Re(e,r,t=null){return[Pe(r),...e?[`${le}${ve(r.port,e)}`]:[],`${$}${e?await xe(r.port,{slug:e,block:t}):j(r.port)}`]}async function Ke(e,{skipped:r,command:t,ports:s=null}){let n=`gallery open ${e} starts it and prints the address to give the user`;if(r)return[`Preview: not started (--no-preview or ${D}): ${n}.`];let o=await be({slug:e,command:t,ports:s});return o.ok?Re(e,o):[`Preview: not started: ${o.message}`,`When that is fixed, ${n}.`]}export{Ve as a,ze as b,Ue as c,ve as d,j as e,ke as f,be as g,Re as h,Ke as i};
8
+ `).catch(()=>{}),{ok:!0,port:l,pid:d?.pid??y?.pid??null,kind:y?.kind??"cli",started:!!d,replaced:W??null,passed:b}}var Ae=e=>e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`;function Pe({port:e,pid:r,kind:t,started:s,replaced:n,passed:o=[]}){let p=[`pid ${r}`,...t==="dev"?["npm run dev's"]:[],...s?[`started now${o.length?`, after passing over ${Ae(o)}`:""}`]:[],...n?[`it replaced Gallery ${n.version??"an older version"}'s server, pid ${n.pid}`]:[]],L=s?`; its log: ${f}`:"";return`This workspace's Gallery server runs on port ${e} (${p.join(", ")}${L}). This command is done; the server runs on after it (nothing to wait for or keep running).`}async function Re(e,r,t=null){return[Pe(r),...e?[`${le}${ve(r.port,e)}`]:[],`${$}${e?await xe(r.port,{slug:e,block:t}):j(r.port)}`]}async function Ke(e,{skipped:r,command:t,ports:s=null}){let n=`gallery open ${e} starts it and prints the address to give the user`;if(r)return[`Preview: not started (--no-preview or ${D}): ${n}.`];let o=await be({slug:e,command:t,ports:s});return o.ok?Re(e,o):[`Preview: not started: ${o.message}`,`When that is fixed, ${n}.`]}export{$ as a,le as b,Ve as c,ze as d,Ue as e,ve as f,j as g,ke as h,be as i,Pe as j,Re as k,Ke as l};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{g as a,h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m,t as n,u as o,v as p,w as q}from"./chunk-HMYTM3GT.mjs";import"./chunk-OW5NWPOJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-SX4LJYT6.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-W3BGBJQW.mjs";import"./chunk-JVHHHGEA.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{h as buildReports,d as checkReports,f as checkSelectedReports,b as exportFailures,k as exportReports,p as failureSummary,e as handInBlockers,l as notesByKind,m as notesOf,j as offlineReports,o as printFailures,c as quickFailures,a as repeatedIdFailures,q as reportFailures,n as reportNotes,i as withExportPolicy,g as writeSharedAssets};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{E as re,J as ae,K as ne,O as ie,P as ce,a as C,b as Q,c as F,g as X,h as Z,n as D,o as ee,r as te,s as se,t as oe}from"./chunk-RFDZXFJF.mjs";import{j as K}from"./chunk-QOUEFUCH.mjs";import{d as le}from"./chunk-6A53MZYZ.mjs";import{i as q}from"./chunk-NFMCP2HI.mjs";import{a as L}from"./chunk-JEUK3ZO7.mjs";import{a as M,b as z,g as J}from"./chunk-PUOQ65NC.mjs";import{b as x,c as T}from"./chunk-UFNYFFKO.mjs";import{b as E}from"./chunk-4OZWXZE5.mjs";import{f as H,j as Y}from"./chunk-FWNRPMCJ.mjs";import{b as V,e as pe}from"./chunk-A55HN5OK.mjs";pe();import N from"node:fs/promises";import P from"node:path";import{isInstance as ge}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as me}from"../browser/shared/components/installed.mjs";import{attr as we,walk as $e}from"../browser/shared/html-tree.mjs";import{pageExists as ye,pageFiles as be}from"../browser/shared/pages.mjs";import{layoutOf as Ee}from"../browser/shared/workspace.mjs";var xe="card ids aside",ke="nothing else in page.html changed (card ids aside)",Se=e=>new Promise(s=>setTimeout(s,e)),Te=/^\/__gallery\/pages\/[a-z0-9-]+\/cards$/,de=e=>{let s=null;return $e(V(e,{sourceCodeLocationInfo:!0}),n=>{s??=ge(n)?n:null},{inTemplates:!1}),s},fe=(e,s)=>{let n=s.node.sourceCodeLocation.startTag.endOffset;return{frame:e.slice(s.start,n).replace(/\s+data-[xywh]="[^"]*"/g,""),rest:e.slice(n,s.end)}};function Ce(e,s,n,a){let[o,d]=[x(e).cards,x(s).cards],c=[],t=r=>`card ${r.id}${r.block?` (${r.block})`:""}`,l=r=>["x","y","w","h"].map(i=>`${i} ${we(r.node,`data-${i}`)??"-"}`).join(", ");for(let r of o){let i=d.find(g=>g.id===r.id);if(!i){c.push(`${t(r)} taken out`);continue}let m=r.board!==i.board;(m||l(r)!==l(i))&&c.push(`${t(r)}'s place, ${l(r)}${m?` on ${r.board}`:""} then ${l(i)}${m?` on ${i.board}`:""}`);let[h,p]=[fe(e,r),fe(s,i)];if(h.frame===p.frame&&h.rest===p.rest)continue;if(r.id!==n){c.push(t(r));continue}h.frame!==p.frame&&c.push(`${t(r)}'s own frame (an attribute of its <section> but its place)`);let[f,$]=[D(h.rest,de,a),D(p.rest,de,a)];!f||!$?c.push(`${t(r)}'s instance`):f.outside!==$.outside&&c.push(`${t(r)} itself, outside its data parts (a part edited as text or none, or what its instance holds besides its parts)`)}for(let r of d)o.some(i=>i.id===r.id)||c.push(`a ${t(r)} put in`);let w=(r,i)=>{let m="",h=0;for(let p of[...i].sort((f,$)=>f.start-$.start))m+=r.slice(h,p.start),h=p.end;return(m+r.slice(h)).replace(/\s+/g," ")};return(w(e,o)!==w(s,d)||!c.length)&&c.push("the page's own HTML outside its cards (its head, its style, its header)"),c.join("; ")}function Ie(e,s,{card:n,found:a}){let[o,d]=[T(e).text,T(s).text],t=ee(o,d,l=>x(l).cards.find(w=>w.id===n)?.instance??null,a);return t.outside&&(t.outside={...t.outside,what:Ce(o,d,n,a)}),t}async function Oe(e){try{return await e.waitForSelector("[data-doc-ready]",{timeout:C}).catch(s=>{if(s.name==="TimeoutError")throw s;return e.waitForSelector("[data-doc-ready]",{timeout:C})}),await e.waitForFunction(()=>globalThis.__galleryTryEditable===!0&&!!document.querySelector("script[data-ge-page]"),{timeout:C}),!0}catch(s){if(s.name!=="TimeoutError")throw s;return!1}}function ve(e){return e?.startsWith("stopped")?`the page service refused the board's write (${e.slice(7).trim()||"no reason given"}), and the page showed itself again as the file holds it`:{refused:"the page service refused the board's write: the card was changed or taken out meanwhile (someone else's write of page.html), and the page showed itself again as the file holds it",offline:"the page could not reach the server (offline)",reloading:"the page loaded itself again (page.html or a custom block it holds changed meanwhile, or the page service refused a write)",syncing:`its write took more than ${F/1e3}s to be answered`}[e]}function Ae(e){let s=[],n=new Map;return e.on("request",a=>{if(a.method()!=="POST"||!Te.test(new URL(a.url()).pathname))return;let o={done:!1,status:null,answer:null,failed:null};s.push(o),n.set(a,o)}),e.on("response",a=>{let o=n.get(a.request());o&&(o.status=a.status(),o.done=!0,o.status!==200&&a.json().then(d=>{o.answer=d},()=>{}))}),e.on("requestfailed",a=>{let o=n.get(a);o&&(o.failed=a.failure()?.errorText??"failed",o.done=!0)}),{mark:async()=>s.length,async until(a){let o=Date.now();for(let d=0;;await Se(100)){let c=s.slice(a);if(c.length===0){if(Date.now()-o>Q)return"unchanged";continue}if(c.some(l=>!l.done)){if(d=0,Date.now()-o>F)return"syncing";continue}if(++d<4)continue;if(c.some(l=>l.failed))return"offline";let t=c.find(l=>l.status!==200);return t?t.answer?.refused||t.status===409&&!t.answer?"refused":`stopped ${t.answer?.reason??`HTTP ${t.status}`}`:"saved"}}}}function Re({card:e,found:s}){let n={...s,parts:Object.fromEntries(Object.entries(s.parts).filter(([,a])=>a.edit==="data"))};return{where:{card:e},ready:Oe,saves:Ae,changes:(a,o)=>Ie(a,o,{card:e,found:n}),plain:()=>!1,stayed:ve,outside:"problem",outsideSaid:a=>`card ${e}'s data parts: ${a.what}, where a reader's gesture on the card is to change its data parts alone`,aside:xe,inside:ke,framed:a=>a.closest(".gallery-card")??a}}var Le=e=>` ${e.id} ${e.block??"(no instance)"} x ${e.x}, y ${e.y}, w ${e.w}, h ${e.h}${e.board?` on board ${e.board}`:""}`;async function Ke(e,{named:s,values:n,seconds:a={},keep:o,replace:d=!1}){if(s.length===0)throw new E("Name the page and the card: gallery page try <slug> <card id> and the gesture.");if(s.length===1)throw new E(`Name the card of ${s[0]} to try: gallery page try ${s[0]} <card id> and the gesture (its data-card-id; gallery page check ${s[0]} lists the cards).`);if(s.length>2)throw new E("gallery page try takes a page's slug and a card's id.");let c=await X(n,a,d),[t,l]=s,w=n.has("--steps")?P.resolve(n.get("--steps")):null,r=c?[c]:await Z(w),i=be(t,e);ye(t,e)||(console.error(await le(t,e)),process.exit(1));let m=await N.readFile(i.html,"utf8"),{cards:h}=x(T(m).text),p=h.find(u=>u.id===l);if(!p)throw new E(h.length?`${t} has no card ${l}: its cards are
3
+ ${h.map(Le).join(`
4
+ `)}`:`${t} has no card yet: gallery page add ${t} <block> puts one on it.`);let f=P.basename(i.html),$=p.node.sourceCodeLocation?.startLine??null;p.instance||(console.error(`Card ${l} of ${t} (${f}:${$}) holds no instance of a custom block (an element with ${me}): there is nothing on it to try.`),process.exit(1));let g=p.block,_=H(e),k=_.packages.get(g);if(!k){let u=_.problems.get(g);console.error(u?.off?`${g} is turned off in \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868: its card says so on the page and runs nothing.`:u?`${g} does not load (${Y("en",u.problem)}), so its card runs nothing: gallery block check ${g} says why.`:`No custom block ${g} in this workspace, so its card runs nothing: gallery block list says which there are${g.startsWith("gallery/")?`, and gallery block add ${g.slice(8)} puts one of Gallery's own in`:""}.`),process.exit(1)}k.places.includes("page")||(console.error(`${g} is a block of documents (its manifest's places has no "page"): on a custom page its card says so and runs nothing, so there is nothing to try there (gallery block try tries it in a document).`),process.exit(1)),console.log(`${g} in card ${l} of ${t}, at ${f}:${$}: ${L(i.html)}`),w&&console.log(`Steps: ${r.length} from ${L(w)}, made one after another in one page`);let S=await q({command:`gallery page try ${t}`});if(!S.ok){console.log(`UNVERIFIED ${t}: ${S.message}`),process.exitCode=3;return}let{pageAloneOf:j}=await import("./chunk-2NRBY6AJ.mjs");await oe(e);let B=[],G=async u=>{let b=await te(e,{directory:i.folder,files:i,text:u});return B.push(b.slug),b},I=Re({card:l,found:k});try{let u=o?{slug:t,file:i.html}:await G(m),b=j(S.port,u.slug);console.log(o?`Page: ${b} (the custom page alone, editable: the Agent's own; --keep: what ${re(r)} write stays in ${f}, and every page open on it shows it, the user's too; the server runs on after this command)`:`Page: ${b} (a scratch copy of ${t}, its page alone, editable, made for this trial and gone at its end: ${f} is not written, and no page of the user's shows the trial; the server runs on after this command)`);let O=M();if(!O){console.log(`UNVERIFIED ${t}: no Chrome, Edge or Chromium found (GALLERY_BROWSER=<its executable> picks one), so nothing was tried`),process.exitCode=3;return}let v;try{v=await J({executablePath:O,args:z()})}catch(R){console.log(`UNVERIFIED ${t}: the browser ${O} did not start, twice, each time with a fresh profile (${K(R)}; GALLERY_BROWSER=<its executable> picks another), so nothing was tried`),process.exitCode=3;return}let A=P.join(Ee(e).qa,t,"try");try{await N.rm(A,{recursive:!0,force:!0}),await N.mkdir(A,{recursive:!0});let R=async y=>{if(o)return{address:b,file:u.file};let W=await G(y);return{address:j(S.port,W.slug),file:W.file}},U;try{U=await ae(v.browser,{root:e,address:b,fresh:R,steps:r,keep:o,file:u.file,name:f,line:$,found:k,out:A,host:I})}catch(y){if(y instanceof E&&y.made&&console.log(ce({name:f,steps:r,keep:o,host:I},y.made).join(`
5
+ `)),y.stuck)return ne(t,y,f,o);throw y}let{lines:ue,code:he}=ie({slug:t,name:f,steps:r,keep:o,host:I},U);console.log(ue.join(`
6
+ `)),process.exitCode=he}finally{await v.close()}}finally{for(let u of B)await se(e,u)}}export{xe as a,ke as b,de as c,Ce as d,Ie as e,Ae as f,Re as g,Ke as h};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{e as H,f as K,g as Q}from"./chunk-OJKMINIU.mjs";import{d as D,f as E,g as T,h as F}from"./chunk-FWNRPMCJ.mjs";import{existsSync as R}from"node:fs";var U=120;function W(n,I){let p=({packages:s,problems:c})=>new Map([...s,...c].map(([a,{stamp:t}])=>[a,t])),[l,f]=[p(n),p(I)];return[...new Set([...l.keys(),...f.keys()])].filter(s=>l.get(s)!==f.get(s)).sort()}function A({root:n,tell:I,delay:p=U,quiet:l=Q,hold:f=H,limit:s=K,now:c=Date.now,timers:a={set:(t,m)=>setTimeout(t,m),clear:t=>clearTimeout(t)}}){let t=null,m=0,u=null,r=new Map;T(n);let M=i=>{t&&m<=c()+i||(a.clear(t),m=c()+i,t=a.set(w,i),t.unref?.())};function w({settled:i=!1}={}){t=null;let d=T(n),o=E(n,d.settings),b=c();o.stamp!==u?.stamp&&(u={stamp:o.stamp,at:b});let y=b-u.at;if(y<l&&!i)return M(l-y);let g=new Map(o.packages),k=new Map(o.problems),h=1/0;for(let[e,L]of d.packages){if(!(!o.settings.disabled.includes(e)&&(k.has(e)||!g.has(e)&&R(L.folder)))){r.delete(e);continue}r.has(e)||r.set(e,u.at);let O=Math.min(f-y,s-(b-r.get(e)));if(O<=0){r.delete(e);continue}g.set(e,L),k.delete(e),h=Math.min(h,O)}let{settings:C,packs:S}=o,x=D({packages:g,problems:k,settings:C,packs:S});if(x!==d.stamp){let e={packages:g,problems:k,settings:C,packs:S,stamp:x};F(n,e),I(e,W(d,e))}h!==1/0&&M(h)}return{changed:()=>M(p),taken(){a.clear(t),w({settled:!0})},close(){a.clear(t),t=null}}}export{U as a,A as b};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-SXHBYZST.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{g as changeLines,c as handedInSource,f as headerChanged,e as inStep,a as naturalize,d as pendingBlockIds,h as readOnlyTexts,j as scriptKept,b as shownSource,i as writingNotes};
@@ -0,0 +1,20 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as Ee,b as Re}from"./chunk-IA4PSIMD.mjs";import{b as Te}from"./chunk-6EZ7FNIK.mjs";import{a as ye,b as je,c as pt,d as Me,e as Ae,f as Ne}from"./chunk-V6RIYQZZ.mjs";import{b as Se,c as ve,e as Oe,g as Ht}from"./chunk-SXHBYZST.mjs";import{a as me}from"./chunk-UMHUSOPJ.mjs";import{a as ge,d as ke,e as be,f as $e,g as xe}from"./chunk-N76HWBA3.mjs";import{e as pe,f as we,g as he,h as Ct}from"./chunk-FJYN7RTH.mjs";import{a as _,m as de}from"./chunk-UBBRTJ2R.mjs";import{g as le,u as ue}from"./chunk-FWNRPMCJ.mjs";var vn=3e4,On=12e4,jn=1500,Fe=1e4,Ie=l=>l.reduce((i,{key:w,tag:u})=>i.set(`${w}
3
+ ${u}`,(i.get(`${w}
4
+ ${u}`)??0)+1),new Map);function De({now:l=Date.now,hold:i=vn,limit:w=On,quiet:u=jn}={}){let k=new Map,d=new Map,O=new Map,h=new Map,f=new Map;return{wrote(p,b){h.set(p,_(b))},judge(p,{source:b,mtime:I}){if(b===null)return k.delete(p),O.delete(p),{held:!1,signs:[],wait:0,own:!1};let N=_(b),$=f.get(p)?.hash===N?f.get(p).signs:null;$||($=je(b),f.set(p,{hash:N,signs:$}));let Z=l(),W=(J,Q=!1)=>(k.delete(p),d.set(p,Ie($)),O.set(p,b),{held:!1,signs:[],wait:J,own:Q});if(h.get(p)===N)return W(0,!0);let L=d.get(p)??new Map,H=Ie($);if([...H].some(([J,Q])=>Q>(L.get(J)??0))){let J=Math.min(I,Z),Q=k.get(p)??J;k.set(p,Q);let st=Math.min(i-(Z-J),w-(Z-Q));if(st>0)return{held:!0,signs:$.filter(({key:s,tag:g})=>H.get(`${s}
5
+ ${g}`)>(L.get(`${s}
6
+ ${g}`)??0)),wait:st,own:!1,taken:O.get(p)}}return W(Math.min(u,Math.max(0,u-(Z-I))))}}}import{createHmac as Xn,randomBytes as qt}from"node:crypto";import{existsSync as tr,mkdirSync as er,readFileSync as nr,writeFileSync as rr}from"node:fs";import z from"node:fs/promises";import P from"node:path";import{FILE as or}from"../browser/shared/annotations.mjs";import{escapeTyped as ar}from"../browser/shared/escape.mjs";import{writeAtomic as Ft}from"../browser/shared/files.mjs";import{sendJson as C}from"../browser/shared/http.mjs";import{REQUEST_ID as Qt}from"../browser/shared/ids.mjs";import{UPLOAD_REQUEST_LIMIT as sr}from"../browser/shared/media.mjs";import{reportsDirectory as ir}from"../browser/shared/paths.mjs";import{sameDirectory as cr}from"../browser/shared/preview-server.mjs";import{slugPattern as rt}from"../browser/shared/reports.mjs";import{TODO_MOST as fr}from"../browser/shared/workspace-query.mjs";import{documentDirectory as lr,documentFiles as Mt,isDocumentSource as ur}from"../browser/shared/workspace.mjs";import zt from"node:fs/promises";import Pe from"node:path";import{checkAnnotations as Mn,cleanAnchor as An,cleanItem as Je,FILE as Nn,itemsText as Tn,readItems as En,treeText as _e}from"../browser/shared/annotations.mjs";import{writeAtomic as Rn}from"../browser/shared/files.mjs";import{slugPattern as In}from"../browser/shared/reports.mjs";import{documentDirectory as Le,documentFiles as Fn}from"../browser/shared/workspace.mjs";var Dn=600*1e3,Pn=600*1e3;function Jn(l){let{units:i,boxes:w}=he(l),u=[...i].sort((h,f)=>h.elStart-f.elStart),k=new Map(u.map((h,f)=>[h.id,f])),d=new Map(u.map(h=>[h.id,_e(h.node)])),O={h2:null,h3:null,h4:null};return u.map(h=>{let f=[];for(let N=h;N;N=N.parent===null?null:i[N.parent]){let $=w[N.box];if($?.kind==="panel"&&$.key!==null){let W=i.find(L=>L.kind==="tab"&&L.parent===$.unit&&L.key===$.key);W&&f.unshift({tab:d.get(W.id)})}let Z=$?.unit===null||$?.unit===void 0?null:i[$.unit];if(Z?.tag==="details"&&$.kind==="details"){let W=Z.node.childNodes.find(L=>L.tagName==="summary");W&&f.push({details:_e(W)})}}let p=f.find(N=>N.tab)?.tab,b=f.find(N=>N.details)?.details,I=[p,O.h2,O.h3,O.h4,b].filter(Boolean);return h.tag==="h2"?Object.assign(O,{h2:d.get(h.id),h3:null,h4:null}):h.tag==="h3"?Object.assign(O,{h3:d.get(h.id),h4:null}):h.tag==="h4"&&(O.h4=d.get(h.id)),{id:h.blockId,text:d.get(h.id),parent:h.parent===null?null:k.get(h.parent)??null,where:I,heading:/^h[2-4]$/.test(h.tag)}})}function Ue({reportsDirectory:l,read:i,write:w=Rn,dropped:u=()=>{},now:k=Date.now}){let d=new Map,O=new Map,h=new Map,f=(s,g)=>{let r=h.get(s);if(r?.text===g)return r.units;let a=Jn(g);return h.set(s,{text:g,units:a}),a},p=s=>Pe.join(Le(s,l),Nn),b=s=>typeof s=="string"&&In.test(s);async function I(s){let g=await zt.readFile(p(s),"utf8").catch(()=>null);return{text:g,items:g===null?[]:En(g)}}async function N(s,g,r){let a=Tn(g);return a===r||(a===null?await zt.rm(p(s),{force:!0}):await w(p(s),a)),$(a)}let $=s=>s===null?"":_(s),Z=s=>{let g=d.get(s)??new Map;for(let[r,a]of g)k()-a>Dn&&g.delete(r);return[...g.keys()]},W=(s,g)=>g.forEach(r=>d.get(s)?.delete(r)),L=s=>{let g=O.get(s)??O.set(s,new Map).get(s);for(let[r,a]of g)k()-a>Pn&&g.delete(r);return g};async function H(s,{keep:g=null,items:r=null,before:a=void 0}={}){let S=r?{items:r,text:a}:await I(s),v=await i(s).catch(()=>null);if(!v)return{items:S.items,units:[],places:new Map,version:$(S.text),missing:!0};let D=f(s,v.text),T=L(s),x=Mn(S.items,D,{keep:new Set([...T.keys(),g])});for(let M of T.keys())x.waiting.has(M)||T.delete(M);if(x.dropped.length>0){let M=d.get(s)??d.set(s,new Map).get(s);for(let ot of x.dropped)M.set(ot.id,k())}let A=x.changed||r?await N(s,x.items,S.text):$(S.text);return x.dropped.length>0&&u(s,x.dropped),{items:x.items,units:D,places:x.places,version:A,missing:!1}}let F=(s,{items:g,version:r})=>({ok:!0,version:r,items:g,dropped:Z(s)});async function J(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);return g.missing?[404,{ok:!1,reason:"missing"}]:[200,F(s,g)]}async function Q(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);if(g.missing)return[404,{ok:!1,reason:"missing"}];let r=null,a=Fn(Le(s,l));try{r=JSON.parse(await zt.readFile(a.json,"utf8"))}catch{}let S=await i(s).catch(()=>null),v=/<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(S?.text??"")?.[1]?.replace(/<[^>]*>/g,"").trim(),D=typeof r?.title=="string"&&r.title.trim()?r.title.trim():v||s,T=g.units.some(A=>A.heading),x=g.items.map(A=>{let M=g.units[g.places.get(A.id)?.at],ot=M?.where?.length?M.where:M?.heading?[M.text]:[];return{where:ot,top:T&&ot.length===0,blocks:A.anchor.blocks.filter(B=>g.units.some(nt=>nt.id===B)),whole:A.anchor.kind==="blocks",quote:A.anchor.quote,text:A.text}});return[200,{ok:!0,title:D,path:Pe.resolve(a.html),items:x}]}async function st(s){let{slug:g}=s??{};if(!b(g))return[400,{ok:!1,reason:"body"}];if(!await i(g).catch(()=>null))return[404,{ok:!1,reason:"missing"}];let r=await I(g);if(s.anchors&&typeof s.anchors=="object"&&!Array.isArray(s.anchors)){let T=r.items.map(A=>{let M=Object.hasOwn(s.anchors,A.id)?An(s.anchors[A.id]):null;return M&&M.kind===A.anchor.kind?{...A,anchor:M}:A}),x=await N(g,T,r.text);return[200,F(g,{items:T,version:x})]}let a=r.items,S=null,v=null;if(s.put!==void 0){let T=a.find(A=>A.id===s.put?.id),x=Je({...s.put,created:T?.created??s.put?.created});if(!x)return[400,{ok:!1,reason:"item"}];a=T?a.map(A=>A.id===x.id?x:A):[...a,x],S=x.id,T||L(g).set(x.id,k()),W(g,[x.id])}else if(typeof s.remove=="string")a=a.filter(T=>T.id!==s.remove);else if(s.clear===!0)v=a,a=[];else if(Array.isArray(s.restore)){let T=new Map(a.map(M=>[M.id,M])),x=s.restore.map(M=>Je(M,M?.updated)).filter(M=>M&&!(T.get(M.id)?.updated>M.updated)),A=new Set(x.map(M=>M.id));for(let M of A)T.has(M)||L(g).set(M,k());a=[...a.filter(M=>!A.has(M.id)),...x],W(g,[...A])}else return[400,{ok:!1,reason:"body"}];let D=await H(g,{keep:S,items:a,before:r.text});return[200,{...F(g,D),...v?{removed:v}:{}}]}async function q(s){if(!b(s))return;let{text:g}=await I(s);g!==null&&await H(s)}return{list:J,copy:Q,change:st,afterWrite:q}}import wt from"node:fs/promises";import ht from"node:path";import{writeAtomic as We}from"../browser/shared/files.mjs";import{slugPattern as Gt}from"../browser/shared/reports.mjs";var It=1,Ot={seen:"seen.html",base:"base.html",state:"state.json"},_n=4,Ln=1800*1e3;function Be({stateDirectory:l=null,shown:i,folderOf:w,isPage:u=()=>!1,log:k=null,now:d=Date.now,quiet:O=Ln}){let h=new Map,f=r=>ht.join(l,"changes",r),p=Promise.resolve(),b=r=>{let a=p.then(r);return p=a.catch(S=>k?.(`changes: ${S.message}`)),a};async function I(r){if(!l)return h.get(r)?.state??null;try{let a=JSON.parse(await wt.readFile(ht.join(f(r),Ot.state),"utf8"));return a?.v===It&&typeof a.seen=="string"?a:null}catch{return null}}async function N(r,a){return l?wt.readFile(ht.join(f(r),Ot[a]),"utf8").catch(()=>null):h.get(r)?.[a]??null}async function $(r,a,S={}){if(!l){let v=h.get(r)??{};h.set(r,{...v,...S,state:a});return}await wt.mkdir(f(r),{recursive:!0});for(let[v,D]of Object.entries(S))D===null?await wt.rm(ht.join(f(r),Ot[v]),{force:!0}):await We(ht.join(f(r),Ot[v]),D);await We(ht.join(f(r),Ot.state),`${JSON.stringify(a)}
7
+ `)}async function Z(r){h.delete(r),l&&await wt.rm(f(r),{recursive:!0,force:!0,maxRetries:3})}let W=async r=>Math.round((await wt.stat(w(r)).catch(()=>null))?.birthtimeMs??0),L=r=>r?.base?`${r.since}|${r.writes}`:null,H=r=>Number.isFinite(r?.draft)&&d()-r.draft<O?r.draft:null,F=(r,a,S,v=H(r))=>[{v:It,born:r?.born??0,seen:a,...v===null?{}:{draft:v}},{seen:S,base:null}];async function J(r){let a=await I(r);if(!a)return null;let S=await W(r);return a.born&&S&&a.born!==S?(await Z(r),null):a}async function Q(r,a){if(typeof a!="string"||!Gt.test(r)||u(r))return!1;let S=_(a),v=await J(r);if(!v)return await $(r,{v:It,born:await W(r),seen:S},{seen:a}),!1;if(v.seen===S)return!1;let D=await N(r,"seen"),T=new Date(d()).toISOString();if(D===null)return await $(r,...F(v,S,a)),!1;let x=i(D),A=i(a);if(!v.base){if(!pt(x,A))return await $(r,...F(v,S,a)),!1;if(H(v)!==null||Me(x))return await $(r,...F(v,S,a,d())),!1;let{draft:B,...nt}=v;return await $(r,{...nt,seen:S,base:_(x),since:T,at:T,writes:1},{seen:a,base:x}),!0}let M=await N(r,"base");if(M===null||!pt(M,A))return await $(r,...F(v,S,a)),!0;let ot=pt(x,A)!==null;return await $(r,{...v,seen:S,...ot?{at:T,writes:v.writes+1}:{}},{seen:a}),ot}async function st(r,a,S,v){if(!Gt.test(r)||u(r))return!1;let D=await J(r),T=_(a);if(!D?.base)return await $(r,...F(D??{born:await W(r)},T,a,v?null:H(D))),!1;let x=await N(r,"base");if(x!==null&&S)try{x=S(x)}catch(A){k?.(`changes: ${r}: the baseline did not take the edit (${A.message})`)}return x===null||!pt(x,i(a))?(await $(r,...F(D,T,a)),!0):(await $(r,{...D,seen:T,base:_(x)},{seen:a,base:x}),!1)}async function q(r,a){if(!Gt.test(r)||u(r))return{ended:!1,moved:!1};let S=typeof a=="string"?await Q(r,a):!1,v=await J(r);if(v?.draft===void 0)return{ended:!1,moved:S};let{draft:D,...T}=v;return await $(r,T),{ended:H(v)!==null,moved:S}}let s=new Map;async function g(r,a){await Q(r,a);let S=i(a),v=_(S),D=await J(r);if(!D?.base)return{pending:!1,version:v};let T=`${r} ${D.base} ${v}`,x=s.get(T);if(x===void 0){let A=await N(r,"base");for(x=A===null?null:pt(A,S),s.set(T,x);s.size>_n;)s.delete(s.keys().next().value)}return x?{pending:!0,version:v,stamp:L(D),since:D.since,writes:D.writes,...x}:{pending:!1,version:v}}return{look:(r,a)=>b(()=>Q(r,a)),wrote:(r,a,S=null,{reader:v=!1}={})=>b(()=>st(r,a,S,v)),endDraft:(r,a=null)=>b(()=>q(r,a)),read:(r,a)=>b(()=>g(r,a)),stamp:r=>b(async()=>L(await J(r))),snapshot:r=>b(async()=>{let a=await J(r);return a?{state:a,seen:await N(r,"seen"),base:await N(r,"base")}:null}),clear:r=>b(async()=>{let a=await J(r);a?.base&&await $(r,{v:It,born:a.born,seen:a.seen},{base:null})}),restore:(r,a)=>b(async()=>{a?.state&&await $(r,a.state,{seen:a.seen,base:a.base})}),forget:r=>b(()=>Z(r)),idle:()=>b(async()=>{})}}import{randomBytes as Un}from"node:crypto";import ct from"node:fs/promises";import yt from"node:path";import{FILE as Wn,readItems as Bn}from"../browser/shared/annotations.mjs";import{writeAtomic as Yn}from"../browser/shared/files.mjs";import{documentDirectory as Zn}from"../browser/shared/workspace.mjs";var Cn=20,Ce=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Ye=80,He=({stateDirectory:l,slug:i})=>yt.join(l,"dropped-annotations",i),ze=l=>({id:l.id,text:l.text,quote:l.anchor?.quote??"",kind:l.anchor?.kind??"text"});async function Ge({stateDirectory:l,reportsDirectory:i,slug:w,time:u,items:k}){let d=He({stateDirectory:l,reportsDirectory:i,slug:w});await ct.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Yn(yt.join(d,`${O}-${Un(4).toString("hex")}.json`),JSON.stringify({time:u,items:k}));let h=(await ct.readdir(d)).filter(f=>Ce.test(f)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Cn)).map(f=>ct.rm(yt.join(d,f),{force:!0})))}async function Vr({stateDirectory:l,reportsDirectory:i,slug:w}){let u=He({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await ct.readdir(u).catch(()=>[])).filter(h=>Ce.test(h)).sort();if(k.length===0)return[];let d=new Set(Bn(await ct.readFile(yt.join(Zn(w,i),Wn),"utf8").catch(()=>"")).map(h=>h.id)),O=[];for(let h of k){let f=yt.join(u,h);try{let p=JSON.parse(await ct.readFile(f,"utf8")),b=Array.isArray(p?.items)?p.items.filter(I=>typeof I?.id=="string"&&!d.has(I.id)):[];typeof p?.time=="string"&&b.length&&O.push({time:p.time,items:b})}catch{}await ct.rm(f,{force:!0}).catch(()=>{})}return O}var Hn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`},Ze=l=>{let i=String(l??"").replace(/\s+/g," ").trim();return JSON.stringify(i.length>Ye?`${i.slice(0,Ye-1)}\u2026`:i)};function Kt(l,{time:i=null,items:w},{today:u=new Date}={}){let k=yt.resolve(l),d=`${w.length} \u6279\u6CE8 (annotation${w.length===1?"":"s"})`;return[`annotations ${k}: ${i?`at ${Hn(i,u)}, `:""}Gallery deleted ${d} whose words are gone from the document (rewritten or deleted):`,...w.map(({id:O,text:h,quote:f,kind:p})=>` ${O} ${Ze(h)} on ${p==="blocks"?"the blocks ":""}${Ze(f)}`)]}function qr(l,i,{today:w=new Date}={}){return i.length?[...i.flatMap(u=>Kt(l,u,{today:w}))," they were the reader's: say in your hand-off which your edit carried out and which you left, and never write them back"]:[]}import{randomBytes as zn}from"node:crypto";import gt from"node:fs/promises";import jt from"node:path";import{writeAtomic as Gn}from"../browser/shared/files.mjs";var Kn=20,Ke=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Qe=({stateDirectory:l,slug:i})=>jt.join(l,"rewrites",i);async function Ve({stateDirectory:l,reportsDirectory:i,slug:w,time:u,changes:k}){let d=Qe({stateDirectory:l,reportsDirectory:i,slug:w});await gt.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Gn(jt.join(d,`${O}-${zn(4).toString("hex")}.json`),JSON.stringify({time:u,changes:k}));let h=(await gt.readdir(d)).filter(f=>Ke.test(f)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Kn)).map(f=>gt.rm(jt.join(d,f),{force:!0})))}async function qe({stateDirectory:l,reportsDirectory:i,slug:w}){let u=Qe({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await gt.readdir(u).catch(()=>[])).filter(O=>Ke.test(O)).sort(),d=[];for(let O of k){let h=jt.join(u,O);try{let f=JSON.parse(await gt.readFile(h,"utf8"));typeof f?.time=="string"&&Array.isArray(f.changes)&&d.push(f)}catch{}await gt.rm(h,{force:!0}).catch(()=>{})}return d}var Qn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`};function oo(l,i,{today:w=new Date}={}){if(!i.length)return[];let u=jt.resolve(l),k=[];for(let{time:d,changes:O}of i){let h=[];for(let{line:f,rule:p,key:b}of[...O].sort((I,N)=>I.line-N.line)){let I=`line ${f} ${p}${b?` ${b}`:""}`;h.includes(I)||h.push(I)}k.push(`preview ${u}: at ${Qn(d,w)}, when the reader edited the page, the preview wrote your natural HTML as the kit's markup: ${h.join(", ")}`),k.push(...O.filter(f=>f.note).map(({line:f,rule:p,note:b})=>` line ${f}, ${p}: ${b}`))}return k.push(" re-read the file before editing it (those lines are the file's as you had left it)"),k}import{todoRef as Vn}from"../browser/shared/workspace-query.mjs";var qn=(l,i)=>l.length===i.length&&l.every((w,u)=>w===i[u]);function Xe(l,i,w,u){let k=Re(i),d=Ee(w,{at:!0}),O=null,h=f=>(O??=pe(w).units).find(p=>p.elStart===f)??null;return u.map(f=>{let p=Vn(f?.ref);if(!p||p.slug!==l||typeof f.done!="boolean")return{reason:"ref"};let b=p.block?d.find(N=>N.block===p.block)??null:null;if(b&&b.text!==p.text)return{reason:"changed"};if(!b){let N=d.filter($=>$.text===p.text&&qn($.path,p.path));if(p.version===k)b=N.find($=>$.nth===p.nth)??null;else{if(N.length>1)return{reason:"ambiguous"};b=N[0]??null}}if(!b)return{reason:"changed"};let I=h(b.at);return I?{unit:I,done:b.done,want:f.done}:{reason:"locked"}})}function tn(l,i){let w=new Map,u=i.map(f=>{if(!f.unit)return!1;let p=w.has(f.unit.id)?w.get(f.unit.id):f.done;return w.set(f.unit.id,f.want),p!==f.want}),k=new Map;for(let f of i)f.unit&&w.get(f.unit.id)!==f.done&&k.set(f.unit.id,f);if(k.size===0)return{commit:null,changed:u};let d=[],O=[],h=new Map;for(let[f,p]of k){let b=`todo${d.length}`,I=p.unit.blockId?{key:b,id:p.unit.blockId}:{key:b,open:f,hash:de(l,p.unit)};d.push({key:b,unit:I,attribute:"data-checked",value:w.get(f)?"":null}),O.push(I),h.set(f,b)}return{commit:{units:d,touch:O,keys:h},changed:u}}import{EMPTY_STYLE as dr,emptyWordsScript as mr,showEmpty as pr}from"../browser/editor/components/placeholder.mjs";import{TOKENS as wr}from"../browser/editor/page/look.mjs";import{MARGIN_STYLE as hr,earlyMarginScript as yr}from"../browser/editor/page/margin.mjs";var Vt=/^[a-f0-9]{16}$/,Xt=2*1024*1024,gr=sr,en=50,nn=/^\d{8}T\d{6}Z-[a-f0-9]{16}\.html$/,kr=30,rn=3,on=200,ft="\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u7A0D\u540E\u518D\u540C\u6B65",br="\u8FD9\u6B21\u7684\u4FEE\u6539\u592A\u5927\uFF0C\u4E00\u6B21\u5B58\u4E0D\u4E0B",$r=250,lt=Symbol("again"),xr="/__gallery/edit/src/editor/page/editor.mjs",Sr=l=>new Promise(i=>setTimeout(i,l));function vr(l,i=Xt){return new Promise((w,u)=>{let k=[],d=0;l.on("data",O=>{d+=O.length,d>i?k.length=0:k.push(O)}),l.on("end",()=>d>i?u(new Error("too-large")):w(Buffer.concat(k).toString("utf8"))),l.on("error",u)})}function Or(l){if(!l)return qt(16).toString("hex");let i=P.join(l,"token");try{let u=nr(i,"utf8").trim();if(/^[a-f0-9]{32}$/.test(u))return u}catch{}let w=qt(16).toString("hex");try{er(l,{recursive:!0,mode:448}),rr(i,w,{mode:384})}catch{}return w}function Uo({reportsDirectory:l=ir,stateDirectory:i=null,write:w=Ft,ids:u=!0,finish:k=p=>p,log:d=null,settling:O={},reviewing:h={},onChanges:f=()=>{}}={}){let p=Or(i),b=De(O),I=O.wait??Fe,N=new Map,$=async(t,n,e,o="reader")=>{let c=await w(t,n,e);if(c!==!1&&ur(P.basename(t))){let y=P.basename(P.dirname(t));b.wrote(y,n),N.set(y,{hash:_(n),by:o})}return c},Z=t=>lr(t,l),W=t=>Mt(Z(t)).html,L=new Map,H=i&&P.join(i,"snapshots"),F=Promise.resolve(),J=Promise.resolve(),Q=async(t,n,e,{by:o="time"}={})=>{let c=(await z.readdir(t)).filter(m=>n.test(m));if(c.length<=e)return;let y=o==="name"?c.sort():(await Promise.all(c.map(async m=>({name:m,time:(await z.stat(P.join(t,m))).mtimeMs})))).sort((m,j)=>m.time-j.time).map(({name:m})=>m);await Promise.all(y.slice(0,y.length-e).map(m=>z.rm(P.join(t,m),{force:!0})))},st=(t,n)=>{H&&(F=F.then(async()=>{let e=P.join(H,`${t}.html`),o=new Date;try{await z.utimes(e,o,o);return}catch{}await z.mkdir(H,{recursive:!0}),await Ft(e,n),await Q(H,/^[a-f0-9]{16}\.html$/,en)}).catch(()=>{}))},q=(t,n)=>{i&&(F=F.then(async()=>{let e=P.join(i,"history",t),o=_(n);if(await z.mkdir(e,{recursive:!0}),(await z.readdir(e)).filter(m=>nn.test(m)).sort().at(-1)?.endsWith(`-${o}.html`))return;let y=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Ft(P.join(e,`${y}-${o}.html`),n),await Q(e,nn,kr,{by:"name"})}).catch(()=>{}))},s=new Map,g=t=>i&&P.join(i,"receipts",t),r=(t,n,e,o)=>{for(s.set(`${t} ${n}`,{digest:e,answer:o});s.size>on*4;)s.delete(s.keys().next().value);let c=g(t);c&&(F=F.then(async()=>{await z.mkdir(c,{recursive:!0}),await Ft(P.join(c,`${n}.json`),JSON.stringify({digest:e,answer:o})),await Q(c,{test:y=>y.endsWith(".json")&&Qt.test(y.slice(0,-5))},on)}).catch(()=>{}))},a=async(t,n)=>{let e=s.get(`${t} ${n}`);if(e)return e;let o=g(t);if(!o)return null;await F;try{let c=JSON.parse(await z.readFile(P.join(o,`${n}.json`),"utf8"));return typeof c?.digest=="string"&&c.answer?.ok?c:null}catch{return null}},S=new Map,v=(t,n)=>{let e=new Date().toISOString();if(!i)return void S.set(t,[...S.get(t)??[],{time:e,changes:n}].slice(-20));F=F.then(()=>Ve({stateDirectory:i,reportsDirectory:l,slug:t,time:e,changes:n})).catch(()=>{})},D=async t=>{if(!i){let n=S.get(t)??[];return S.delete(t),n}return await F,qe({stateDirectory:i,reportsDirectory:l,slug:t})},T=(t,n)=>{for(L.delete(t),L.set(t,n);L.size>en;)L.delete(L.keys().next().value);st(t,n)},x=async t=>{if(L.has(t))return L.get(t);if(!H||!Vt.test(t))return null;await F;let n=await z.readFile(P.join(H,`${t}.html`),"utf8").catch(()=>null);return n===null||_(n)!==t?null:(T(t,n),n)},A=new Map,M=t=>{let n=A.get(t);if(n)return n;let e=Se(t,{finish:k});for(A.set(t,e);A.size>8;)A.delete(A.keys().next().value);return e},ot=P.join(P.resolve(l),".gallery","pages"),B=Be({...h,stateDirectory:i,shown:t=>M(t).text,folderOf:Z,log:d,isPage:t=>P.resolve(Z(t)).startsWith(ot+P.sep)}),nt=(t,n)=>n.then(e=>{e&&f(t)},e=>d?.(`${t}: the Agent's changes not kept (${e.message})`));async function Dt(t,n=void 0){if(typeof t!="string"||!rt.test(t))return null;let e=W(t),o=n!==void 0?n:await z.readFile(e,"utf8").catch(()=>null);if(o===null)return null;let{text:c,changes:y}=M(o);return{file:e,source:o,text:c,version:_(c),changes:y}}async function it(t){if(typeof t!="string"||!rt.test(t))return{source:null,held:!1,signs:[],wait:0,own:!1};let n=W(t),e=await z.readFile(n,"utf8").catch(()=>null),o=(await z.stat(n).catch(()=>null))?.mtimeMs??0;return{source:e,...b.judge(t,{source:e,mtime:o})}}async function kt(t,n=Date.now()+I){for(;;){let e=await it(t);if(!e.held||Date.now()>=n)return e;await Sr(Math.max(0,Math.min($r,n-Date.now())))}}async function Pt(t,{wait:n=I}={}){let e=await kt(t,Date.now()+n),o=await Dt(t,e.held&&e.taken!==void 0?e.taken:e.source);return o&&{...o,held:e.held===!0}}function an(t,n,{editor:e=xr,kitTags:o=()=>[]}={}){let{html:c,map:y}=ye(n);T(y.version,n);let m=le(l),j=ue(m).map(({assets:Y,...X})=>({...X,kit:o(Y)})),E=`<script type="application/json" id="doc-edit-map" data-doc-dev>${JSON.stringify({slug:t,token:p,...y,components:j,hidden:m.settings.hidden}).replace(/</g,"\\u003c")}</script>
8
+ <script data-doc-dev>document.currentScript.remove(); import(${JSON.stringify(e)});</script>`,U=`<style data-doc-dev>.doc-display { display: none; }</style>
9
+ <style data-doc-dev data-ge-palette>${wr}</style>
10
+ <style data-doc-dev>${dr}</style>
11
+ <script data-doc-dev>${mr()}</script>
12
+ <script data-doc-dev>document.currentScript.remove(); document.documentElement.setAttribute("data-ge-order", "file");</script>
13
+ <style data-doc-dev data-ge-margin-style>${hr}</style>
14
+ <script data-doc-dev>document.currentScript.remove(); ${yr(t,{notes:tr(P.join(Z(t),or))})}</script>`;return{html:pr(c),snippet:E,head:U}}let sn=t=>T(_(t),t);async function ut(t,n=Xt){if(t.method!=="POST")return{error:[405,{ok:!1,reason:"method"}]};let e=t.headers.host??"",o=t.socket.localPort;if(e!==`127.0.0.1:${o}`&&e!==`localhost:${o}`)return{error:[403,{ok:!1,reason:"host"}]};if(t.headers.origin!==`http://${e}`)return{error:[403,{ok:!1,reason:"origin"}]};if(t.headers["x-gallery-token"]!==p)return{error:[403,{ok:!1,reason:"token"}]};if(!/^application\/json\b/i.test(t.headers["content-type"]??""))return{error:[415,{ok:!1,reason:"type"}]};try{return{body:JSON.parse(await vr(t,n))}}catch(c){return{error:c.message==="too-large"?[413,{ok:!1,reason:"body",message:br}]:[400,{ok:!1,reason:"body"}]}}}async function Jt(t,n){let{slug:e,opening:o,known:c=null,texts:y=[],units:m=[],touch:j=[],pageIds:R=null,request:E=null,agent:U=!1}=t;if(typeof e!="string"||!rt.test(e)||![y,m,j].every(Array.isArray))return[400,{ok:!1,reason:"body"}];if(E!==null&&(typeof E!="string"||!Qt.test(E)))return[400,{ok:!1,reason:"body"}];let Y=E===null?null:_(JSON.stringify([o??null,y,m,j])),X=await te(t);if(X)return X;let G=et=>(E!==null&&r(e,E,Y,et),[200,et]),K=W(e),tt=typeof o=="string"&&Vt.test(o)?await x(o):null,V=et=>Xn("sha256",p).update(`${e}
15
+ ${et}`).digest("hex").slice(0,32);for(let et=1;;et++){let{source:at,held:Tt}=await it(e);if(at===null)return[404,{ok:!1,reason:"missing"}];if(Tt)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];nt(e,B.look(e,at));let{text:vt,changes:Zt}=M(at),ae=[],Et=ke({current:vt,opening:tt,texts:y,units:m,touch:j,ids:u?()=>{let Rt=typeof u=="function"?u():Ct();return ae.push(Rt),Rt}:!1,seal:V,pageIds:R}),{title:se,icon:ie,...ce}=Et,mt=Et.text===vt?vt:k(Et.text);mt!==Et.text&&(ce.version=_(mt));let fe={...ce,foreign:typeof c=="string"&&_(vt)!==c};if(mt===vt)return G({ok:!0,...fe,wrote:!1,notes:[]});if(q(e,at),!await $(K,mt,{expect:at},U===!0?"agent":"reader")){if(et===rn)return[409,{ok:!1,reason:"busy",message:ft}];continue}q(e,mt),nt(e,B.wrote(e,mt,Rt=>{let Sn=0;return Ae(Rt,{opening:tt,texts:y,units:m,touch:j,pageIds:R,seal:V,ids:u?()=>ae[Sn++]??(typeof u=="function"?u():Ct()):!1})},{reader:U!==!0})),Zt.length&&(d&&d(Ht(K,Zt).join(`
16
+ `)),v(e,Zt));let xn=[...se?await At(P.dirname(K),se):[],...ie!==void 0?await _t(P.dirname(K),ie):[]];return G({ok:!0,...fe,wrote:!0,notes:xn})}}async function cn(t,n){return typeof t!="string"||!rt.test(t)?[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}]:!Array.isArray(n)||n.length===0||n.length>fr?[400,{ok:!1,reason:"body"}]:Lt({slug:t},async(e,o)=>{let{source:c,held:y}=await it(t);if(c===null)return[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}];if(y)return Date.now()<o?lt:[409,{ok:!1,reason:"busy",message:ft}];let{text:m}=M(c),j=Xe(t,c,m,n),{commit:R,changed:E}=tn(m,j),U=j.map((V,et)=>V.reason?{ok:!1,reason:V.reason}:{ok:!0,changed:E[et],block:V.unit.blockId??null});if(!R)return[200,{ok:!0,results:U,wrote:!1}];let Y=_(m);T(Y,m);let X=await Jt({slug:t,opening:Y,units:R.units,touch:R.touch},o);if(X===lt)return lt;let[G,K]=X;if(!K.ok)return[G,K];let tt=new Map((K.units??[]).map(V=>[V.key,V]));return[200,{ok:!0,wrote:K.wrote===!0,results:U.map((V,et)=>{if(!V.ok)return V;let at=R.keys.get(j[et].unit.id);if(at===void 0)return V;let Tt=tt.get(at);return Tt?.status!=="applied"?{ok:!1,reason:Tt?.reason==="ambiguous"?"ambiguous":"changed"}:{...V,block:K.ids?.[at]??V.block}})}]})}async function te({slug:t,opening:n,texts:e=[],units:o=[],touch:c=[],request:y=null}){if(typeof t!="string"||!rt.test(t)||typeof y!="string"||!Qt.test(y)||![e,o,c].every(Array.isArray))return null;let m=await a(t,y);return m?m.digest===_(JSON.stringify([n??null,e,o,c]))?[200,{...m.answer,again:!0}]:[409,{ok:!1,reason:"request",message:"\u540C\u4E00\u6B21\u4FDD\u5B58\u7684\u5185\u5BB9\u4E0D\u4E00\u81F4"}]:null}async function fn(t,n){let{slug:e,opening:o,texts:c=[],units:y=[],instances:m=[],pageIds:j=null}=t;if(typeof e!="string"||!rt.test(e)||!Array.isArray(c)||!Array.isArray(y)||!Array.isArray(m))return[400,{ok:!1,reason:"body"}];let{source:R,held:E}=await it(e);if(E)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];let U=await Dt(e,R);if(U===null)return[404,{ok:!1,reason:"missing"}];let{text:Y,version:X}=U,G=typeof o=="string"&&Vt.test(o)?await x(o):null;return[200,{ok:!0,version:X,reverted:xe({current:Y,opening:G,texts:c,pageIds:j}),units:be({current:Y,units:y}),parts:$e({current:Y,instances:m,pageIds:j})}]}let ln=600*1e3,bt=new Map;async function ee(t,n){let e=Z(t),o=null;try{o=JSON.parse(await z.readFile(Mt(e).json,"utf8"))}catch{}let{title:c,icon:y}=Oe(n,o);c&&typeof o?.title=="string"&&o.title!==c.to&&await At(e,{from:o.title,to:c.to,synced:!0}),y&&!y.missing&&await _t(e,y.to)}async function un(t,n){let{slug:e,action:o,stamp:c=null,undo:y=null}=t;if(typeof e!="string"||!rt.test(e)||!["accept","revert","undo"].includes(o))return[400,{ok:!1,reason:"body"}];let m=W(e),{source:j,held:R}=await it(e);if(j===null)return[404,{ok:!1,reason:"missing"}];if(R)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];if(o==="undo"){for(let[K,tt]of bt)Date.now()-tt.at>ln&&bt.delete(K);let G=typeof y=="string"?bt.get(y):null;return!G||G.slug!==e?[404,{ok:!1,reason:"gone",message:"\u64A4\u9500\u5DF2\u7ECF\u8FC7\u671F"}]:j!==G.after?[409,{ok:!1,reason:"moved-on",message:"\u64A4\u56DE\u4E4B\u540E\u6587\u6863\u53C8\u6539\u8FC7\u4E86\uFF0C\u6CA1\u6CD5\u64A4\u9500"}]:(q(e,j),await $(m,G.before,{expect:j})?(q(e,G.before),bt.delete(y),await ee(e,G.before),await B.restore(e,G.saved),await B.wrote(e,G.before),f(e),[200,{ok:!0,version:_(M(G.before).text)}]):[409,{ok:!1,reason:"busy",message:ft}])}await B.look(e,j);let E=await B.snapshot(e),U=E?.state?.base?`${E.state.since}|${E.state.writes}`:null;if(U===null)return[200,{ok:!0,none:!0}];if(U!==c)return[409,{ok:!1,reason:"changed",message:"Agent \u521A\u521A\u53C8\u6539\u4E86\u6587\u6863\uFF0C\u518D\u770B\u4E00\u773C"}];if(o==="accept")return await B.clear(e),f(e),[200,{ok:!0}];let Y=E.base;if(q(e,j),!await $(m,Y,{expect:j}))return[409,{ok:!1,reason:"busy",message:ft}];q(e,Y),await ee(e,Y);let X=qt(8).toString("hex");return bt.set(X,{slug:e,before:j,after:Y,saved:E,at:Date.now()}),await B.clear(e),await B.wrote(e,Y),f(e),[200,{ok:!0,version:_(M(Y).text),undo:X}]}async function dn(t,n){let e=await ut(t);if(e.error)return C(n,...e.error);let o=e.body??{};try{if(o.action!=="read")return C(n,...await Lt(o,un));if(typeof o.slug!="string"||!rt.test(o.slug))return C(n,400,{ok:!1,reason:"body"});let c=await Pt(o.slug,{wait:0});return c===null?C(n,404,{ok:!1,reason:"missing"}):C(n,200,{ok:!0,...await B.read(o.slug,c.source)})}catch(c){return C(n,500,{ok:!1,reason:"write",message:c.message})}}async function At(t,{from:n,to:e,synced:o}){let c=["\u6807\u9898\u5DF2\u66F4\u65B0",...o?[]:["\u5355\u72EC\u6253\u5F00\u6216\u5BFC\u51FA\u65F6\u7684\u9875\u9762\u540D\u79F0\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"]],y=Mt(t).json,m=await z.readFile(y,"utf8").catch(()=>""),j=null;try{j=JSON.parse(m)}catch{}if(j?.title!==n)return[...c,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"];let R=new RegExp(`("title"\\s*:\\s*)${JSON.stringify(n).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),E=R.test(m)?m.replace(R,(U,Y)=>Y+JSON.stringify(e)):`${JSON.stringify({...j,title:e},null,2)}
17
+ `;try{await $(y,E)}catch(U){return d?.(`${P.basename(y)}'s title was not written (${U.code??U.message}): ${y}`),[...c,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u6CA1\u80FD\u8DDF\u7740\u6539"]}return c}async function _t(t,n){let e=Mt(t).json,o=null;try{o=JSON.parse(await z.readFile(e,"utf8"))}catch{}if(!o||typeof o!="object")return d?.(`${P.basename(e)} could not be read, so its icon was not written: ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"];if((o.icon??null)===n)return[];let{icon:c,...y}=o,m=n===null?y:{...y,icon:n};try{await $(e,`${JSON.stringify(m,null,2)}
18
+ `)}catch(j){return d?.(`${P.basename(e)}'s icon was not written (${j.code??j.message}): ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"]}return[]}async function mn(t,n){let e=typeof n=="string"?n.replace(/\s+/g," ").trim():"";if(!e)return{ok:!1,reason:"title",message:"\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A"};let o=W(t),c=await z.readFile(o,"utf8").catch(()=>null);if(c===null)return{ok:!1,reason:"missing"};nt(t,B.look(t,c));let y=me(c),m=we(y).find(E=>E.kind==="title");if(!m)return{ok:!1,reason:"no-title",message:"\u8FD9\u4EFD\u6587\u6863\u6CA1\u6709\u6807\u9898"};let j=ar(e),R=ge({current:y,edits:[{id:m.id,parts:[{keep:!0,html:j}]}],ids:u});return R.ok?R.text!==c&&!await $(o,R.text,{expect:c})?{ok:!1,reason:"changed-again"}:(R.text!==c&&nt(t,B.wrote(t,R.text,E=>Ne(E,j))),{ok:!0,title:e,notes:R.title?await At(P.dirname(o),R.title):[]}):{ok:!1,reason:"conflict"}}let $t=t=>(n,e)=>{let o=J.then(()=>t(n));return J=o.catch(()=>{}),o.then(([c,y])=>C(e,c,y),c=>C(e,500,{ok:!1,reason:"write",message:c.message}))},ne=(t,{early:n=null}={})=>async(e,o)=>{let c=await ut(e);if(c.error)return C(o,...c.error);let y=c.body??{};try{let m=n&&await n(y);return m?C(o,...m):C(o,...await Lt(y,t))}catch(m){return C(o,500,{ok:!1,reason:"write",message:m.message})}};async function Lt(t,n){let e=Date.now()+I;for(;;){await kt(t.slug,e);let o=J.then(()=>n(t,e));J=o.catch(()=>{});let c=await o;if(c!==lt)return c}}async function Ut(t,{reader:n=!1}={}){if(typeof t!="string"||!rt.test(t))return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};let e=Z(t),{html:o,json:c}=Mt(e);for(let y=1;;y++){let{source:m,held:j}=n?await it(t):{source:await z.readFile(o,"utf8").catch(()=>null),held:!1};if(m===null)return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};if(j)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};nt(t,B.look(t,m));let R=null;try{R=JSON.parse(await z.readFile(c,"utf8"))}catch{}let{text:E,changes:U,added:Y,given:X,repeated:G,title:K,icon:tt}=ve(m,{finish:k,next:typeof u=="function"?u:void 0,metadata:R});if(E!==m){if(q(t,m),!await $(o,E,{expect:m},n?"reader":"agent")){if(y===rn)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};continue}q(t,E),nt(t,B.wrote(t,E)),n&&U.length&&(d&&d(Ht(o,U).join(`
19
+ `)),v(t,U))}return K&&typeof R?.title=="string"&&R.title!==K.to&&await At(e,{from:R.title,to:K.to,synced:K.page}),tt&&!tt.missing&&await _t(e,tt.to),{ok:!0,changes:E===m?[]:U,added:E===m?0:Y,given:E===m?[]:X,repeated:G,written:E!==m,title:K,icon:tt}}}let pn=async(t,{reader:n=!1}={})=>{n&&await kt(t);let e=J.then(()=>Ut(t,{reader:n}));return J=e.catch(()=>{}),e};async function Wt(t){let n=await ut(t);if(n.error)return{refused:n.error};let{slug:e,workspace:o}=n.body??{};return typeof e!="string"||!rt.test(e)||typeof o!="string"?{refused:[400,{ok:!1,reason:"body"}]}:cr(o,l)?{slug:e}:{refused:[409,{ok:!1,reason:"elsewhere",message:"\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863"}]}}async function wn(t,n){try{let e=J.then(async()=>{let{slug:y,refused:m}=await Wt(t);if(m)return{answer:m};let j=await Ut(y);return{slug:j.ok?y:null,answer:[j.ok?200:j.reason==="missing"?404:409,j]}});J=e.catch(()=>{});let{slug:o,answer:c}=await e;return o&&await Yt(o),C(n,...c)}catch(e){return C(n,500,{ok:!1,reason:"write",message:e.message})}}async function hn(t){let{slug:n,refused:e}=await Wt(t);return e||(await Yt(n),[200,{ok:!0}])}async function re(t){let{source:n}=await kt(t),{ended:e,moved:o}=await B.endDraft(t,n);return o&&f(t),e}async function yn(t){let{slug:n,refused:e}=await Wt(t);return e||[200,{ok:!0,ended:await re(n)}]}let dt=Te({reportsDirectory:l}),xt=Ue({reportsDirectory:l,read:t=>Pt(t,{wait:0}),write:$,dropped:(t,n)=>{let e=n.map(ze);d&&d(Kt(P.join(Z(t),"annotations.json"),{items:e}).join(`
20
+ `)),i&&(F=F.then(()=>Ge({stateDirectory:i,reportsDirectory:l,slug:t,time:new Date().toISOString(),items:e})).catch(()=>{}))}}),oe=Promise.resolve(),Bt=t=>{let n=oe.then(t);return oe=n.catch(()=>{}),n},gn=t=>(n,e)=>Bt(()=>t(n)).then(([o,c])=>C(e,o,c),o=>C(e,500,{ok:!1,reason:"write",message:o.message})),kn=300,St=new Map;async function Yt(t){let n=St.get(t);n&&(clearTimeout(n.timer),St.delete(t));let e=Bt(()=>xt.afterWrite(t));n&&e.then(n.resolve,n.reject),await e.catch(o=>d?.(`${t}: annotations not checked: ${o.message}`)),await F}let bn=t=>{let n=t.headers.host??"",e=t.socket.localPort;return n!==`127.0.0.1:${e}`&&n!==`localhost:${e}`?[403,{ok:!1,reason:"host"}]:t.headers["x-gallery-token"]!==p?[403,{ok:!1,reason:"token"}]:null};async function $n(t){if(t.method==="GET"){let e=bn(t);if(e)return e;let o=new URL(t.url??"/","http://localhost").searchParams;return o.get("as")==="copy"?xt.copy(o.get("slug")):xt.list(o.get("slug"))}let n=await ut(t);return n.error??xt.change(n.body)}let Nt=(t,n=Xt)=>async e=>{let o=await ut(e,n);return o.error??t(o.body)};return{token:p,preview:an,opened:sn,check:ut,upload:$t(Nt(dt.upload,gr)),addEmoji:$t(Nt(dt.addEmoji)),unfurl:$t(Nt(dt.unfurl)),annotations:gn($n),checkAnnotations(t){let n=St.get(t);return n||(n={timer:0},n.done=new Promise((e,o)=>Object.assign(n,{resolve:e,reject:o})),St.set(t,n)),clearTimeout(n.timer),n.timer=setTimeout(()=>{St.delete(t),Bt(()=>xt.afterWrite(t)).then(n.resolve,n.reject)},kn),n.done},frameable:$t(Nt(dt.frameable)),listEmojis:dt.listEmojis,readEmoji:dt.readEmoji,respond:$t,keepVersion:q,renameReport:mn,read:Dt,settled:it,writerOf:(t,n)=>typeof n=="string"&&N.get(t)?.hash===_(n)?N.get(t).by:null,whenTaken:kt,readTaken:Pt,takeRewrites:D,handIn:pn,handInReport:Ut,handInRequest:wn,settleRequest:(t,n)=>hn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),settleNotes:Yt,roundRequest:(t,n)=>yn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),beginRound:re,commit:ne(Jt,{early:te}),handleCommit:Jt,setTodos:cn,reverted:ne(fn),changes:dn,noteTaken:(t,n)=>B.look(t,n),forgetChanges:t=>B.forget(t),stored:async()=>{await B.idle(),await F}}}export{Vr as a,qr as b,qe as c,oo as d,vn as e,On as f,jn as g,Uo as h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{e as p}from"./chunk-6RGJOMJP.mjs";import{f as b}from"./chunk-AUZGSZJH.mjs";import{k as d}from"./chunk-6QXGZM36.mjs";import{g as k}from"./chunk-CY2FNNAB.mjs";import v from"node:fs/promises";import h from"node:path";import{editStateDirectory as m,reportsDirectory as f}from"../browser/shared/paths.mjs";import{findPreviewServer as $}from"../browser/shared/preview-server.mjs";import{documentDirectory as S,documentFiles as g,isDocumentSource as j}from"../browser/shared/workspace.mjs";var u=e=>h.resolve(e),D=e=>h.basename(g(h.dirname(e)).json),N={busy:"it kept changing while it was being written (an Agent writing it?); nothing written. Run the export again.",timeout:"the workspace's Gallery server did not answer in 30s; nothing written. Run the export again."};async function w(e,n,o="hand-in",l=3e4){let t=`127.0.0.1:${e.port}`,s;try{s=await fetch(`http://${t}/__gallery/edit/${o}`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${t}`,"X-Gallery-Token":e.token},body:JSON.stringify({slug:n,workspace:f}),signal:AbortSignal.timeout(l)})}catch(a){return a.name==="TimeoutError"?{ok:!1,reason:"timeout"}:null}let i=await s.json().catch(()=>null);return typeof i?.ok!="boolean"||["elsewhere","token","host","origin"].includes(i.reason)?null:i}async function P(e){let n=await $({reportsDirectory:f}),o=null,l=[],t=new Map,s=[];for(let i of e){let{html:a,json:c}=g(S(i,f)),r=n?await w(n,i):null;if(r===null&&(o??=p({reportsDirectory:f,stateDirectory:m,finish:d}),r=await o.handIn(i),r.ok&&await o.settleNotes(i)),!r.ok){r.reason!=="missing"&&t.set(i,[`${u(a)} was not handed in: ${N[r.reason]??r.message??r.reason}`]);continue}if(r.repeated?.length){t.set(i,b(r.repeated));continue}s.push(...L(a,r)),r.written&&(r.changes.length&&s.push(...k(a,r.changes,{reread:!1})),r.added&&s.push(...T(a,r.given,r.added)),l.push(u(a))),O(r)&&l.push(u(c))}return{written:l,failures:t,lines:s}}async function _(e){let n=await $({reportsDirectory:f});if(n){for(let o of e)if(await w(n,o,"settle")===null)return}}async function C(e,{wait:n=3e4}={}){try{let o=await $({reportsDirectory:f}),l=o?await w(o,e,"round",n):null;return l!==null?l.ok?l.ended===!0:null:await p({reportsDirectory:f,stateDirectory:m,finish:d}).beginRound(e)}catch{return null}}async function H(e){try{let n=p({reportsDirectory:f,stateDirectory:m,finish:d}),{html:o}=g(S(e,f));await n.noteTaken(e,await v.readFile(o,"utf8"))}catch{}}var O=({title:e=null,icon:n=null})=>!!(e&&typeof e.from=="string"&&e.from!==e.to||n&&!n.missing),x=10;function T(e,n,o=n?.length??0,{pending:l=!1}={}){let t=`${o} block${o===1?"":"s"}`;if(l){let i=[`ids ${u(e)}: ${t} without an id yet: the export gives ${o===1?"it":"each"} one`];return o>x?i:[...i,...n.map(({line:a,tag:c})=>` line ${a} ${c}`)]}let s=[`ids ${u(e)}: ${t} given an id`];return!n||o>x?s:[...s,...n.map(({line:i,tag:a,id:c})=>` line ${i} ${a} \u2192 ${c}`)]}function L(e,{title:n=null,icon:o=null}={},{pending:l=!1}={}){let t=u(h.dirname(e)),s=D(e),i=(c,r,y)=>l?`${c} not ${r} yet (${y}): the export writes ${c.includes(" and ")?"them":"it"}`:`${c} written ${r}: ${y}`,a=[];if(n){let c=[...n.page?["<title>"]:[],...typeof n.from=="string"&&n.from!==n.to?[`${s}'s title`]:[]];c.length&&a.push(`title ${t}: ${i(c.join(" and "),"as its h1 says it",JSON.stringify(n.to))}`)}return o?.missing?a.push(`icon ${t}: ${s} has the icon ${JSON.stringify(o.from)} and the page's header none: write it there (<div class="doc-icon">\u2026</div> before the h1) or take "icon" out of ${s} (the export leaves ${s}'s as it is)`):o&&a.push(`icon ${t}: ${i(`${s}'s icon`,"as its header has it",o.to===null?"none":JSON.stringify(o.to))}`),a}function K(e,{by:n="this export"}={}){let o=e.length===1,l=[...e.filter(t=>j(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the kit's markup, block ids`),...e.filter(t=>/^(doc|report)\.json$/.test(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the title or icon said above`)];return`Re-read ${e.join(", ")} before editing ${o?"it":"them"}: ${n} wrote ${o?"it":"them"} (${l.join("; ")}).`}export{P as a,_ as b,C as c,H as d,T as e,L as f,K as g};
2
+ import{h as p}from"./chunk-OJKMINIU.mjs";import{g as k}from"./chunk-SXHBYZST.mjs";import{g as b}from"./chunk-HMYTM3GT.mjs";import{k as d}from"./chunk-SX4LJYT6.mjs";import v from"node:fs/promises";import h from"node:path";import{editStateDirectory as m,reportsDirectory as f}from"../browser/shared/paths.mjs";import{findPreviewServer as $}from"../browser/shared/preview-server.mjs";import{documentDirectory as S,documentFiles as g,isDocumentSource as j}from"../browser/shared/workspace.mjs";var u=e=>h.resolve(e),D=e=>h.basename(g(h.dirname(e)).json),N={busy:"it kept changing while it was being written (an Agent writing it?); nothing written. Run the export again.",timeout:"the workspace's Gallery server did not answer in 30s; nothing written. Run the export again."};async function w(e,n,o="hand-in",l=3e4){let t=`127.0.0.1:${e.port}`,s;try{s=await fetch(`http://${t}/__gallery/edit/${o}`,{method:"POST",headers:{"Content-Type":"application/json",Origin:`http://${t}`,"X-Gallery-Token":e.token},body:JSON.stringify({slug:n,workspace:f}),signal:AbortSignal.timeout(l)})}catch(a){return a.name==="TimeoutError"?{ok:!1,reason:"timeout"}:null}let i=await s.json().catch(()=>null);return typeof i?.ok!="boolean"||["elsewhere","token","host","origin"].includes(i.reason)?null:i}async function P(e){let n=await $({reportsDirectory:f}),o=null,l=[],t=new Map,s=[];for(let i of e){let{html:a,json:c}=g(S(i,f)),r=n?await w(n,i):null;if(r===null&&(o??=p({reportsDirectory:f,stateDirectory:m,finish:d}),r=await o.handIn(i),r.ok&&await o.settleNotes(i)),!r.ok){r.reason!=="missing"&&t.set(i,[`${u(a)} was not handed in: ${N[r.reason]??r.message??r.reason}`]);continue}if(r.repeated?.length){t.set(i,b(r.repeated));continue}s.push(...L(a,r)),r.written&&(r.changes.length&&s.push(...k(a,r.changes,{reread:!1})),r.added&&s.push(...T(a,r.given,r.added)),l.push(u(a))),O(r)&&l.push(u(c))}return{written:l,failures:t,lines:s}}async function _(e){let n=await $({reportsDirectory:f});if(n){for(let o of e)if(await w(n,o,"settle")===null)return}}async function C(e,{wait:n=3e4}={}){try{let o=await $({reportsDirectory:f}),l=o?await w(o,e,"round",n):null;return l!==null?l.ok?l.ended===!0:null:await p({reportsDirectory:f,stateDirectory:m,finish:d}).beginRound(e)}catch{return null}}async function H(e){try{let n=p({reportsDirectory:f,stateDirectory:m,finish:d}),{html:o}=g(S(e,f));await n.noteTaken(e,await v.readFile(o,"utf8"))}catch{}}var O=({title:e=null,icon:n=null})=>!!(e&&typeof e.from=="string"&&e.from!==e.to||n&&!n.missing),x=10;function T(e,n,o=n?.length??0,{pending:l=!1}={}){let t=`${o} block${o===1?"":"s"}`;if(l){let i=[`ids ${u(e)}: ${t} without an id yet: the export gives ${o===1?"it":"each"} one`];return o>x?i:[...i,...n.map(({line:a,tag:c})=>` line ${a} ${c}`)]}let s=[`ids ${u(e)}: ${t} given an id`];return!n||o>x?s:[...s,...n.map(({line:i,tag:a,id:c})=>` line ${i} ${a} \u2192 ${c}`)]}function L(e,{title:n=null,icon:o=null}={},{pending:l=!1}={}){let t=u(h.dirname(e)),s=D(e),i=(c,r,y)=>l?`${c} not ${r} yet (${y}): the export writes ${c.includes(" and ")?"them":"it"}`:`${c} written ${r}: ${y}`,a=[];if(n){let c=[...n.page?["<title>"]:[],...typeof n.from=="string"&&n.from!==n.to?[`${s}'s title`]:[]];c.length&&a.push(`title ${t}: ${i(c.join(" and "),"as its h1 says it",JSON.stringify(n.to))}`)}return o?.missing?a.push(`icon ${t}: ${s} has the icon ${JSON.stringify(o.from)} and the page's header none: write it there (<div class="doc-icon">\u2026</div> before the h1) or take "icon" out of ${s} (the export leaves ${s}'s as it is)`):o&&a.push(`icon ${t}: ${i(`${s}'s icon`,"as its header has it",o.to===null?"none":JSON.stringify(o.to))}`),a}function K(e,{by:n="this export"}={}){let o=e.length===1,l=[...e.filter(t=>j(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the kit's markup, block ids`),...e.filter(t=>/^(doc|report)\.json$/.test(h.basename(t))).map(t=>h.basename(t)).filter((t,s,i)=>i.indexOf(t)===s).map(t=>`${t}: the title or icon said above`)];return`Re-read ${e.join(", ")} before editing ${o?"it":"them"}: ${n} wrote ${o?"it":"them"} (${l.join("; ")}).`}export{P as a,_ as b,C as c,H as d,T as e,L as f,K as g};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as i,l as C}from"./chunk-6QXGZM36.mjs";import{a as g,c as w}from"./chunk-HYMEEXKN.mjs";import{d as j,k as A,l as S}from"./chunk-W4VKN3GF.mjs";import f from"node:path";import{attr as P,hasClass as z,walk as D}from"../browser/shared/html-tree.mjs";import{projectRoot as F,sdkDirectory as O,typeRoots as Y}from"../browser/shared/paths.mjs";var H=new Set(["application/ecmascript","application/javascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript"]);function y(t,{diffs:s=!1,tree:r=g(t)}={}){let n=[];return D(r,a=>{if(a.tagName!=="script"||P(a,"src")!==void 0)return;let o=(P(a,"type")||"").trim().toLowerCase(),l=s&&o==="application/json"&&a.parentNode?.tagName?a.parentNode:null,e=l&&z(l,"doc-diff")?"__declaredDiff(":void 0;if(!e&&o&&o!=="module"&&!H.has(o))return;let{startTag:c,endTag:p}=a.sourceCodeLocation??{};c&&n.push({start:c.endOffset,end:p?.startOffset??t.length,module:o==="module",...e?{call:e}:{}})},{inTemplates:!1}),n}function L(t,s,r=[]){let n=[],a=0,o="",l=e=>e.replace(/[^\r\n]/g," ");for(let{start:e,end:c,call:p}of s){let u=o+l(t.slice(a+o.length,e));if(p){let h=V(u,p,o.length);if(h===null){r.push(e);continue}u=h}n.push(u,t.slice(e,c)),a=c,o=p?");":""}return n.push(o+l(t.slice(a+o.length)),`
2
+ import{a as i,l as C}from"./chunk-SX4LJYT6.mjs";import{a as g,c as w}from"./chunk-HYMEEXKN.mjs";import{g as j,o as A,p as S}from"./chunk-FWNRPMCJ.mjs";import f from"node:path";import{attr as P,hasClass as z,walk as D}from"../browser/shared/html-tree.mjs";import{projectRoot as F,sdkDirectory as O,typeRoots as Y}from"../browser/shared/paths.mjs";var H=new Set(["application/ecmascript","application/javascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript"]);function y(t,{diffs:s=!1,tree:r=g(t)}={}){let n=[];return D(r,a=>{if(a.tagName!=="script"||P(a,"src")!==void 0)return;let o=(P(a,"type")||"").trim().toLowerCase(),l=s&&o==="application/json"&&a.parentNode?.tagName?a.parentNode:null,e=l&&z(l,"doc-diff")?"__declaredDiff(":void 0;if(!e&&o&&o!=="module"&&!H.has(o))return;let{startTag:c,endTag:p}=a.sourceCodeLocation??{};c&&n.push({start:c.endOffset,end:p?.startOffset??t.length,module:o==="module",...e?{call:e}:{}})},{inTemplates:!1}),n}function L(t,s,r=[]){let n=[],a=0,o="",l=e=>e.replace(/[^\r\n]/g," ");for(let{start:e,end:c,call:p}of s){let u=o+l(t.slice(a+o.length,e));if(p){let h=V(u,p,o.length);if(h===null){r.push(e);continue}u=h}n.push(u,t.slice(e,c)),a=c,o=p?");":""}return n.push(o+l(t.slice(a+o.length)),`
3
3
  export {};
4
4
  `),n.join("")}function V(t,s,r){let n=t.length;for(;;){let a=Math.max(t.lastIndexOf(`
5
5
  `,n-1)+1,r),o=t[n-1]==="\r"?n-1:n;if(o-a>=s.length)return t.slice(0,o-s.length)+s+t.slice(o);if(a<=r)return null;n=a-1}}function Pt(t,s=g(t)){return L(t,y(t,{tree:s}))}var q=new Set(["href","src","action","formaction"]),X=t=>{try{return decodeURIComponent(t)}catch{return t}};function Z(t,s){let r=y(t,{tree:s}).map(({start:n,end:a})=>({code:t.slice(n,a),start:n,where:"the document's script"}));return D(s,n=>{for(let{name:a,value:o}of n.attrs){let l=n.sourceCodeLocation?.attrs?.[a]?.startLine??n.sourceCodeLocation?.startLine,e=q.has(a)?o.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""):"";/^on[a-z]+$/.test(a)?r.push({code:o,line:l,where:`the ${a} attribute of <${n.tagName}>`}):/^javascript:/i.test(e)&&r.push({code:X(e.slice(11)),line:l,where:`the javascript: address of <${n.tagName} ${a}>`})}},{inTemplates:!1}),r}var R=new Set(["fetch","XMLHttpRequest","WebSocket","EventSource","sendBeacon","import"]),E=new Set(["window","globalThis","self"]),Q=t=>i.isIdentifier(t)?t.text==="navigator":i.isPropertyAccessExpression(t)&&t.name.text==="navigator"&&i.isIdentifier(t.expression)&&E.has(t.expression.text);function I(t){let{initializer:s}=i.walkUpBindingElementsAndPatterns(t);return!!s&&i.isIdentifier(s)&&E.has(s.text)}function tt(t){let s=t.parent;return i.isPropertyAccessExpression(s)&&s.name===t?i.isIdentifier(s.expression)&&E.has(s.expression.text):i.isBindingElement(s)&&s.propertyName===t?I(s):!((i.isPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isPropertyDeclaration(s)||i.isGetAccessorDeclaration(s)||i.isSetAccessorDeclaration(s))&&s.name===t)}function et(t,s){return i.isIdentifier(t)&&s.has(t.text)&&tt(t)?{name:t.text,reference:i.isPropertyAccessExpression(t.parent)&&t.parent.name===t?t.parent:t}:i.isElementAccessExpression(t)&&i.isIdentifier(t.expression)&&E.has(t.expression.text)&&i.isStringLiteralLike(t.argumentExpression)&&s.has(t.argumentExpression.text)?{name:t.argumentExpression.text,reference:t}:i.isPropertyAccessExpression(t)&&s.has(t.name.text)&&t.name.text==="sendBeacon"&&Q(t.expression)?{name:"sendBeacon",reference:t}:s.has("import")&&i.isCallExpression(t)&&t.expression.kind===i.SyntaxKind.ImportKeyword?{name:"import",reference:t.expression}:null}function st(t,s){let r=new Map,n=(e,c)=>{let p=e.parent;for(;p&&!c(p);)p=p.parent;return p??t},a=e=>i.isFunctionLike(e)||i.isBlock(e)||i.isCaseBlock(e)||i.isForStatement(e)||i.isForInStatement(e)||i.isForOfStatement(e),o=e=>i.isFunctionExpression(e)||i.isClassExpression(e)?e:i.isFunctionDeclaration(e)||i.isClassDeclaration(e)?n(e,a):i.isCatchClause(e.parent)?e.parent:n(e,i.getCombinedNodeFlags(e)&i.NodeFlags.BlockScoped?a:i.isFunctionLike),l=e=>{(i.isParameter(e)||i.isVariableDeclaration(e)||i.isBindingElement(e)||i.isFunctionDeclaration(e)||i.isClassDeclaration(e)||i.isFunctionExpression(e)||i.isClassExpression(e))&&e.name&&i.isIdentifier(e.name)&&s.has(e.name.text)&&!(i.isBindingElement(e)&&I(e))&&r.set(e.name.text,[...r.get(e.name.text)??[],o(e)]),i.forEachChild(e,l)};return l(t),r}function rt(t,s=[]){for(let r=t;r;r=r.parent)if(s.includes(r))return!0;return!1}function Nt(t,s,{tree:r=g(t)}={}){let n=[];for(let{code:a,start:o,line:l,where:e}of Z(t,r))for(let{name:c,how:p,at:u}of k(a,s))n.push({name:c,how:p,line:l??w(t,o+u),where:e});return n.sort((a,o)=>a.line-o.line)}function k(t,s){if(![...s].some(l=>t.includes(l)))return[];let r=[],n=i.createSourceFile("code.js",t,i.ScriptTarget.Latest,!0,i.ScriptKind.JS),a=st(n,s),o=l=>{let e=et(l,s),c=e?.reference.parent;if(e&&!i.isTypeOfExpression(c)&&!(i.isIdentifier(e.reference)&&rt(l,a.get(e.name)))){let p=(i.isCallExpression(c)||i.isNewExpression(c))&&c.expression===e.reference?i.isNewExpression(c)?"new":"call":"use";r.push({name:e.name,how:p,at:l.getStart(n)})}i.forEachChild(l,o)};return o(n),r}var nt=new Set([2304,2552]),it=new Set([2300,2451,2448,2449,2450]),M=t=>nt.has(t)||it.has(t)||t>=1e3&&t<2e3;function at(t,s,r){if(!t.file||r.has(t)||M(t.code))return!1;let n=t.start??-1;return s.some(a=>!a.call&&a.start<=n&&n<a.end)}var ot=(t,s)=>/\bNumberValue\b/.test(t)||/\bd3\.(?:min|max|extent)\(/.test(s)?"; here d3 reads values of no type as strings: give the data its shape once with JSDoc, /** @type {Array<{ label: string, value: number }>} */ const rows = data;, and d3.min or d3.max may give undefined (?? 0)":"";function B(t){let s={allowJs:!0,checkJs:!0,noEmit:!0,allowUmdGlobalAccess:!0,strict:!0,noImplicitAny:!1,target:i.ScriptTarget.ES2022,module:i.ModuleKind.ESNext,moduleResolution:i.ModuleResolutionKind.Bundler,lib:["lib.es2022.d.ts","lib.dom.d.ts","lib.dom.iterable.d.ts"],types:["d3"],typeRoots:Y,skipLibCheck:!1},r=i.createCompilerHost(s),n=r.readFile.bind(r),a=r.fileExists.bind(r);return r.readFile=o=>t.get(f.resolve(o))??n(o),r.fileExists=o=>t.has(f.resolve(o))||a(o),i.createProgram([f.join(O,"index.d.ts"),...t.keys()],s,r)}var ct=/\bDoc[A-Z]\w*/,lt=(t,s)=>ct.test(s)||(t.relatedInformation??[]).some(({file:r})=>r&&f.resolve(r.fileName).startsWith(O+f.sep)),N={katex:"katex","katex-auto-render":"renderMathInElement"};function Dt(t,{assets:s=[]}={}){let r=f.join(F,"reports","__package__","kit.js"),n=t.replace(/^([ \t]*)(?:<!--|-->)/gm,"$1//"),a=s.filter(c=>Object.hasOwn(N,c)).map(c=>`declare const ${N[c]}: any;
@@ -0,0 +1,4 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as u}from"./chunk-UMHUSOPJ.mjs";import l from"node:fs/promises";import p from"node:path";import{escapeMarkup as g}from"../browser/shared/escape.mjs";import{sha256 as b}from"../browser/shared/files.mjs";import{reportsDirectory as E,starterDirectory as y}from"../browser/shared/paths.mjs";import{listReportSlugs as T,slugPattern as S}from"../browser/shared/reports.mjs";import{documentDirectory as N,documentFiles as $,layoutOf as O,slugTaken as P}from"../browser/shared/workspace.mjs";async function j(t,c){if(!S.test(t))throw new Error(`A document's folder name must be lowercase kebab-case: ${t}`);let n=N(t,c),{html:r,json:i}=$(n),[m,o]=[p.basename(r),p.basename(i)],e,f;try{[e,f]=await Promise.all([l.readFile(r),l.readFile(i,"utf8")])}catch(s){if(s.code!=="ENOENT")throw s;let h=await l.stat(n).then(()=>!0,()=>!1);throw new Error(h?`${n} needs both ${m} and ${o}.`:`${n} does not exist.`)}let a;try{a=JSON.parse(f)}catch(s){throw new Error(`${o} is not valid JSON: ${s.message}`)}if(typeof a.title!="string")throw new Error(`${o} is missing a title.`);for(let s of["description","type"])if(typeof a[s]!="string"||a[s].trim()==="")throw new Error(`${o} is missing a non-empty ${s}.`);if(a.source!==void 0&&typeof a.source!="string")throw new Error(`${o} source must be a string when given.`);return{slug:t,directory:n,htmlPath:r,metadataPath:i,html:e.toString("utf8"),fileSha256:b(e),metadata:a}}async function z(t=[],{directory:c=E,prepare:n=null}={}){let r=t.length>0?[...new Set(t)]:await T(c);if(r.length===0)throw new Error(`No documents in ${p.resolve(c)} yet: gallery new <slug> "<title>" makes one.`);let i=[],m=new Map;for(let o of r)try{let e=await j(o,c);n&&([e.written,e.html]=[u(e.html),n(e)]),i.push(e)}catch(e){m.set(o,[e.message])}return{reports:i,failures:m}}var v=/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,F=/\n[ \t]*<!-- Starter content:[^\n]*-->\n[ \t]*<section\b[^>]*\sdata-doc-placeholder\b[\s\S]*?<\/section>/;async function M(t,c,n,{directory:r=E,blank:i=!1,lang:m=null,page:o=!1}={}){if(!S.test(t))throw new Error("Slug must be lowercase kebab-case.");if(P(t,r))throw Object.assign(new Error(`"${t}" is taken in ${p.resolve(r)}`),{code:"EEXIST"});let e=o?O(r).preferencesPage:p.resolve(r),f=p.join(e,t),{html:a,metadata:s}=await R(t,c,n,{blank:i,lang:m});await l.mkdir(e,{recursive:!0}),await l.mkdir(f,{recursive:!1});let h=$(f);return await Promise.all([l.writeFile(h.html,a),l.writeFile(h.json,`${JSON.stringify(s,null,2)}
3
+ `)]),{slug:t,directory:f,metadata:s}}async function R(t,c,n,{blank:r=!1,lang:i=null}={}){let m=w=>g(w).replaceAll("'","&#39;"),[o,e]=await Promise.all([l.readFile(p.join(y,"doc.html"),"utf8"),l.readFile(p.join(y,"doc.json"),"utf8")]),f={...JSON.parse(e),title:c,description:n},a=r?o.replace(F,`
4
+ <p></p>`):o;if(r&&a===o)throw new Error("The starter's placeholder section was not found.");let s=typeof i=="string"&&v.test(i)?a.replace(/(<html\b[^>]*\slang=")[^"]*"/,(w,d)=>`${d}${i}"`):a,h={SLUG:t,TITLE:m(c)};return{html:s.replace(/__REPORT_(SLUG|TITLE)__/g,(w,d)=>h[d]),metadata:f}}export{z as a,M as b,R as c};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{$ as ha,A as I,B as J,C as K,D as L,E as M,F as N,G as O,H as P,I as Q,J as R,K as S,L as T,M as U,N as V,O as W,P as X,Q as Y,R as Z,S as _,T as $,U as aa,V as ba,W as ca,X as da,Y as ea,Z as fa,_ as ga,a as i,aa as ia,b as j,ba as ja,c as k,ca as ka,d as l,e as m,f as n,g as o,h as p,i as q,j as r,k as s,l as t,m as u,n as v,o as w,p as x,q as y,r as z,s as A,t as B,u as C,v as D,w as E,x as F,y as G,z as H}from"./chunk-VTKNEYT3.mjs";import"./chunk-342HXE3Q.mjs";import"./chunk-BPL64HGA.mjs";import"./chunk-OUUP3WKT.mjs";import"./chunk-PUOQ65NC.mjs";import{a,b,c,f as d,g as e,h as f,k as g,l as h}from"./chunk-6VTU6KEO.mjs";import"./chunk-OJKMINIU.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-6EZ7FNIK.mjs";import"./chunk-35NQ4PLQ.mjs";import"./chunk-V6RIYQZZ.mjs";import"./chunk-SXHBYZST.mjs";import"./chunk-4OZWXZE5.mjs";import"./chunk-HMYTM3GT.mjs";import"./chunk-OW5NWPOJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-SX4LJYT6.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-W3BGBJQW.mjs";import"./chunk-JVHHHGEA.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-N76HWBA3.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{_ as ADVICE,t as BLOCK_PICTURES,$ as CODE_SIDEWAYS,X as HAND_OVER,u as INK_MARGIN,i as KINDS,j as LEVELS,k as LOOKS,Y as LOOK_YOURSELF,W as MORE_PICTURES,M as MOSTLY_CHANGED,y as MOVED_PART,x as MOVED_WHOLE,w as NEIGHBOUR_EDGE,p as PICTURED_INFO,ca as SCROLLS,v as SCROLL_FRAMES,s as SCROLL_SLACK,ba as WARNED,l as WIDE,m as WIDTHS,f as adoptIdless,aa as adviceOf,e as baselineOf,L as baselineSaid,b as blocksOf,N as blocksToPicture,da as describeLooks,S as disclosuresSaid,g as exportBaselines,G as exportOf,ga as exportingFirst,Q as findingKey,q as findingLevel,O as inkOf,P as inventory,n as layoutNotesOf,o as levelOf,R as lookAt,J as missedWidths,V as morePictures,H as movedBlocks,z as movedClips,ha as namedBlocks,I as nextBaseline,ea as notPicturedLine,c as pageOf,r as picturedAt,T as picturesSaid,D as placeOf,h as previewBaseline,a as rankOf,d as readBaseline,ka as run,K as seenOf,C as sourceIndex,F as staleExport,Z as startFailure,E as timeOf,ia as unknownBlocks,ja as unknownBlocksSaid,U as unopenedSaid,A as urlName,fa as verdictOf,B as wordsOf};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{spawn as O}from"node:child_process";import{existsSync as I}from"node:fs";import C from"node:fs/promises";import _ from"node:os";import q from"node:path";import{APART as S}from"../browser/editor/components/registry.mjs";var N=6e4,x=600,B=["A4","A3","Letter","Legal","Tabloid"];function F(){if(process.env.GALLERY_BROWSER)return process.env.GALLERY_BROWSER;let{PROGRAMFILES:o="","PROGRAMFILES(X86)":e="",LOCALAPPDATA:r="",HOME:i=""}=process.env;return({win32:[`${o}\\Google\\Chrome\\Application\\chrome.exe`,`${e}\\Google\\Chrome\\Application\\chrome.exe`,`${r}\\Google\\Chrome\\Application\\chrome.exe`,`${e}\\Microsoft\\Edge\\Application\\msedge.exe`,`${o}\\Microsoft\\Edge\\Application\\msedge.exe`],darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Chromium.app/Contents/MacOS/Chromium",...i?[`${i}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,`${i}/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge`,`${i}/Applications/Chromium.app/Contents/MacOS/Chromium`]:[]],linux:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome","/usr/bin/microsoft-edge","/usr/bin/microsoft-edge-stable","/opt/microsoft/msedge/msedge","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"]}[process.platform]??[]).find(s=>s&&I(s))??null}var $=()=>process.getuid?.()===0?["--no-sandbox"]:[],te=()=>["--no-first-run","--no-default-browser-check","--disable-extensions","--hide-scrollbars","--lang=zh-CN",...$()];function oe(o,e,r=[]){let i=o.location()?.url??"";return!/^Failed to load resource|^Refused to |Content Security Policy/.test(o.text())&&(!i||i.startsWith(e)||r.includes(i))}var re=o=>o.evaluateOnNewDocument(()=>{globalThis.__qaViolations=[],document.addEventListener("securitypolicyviolation",e=>{globalThis.__qaViolations.push({url:e.blockedURI,directive:e.effectiveDirective||e.violatedDirective,source:e.sourceFile,line:e.lineNumber})})}),V=3e4,W=5e3;function ie(o,e=W){let r=0,i=new Promise(c=>{r=setTimeout(c,e)});return Promise.race([Promise.resolve(o).catch(()=>{}),i]).finally(()=>clearTimeout(r))}var E=o=>new Promise(e=>setTimeout(e,o).unref()),D=o=>String(o??"").replace(/\s+/g," ").trim(),M=o=>{let e=o.split(/\r?\n/).map(D).filter(Boolean).at(-1);return e?`: ${e.slice(0,200)}`:""};async function se({executablePath:o,args:e=[],attempts:r=2,start:i=H}){let c=[];for(let s=0;s<r;s+=1){let n=await C.mkdtemp(q.join(_.tmpdir(),"gallery-browser-")),t=()=>C.rm(n,{recursive:!0,force:!0,maxRetries:5,retryDelay:200}).catch(()=>{});try{let{browser:a,stop:l}=await i({executablePath:o,args:e,profile:n});return{browser:a,failures:c,close:async()=>{await l().catch(()=>{}),await t()}}}catch(a){c.push(D(a?.message??a)),await t()}}throw Object.assign(new Error(c.at(-1)??"the browser did not start"),{failures:c})}async function H({executablePath:o,args:e,profile:r,starting:i=V}){let{default:c}=await import("./chunk-ERLAIBOA.mjs"),s=await c.defaultArgs({headless:!0,userDataDir:r,args:[...e,"--remote-debugging-port=0"]}),n=process.platform!=="win32",t=O(o,s,{stdio:["ignore","ignore","pipe"],windowsHide:!0,detached:n}),a=!1;t.on("error",()=>a||=t.pid===void 0);let l=()=>a||t.exitCode!==null||t.signalCode!==null,u=new Promise(f=>t.once("exit",f)),m=()=>{if(!l())try{n?process.kill(-t.pid,"SIGKILL"):t.kill()}catch{try{t.kill("SIGKILL")}catch{}}};process.once("exit",m);let p="",d=new Promise((f,w)=>{let g=setTimeout(()=>w(new Error(`it said nothing of its DevTools port in ${i/1e3}s${M(p)}`)),i);t.stderr.setEncoding("utf8"),t.stderr.on("data",h=>{p=`${p}${h}`.slice(-4e3);let y=/DevTools listening on (ws:\/\/\S+)/.exec(p);y&&(clearTimeout(g),f(y[1]))}),t.once("error",h=>(clearTimeout(g),w(h))),t.once("exit",(h,y)=>(clearTimeout(g),w(new Error(`it stopped (${y??`exit ${h}`}) before it opened its DevTools port${M(p)}`))))}),A=async()=>{try{l()||await Promise.race([u,E(5e3)]),m(),l()||await Promise.race([u,E(3e3)])}finally{process.off("exit",m)}},v;try{let f=await d,w=0,g=new Promise((y,G)=>{w=setTimeout(()=>G(new Error(`it opened its DevTools port and did not answer in ${i/1e3}s`)),i)}),h=c.connect({browserWSEndpoint:f,defaultViewport:{width:800,height:600}});h.catch(()=>{}),v=await Promise.race([h,g]).finally(()=>clearTimeout(w))}catch(f){throw m(),await A(),f}return{browser:v,stop:async()=>{await Promise.race([v.close().catch(()=>{}),E(5e3)]),await A()}}}var b=null,L=0,T=0;async function K(){let o=F();if(!o)throw Object.assign(new Error("\u6CA1\u6709\u627E\u5230 Chrome \u6216 Edge\uFF1A\u5BFC\u51FA PDF \u9700\u8981\u7535\u8111\u4E0A\u88C5\u6709\u5176\u4E2D\u4E00\u4E2A\u6D4F\u89C8\u5668"),{reason:"browser"});let{default:e}=await import("./chunk-ERLAIBOA.mjs");return e.launch({executablePath:o,headless:!0,args:["--no-first-run","--no-default-browser-check","--disable-extensions",...$()]})}async function R(o,e){clearTimeout(L),T+=1,b??=K().catch(i=>{throw b=null,i});let r=await(await b).newPage();try{return await r.emulateMediaFeatures([{name:"prefers-reduced-motion",value:"reduce"},{name:"prefers-color-scheme",value:"light"}]),await r.setViewport({width:1200,height:900}),await r.setContent(o,{waitUntil:"load",timeout:6e4}),await P(r,{changing:x}),await e(r)}finally{await r.close().catch(()=>{}),T-=1,T===0&&(L=setTimeout(async()=>{let i=b;b=null,(await i?.catch(()=>null))?.close().catch(()=>{})},N))}}async function P(o,{timeout:e=15e3,changing:r=e}={}){let i=[],c=(n,t,a=e)=>{t!==!0&&i.push(`${n} (${t===!1?`not in ${a/1e3}s`:t})`)},s=(n,t=e)=>o.evaluate(n,t).catch(a=>a.message);return c("the fonts loaded",await s(n=>Promise.race([Promise.resolve(document.fonts?.ready).then(()=>!0),new Promise(t=>setTimeout(()=>t(!1),n))]))),c("the kit's first drawing done (data-doc-drawn)",await s(n=>new Promise(t=>{let a=Date.now(),l=()=>{!globalThis.DocKit||document.documentElement.hasAttribute("data-doc-drawn")?(globalThis.DocCode?.colorAll?.(),t(!0)):Date.now()-a>n?t(!1):setTimeout(l,50)};l()}))),c("the page done changing",await s(n=>new Promise(t=>{let a=()=>[document.documentElement.scrollHeight,...[...document.querySelectorAll("[style]")].map(d=>d.getAttribute("style")),...[...document.adoptedStyleSheets??[]].flatMap(d=>[...d.cssRules].map(A=>A.cssText)),...[...document.querySelectorAll("svg, canvas")].map(d=>d.outerHTML.length),[...document.images].filter(d=>d.complete).length].join("|"),l=Date.now(),u=a(),m=0,p=()=>{let d=a();m=d===u?m+1:0,u=d,m>=3?t(!0):Date.now()-l>n?t(!1):setTimeout(p,100)};setTimeout(p,100)}),r),r),i}async function k(o){await o.evaluate(()=>{document.documentElement.setAttribute("data-doc-theme","light");for(let e of document.querySelectorAll("[data-doc-sheets]")){let r=e.querySelector(":scope > .doc-sheet-tabs");if(r){for(let i of r.querySelectorAll(":scope > .doc-sheet-tab")){let c=i.getAttribute("data-sheet-tab"),s=[...e.querySelectorAll(":scope > [data-doc-sheet]")].find(a=>a.getAttribute("data-doc-sheet")===c);if(!s)continue;s.hidden=!1,s.removeAttribute("aria-hidden"),s.style.setProperty("display","block","important");let n=r.cloneNode(!1);n.removeAttribute("id"),n.removeAttribute("role"),n.style.setProperty("break-after","avoid");let t=i.cloneNode(!0);t.removeAttribute("id"),t.setAttribute("aria-selected","true"),t.classList.add("is-active"),n.append(t),s.before(n)}r.style.setProperty("display","none","important")}}for(let e of document.querySelectorAll("details"))e.open=!0;window.dispatchEvent(new Event("resize"))}),await P(o,{changing:x})}var j={A4:793.7,A3:1122.5,Letter:816,Legal:816,Tabloid:1056},z=96;async function U(o,e){await o.emulateMediaType("print");let r=await o.evaluate(()=>Math.max(0,innerWidth-document.documentElement.clientWidth));await o.setViewport({width:Math.floor(e)+r,height:900}),await P(o,{changing:x})}function ne(o,{paper:e="A4",scale:r=1}={}){let i=B.includes(e)?e:"A4",c=Math.min(2,Math.max(.1,r));return R(o,async s=>(await k(s),await U(s,(j[i]-2*z)/c),Buffer.from(await s.pdf({format:i,scale:c,printBackground:!0,margin:{top:"1in",right:"1in",bottom:"1in",left:"1in"}}))))}function ae(o){return R(o,async e=>{await k(e);let r=e.viewport(),i=await e.$$("main figure.doc-figure"),c=[];for(let s of i){let n=0;try{n=await s.evaluate(async(t,a)=>{let l=[];for(let u=t.closest(a);u;u=u.parentElement.closest(a))l.unshift(u);for(let u of l)u.style.setProperty("height","auto"),u.style.setProperty("max-height","calc(100dvh - (2 * var(--doc-dialog-margin)))"),u.showModal();return await new Promise(u=>requestAnimationFrame(()=>requestAnimationFrame(u))),l.length?Math.ceil(t.getBoundingClientRect().height):0},S),n&&(await e.setViewport({...r,height:r.height+n}),await P(e,{changing:x})),await s.evaluate(t=>t.scrollIntoView({block:"center"})),c.push(Buffer.from(await s.screenshot({type:"png"})))}catch{c.push(null)}await s.evaluate((t,a)=>{for(let l=t.closest(a);l;l=l.parentElement.closest(a))l.close(),l.style.removeProperty("height"),l.style.removeProperty("max-height"),l.getAttribute("style")||l.removeAttribute("style")},S).catch(()=>{}),n&&await e.setViewport(r).catch(()=>{})}return c})}export{F as a,te as b,oe as c,re as d,W as e,ie as f,se as g,P as h,ne as i,ae as j};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{e as n,f as g}from"./chunk-5ZKJ3H4P.mjs";import{b as m,f as d}from"./chunk-NSKUTQ5J.mjs";import"./chunk-5L7RYZCL.mjs";import{spawn as P}from"node:child_process";import h from"node:fs/promises";import R from"node:path";import{projectRoot as v,release as k,reportsDirectory as t}from"../browser/shared/paths.mjs";import{answerOf as S,findPreviewServer as x,portIsFree as E,readAnnouncement as G}from"../browser/shared/preview-server.mjs";import{layoutOf as $}from"../browser/shared/workspace.mjs";var b=a=>new Promise(s=>setTimeout(s,a));async function O(a){let{positional:s,values:l}=d({values:["--port"],argv:a});if(s.length>0)throw new m(`gallery serve takes no arguments: ${s[0]}`);let o=l.has("--port")?Number(l.get("--port")):null;if(o!==null&&!(Number.isInteger(o)&&o>0&&o<65536))throw new m(`--port takes a port number: ${l.get("--port")}`);let i=await G({reportsDirectory:t}),f=i?await S(i,t,1e4):"no";f!=="no"&&(console.error(`This workspace's Gallery server runs already: ${n(i.port)} (pid ${i.pid}${f==="busy"?", not answering now":""}). gallery stop stops it; one server serves a workspace.`),process.exit(1));let r=null;if(o!==null)await E(o)||(console.error(`Port ${o} is taken: name another (--port), or leave it out for the first free one.`),process.exit(1)),r=o;else{for(let e of await g())if(await E(e)){r=e;break}r===null&&(console.error("No port from 4317 is free: name one (--port <n>)."),process.exit(1))}if(k){process.env.GALLERY_SERVER_KIND="cli";let{startProductionServer:e}=await import("./chunk-VPD2PS35.mjs");await e({port:r,kind:"cli"}),await h.writeFile($(t).lastPortFile,`${r}
3
- `).catch(()=>{}),console.log(`Gallery serves ${t} at ${n(r)} (Chrome or Edge). Ctrl+C stops it.`);return}let{writeSharedAssets:y}=await import("./chunk-VNV55RUA.mjs");await y();let c=P(process.execPath,[R.join(v,"node_modules","vite","bin","vite.js"),"--host","127.0.0.1","--port",String(r),"--strictPort"],{cwd:v,env:{...process.env,GALLERY_WORKSPACE:t,GALLERY_SERVER_KIND:"cli"},stdio:"inherit"});for(let e of["SIGINT","SIGTERM"])process.on(e,()=>c.kill(e));let w=new Promise(e=>c.once("exit",(u,p)=>e(u??(p?1:0))));for(;;){let e=await Promise.race([w.then(p=>({code:p})),b(300).then(()=>null)]);if(e&&process.exit(e.code),(await x({reportsDirectory:t,answering:!0,timeout:2e3}))?.pid===c.pid)break}await h.writeFile($(t).lastPortFile,`${r}
2
+ import{g as n,h as g}from"./chunk-NFMCP2HI.mjs";import{b as m,f as d}from"./chunk-4OZWXZE5.mjs";import"./chunk-5L7RYZCL.mjs";import{spawn as P}from"node:child_process";import h from"node:fs/promises";import R from"node:path";import{projectRoot as v,release as k,reportsDirectory as t}from"../browser/shared/paths.mjs";import{answerOf as S,findPreviewServer as x,portIsFree as E,readAnnouncement as G}from"../browser/shared/preview-server.mjs";import{layoutOf as $}from"../browser/shared/workspace.mjs";var b=a=>new Promise(s=>setTimeout(s,a));async function O(a){let{positional:s,values:l}=d({values:["--port"],argv:a});if(s.length>0)throw new m(`gallery serve takes no arguments: ${s[0]}`);let o=l.has("--port")?Number(l.get("--port")):null;if(o!==null&&!(Number.isInteger(o)&&o>0&&o<65536))throw new m(`--port takes a port number: ${l.get("--port")}`);let i=await G({reportsDirectory:t}),f=i?await S(i,t,1e4):"no";f!=="no"&&(console.error(`This workspace's Gallery server runs already: ${n(i.port)} (pid ${i.pid}${f==="busy"?", not answering now":""}). gallery stop stops it; one server serves a workspace.`),process.exit(1));let r=null;if(o!==null)await E(o)||(console.error(`Port ${o} is taken: name another (--port), or leave it out for the first free one.`),process.exit(1)),r=o;else{for(let e of await g())if(await E(e)){r=e;break}r===null&&(console.error("No port from 4317 is free: name one (--port <n>)."),process.exit(1))}if(k){process.env.GALLERY_SERVER_KIND="cli";let{startProductionServer:e}=await import("./chunk-BVEFGE4B.mjs");await e({port:r,kind:"cli"}),await h.writeFile($(t).lastPortFile,`${r}
3
+ `).catch(()=>{}),console.log(`Gallery serves ${t} at ${n(r)} (Chrome or Edge). Ctrl+C stops it.`);return}let{writeSharedAssets:y}=await import("./chunk-NG375ILQ.mjs");await y();let c=P(process.execPath,[R.join(v,"node_modules","vite","bin","vite.js"),"--host","127.0.0.1","--port",String(r),"--strictPort"],{cwd:v,env:{...process.env,GALLERY_WORKSPACE:t,GALLERY_SERVER_KIND:"cli"},stdio:"inherit"});for(let e of["SIGINT","SIGTERM"])process.on(e,()=>c.kill(e));let w=new Promise(e=>c.once("exit",(u,p)=>e(u??(p?1:0))));for(;;){let e=await Promise.race([w.then(p=>({code:p})),b(300).then(()=>null)]);if(e&&process.exit(e.code),(await x({reportsDirectory:t,answering:!0,timeout:2e3}))?.pid===c.pid)break}await h.writeFile($(t).lastPortFile,`${r}
4
4
  `).catch(()=>{}),console.log(`Gallery serves ${t} at ${n(r)} (Chrome or Edge). Ctrl+C stops it.`),process.exit(await w)}export{O as run};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as q,b as B}from"./chunk-IA4PSIMD.mjs";import{b as C}from"./chunk-ZTHICSSF.mjs";import x from"node:fs/promises";import W from"node:path";import{MENTION as L}from"../browser/shared/components/mention.mjs";import{writeAtomic as R}from"../browser/shared/files.mjs";import{reportLines as U}from"../browser/shared/search.mjs";import{countWords as Q}from"../browser/shared/words.mjs";import{FACT_KINDS as V,QUERY_KINDS as Y,SNAPSHOT_LIMITS as y,queryOptions as G}from"../browser/shared/workspace-query.mjs";import{documentDirectory as M,documentFiles as T,layoutOf as X,listDocumentSlugs as _,listTrash as Z}from"../browser/shared/workspace.mjs";var ut=d=>l=>d.readTaken(l,{wait:0}),z=({todos:d})=>{let l=new Map,g=c=>JSON.stringify([c.text,c.path]);for(let c of d)l.set(g(c),(l.get(g(c))??0)+1);return d.some(c=>!c.block&&l.get(g(c))>1)},tt=(d,l)=>({hash:B(d),words:Q(l),todos:q(l)});function et(d){let l=new Date(d);return l.setHours(0,0,0,0),l.setDate(l.getDate()-(l.getDay()+6)%7),l.getTime()}function mt({root:d,read:l,draw:g=u=>u,activity:c=null,now:I=()=>new Date}){let u=new Map,h=new Map,b=t=>x.stat(t).then(({mtimeMs:e})=>e,()=>null);async function J(t,e=null){let o=T(M(t,d)),[a,n]=await Promise.all([b(o.html),b(o.json)]);if(a===null)return null;let s=e??await l(t);if(!s)return null;let r={};try{r=JSON.parse(await x.readFile(o.json,"utf8"))??{}}catch{}let{title:i,icon:w}=r,f={slug:t,title:typeof i=="string"&&i.trim()?i:t,icon:typeof w=="string"&&w?w:null,edited:Math.round(a),...tt(s.source,s.text)};return u.set(t,{html:a,json:n,facts:f,held:s.held===!0}),h.has(t)||h.set(t,f),f}async function O(t){let e=u.get(t);if(e&&!e.held){let o=T(M(t,d)),[a,n]=await Promise.all([b(o.html),b(o.json)]);if(a===e.html&&n===e.json)return e.facts}return J(t)}async function S(){let t=await _(d);for(let e of u.keys())t.includes(e)||u.delete(e);for(let e of h.keys())t.includes(e)||h.delete(e);return(await Promise.all(t.map(e=>O(e).catch(()=>null)))).filter(Boolean)}let P={async todos({done:t,slugs:e,limit:o}){let a=(await S()).filter(s=>!e||e.includes(s.slug)).sort((s,r)=>r.edited-s.edited||s.slug.localeCompare(r.slug)),n=[];for(let{slug:s,title:r,todos:i,hash:w}of a)for(let f of i)if(!(t!==void 0&&f.done!==t)){if(n.length>=o)return n;n.push({ref:{slug:s,block:f.block,text:f.text,path:f.path,nth:f.nth,version:w},text:f.text,done:f.done,slug:s,title:r,path:f.path})}return n},async recent({limit:t}){return(await S()).sort((e,o)=>o.edited-e.edited||e.slug.localeCompare(o.slug)).slice(0,t).map(({slug:e,title:o,icon:a,edited:n})=>({slug:e,title:o,icon:a,edited:new Date(n).toISOString()}))},async stats(){let t=await S(),e=et(I()),o=t.flatMap(a=>a.todos);return{documents:t.length,todos:{done:o.filter(a=>a.done).length,total:o.length},words:t.reduce((a,n)=>a+n.words,0),editedThisWeek:t.filter(a=>a.edited>=e).length}},async activity({days:t}){return c?(await c.load(),await $,c.days(t)):[]},async table({slug:t,key:e,where:o,limit:a},{words:n=!1}={}){let s=await O(t).catch(()=>null),r=u.get(t);if(!s||!r)return k(404,"missing",`no document "${t}"`);if(r.tables??=new Map,!r.tables.has(e)){let m=await l(t);if(!m)return k(404,"missing",`no document "${t}"`);r.tables.set(e,C(m.text,e,t))}let i=r.tables.get(e);if(i.error==="missing")return k(404,"missing",`"${t}" holds no table whose frame carries data-doc-chart-source="${e}"`);if(i.error)return k(422,"missing",`the table "${e}" of "${t}" has merged cells, which no view reads: write each value in its own cell`);let w=Object.keys(o).filter(m=>!i.columns.includes(m));if(w.length>0)return k(400,"options",`table: the table "${e}" of "${t}" has no column ${w.map(m=>JSON.stringify(m)).join(", ")} (its columns: ${i.columns.map(m=>JSON.stringify(m)).join(", ")})`);let f=i.rows.filter(m=>Object.entries(o).every(([D,v])=>m.words[D]===v.replace(/\s+/g," ").trim()));return{columns:[...i.columns],rows:f.slice(0,a).map(({values:m,links:D,words:v})=>({values:{...m},links:D.map(K=>({...K})),...n?{words:{...v}}:{}})),total:f.length}}},k=(t,e,o)=>{throw Object.assign(new Error(o),{refusal:[t,{ok:!1,reason:e,message:o}]})},p=new Map,j=t=>W.join(X(d).gallery,"cache","workspace",`${t}.json`),A=async t=>{if(!p.has(t)){let e=[];try{let o=JSON.parse(await x.readFile(j(t),"utf8"));Array.isArray(o?.tables)&&(e=o.tables.filter(a=>typeof a=="string").slice(-y.tables))}catch{}p.has(t)||p.set(t,e)}return p.get(t)},N=Promise.resolve(),H=async(t,e)=>{let o=await A(t);if(o.at(-1)===e)return;let a=[...o.filter(n=>n!==e),e].slice(-y.tables);p.set(t,a),N=N.then(async()=>{await x.mkdir(W.dirname(j(t)),{recursive:!0}),await R(j(t),`${JSON.stringify({tables:p.get(t)})}
3
+ `)}).catch(()=>{})},F=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,$=Promise.resolve(),E={facts:O,all:S,async lines(t,e){let o=u.get(t);if(!await O(t))return null;let n=u.get(t);if(n!==o||!n.lines||n.lines.titles!==null&&n.lines.titles!==e){let s=await l(t);if(!s)return null;n.lines={titles:s.text.includes(L)?e:null,value:U(g(s.text,t))}}return n.lines.value},async query(t,e,{doc:o=null}={}){if(!Y.includes(t))return[400,{ok:!1,reason:"kind",message:`no kind "${t}": todos, recent, stats, activity or table`}];let{problem:a,options:n}=G(t,e);if(a)return[400,{ok:!1,reason:"options",message:`${t}: ${a}`}];let s;try{s=await P[t](n)}catch(r){if(r.refusal)return r.refusal;throw r}return t==="table"&&typeof o=="string"&&F.test(o)&&await H(o,`${n.slug}#${n.key}`),[200,{ok:!0,kind:t,data:s,at:new Date(I()).toISOString()}]},async snapshot(t){let e=async(n,s)=>{let[r,i]=await E.query(n,s);return r===200?i.data:null},o={todos:await e("todos",{limit:y.todos}),recent:await e("recent",{limit:y.recent}),stats:await e("stats"),activity:await e("activity",{days:y.activity})},a={};for(let n of F.test(t)?await A(t):[]){let[s,r]=n.split("#"),i=await P.table({slug:s,key:r,where:{},limit:y.rows},{words:!0}).catch(()=>null);i&&(a[n]=i)}return Object.keys(a).length>0&&(o.tables=a),Object.fromEntries(Object.entries(o).filter(([,n])=>n!==null))},stored:()=>N,async changed(t,{source:e=null,text:o=null,by:a="agent"}={}){let n=h.get(t)??u.get(t)?.facts??null;u.delete(t);let s=e===null?null:await J(t,{source:e,text:o??e}).catch(()=>null);s?h.set(t,s):h.delete(t);let r=new Set;if(!!n!=!!s)for(let i of["todos","recent","stats","table"])r.add(i);return n&&s&&n.hash!==s.hash&&r.add("table"),n&&s&&n.hash!==s.hash&&(z(n)||z(s))&&r.add("todos"),n&&s&&((n.title!==s.title||JSON.stringify(n.todos)!==JSON.stringify(s.todos))&&r.add("todos"),(n.title!==s.title||n.icon!==s.icon||n.edited!==s.edited)&&r.add("recent"),(n.words!==s.words||n.todos.length!==s.todos.length||n.todos.filter(i=>i.done).length!==s.todos.filter(i=>i.done).length||n.edited!==s.edited)&&r.add("stats")),!n&&s&&r.add("recent"),c&&s&&(await c.load(),await $,c.record(t,{hash:s.hash,words:s.words,mtime:s.edited,by:a})&&r.add("activity")),V.filter(i=>r.has(i))},start(){return c?($=(async()=>{await c.load();let t=await _(d),e=(await Promise.all(t.map(async a=>({slug:a,mtime:await b(T(M(a,d)).html)})))).filter(({mtime:a})=>a!==null),o=(await Z(d).catch(()=>[])).map(a=>a.slug);return c.catchUp(e.map(({slug:a,mtime:n})=>({slug:a,mtime:Math.round(n)})),O,{kept:o})})().catch(()=>0),$):Promise.resolve(0)},forget(t){u.delete(t),h.delete(t)}};return E}export{ut as a,mt as b};
@@ -0,0 +1,15 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as b}from"./chunk-UKSHDZZ6.mjs";import{c as L,d as F}from"./chunk-Q4UEPUWF.mjs";import{c as x,d as j,k as w}from"./chunk-4OZWXZE5.mjs";import"./chunk-5L7RYZCL.mjs";import l from"node:fs";import c from"node:path";import{pathToFileURL as K}from"node:url";import{projectRoot as p}from"../browser/shared/paths.mjs";import{sha256 as A}from"../browser/shared/files.mjs";var g=["SKILL.md","references/writing-html.md","references/building-blocks.md","references/block-script.md","references/pages-and-data.md","references/extensions.md","references/example-report.html","sdk","agents/openai.yaml"],u="## Before anything: the gallery command";function T(n){let[t,s]=n.split(/[.+-]/).map(Number);return{range:`^${n}`,takes:`${n} or a later ${t===0?`0.${s}`:t}.x`}}function N(n,t){let s=n.indexOf(`
3
+ ${u}
4
+ `);if(s<0)throw new Error(`SKILL.md has no section "${u}" (the version range of the command stands there)`);let e=n.indexOf(`
5
+ ## `,s+u.length+1),i=e<0?n.length:e,{range:r,takes:o}=T(t),a=n.slice(s,i).replace(new RegExp(L.source,"g"),F(t)).replace(/\^\d+\.\d+\.\d+(?:-[\w.]+)?/g,r).replace(/\b\d+\.\d+\.\d+(?:-[\w.]+)? or a later \d+(?:\.\d+)?\.x\b/g,o);return n.slice(0,s)+a+n.slice(i)}function y(n=p){let t=g.filter(r=>!l.existsSync(c.join(n,r)));if(t.length)return t.map(r=>`the skill takes ${r}, which is not there`);let s=E(g,n),e=r=>l.readFileSync(c.join(n,r),"utf8"),i=P(s,e).map(r=>`${r}, which the skill does not hold: link only what it holds`);for(let r of s.filter(o=>o.startsWith("sdk/")&&o.endsWith(".ts")))for(let[,o]of e(r).matchAll(/\bfrom\s+["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)/g))o&&(!o.startsWith("./")||o.includes("/../"))&&i.push(`${r} imports ${o}, outside sdk/: write the types it needs in sdk/`);return i}function R(n,{root:t=p,version:s=JSON.parse(l.readFileSync(c.join(t,"package.json"),"utf8")).version}={}){let e=y(t);if(e.length)throw new Error(`The skill cannot be made:
6
+ ${e.map(i=>` ${i}`).join(`
7
+ `)}`);l.rmSync(n,{recursive:!0,force:!0});for(let i of E(g,t)){let r=c.join(n,i);l.mkdirSync(c.dirname(r),{recursive:!0}),i==="SKILL.md"?l.writeFileSync(r,N(l.readFileSync(c.join(t,i),"utf8"),s)):l.copyFileSync(c.join(t,i),r)}return k(n)}function k(n,t=""){let s=[];for(let e of l.readdirSync(n,{withFileTypes:!0}).sort((i,r)=>i.name.localeCompare(r.name))){let i=t?`${t}/${e.name}`:e.name;e.isDirectory()?s.push(...k(c.join(n,e.name),i)):e.isFile()&&s.push(i)}return s}function E(n,t=p){return n.flatMap(s=>{let e=c.join(t,s);return l.existsSync(e)?l.statSync(e).isDirectory()?k(e,s):[s]:[]})}function v(n){let t=null;return n.split(`
8
+ `).map(s=>{let e=/^\s*(`{3,}|~{3,})(.*)$/.exec(s);return t?(e&&e[1][0]===t[0]&&e[1].length>=t.length&&!e[2].trim()&&(t=null),""):e&&!(e[1][0]==="`"&&e[2].includes("`"))?(t=e[1],""):s}).join(`
9
+ `)}function z(n){let t=v(n).replace(/(`+)(?!`)(?:(?!\n[ \t]*\n)[\s\S])*?[^`]\1(?!`)/g,e=>" ".repeat(e.length));return[...[...t.matchAll(/\]\(\s*(?:<([^<>\n]*)>|((?:[^\s()<>]|\([^\s()<>]*\))+))(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^()\n]*\)))?\s*\)/g)].map(e=>[e.index,e[1]??e[2]]),...[...t.matchAll(/^ {0,3}\[(?!\^)[^\]\n]+\]:[ \t]*(?:<([^<>\n]*)>|(\S+))/gm)].map(e=>[e.index,e[1]??e[2]]),...[...t.matchAll(/<(?:a|img)\s[^>]*?\b(?:href|src)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].map(e=>[e.index,e[1]??e[2]])].sort(([e],[i])=>e-i).map(([,e])=>e)}function C(n,t){if(/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(t))return null;let[,s,e=""]=/^([^?#]*)(?:\?[^#]*)?(?:#(.*))?$/s.exec(t),i=o=>{try{return decodeURIComponent(o)}catch{return o}};return{file:s?c.posix.normalize(c.posix.join(c.posix.dirname(n),i(s))).replace(/\/$/,""):n,anchor:i(e)}}function P(n,t){let s=new Set(n),e=new Set(n.flatMap(r=>r.split("/").slice(0,-1).map((o,a,f)=>f.slice(0,a+1).join("/")))),i=[];for(let r of n.filter(o=>/\.md$/i.test(o)))for(let o of z(t(r))){let a=C(r,o);!a||a.file===r||!s.has(a.file)&&!e.has(a.file)&&i.push(`${r} links ${o}`)}return i}function M(n,{root:t=p,version:s=JSON.parse(l.readFileSync(c.join(t,"package.json"),"utf8")).version}={}){let e=y(t);if(e.length)throw new Error(`The skill cannot be made:
10
+ ${e.map(m=>` ${m}`).join(`
11
+ `)}`);let i=c.join(n,"skill","gallery"),r=`gallery-skill-${s}.zip`,o=c.join(n,r);l.rmSync(c.join(n,"skill"),{recursive:!0,force:!0}),l.existsSync(c.join(n,"gallery","PACKAGE-MANIFEST.json"))&&l.rmSync(c.join(n,"gallery"),{recursive:!0,force:!0});for(let m of l.existsSync(n)?l.readdirSync(n):[])/^gallery-skill-.+\.zip(?:\.sha256)?$|^PACKAGE-MANIFEST\.json$/.test(m)&&l.rmSync(c.join(n,m),{force:!0});let a=R(i,{root:t,version:s}),f=a.map(m=>({name:`gallery/${m}`,data:l.readFileSync(c.join(i,m))})),h=b(f);l.writeFileSync(o,h);let S=A(h);l.writeFileSync(`${o}.sha256`,`${S} ${r}
12
+ `);let{range:$}=T(s),I={name:"gallery",version:s,archive:r,holds:"The Agent's documents (SKILL.md, references/writing-html.md, references/building-blocks.md, references/block-script.md, references/pages-and-data.md, references/extensions.md, the example references/example-report.html), the SDK's types (sdk/) and Codex's display metadata (agents/openai.yaml). The tools are the npm package @heycys/gallery, which SKILL.md has the Agent check for and install (with the user's consent); gallery skill install writes this same skill.",skillEntrypoint:"SKILL.md",requires:`@heycys/gallery@${$}`,files:f.map(({name:m,data:d})=>({path:m.slice(8),bytes:d.byteLength,sha256:A(d)}))};l.writeFileSync(c.join(n,"PACKAGE-MANIFEST.json"),`${JSON.stringify(I,null,2)}
13
+ `);let O=f.reduce((m,{data:d})=>m+d.byteLength,0);return{archive:o,skill:i,files:a,bytes:O,zipBytes:h.byteLength,sha256:S,range:$}}if(import.meta.url===K(process.argv[1]).href){let{positional:n}=await w(import.meta.url);n.length>0&&(console.error(j(x(import.meta.url),`Unknown argument: ${n[0]} (skill:package takes none: there is one skill).`)),process.exit(2));let t=y();t.length>0&&(console.error(`Not packaged:
14
+ ${t.map(e=>` ${e}`).join(`
15
+ `)}`),process.exit(1));let s=M(c.join(p,"release"));console.log(`Packaged ${s.archive} (${s.files.length} files, ${s.bytes.toLocaleString("en-US")} bytes; the ZIP ${s.zipBytes.toLocaleString("en-US")} bytes), for @heycys/gallery ${s.range}`),console.log(`The skill's folder: ${s.skill}`),console.log(`SHA-256 ${s.sha256}`)}export{u as BOOTSTRAP,g as SKILL_FILES,R as buildSkill,P as deadLinks,E as filesOf,C as linkTarget,z as linksOf,k as listFiles,M as packageSkill,y as skillProblems,T as skillRange,N as withRange,v as withoutSamples};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import r from"node:os";import l from"node:path";var t={claude:{name:"Claude Code",home:e=>e.CLAUDE_CONFIG_DIR||l.join(r.homedir(),".claude"),project:".claude"},codex:{name:"Codex",home:e=>e.CODEX_HOME||l.join(r.homedir(),".codex"),project:".codex"}};function d(e){let o=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e.replace(/^/,""));return o?/^name:\s*["']?([\w.-]+)["']?\s*$/m.exec(o[1])?.[1]??null:null}var c=/\bThis skill is Gallery (\d+\.\d+\.\d+(?:-[\w.]+)?)'s\b/,i=e=>`This skill is Gallery ${e}'s`,m=e=>c.exec(e)?.[1]??null;export{t as a,d as b,c,i as d,m as e};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{d as a,e as b,f as c,g as d}from"./chunk-N76HWBA3.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as commitEdits,c as revertedParts,d as revertedTexts,b as revertedUnits};
@@ -0,0 +1,16 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as je}from"./chunk-JEUK3ZO7.mjs";import{a as Te,b as Ne,c as Xe,d as Ze,g as Oe,h as et}from"./chunk-PUOQ65NC.mjs";import{g as Qe}from"./chunk-V6RIYQZZ.mjs";import{b as Se}from"./chunk-SXHBYZST.mjs";import{p as Ee}from"./chunk-HMYTM3GT.mjs";import{a as le}from"./chunk-HYMEEXKN.mjs";import{a as ve,f as Ye,p as ze}from"./chunk-FWNRPMCJ.mjs";import T from"node:fs/promises";import he from"node:os";import x from"node:path";import{pathToFileURL as Re}from"node:url";import{instancesOf as ot,isInstance as bt}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as $t,FALLBACK as xt,INSTANCE as de,SLOT as vt,SLOT_PART as tt}from"../browser/shared/components/installed.mjs";import{jsonIn as Et}from"../browser/shared/json-layout.mjs";import{QUERY_ROUTE as St}from"../browser/shared/workspace-query.mjs";import{documentDirectory as jt,documentFiles as Tt,layoutOf as it,listDocumentSlugs as Nt,PACKAGE_MANIFEST as Ot}from"../browser/shared/workspace.mjs";var At="in a browser, under the export's policy",ce=(e=null)=>e?`the instances in ${e}, in a browser under the export's policy`:"the workspace's documents",q="component-check",ae=[360,736,1024],Ae=["light","dark"],Lt=[1024,360],nt=1e4,rt=6e4,se=3e4,Dn=12e4,lt=2e3,Rt=3e3,Dt=60,Mn=15e3,Mt=2,Pt=8,Ct=se/2,_t=/^(?:wasm-)?eval$/,It=new Set(["TargetCloseError","ConnectionClosedError"]),Pn=e=>e.evaluateOnNewDocument(Ft,St);function Ft(e){let t=globalThis.fetch;if(typeof t!="function"||globalThis.__galleryQueries)return;let i={pending:new Map,count:0};globalThis.__galleryQueries=i,globalThis.fetch=function(r,n){let a=t.apply(this,arguments);try{let p=new URL(typeof r=="string"?r:r?.url??String(r),location.href);if(p.pathname===e){let u=++i.count,w=/\/__gallery\/components\/([a-z0-9-]+\/[a-z0-9-]+)\/kit\.js/.exec(new Error().stack??"");i.pending.set(u,{kind:p.searchParams.get("kind"),block:w?w[1]:null,at:Date.now()});let l=()=>{i.pending.delete(u)};Promise.resolve(a).then(l,l)}}catch{}return a}}var oe=e=>String(e?.message??e).split(`
3
+ `)[0],ct=(e,t)=>`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${e}</title></head><body><main class="doc-page" data-doc-id="${e}">${t}
4
+ </main></body></html>
5
+ `,Bt=({example:e,template:t})=>`<p>example.html</p>${e}
6
+ <hr><p>template.html</p>${t}`,Ht=e=>{for(let t=e.parentNode;t;t=t.parentNode)if(bt(t))return!0;return!1},dt=(e,t)=>ot(e,t).filter(i=>!Ht(i)),De=(e,t)=>dt(le(e),t).map(({sourceCodeLocation:{startLine:i,startOffset:r,endOffset:n}})=>({line:i,markup:e.slice(r,n)}));async function ht(e,t){let i=x.join(t,"components",...e.id.split("/"));for(let r of[Ot,"template.html",...e.files]){let n=ze(e,r);if(!n)continue;let a=await T.readFile(n);await T.mkdir(x.dirname(x.join(i,r)),{recursive:!0}),await T.writeFile(x.join(i,r),r==="kit.js"?`${a}
7
+ //# sourceURL=kit.js
8
+ `:a)}}async function Wt(e,{example:t,template:i},r){await ht(e,r);let n=x.join(r,q);await T.mkdir(n);let a=`${t}
9
+ `,p=Se(ct(q,Bt({example:t,template:i}))).text;await T.writeFile(x.join(n,"doc.html"),p),await T.writeFile(x.join(n,"doc.json"),JSON.stringify({title:q,description:q,type:"component"}));let w=await(await Ee({directory:r}))(q),l=x.join(r,"export.html");await T.writeFile(l,w);let f=a.split(`
10
+ `).length-1,s=De(p,e).map(({line:c})=>c>f?{file:"template.html",line:c-f}:{file:"example.html",line:c});return{html:w,file:l,places:s,source:p}}function qt({match:e,instance:t,slot:i,parts:r,boards:n}){if(!Object.entries(r).some(([l,{edit:f}])=>f==="data"&&!n.includes(l)))return[];let a=[...document.querySelectorAll(e)].filter(l=>!l.parentElement.closest(t)),p=l=>l.parentElement?.closest(`${t}, ${i}`)??null,u=l=>`<${l.localName}${l.classList.length?` class="${l.getAttribute("class")}"`:""}>`,w=l=>{let f=(l.textContent||l.getAttribute("aria-label")||l.getAttribute("placeholder")||l.getAttribute("title")||"").replace(/\s+/g," ").trim().slice(0,24);return`${u(l)}${f?` "${f}"`:""}`};return a.flatMap((l,f)=>{let s=[...l.querySelectorAll("button, input, select, textarea")].filter(c=>p(c)===l).filter(c=>{if(c.disabled||c.readOnly||c.type==="hidden")return!1;let h=c.getBoundingClientRect(),b=getComputedStyle(c);return h.width>0&&h.height>0&&b.visibility!=="hidden"&&b.display!=="none"});return s.length?[{at:f,what:s.slice(0,3).map(w).join(", "),counts:[s.length]}]:[]})}async function Gt({match:e,instance:t,slotPart:i,slotName:r,fallback:n,parts:a,boards:p,at:u,source:w,still:l,step:f,times:s,typed:c,typing:h}){let b=()=>[...document.querySelectorAll(e)].filter(o=>!o.parentElement.closest(t)),k=o=>new Promise(d=>setTimeout(d,o)),g=()=>new Promise(o=>{requestAnimationFrame(o),setTimeout(o,100)}),m=async o=>{await g(),await g();let d=o.outerHTML;for(let y=0,v=Date.now()+l;y<3;){if(Date.now()>v)return null;await k(f);let E=o.outerHTML;y=E===d?y+1:0,d=E}return d},_=o=>{let d=document.createElement("template");return d.innerHTML=o,d.content.firstElementChild},$=o=>`<${o.localName}${o.classList.length?` class="${o.getAttribute("class")}"`:""}>`,S=o=>o.nodeType===1?$(o):`the words "${o.data.trim().slice(0,40)}"`,B=o=>[...o.childNodes].filter(d=>d.nodeType===1||d.nodeType===3&&d.data.trim()),H=(o,d)=>["style","class"].includes(d)&&!o.getAttribute(d)?.trim()?null:o.getAttribute(d),D=(o,d)=>{for(let E of new Set([...o.getAttributeNames(),...d.getAttributeNames()]))if(H(o,E)!==H(d,E))return`${E} on ${$(d)}, ${JSON.stringify(H(o,E))} then ${JSON.stringify(H(d,E))}`;let[y,v]=[B(o),B(d)];for(let E=0;E<Math.max(y.length,v.length);E++){let[N,M]=[y[E],v[E]];if(!N||!M)return`${$(d)} ${N?`without ${S(N)}`:`with ${S(M)} more`}`;if(N.nodeType!==M.nodeType||N.localName!==M.localName||N.nodeType===3&&N.data.trim()!==M.data.trim())return`in ${$(d)}, ${S(N)} then ${S(M)}`;let I=N.nodeType===1?D(N,M):null;if(I)return I}return null},pe=o=>{let d=new Map;for(let y of o)d.set($(y),(d.get($(y))??0)+1);return d},Ce=()=>[...document.querySelectorAll("*")].filter(o=>!o.closest(t)),_e=o=>[...o.at(-1).keys()].filter(d=>o.length>2&&o.every((y,v)=>v===0||(y.get(d)??0)>(o[v-1].get(d)??0))),Ie=o=>o.parentElement?.closest(`${t}, ${i}`)??null,Fe=o=>[...o.querySelectorAll(i)].filter(d=>Ie(d)===o),G=o=>{let d=o.cloneNode(!0);return Fe(d).forEach(y=>y.replaceChildren()),d},Z=o=>Fe(o).map(d=>{let y=[];for(let v=d.parentElement;v&&v!==o;v=v.parentElement)y.unshift($(v));return{name:d.getAttribute(r),place:y.join(" > "),blocks:[...DocKit.dehydrate(d.cloneNode(!0)).children].map(v=>v.localName).join(" "),html:DocKit.dehydrate(d.cloneNode(!0)).outerHTML}}),ue=(o,d,y,{markup:v=!0}={})=>o.flatMap(({name:E,place:N,blocks:M,html:I})=>{let A=d.find(W=>W.name===E),X=A?A.place!==N?`moved the slot ${E} (${A.place?`in ${A.place}`:"straight in the instance"}, where the file has it ${N?`in ${N}`:"straight in the instance"})`:A.blocks!==M?`changed the blocks the slot ${E} holds (${M||"none"}, then ${A.blocks||"none"})`:v&&A.html!==I?`changed what the slot ${E} holds`:null:`took the slot ${E} off the instance`;return X?[{kind:"written-in",part:E,how:`${X}, ${y}`}]:[]}),Be=o=>d=>Ie(d)===o,we=(o,d=()=>!0)=>Object.entries(a).filter(([,{edit:y}])=>d(y)).flatMap(([y,v])=>[...o.querySelectorAll(v.at)].filter(Be(o)).map(E=>({name:y,node:E}))),ee=o=>we(o,d=>d==="text"),K=o=>Object.entries(a).filter(([,{edit:d}])=>d==="data").map(([d,y])=>({name:d,node:[...o.querySelectorAll(y.at)].find(Be(o))})).filter(({node:d})=>d),C=[],V=b()[u];if(!V)return[{kind:"gone"}];if(V.hasAttribute(n))return[{kind:"fallback"}];let fe=await m(V);if(fe===null)return[{kind:"moving"}];let ie=_(w),He=Z(V);C.push(...ue(Z(ie),He,"as it mounts",{markup:!1}));let me=ee(ie);ee(V).forEach(({name:o,node:d},y)=>{me[y]&&me[y].node.innerHTML!==d.innerHTML&&C.push({kind:"redrawn",part:o,how:`the file says ${JSON.stringify(me[y].node.textContent.trim())}, the page ${JSON.stringify(d.textContent.trim())}`})});let ge=DocKit.dehydrate(V.cloneNode(!0)),[We,qe]=[G(ie),G(ge)],ke=D(We,qe);if(ke){let o=we(qe),d=we(We).find(({node:y},v)=>o[v]&&D(y,o[v].node))?.name;C.push({kind:"left",what:ke,...d?{part:d}:{}})}let ft=K(ge);for(let[o,{name:d,node:y}]of K(ie).entries())!ke&&ft[o]?.node.innerHTML!==y.innerHTML&&C.push({kind:"data",part:d});let Q=[],ye=new MutationObserver(o=>Q.push(...o));ye.observe(document.documentElement,{subtree:!0,childList:!0,characterData:!0});let Ge=new Set,Ue=o=>{Q.push(...ye.takeRecords());for(let{name:d,node:y}of o)(!y.isConnected||Q.some(({target:v})=>y.contains(v)))&&Ge.add(d);Q.length=0},be=[fe],$e=[pe(Ce())],Je=o=>{be.push(o),$e.push(pe(Ce())),C.push(...ue(He,Z(j),"as it mounts again"))},j=ge,xe=ee(j);Q.length=0,V.replaceWith(j);let U=await m(j);if(Ue(xe),U!==null){Je(U);for(let o=0;o<s&&U!==null;o++){let d=j.cloneNode(!0);xe=ee(d),Q.length=0,j.replaceWith(d),j=d,U=await m(j),Ue(xe),U!==null&&Je(U)}}ye.disconnect(),U===null&&C.push({kind:"moving"});for(let o of Ge)C.push({kind:"redrawn",part:o,how:"a mount changes it"});let Ke=be.map(o=>pe(G(_(o)).querySelectorAll("*"))),Ve=_e(Ke);for(let o of Ve)C.push({kind:"piles",what:o,counts:Ke.map(d=>d.get(o)??0)});for(let o of _e($e))C.push({kind:"piles",what:o,outside:!0,counts:$e.map(d=>d.get(o)??0)});if(!Ve.length){let o=be.slice(1).map(d=>D(G(_(fe)),G(_(d)))).find(Boolean);o&&C.push({kind:"changed",what:o})}let re=U===null?[]:ee(j).filter(({node:o})=>o.textContent.trim()),mt=[...new Set([...new Map(re.map(o=>[o.name,o])).values(),...re])].slice(0,c),gt=Date.now()+h;for(let{node:o}of mt){if(Date.now()>gt)break;let d=document.createTreeWalker(o,NodeFilter.SHOW_TEXT).nextNode(),y=d.data;d.data=`${y}\u2026`;let v=re.map(({node:N})=>N.textContent);await m(j);let E=re.find(({node:N},M)=>!N.isConnected||N.textContent!==v[M]);if(E){C.push({kind:"redrawn",part:E.name,how:"a change of its words does not stand"});break}d.data=y,await m(j)}return U!==null&&K(j).length>0&&C.push(...await kt()),C;async function kt(){let o=[],d=null,y=!1,v="as it hears that it can write (the editable signal)",E=[],N=I=>{if(I.target!==j)return;let{parts:A,run:X}=I.detail,W=A.map(({part:O})=>O.innerHTML),P=A.map(({part:O})=>O.cloneNode(!0)),te=X(Object.fromEntries(A.map(({name:O},R)=>[O,P[R]]))),J=A.find(({part:O},R)=>O.innerHTML!==W[R]),Y=A.find(({part:O},R)=>P[R].cloneNode(!1).outerHTML!==O.cloneNode(!1).outerHTML);if(J&&A.forEach(({part:O},R)=>{O.innerHTML=W[R]}),!y){let O=J??Y??A.find((R,ne)=>P[ne].innerHTML!==W[ne]);O&&!E.some(R=>R.when===v)?E.push({kind:"unasked",part:O.name,when:v}):te&&!O&&I.preventDefault();return}J?d??=`it writes the part ${J.name} on the page, not the draft context.edit hands it, so the editor refuses the edit`:te&&Y&&(d??=`it changes the part ${Y.name}'s own tag or attributes, which are the file's: a change writes what a part holds, so the editor refuses the edit`),!(J||!te||Y)&&(A.forEach(({part:O},R)=>{o.push({part:O,before:W[R]}),O.replaceChildren(...P[R].childNodes)}),I.preventDefault())};document.addEventListener("doc-component-edit",N);try{return[...await M(),...E]}finally{document.removeEventListener("doc-component-edit",N)}async function M(){dispatchEvent(new Event("doc-editable")),await m(j),v="as it mounts";let I=j.cloneNode(!0);j.replaceWith(I),j=I;let A=await m(j);v="as it hears its part changed (the source signal)";let X=Z(j),W=DocKit.dehydrate(j.cloneNode(!0)),P=[];y=!0;try{if(!DocKit.example(j))return K(j).every(({name:F})=>p.includes(F))?[]:[{kind:"no-example"}]}catch(F){return[{kind:"example",what:`it throws: ${F?.message??F}`}]}finally{y=!1}let te=await m(j),J=DocKit.dehydrate(j.cloneNode(!0)),Y=Object.fromEntries(K(J).map(({name:F,node:z},yt)=>[F,z.innerHTML,K(W)[yt]?.node.innerHTML]).filter(([,F,z])=>F!==z));d?P.push({kind:"example",what:d}):o.length===0?P.push({kind:"example",what:"context.edit was not taken: it was not called, or it answered false, and the console says why"}):Object.keys(Y).length===0?P.push({kind:"example",what:"it changes nothing a part holds"}):P.push({kind:"wrote",parts:Y});for(let F of[W,J])for(let{node:z}of K(F))z.textContent="";let O=D(G(W),G(J));O&&P.push({kind:"example",what:`it changes what is no data part: ${O}`}),P.push(...ue(X,Z(j),"as its example makes its edit"));for(let{part:F,before:z}of o.reverse())F.innerHTML=z;let R=await m(j),ne=A!==null&&R!==null?D(G(_(A)),G(_(R))):null;return te===null||R===null?P.push({kind:"moving"}):ne&&!O&&P.push({kind:"undo",what:ne}),P}}}var Ut=e=>e.map(({name:t,removed:i,added:r,lines:n})=>`${t} (-${i} +${r} of its ${n} line${n===1?"":"s"})`).join(" and "),Jt="a write changes the lines it means and no others: a row moved by context.rows, which takes the blank before it along, JSON written back by context.editJSON and laid out in template.html and example.html as it writes it (block-script.md, Two examples)";function Le(e,t){try{return JSON.parse(e),Et(e,JSON.parse(t))===t}catch{return!1}}var Kt="it changes nothing a part holds";function Vt({kind:e,what:t,part:i,how:r,when:n,counts:a,outside:p,parts:u,back:w,line:l,json:f},s,{script:c}){let h=k=>({...s,what:k}),b=k=>({...s,what:k,note:!0});switch(e){case"wrote":return{...s,told:!0,what:`its example wrote ${Ut(u)}; the server took it${w?"; put back as an undo does, it shows what it showed":""}`};case"laid":return b(`its example's write lays the part ${i} out anew (${r}): ${Jt}${f?`; this write is context.editJSON's, and what the file held is laid out otherwise: lay ${i} out as it writes it`:""}`);case"drops":return{...b(`${t} listens for dragover and not for dragenter: a drop goes where both are cancelled, and the move that enters it asks dragenter alone, so that a release then (on a card's words, its padding) drops nothing: cancel dragenter as dragover is cancelled (preventDefault)`),file:"kit.js",line:l};case"controls":return{...b(`where nothing is written (this look is an export: context.canEdit() is false) the instance of ${s.file}${s.line?`:${s.line}`:""} still shows ${t}${a[0]>3?` and ${a[0]-3} more`:""}, enabled, and the block has a data part: a reader presses a control that writes to no effect, and the export says the block can be edited. Draw a control that writes only while context.canEdit(), and hide it by the hidden attribute (the kit holds [hidden] over any display the style gives it) or disable it; ignore this for a control that only changes what a reader looks at, a filter or a tab, which an export keeps. Compare 1024-light.png with edit-1024-light.png: the second is what a reader who can edit sees`),file:"kit.js",line:void 0};case"gone":return h("the page does not hold this instance");case"fallback":return h(c?"its component failed or never started: the instance shows what it holds, read-only":"the instance shows as one of no custom block");case"moving":return b("what it shows never holds still (an animation?), so its mounts could not be compared");case"redrawn":return h(`the component redraws its text part ${i}: ${r}. A text part is the file's, what the user types in: read it, and draw in what is the component's`);case"left":return h(`dehydrate does not leave it as the file has it, so a copy of the view would hold what the kit made of it: ${t}. ${i?`That stands in its part ${i}, which is the file's: read a part, and draw in what is the component's`:"Name what it draws in the manifest's runtime, or take it off in dehydrate"}`);case"data":return h(`a mount changes its data part ${i}, so that a page would write what the component left there, with nothing edited: read a data part, and change it by context.edit alone`);case"no-example":return b("it has a data part and its component offers no example of an edit, so nothing has tried the way back to the file: give DocKit.component an example(host, context) that makes a small context.edit");case"example":return t===Kt?{...s,file:"kit.js",line:void 0,what:`its example(host, context) changes nothing a part holds on the instance of ${s.file}${s.line?`:${s.line}`:""}: the check runs it on every instance of example.html and of template.html, and template.html's is empty, with nothing to change a value of (the first entry of a list it does not hold yet). Make example() make a change that works on an empty instance too (add an entry, set a field), and have it call the function a reader's control calls, so that it tries the code a reader runs`}:h(`its example: ${t}`);case"refused":return h("what its example wrote cannot go in the file: a script, a handler, an address of code, data-block-id or data-ge-*, what does not read back as itself, or what is no JSON in a script of data");case"undo":return h(`with what its example wrote put back, as an undo does, it does not show what it showed: ${t}: draw from the part, and on the source signal`);case"unasked":return h(`it writes its data part ${i} with no reader's gesture, ${n}, once the page takes edits: a page would write it each time it opened. Call context.edit on a gesture alone, a press, a drop or a key, and draw what the part holds as it is`);case"written-in":return h(`kit.js ${r}: a slot is the document's, its blocks the reader's: read it with context.part, never write in it or move it, and draw outside it`);case"piles":return h(p?`${t} piles up outside the instance on each put-back (${a.join(", then ")} of them), so an undo adds another: a component draws in its instance, and what it has to put elsewhere it takes away again in destroy`:`${t} piles up on each put-back (${a.join(", then ")} of them): it is declared in neither the manifest's runtime nor dehydrate, so an undo adds another`);default:return h(`a mount does not give the same DOM again: ${t}`)}}var Yt=e=>[...new Map(e.toReversed().map(t=>[`${t.finding.kind}|${t.finding.part??""}|${["piles","example"].includes(t.finding.kind)?t.finding.what:""}|${t.finding.when??""}|${t.finding.line??""}`,t])).values()].toReversed(),zt=4e6;function Me(e,t,i=(r,n)=>r===n){let[r,n]=[e.split(`
11
+ `),t.split(`
12
+ `)],a=0;for(;a<r.length&&a<n.length&&i(r[a],n[a]);)a++;let p=0;for(;p<r.length-a&&p<n.length-a&&i(r[r.length-1-p],n[n.length-1-p]);)p++;let[u,w]=[r.slice(a,r.length-p),n.slice(a,n.length-p)];if(u.length===0&&w.length===0)return[];if(u.length*w.length>zt)return[{removed:u,added:w}];let l=Array.from({length:u.length+1},()=>new Uint32Array(w.length+1));for(let c=u.length-1;c>=0;c--)for(let h=w.length-1;h>=0;h--)l[c][h]=i(u[c],w[h])?l[c+1][h+1]+1:Math.max(l[c+1][h],l[c][h+1]);let f=[],s=null;for(let c=0,h=0;c<u.length||h<w.length;)c<u.length&&h<w.length&&i(u[c],w[h])?(s=null,c++,h++):(s||f.push(s={removed:[],added:[]}),h<w.length&&(c===u.length||l[c][h+1]>=l[c+1][h])?s.added.push(w[h++]):s.removed.push(u[c++]));return f}function Qt(e,t){let i=n=>n.filter(a=>a.trim()).length,r=Me(e,t);return{removed:r.reduce((n,a)=>n+i(a.removed),0),added:r.reduce((n,a)=>n+i(a.added),0),lines:i(e.split(`
13
+ `))}}function Cn(e,t){let i=r=>r.map(n=>n.trim()).filter(Boolean);return Me(e,t).map(({removed:r,added:n})=>({removed:i(r),added:i(n)})).filter(({removed:r,added:n})=>r.length+n.length>0)}function at(e,t){let i=0,r=0;for(let[n,a]of e.entries())if(n>0&&i>0&&i<t&&r++,i+=a.replace(/\s+/g,"").length,i>=t)break;return r}function Xt(e,t){let i=r=>r.filter(n=>!n.trim()).length;for(let{removed:r,added:n}of Me(e,t,(a,p)=>a.trim()===p.trim())){if(i(n)>i(r))return"a line left blank";let[a,p]=[r.join("").replace(/\s+/g,""),n.join("").replace(/\s+/g,"")],u=0;for(;u<a.length&&u<p.length&&a[u]===p[u];)u++;let w=0;for(;w<a.length-u&&w<p.length-u&&a[a.length-1-w]===p[p.length-1-w];)w++;for(let[l,f,s]of[[u,r,n],[w,r.toReversed(),n.toReversed()]]){let[c,h]=[at(f,l)+1,at(s,l)+1];if(c!==h)return`${c} line${c===1?"":"s"} became ${h}`}}return null}function Zt(e,t){let i=Xt(e,t);return i&&!(Le(e,t)&&Le(e,e))?i:null}function en(e,{source:t,found:i,at:r,findings:n}){let a=Qe(t,dt(le(t),i)[r],e.parts,new Map([[i.id,i]]));if(!a)return[{kind:"refused"}];let p=Object.keys(e.parts),u=a.map(({start:l,end:f,text:s},c)=>({name:p[c],before:t.slice(l,f),after:s}));return[{kind:"wrote",back:!n.some(({kind:l})=>l==="undo"||l==="moving"),parts:u.map(({name:l,before:f,after:s})=>({name:l,...Qt(f,s)}))},...u.flatMap(({name:l,before:f,after:s})=>{let c=Zt(f,s);return c?[{kind:"laid",part:l,how:c,json:Le(f,s)}]:[]})]}var tn=2e3;function nn({match:e,instance:t,at:i,most:r}){let n=[...document.querySelectorAll(e)].filter(a=>!a.parentElement.closest(t))[i];return n?[window,document,n,...n.querySelectorAll("*")].slice(0,r):[]}function an(e){return e.map((t,i)=>i<2?{parent:i-1,named:""}:{parent:i===2?1:e.indexOf(t.parentElement),named:`<${t.localName}${t.classList.length?` class="${t.getAttribute("class")}"`:""}>`})}function sn(){let e=new DragEvent("dragenter",{bubbles:!0,cancelable:!0,composed:!0,dataTransfer:new DataTransfer});return this.dispatchEvent(e),e.defaultPrevented}async function on(e,{match:t,at:i}){let r=new Map,n=({scriptId:a,url:p})=>r.set(a,p);e.on("Debugger.scriptParsed",n);try{await e.send("Debugger.enable"),await e.send("Debugger.setSkipAllPauses",{skip:!0});let{result:a}=await e.send("Runtime.evaluate",{expression:`(${nn})(${JSON.stringify({match:t,instance:de,at:i,most:tn})})`,objectGroup:"drops"}),{result:p}=await e.send("Runtime.callFunctionOn",{objectId:a.objectId,functionDeclaration:String(an),arguments:[{objectId:a.objectId}],returnByValue:!0}),{result:u}=await e.send("Runtime.getProperties",{objectId:a.objectId,ownProperties:!0}),w=u.filter(({name:c,value:h})=>/^\d+$/.test(c)&&h?.objectId).sort((c,h)=>Number(c.name)-Number(h.name)),l=[];for(let{value:c}of w)l.push((await e.send("DOMDebugger.getEventListeners",{objectId:c.objectId})).listeners);let f=(c,h)=>l[c]?.some(b=>b.type===h),s=[];for(let c=2;c<l.length;c++){let h=l[c].find(k=>k.type==="dragover"&&r.get(k.scriptId)==="kit.js");if(!h)continue;let b=!1;for(let k=c;k>=2&&!b;k=p.value[k].parent)b=f(k,"dragenter");if(!b&&(f(0,"dragenter")||f(1,"dragenter"))){let{result:k}=await e.send("Runtime.callFunctionOn",{objectId:w[c].value.objectId,functionDeclaration:String(sn),returnByValue:!0});b=k.value===!0}b||s.push({kind:"drops",what:p.value[c].named,line:h.lineNumber+1})}return s}finally{e.off("Debugger.scriptParsed",n),await e.send("Runtime.releaseObjectGroup",{objectGroup:"drops"}).catch(()=>{}),await e.send("Debugger.disable").catch(()=>{})}}function rn(e,t){let i={errors:new Map,notes:new Set,failed:new Set,dialogs:new Set,windows:0,opened:[],asked:1,pending:[]},r=n=>{let[a]=n.split(`
14
+ `);i.errors.has(a)||i.errors.set(a,Number(/\bkit\.js:(\d+)/.exec(n)?.[1])||null)};return e.on("pageerror",n=>r(n.stack??n.message)),e.on("console",n=>{let a=n.type();!["error","warn","warning"].includes(a)||!Xe(n,t,["kit.js"])||i.pending.push(Promise.all(n.args().map(p=>p.evaluate(u=>u instanceof Error?u.stack:String(u)).catch(()=>""))).then(p=>{let u=p.join(" ")||n.text();a==="error"?r(u):i.notes.add(u.split(`
15
+ `)[0])}))}),e.on("requestfailed",n=>{n.frame()===e.mainFrame()&&!n.isNavigationRequest()&&i.failed.add(n.url())}),e.on("request",n=>{n.isNavigationRequest()&&n.frame()===e.mainFrame()&&i.opened.push(n.url())}),i}async function ln(e,t){let i=await e.createCDPSession();return await i.send("Page.enable"),i.on("Page.javascriptDialogOpening",({type:r})=>{t.add(r),i.send("Page.handleJavaScriptDialog",{accept:!1}).catch(()=>{})}),i}function L(e,t,i=se){let r=0,n=()=>Object.assign(new Error(t),{stuck:!0,doing:t,limit:i}),a=new Promise((u,w)=>{r=setTimeout(()=>w(n()),i)}),p=e.catch(u=>{throw It.has(u.name)?n():Object.assign(u,{doing:t})});return Promise.race([p,a]).finally(()=>clearTimeout(r))}var cn=e=>`${Number((e/1e3).toFixed(1))} s`,pt=e=>`the browser did not answer within ${cn(e.limit)}, waiting until ${e.doing}`,Pe=e=>new Promise(t=>{if(!e.connected)return t(!0);e.once("disconnected",()=>t(!0)),setTimeout(()=>t(!1),lt)});function dn({match:e,instance:t}){let{clientWidth:i,scrollWidth:r}=document.documentElement;if(r<=i+1)return null;let n=[...document.querySelectorAll(e)].filter(a=>!a.parentElement.closest(t));return{wide:r,at:n.findIndex(a=>[a,...a.querySelectorAll("*")].some(p=>p.getBoundingClientRect().right>i+1))}}var st=16,hn="#8f8f8f";async function pn(e,t,i){let r=await Promise.all(t.map(async n=>`data:image/png;base64,${(await T.readFile(n)).toString("base64")}`));await e.setViewport({width:ae.reduce((n,a)=>n+a,0)+st*(ae.length-1),height:900}),await e.setContent(`<!doctype html><body style="margin: 0; display: flex; align-items: flex-start; gap: ${st}px; background: ${hn}">${r.map((n,a)=>`<img src="${n}" width="${ae[a]}" alt="" style="display: block">`).join("")}</body>`,{waitUntil:"load"}),await e.screenshot({path:i,fullPage:!0})}async function ut(e,{file:t,html:i,source:r,places:n,found:a,out:p,loading:u,answer:w=se}){let l=(m,_)=>L(m,_,w),f=await l(e.createBrowserContext(),"a browser context opened"),s=await l(f.newPage(),"a tab opened"),c=Re(t).href,h=rn(s,c),b=await l(ln(s,h.dialogs),"the tab was set to refuse dialogs");f.on("targetcreated",m=>{m.type()==="page"&&(h.windows+=1,m.page().then(_=>_?.close()).then(()=>s.bringToFront()).catch(()=>{}))});let k={heard:h,blocked:[],late:[],taken:[],overviews:[],edited:[],asExport:[],answers:[],wide:[],stuck:null,stopped:null,gone:null},g=async m=>k.late.push(...await L(et(s,{timeout:nt}),m,3*nt+se));await l(Ze(s),"the tab was set to keep what the policy blocks"),await l(s.setViewport({width:736,height:900}),"the window went to 736px"),await l(s.emulateMediaFeatures([{name:"prefers-color-scheme",value:"light"}]),"the light theme came");try{await L(s.goto(c,{waitUntil:"load",timeout:0}),"the page opened",u),await g("the page opened");for(let $ of Ae){await L(s.emulateMediaFeatures([{name:"prefers-color-scheme",value:$}]),`the ${$} theme came`);for(let S of ae){if(await L(s.setViewport({width:S,height:900}),`the window went to ${S}px`),await g(`it was drawn at ${S}px`),$===Ae[0]){let H=await L(s.evaluate(dn,{match:a.match,instance:de}),`it was measured at ${S}px`);H&&k.wide.push({width:S,...H})}let B=x.join(p,`${S}-${$}.png`);await L(s.screenshot({path:B,fullPage:!0}),`it was pictured at ${S}px`),k.taken.push(B)}}await L(s.emulateMediaFeatures([{name:"prefers-color-scheme",value:"light"}]),"the light theme came"),await L(s.setViewport({width:736,height:900}),"the window went to 736px");let m=De(i,a);for(let{at:$,...S}of await L(s.evaluate(qt,{match:a.match,instance:de,slot:tt,parts:a.parts,boards:a.settings?.length?[ve]:[]}),"the page was asked what each instance still shows"))k.answers.push({finding:{kind:"controls",...S},place:n[$]});let _=a.files.includes("kit.js")&&Object.values(a.parts).some(({edit:$})=>$==="data");for(let $=0;$<m.length;$++){let S=await L(s.evaluate(Gt,{match:a.match,instance:de,slotPart:tt,slotName:vt,fallback:xt,parts:a.parts,boards:a.settings?.length?[ve]:[],at:$,source:m[$].markup,still:Rt,step:Dt,times:Mt,typed:Pt,typing:Ct}),"an instance was put back"),B=S.find(({kind:D})=>D==="wrote"),H=[...S.filter(D=>D!==B),...B?en(B,{source:r,found:a,at:$,findings:S}):[]];_&&!S.some(({kind:D})=>D==="gone"||D==="fallback")&&H.push(...await L(on(b,{match:a.match,at:$}),"the page was asked what an instance listens to")),k.answers.push(...H.map(D=>({finding:D,place:n[$]})))}k.blocked=await L(s.evaluate(()=>globalThis.__qaViolations),"the page was asked what it blocked"),h.asked+=1,await L(s.goto(c,{waitUntil:"load",timeout:0}),"the page opened again",u),await g("the page opened again"),await L(s.evaluate(()=>dispatchEvent(new Event("doc-editable"))),"the page was told it takes edits"),await g("it was drawn as the editing page draws it");for(let $ of Lt){await L(s.setViewport({width:$,height:900}),`the window went to ${$}px`),await g(`it was drawn at ${$}px as the editing page draws it`);let S=x.join(p,`edit-${$}-light.png`);await L(s.screenshot({path:S,fullPage:!0}),`it was pictured at ${$}px as the editing page draws it`),k.edited.push(S),(await T.readFile(S)).equals(await T.readFile(x.join(p,`${$}-light.png`)))&&k.asExport.push(S)}k.blocked.push(...await L(s.evaluate(()=>globalThis.__qaViolations),"the page was asked what it blocked"));for(let $ of Ae){let S=x.join(p,`overview-${$}.png`);await L(pn(s,ae.map(B=>x.join(p,`${B}-${$}.png`)),S),`the ${$} pictures were put side by side`),k.overviews.push(S)}}catch(m){if(m.syscall)throw m;await Pe(e)?k.gone=m.doing??"the page answered":m.stuck?k.stuck=m.doing:k.stopped=oe(m)}return await Promise.race([Promise.all(h.pending),new Promise(m=>setTimeout(m,lt).unref())]),k}var un=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function wn(e,t,i){let r=new Map;for(let{url:n,directive:a,source:p,line:u}of e){if(_t.test(n)){let l=!p&&u>0;r.set(`${n}|${p}|${u}`,{file:l?"kit.js":"the page",...l?{line:u}:{},what:"the export's policy blocks code made from words (eval, new Function, a string given to setTimeout): an export runs none"});continue}let w=/^[a-z][a-z0-9+.-]*$/.test(n)?t.filter(l=>l.startsWith(`${n}:`)):[];for(let l of w.length?w:[n])r.set(`${l}|${a}`,{file:"the page",what:`the export's policy blocks ${un(l,i)||"something"} (${a}): ${a==="img-src"?"a picture of an instance is a data: address, or a file its style names":"an export holds all it needs"}`})}return[...r.values()]}function wt({heard:e,blocked:t,late:i,answers:r,wide:n,stuck:a,stopped:p},{places:u,script:w,folder:l}){let f=Yt(r).map(({finding:g,place:m})=>Vt(g,m,{script:w})),s=[...e.failed],c=s.filter(g=>!t.some(m=>m.url&&g.startsWith(m.url))),h=e.opened.length>e.asked?"it loads itself again (location.reload(), a new location.href), so a reader's page would not stay":a?`it stopped answering while waiting until ${a}${w?": a script that never ends, or a component that changes what it hears (a text part, on its source signal)":""}`:p&&`the look at it stopped: ${p}`,b=n.map(({width:g,wide:m})=>`${m}px wide in a ${g}px window`).join(", "),k=u[n.find(({at:g})=>g>=0)?.at]??{file:"the page"};return{problems:[...[...e.errors].map(([g,m])=>({file:m?"kit.js":"the page",line:m,what:`the console says ${g}`})),...wn(t,s,l),...c.map(g=>({file:"the page",what:`it could not load ${g.slice(0,120)}`})),...[...e.dialogs].map(g=>({file:"the page",what:`it opens a dialog (${g}), which stops a reader's page until it is answered: show what it says in the instance`})),...e.windows?[{file:"the page",what:"it opens a window, which takes a reader away from the page: show it in the instance, or link to it"}]:[],...h?[{file:"the page",what:h}]:[],...n.length?[{...k,what:`the page is ${b}: a reader scrolls the whole page sideways, and gallery qa fails it: let it fit the window (max-width: 100%), or put what is wider in a frame of its own that scrolls`}]:[],...f.filter(({note:g,told:m})=>!g&&!m)],notes:[...[...e.notes].map(g=>({file:"the page",what:`the console says ${g}`})),...f.filter(({note:g})=>g),...i.map(g=>({file:"the page",what:`waited for ${g}`}))],told:f.filter(({told:g})=>g)}}async function _n(e,t,{example:i,template:r},{find:n=Te,start:a=Oe,loading:p=rt,answer:u=se}={}){let w=At,l=null,f=null;try{l=await T.mkdtemp(x.join(he.tmpdir(),"gallery-component-check-"));let s=await Wt(t,{example:i,template:r},l),c=n();if(!c)return{title:w,unverified:"no Chrome, Edge or Chromium found (GALLERY_BROWSER=<its executable> picks one)"};try{f=await a({executablePath:c,args:Ne()})}catch(g){return{title:w,unverified:`the browser ${c} did not start, twice, each time with a fresh profile (${oe(g)}; GALLERY_BROWSER=<its executable> picks another)`}}let h=x.join(it(e).qa,"components",...t.id.split("/"));await T.rm(h,{recursive:!0,force:!0}),await T.mkdir(h,{recursive:!0});let b=await ut(f.browser,{...s,found:t,out:h,loading:p,answer:u}),k=wt(b,{places:s.places,script:t.files.includes("kit.js"),folder:Re(`${l}${x.sep}`).href});return b.gone?{title:w,...k,unverified:`the browser went while waiting until ${b.gone}, so it says nothing of the block`}:{title:w,...k,...b.taken.length?{pictures:{folder:h,overviews:b.overviews.map(g=>x.basename(g)),each:b.taken.map(g=>x.basename(g)),edited:b.edited.map(g=>x.basename(g)),asExport:b.asExport.map(g=>x.basename(g))}}:{}}}catch(s){return s.reason==="check"?{title:w,problems:s.failures.map(c=>({file:"the export",what:c}))}:s.syscall?{title:w,unverified:`cannot write ${je(s.syscall==="mkdtemp"?he.tmpdir():s.path)} (${s.code})`}:f&&await Pe(f.browser)?{title:w,unverified:"the browser went before the page opened"}:s.stuck?{title:w,problems:[{file:"the page",what:`${pt(s)}, so the look stopped and the browser was closed`}]}:{title:w,problems:[{file:"the page",what:`the look at it stopped: ${oe(s)}`}]}}finally{await f?.close(),l&&await T.rm(l,{recursive:!0,force:!0,maxRetries:5,retryDelay:200}).catch(()=>{})}}async function fn(e,t){let i=[];for(let r of await Nt(e)){let n=jt(r,e),a=Tt(n).html,p=await T.readFile(a,"utf8").catch(()=>null);if(p===null)continue;let u=ot(le(p),t),w=f=>{for(let s=f.parentNode;s;s=s.parentNode)if(u.includes(s))return!0;return!1},l=u.filter(f=>!w(f)).map(({sourceCodeLocation:{startLine:f,startOffset:s,endOffset:c}})=>({line:f,markup:p.slice(s,c)}));l.length&&i.push({slug:r,place:`${r}/${x.basename(a)}`,directory:n,instances:l})}return i}async function mn(e,t,i,r){let n=t.instances.map(({line:s,markup:c})=>`<p>${t.place}:${s}</p>${c}`).join(`
16
+ `);for(let s of new Set([e.id,...[...n.matchAll(new RegExp(`${$t}="([^"]+)"`,"g"))].map(([,c])=>c)])){let c=s===e.id?e:i.get(s);c&&await ht(c,r)}let a=x.join(r,q);await T.mkdir(a),await T.cp(x.join(t.directory,"assets"),x.join(a,"assets"),{recursive:!0}).catch(s=>{if(s.code!=="ENOENT")throw s});let p=Se(ct(q,n)).text;await T.writeFile(x.join(a,"doc.html"),p),await T.writeFile(x.join(a,"doc.json"),JSON.stringify({title:q,description:q,type:"component"}));let w=await(await Ee({directory:r}))(q),l=x.join(r,"export.html");await T.writeFile(l,w);let f=De(p,e).map((s,c)=>({file:t.place,line:t.instances[c]?.line??null}));return{html:w,file:l,places:f,source:p}}async function In(e,t,{find:i=Te,start:r=Oe,loading:n=rt}={}){let a=await fn(e,t);if(a.length===0)return[{title:ce(),none:`none holds an instance of ${t.id}`}];let p=i();if(!p)return[{title:ce(),unverified:"no Chrome, Edge or Chromium found (GALLERY_BROWSER=<its executable> picks one)"}];let u;try{u=await r({executablePath:p,args:Ne()})}catch(f){return[{title:ce(),unverified:`the browser ${p} did not start, twice, each time with a fresh profile (${oe(f)}; GALLERY_BROWSER=<its executable> picks another)`}]}let{packages:w}=Ye(e),l=[];try{for(let f of a){let s=ce(f.place),c=null;try{c=await T.mkdtemp(x.join(he.tmpdir(),"gallery-component-check-"));let h=await mn(t,f,w,c),b=x.join(it(e).qa,"components",...t.id.split("/"),"documents",f.slug);await T.rm(b,{recursive:!0,force:!0}),await T.mkdir(b,{recursive:!0});let k=await ut(u.browser,{...h,found:t,out:b,loading:n}),g=wt(k,{places:h.places,script:t.files.includes("kit.js"),folder:Re(`${c}${x.sep}`).href});if(k.gone){l.push({title:s,...g,unverified:`the browser went while waiting until ${k.gone}, so it says nothing of these instances`});break}l.push({title:s,...g,...k.taken.length?{pictures:{folder:b,overviews:k.overviews.map(m=>x.basename(m)),each:k.taken.map(m=>x.basename(m)),edited:k.edited.map(m=>x.basename(m)),asExport:k.asExport.map(m=>x.basename(m)),documents:!0}}:{}})}catch(h){if(h.reason==="check")l.push({title:s,problems:h.failures.map(b=>({file:f.place,what:`its instances, exported alone: ${b}`}))});else if(h.syscall)l.push({title:s,unverified:`cannot write ${je(h.syscall==="mkdtemp"?he.tmpdir():h.path)} (${h.code})`});else if(await Pe(u.browser)){l.push({title:s,unverified:"the browser went before the page opened"});break}else if(h.stuck){l.push({title:s,problems:[{file:"the page",what:`${pt(h)}, so the look at them stopped, the browser was closed, and no document after them was looked at`}]});break}else l.push({title:s,problems:[{file:"the page",what:`the look at them stopped: ${oe(h)}`}]})}finally{c&&await T.rm(c,{recursive:!0,force:!0,maxRetries:5,retryDelay:200}).catch(()=>{})}}}finally{await u.close()}return l}export{At as a,ce as b,rt as c,se as d,Dn as e,Rt as f,Dt as g,Mn as h,Pn as i,oe as j,ct as k,Ut as l,Jt as m,Qt as n,Cn as o,Zt as p,ln as q,L as r,cn as s,pt as t,Pe as u,_n as v,In as w};