thursday-agent 0.16.0 → 0.17.1

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 (278) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +3 -3
  3. package/.next/prerender-manifest.json +3 -3
  4. package/.next/server/app/_global-error/page.js.nft.json +1 -1
  5. package/.next/server/app/_global-error.html +1 -1
  6. package/.next/server/app/_global-error.rsc +1 -1
  7. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  8. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  10. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  11. package/.next/server/app/_not-found.html +1 -1
  12. package/.next/server/app/_not-found.rsc +1 -1
  13. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  14. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  15. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/api/artifact/route.js +9 -9
  17. package/.next/server/app/api/artifact/route.js.nft.json +1 -1
  18. package/.next/server/app/api/bot/memory/files/route.js +3 -3
  19. package/.next/server/app/api/bot/memory/files/route.js.nft.json +1 -1
  20. package/.next/server/app/api/bot/memory/route.js +8 -8
  21. package/.next/server/app/api/bot/memory/route.js.nft.json +1 -1
  22. package/.next/server/app/api/bot/route.js +8 -8
  23. package/.next/server/app/api/bot/route.js.nft.json +1 -1
  24. package/.next/server/app/api/bot/thread/[id]/route.js +3 -3
  25. package/.next/server/app/api/bot/thread/[id]/route.js.nft.json +1 -1
  26. package/.next/server/app/api/bot/thread/route.js +3 -3
  27. package/.next/server/app/api/bot/thread/route.js.nft.json +1 -1
  28. package/.next/server/app/api/config/route.js.nft.json +1 -1
  29. package/.next/server/app/api/events/route.js.nft.json +1 -1
  30. package/.next/server/app/api/favicon/[host]/route.js.nft.json +1 -1
  31. package/.next/server/app/api/file/[...path]/route.js +4 -4
  32. package/.next/server/app/api/file/[...path]/route.js.nft.json +1 -1
  33. package/.next/server/app/api/llm-model/catalog/route.js.nft.json +1 -1
  34. package/.next/server/app/api/llm-model/credits/route.js.nft.json +1 -1
  35. package/.next/server/app/api/llm-model/route.js.nft.json +1 -1
  36. package/.next/server/app/api/llm-model/subscription/route.js.nft.json +1 -1
  37. package/.next/server/app/api/mcp/[name]/route.js.nft.json +1 -1
  38. package/.next/server/app/api/mcp/oauth/callback/route.js.nft.json +1 -1
  39. package/.next/server/app/api/mcp/route.js.nft.json +1 -1
  40. package/.next/server/app/api/mcp/tools/route.js.nft.json +1 -1
  41. package/.next/server/app/api/memory/edit/route.js +11 -11
  42. package/.next/server/app/api/memory/edit/route.js.nft.json +1 -1
  43. package/.next/server/app/api/memory/route.js.nft.json +1 -1
  44. package/.next/server/app/api/reach/route.js +11 -11
  45. package/.next/server/app/api/reach/route.js.nft.json +1 -1
  46. package/.next/server/app/api/routine/route.js +7 -7
  47. package/.next/server/app/api/routine/route.js.nft.json +1 -1
  48. package/.next/server/app/api/signins/route.js +5 -5
  49. package/.next/server/app/api/signins/route.js.nft.json +1 -1
  50. package/.next/server/app/api/skills/[source]/[name]/route.js +7 -7
  51. package/.next/server/app/api/skills/[source]/[name]/route.js.nft.json +1 -1
  52. package/.next/server/app/api/skills/route.js +7 -7
  53. package/.next/server/app/api/skills/route.js.nft.json +1 -1
  54. package/.next/server/app/api/thursday/call/route.js +5 -5
  55. package/.next/server/app/api/thursday/call/route.js.nft.json +1 -1
  56. package/.next/server/app/api/thursday/settings/route.js +5 -5
  57. package/.next/server/app/api/thursday/settings/route.js.nft.json +1 -1
  58. package/.next/server/app/api/thursday/text/route.js +13 -13
  59. package/.next/server/app/api/thursday/text/route.js.nft.json +1 -1
  60. package/.next/server/app/api/thursday/tool-call/route.js +12 -12
  61. package/.next/server/app/api/thursday/tool-call/route.js.nft.json +1 -1
  62. package/.next/server/app/api/workspace/files/route.js +8 -8
  63. package/.next/server/app/api/workspace/files/route.js.nft.json +1 -1
  64. package/.next/server/app/api/workspace/route.js +9 -9
  65. package/.next/server/app/api/workspace/route.js.nft.json +1 -1
  66. package/.next/server/app/artifact/[...path]/page/server-reference-manifest.json +3 -3
  67. package/.next/server/app/artifact/[...path]/page.js +4 -4
  68. package/.next/server/app/artifact/[...path]/page.js.nft.json +1 -1
  69. package/.next/server/app/artifact/[...path]/page_client-reference-manifest.js +1 -1
  70. package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
  71. package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
  72. package/.next/server/app/page/server-reference-manifest.json +60 -60
  73. package/.next/server/app/page.js +5 -5
  74. package/.next/server/app/page.js.nft.json +1 -1
  75. package/.next/server/app/page_client-reference-manifest.js +1 -1
  76. package/.next/server/chunks/[root-of-the-server]__00qyw01._.js +1 -1
  77. package/.next/server/chunks/[root-of-the-server]__01ypm_z._.js +3 -0
  78. package/.next/server/chunks/[root-of-the-server]__021dkui._.js +3 -0
  79. package/.next/server/chunks/{[root-of-the-server]__18e65_-._.js → [root-of-the-server]__03xamry._.js} +2 -2
  80. package/.next/server/chunks/[root-of-the-server]__05dp5tr._.js +1 -1
  81. package/.next/server/chunks/[root-of-the-server]__09gdscj._.js +7 -0
  82. package/.next/server/chunks/{[root-of-the-server]__10_7vqz._.js → [root-of-the-server]__0b36yfw._.js} +1 -1
  83. package/.next/server/chunks/{[root-of-the-server]__1gamvcz._.js → [root-of-the-server]__0jzwdg-._.js} +2 -2
  84. package/.next/server/chunks/[root-of-the-server]__0mrk2it._.js +1 -1
  85. package/.next/server/chunks/[root-of-the-server]__0nmust6._.js +5 -0
  86. package/.next/server/chunks/[root-of-the-server]__0svzjwa._.js +7 -0
  87. package/.next/server/chunks/{[root-of-the-server]__16yw3mb._.js → [root-of-the-server]__12m24xl._.js} +1 -1
  88. package/.next/server/chunks/{[root-of-the-server]__1zrwxis._.js → [root-of-the-server]__12tahb4._.js} +1 -1
  89. package/.next/server/chunks/{[root-of-the-server]__1ep-pao._.js → [root-of-the-server]__1_h4hf9._.js} +4 -4
  90. package/.next/server/chunks/{[root-of-the-server]__1-tdj60._.js → [root-of-the-server]__1de1o6m._.js} +2 -2
  91. package/.next/server/chunks/{[root-of-the-server]__1voqqyc._.js → [root-of-the-server]__1ignh6-._.js} +1 -1
  92. package/.next/server/chunks/[root-of-the-server]__1t02-1p._.js +3 -0
  93. package/.next/server/chunks/[root-of-the-server]__1ygplx1._.js +1 -1
  94. package/.next/server/chunks/{[root-of-the-server]__11g20j-._.js → [root-of-the-server]__1yl5l25._.js} +1 -1
  95. package/.next/server/chunks/{[root-of-the-server]__1mbd2w_._.js → [root-of-the-server]__208vmyf._.js} +1 -1
  96. package/.next/server/chunks/{_1mfu9a3._.js → _02lipqs._.js} +1 -1
  97. package/.next/server/chunks/_05sa7xl._.js +1 -1
  98. package/.next/server/chunks/{_1rg5bfd._.js → _074f2ts._.js} +1 -1
  99. package/.next/server/chunks/_07nxi75._.js +37 -37
  100. package/.next/server/chunks/_08354bn._.js +12 -12
  101. package/.next/server/chunks/_08btiir._.js +7 -0
  102. package/.next/server/chunks/_0caua_s._.js +1 -1
  103. package/.next/server/chunks/{_0qoush_._.js → _0gt6cbj._.js} +1 -1
  104. package/.next/server/chunks/_0xygcxs._.js +37 -37
  105. package/.next/server/chunks/{_09c4we8._.js → _17i1lt2._.js} +1 -1
  106. package/.next/server/chunks/_19kea1l._.js +9 -9
  107. package/.next/server/chunks/_1gn2r2q._.js +3 -3
  108. package/.next/server/chunks/{_03niwml._.js → _1ntwp1s._.js} +1 -1
  109. package/.next/server/chunks/_1q6e56i._.js +3 -3
  110. package/.next/server/chunks/{_02fn1o3._.js → _1tkzgtm._.js} +1 -1
  111. package/.next/server/chunks/_1wl2g8_._.js +2 -2
  112. package/.next/server/chunks/{_1w6uf9k._.js → _1y3mnz4._.js} +1 -1
  113. package/.next/server/chunks/features_workspace_workspace_ts_13h82gv._.js +4 -4
  114. package/.next/server/chunks/features_workspace_workspace_ts_1iyjroj._.js +4 -4
  115. package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0cux6zt._.js → node_modules_consola_dist_chunks_prompt_mjs_04oxl25._.js} +1 -1
  116. package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_0w32bqh._.js → node_modules_consola_dist_chunks_prompt_mjs_0g87zst._.js} +1 -1
  117. package/.next/server/chunks/{node_modules_consola_dist_chunks_prompt_mjs_1clmnaj._.js → node_modules_consola_dist_chunks_prompt_mjs_1341cnf._.js} +1 -1
  118. package/.next/server/chunks/ssr/{[root-of-the-server]__02jdtqa._.js → [root-of-the-server]__07660xu._.js} +3 -3
  119. package/.next/server/chunks/ssr/[root-of-the-server]__07iyl1_._.js +3 -0
  120. package/.next/server/chunks/ssr/{[root-of-the-server]__0rnjkw2._.js → [root-of-the-server]__0g__u45._.js} +2 -2
  121. package/.next/server/chunks/ssr/[root-of-the-server]__17h1ggo._.js +1 -1
  122. package/.next/server/chunks/ssr/[root-of-the-server]__1jyeu61._.js +1 -1
  123. package/.next/server/chunks/ssr/_0-i6wdi._.js +3 -0
  124. package/.next/server/chunks/ssr/{_1k0efi3._.js → _00g5sq-._.js} +2 -2
  125. package/.next/server/chunks/ssr/{_0ncuqct._.js → _03akcjz._.js} +2 -2
  126. package/.next/server/chunks/ssr/{_0l1-xc6._.js → _06xy39t._.js} +2 -2
  127. package/.next/server/chunks/ssr/_088vzgn._.js +3 -0
  128. package/.next/server/chunks/ssr/_0fo4552._.js +7 -7
  129. package/.next/server/chunks/ssr/_0r0g9ki._.js +1 -1
  130. package/.next/server/chunks/ssr/{_1dqaksc._.js → _0sefgiu._.js} +2 -2
  131. package/.next/server/chunks/ssr/_0v9r8g2._.js +3 -0
  132. package/.next/server/chunks/ssr/_0x8ophf._.js +1 -1
  133. package/.next/server/chunks/ssr/{_0w8r7o7._.js → _1-41lck._.js} +2 -2
  134. package/.next/server/chunks/ssr/{_11pnnvd._.js → _113ukfo._.js} +3 -3
  135. package/.next/server/chunks/ssr/_12p8f9_._.js +3 -0
  136. package/.next/server/chunks/ssr/{_10fwcz_._.js → _14dfh7a._.js} +2 -2
  137. package/.next/server/chunks/ssr/{_1f6s34p._.js → _1_gwau0._.js} +2 -2
  138. package/.next/server/chunks/ssr/{_0wupyvd._.js → _1hn3szq._.js} +2 -2
  139. package/.next/server/chunks/ssr/_1neoj22._.js +1 -1
  140. package/.next/server/chunks/ssr/{_17ble8k._.js → _1o7a11b._.js} +3 -3
  141. package/.next/server/chunks/ssr/{_0y28gl3._.js → _1swhm5m._.js} +3 -3
  142. package/.next/server/chunks/ssr/_1uij_rj._.js +1 -1
  143. package/.next/server/chunks/ssr/_1umbr78._.js +1 -1
  144. package/.next/server/chunks/ssr/_1w9w1ok._.js +1 -1
  145. package/.next/server/chunks/ssr/_1wac78_._.js +3 -0
  146. package/.next/server/chunks/ssr/{_1z586yw._.js → _20ywznt._.js} +2 -2
  147. package/.next/server/chunks/ssr/features_0796o8r._.js +1 -1
  148. package/.next/server/chunks/ssr/{features_bot_1k25jdg._.js → features_bot_0j4h9qu._.js} +2 -2
  149. package/.next/server/chunks/ssr/features_bot_1knyan7._.js +3 -0
  150. package/.next/server/chunks/ssr/{features_config_11dpa7r._.js → features_config_1xrlh3l._.js} +3 -3
  151. package/.next/server/chunks/ssr/features_connectors_components_mcp-setting_tsx_0jmbgvp._.js +1 -1
  152. package/.next/server/chunks/ssr/features_memory_components_memory-setting_tsx_0oa43sw._.js +1 -1
  153. package/.next/server/chunks/ssr/features_routine_components_routine-setting_tsx_055fknz._.js +1 -1
  154. package/.next/server/chunks/ssr/features_workspace_workspace_ts_1wc7_u_._.js +4 -4
  155. package/.next/server/chunks/ssr/{node_modules_1r5o-bo._.js → node_modules_00kqq8n._.js} +1 -1
  156. package/.next/server/chunks/ssr/{node_modules_0u24mg0._.js → node_modules_04o9dd2._.js} +1 -1
  157. package/.next/server/chunks/ssr/{node_modules_0mark4f._.js → node_modules_05jatne._.js} +1 -1
  158. package/.next/server/chunks/ssr/{node_modules_0bas34k._.js → node_modules_06rkzq5._.js} +1 -1
  159. package/.next/server/chunks/ssr/{node_modules_0y5uubt._.js → node_modules_07w6r9n._.js} +1 -1
  160. package/.next/server/chunks/ssr/{node_modules_0ka8te1._.js → node_modules_08ld3lm._.js} +1 -1
  161. package/.next/server/chunks/ssr/{node_modules_0n1js5k._.js → node_modules_0ft86sp._.js} +1 -1
  162. package/.next/server/chunks/ssr/{node_modules_156m1qh._.js → node_modules_0g0lr19._.js} +1 -1
  163. package/.next/server/chunks/ssr/{node_modules_0bbwe-u._.js → node_modules_0kg-vd-._.js} +1 -1
  164. package/.next/server/chunks/ssr/{node_modules_0x_2io2._.js → node_modules_0nl9i29._.js} +1 -1
  165. package/.next/server/chunks/ssr/{node_modules_18yn_bs._.js → node_modules_0p0xf5f._.js} +1 -1
  166. package/.next/server/chunks/ssr/{node_modules_0-8r9yw._.js → node_modules_0pyepmf._.js} +1 -1
  167. package/.next/server/chunks/ssr/{node_modules_1dzye0n._.js → node_modules_0vg-4fo._.js} +1 -1
  168. package/.next/server/chunks/ssr/{node_modules_1xua-g1._.js → node_modules_0y5upun._.js} +1 -1
  169. package/.next/server/chunks/ssr/{node_modules_1o9n7_n._.js → node_modules_13seln7._.js} +1 -1
  170. package/.next/server/chunks/ssr/{node_modules_1ozyial._.js → node_modules_15vsfpv._.js} +1 -1
  171. package/.next/server/chunks/ssr/{node_modules_0sdjzae._.js → node_modules_17azpeb._.js} +1 -1
  172. package/.next/server/chunks/ssr/{node_modules_1zkzksd._.js → node_modules_1_il5l7._.js} +1 -1
  173. package/.next/server/chunks/ssr/{node_modules_0-ew8f8._.js → node_modules_1aeg65a._.js} +1 -1
  174. package/.next/server/chunks/ssr/{node_modules_0etz1i0._.js → node_modules_1d73q89._.js} +1 -1
  175. package/.next/server/chunks/ssr/{node_modules_0ld7p-1._.js → node_modules_1iq8zjs._.js} +1 -1
  176. package/.next/server/chunks/ssr/{node_modules_138kcrz._.js → node_modules_1mcsva4._.js} +1 -1
  177. package/.next/server/chunks/ssr/{node_modules_0uibk9z._.js → node_modules_1mhg5br._.js} +1 -1
  178. package/.next/server/chunks/ssr/{node_modules_1tj7_9z._.js → node_modules_1mqisle._.js} +1 -1
  179. package/.next/server/chunks/ssr/{node_modules_02uwbwp._.js → node_modules_1va4lz9._.js} +1 -1
  180. package/.next/server/chunks/ssr/{node_modules_097cl9f._.js → node_modules_207ay1p._.js} +1 -1
  181. package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_133hjui._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_0hefprb._.js} +1 -1
  182. package/.next/server/chunks/ssr/{node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1b3vwd3._.js → node_modules_@mermaid-js_parser_dist_chunks_mermaid-parser_core_1uuvrfp._.js} +1 -1
  183. package/.next/server/middleware-build-manifest.js +3 -3
  184. package/.next/server/pages/404.html +1 -1
  185. package/.next/server/pages/500.html +1 -1
  186. package/.next/server/server-reference-manifest.js +1 -1
  187. package/.next/server/server-reference-manifest.json +61 -61
  188. package/.next/static/chunks/04toe_3nqfjqt.js +1 -0
  189. package/.next/static/chunks/{245_cp14iz637.js → 0780wmy0_rva8.js} +1 -1
  190. package/.next/static/chunks/{314szf8yer-3n.js → 09opsnra7k4k0.js} +2 -2
  191. package/.next/static/chunks/{42m371fn687r5.js → 0if7xqoj3ysfj.js} +1 -1
  192. package/.next/static/chunks/{0609ejkwuy4sf.js → 1-q6so9vze75d.js} +2 -2
  193. package/.next/static/chunks/{23tx-2paw9qa6.js → 106jbz6qd0c5l.js} +1 -1
  194. package/.next/static/chunks/19wkcgzetkh6-.js +1 -0
  195. package/.next/static/chunks/{39miwvg4k-b2d.js → 1_me_-lnpwdfd.js} +1 -1
  196. package/.next/static/chunks/{2oa4gpkzjtpni.js → 1mkw_05uc8_ft.js} +1 -1
  197. package/.next/static/chunks/1njjf8bfkg4_v.js +1 -0
  198. package/.next/static/chunks/{1ub9obhgfm4jl.js → 25ciqm-ee14nf.js} +1 -1
  199. package/.next/static/chunks/{2xjr5b-yk_h3o.js → 29laj9_xhx0d1.js} +1 -1
  200. package/.next/static/chunks/{2jbjyazqfqyoh.js → 2b306ek_blfp1.js} +1 -1
  201. package/.next/static/chunks/2mpqmpf8wcst1.js +15 -0
  202. package/.next/static/chunks/{3ro66d9dc70bc.js → 2rpyc6mevfhu6.js} +1 -1
  203. package/.next/static/chunks/{0cl_fgkphk1oz.js → 2wj77vx62ng3n.js} +1 -1
  204. package/.next/static/chunks/{3j-l8un0d77v7.js → 2y2v3bk65fdle.js} +3 -3
  205. package/.next/static/chunks/{3vwjs5kq11417.js → 32oho7re_n3dq.js} +1 -1
  206. package/.next/static/chunks/388l-zszwa_jf.js +1 -0
  207. package/.next/static/chunks/{0q4ws7qd21chx.js → 3_s5svfgu9kl_.js} +3 -3
  208. package/.next/static/chunks/3bwrvpjk95_x4.js +1 -0
  209. package/.next/static/chunks/{07vcuxousbmy1.js → 3suz18umxycuk.js} +1 -1
  210. package/.next/static/chunks/{0unonxbajyknw.js → 44n-w1bs83ejz.js} +1 -1
  211. package/README.md +12 -12
  212. package/guide/bots.md +48 -8
  213. package/guide/calls.md +13 -12
  214. package/guide/setup.md +4 -2
  215. package/package.json +1 -1
  216. package/public/sounds/NOTICE +3 -0
  217. package/public/sounds/opening-land.ogg +0 -0
  218. package/public/sounds/opening-rise.ogg +0 -0
  219. package/public/sounds/opening-step-1.ogg +0 -0
  220. package/public/sounds/opening-step-2.ogg +0 -0
  221. package/public/sounds/opening-step-3.ogg +0 -0
  222. package/skills/README.md +3 -0
  223. package/skills/artifact/SKILL.md +6 -5
  224. package/skills/artifact/references/book.md +23 -8
  225. package/skills/artifact/references/deck.md +4 -2
  226. package/skills/artifact/references/document.md +9 -0
  227. package/skills/artifact/references/sheet.md +113 -0
  228. package/skills/artifact/runtime/book/book.css +75 -0
  229. package/skills/artifact/runtime/book/book.html +6 -3
  230. package/skills/artifact/runtime/book/book.js +21 -0
  231. package/skills/artifact/runtime/canvas/canvas.css +1 -1
  232. package/skills/artifact/runtime/canvas/canvas.js +11 -1
  233. package/skills/artifact/runtime/deck/deck.css +164 -1
  234. package/skills/artifact/runtime/deck/deck.js +76 -1
  235. package/skills/artifact/runtime/document/docx.js +631 -0
  236. package/skills/artifact/runtime/document/markdown.mjs +58 -2
  237. package/skills/artifact/runtime/document/quick.css +66 -0
  238. package/skills/artifact/runtime/document/quick.html +1 -0
  239. package/skills/artifact/runtime/document/quick.js +154 -0
  240. package/skills/artifact/runtime/document/word.mjs +65 -0
  241. package/skills/artifact/runtime/sheet/format.mjs +392 -0
  242. package/skills/artifact/runtime/sheet/formula.mjs +755 -0
  243. package/skills/artifact/runtime/sheet/sheet.css +499 -0
  244. package/skills/artifact/runtime/sheet/sheet.html +102 -0
  245. package/skills/artifact/runtime/sheet/sheet.js +1361 -0
  246. package/skills/artifact/runtime/sheet/xlsx.mjs +320 -0
  247. package/skills/artifact/runtime/shell/head.html +1 -1
  248. package/skills/artifact/runtime/shell/shell.css +3 -0
  249. package/skills/artifact/runtime/shell/wear.mjs +47 -1
  250. package/skills/artifact/runtime/vendor/fflate.LICENSE.md +23 -0
  251. package/skills/artifact/runtime/vendor/fflate.mjs +2710 -0
  252. package/skills/artifact/scripts/book.mjs +160 -11
  253. package/skills/artifact/scripts/chart.mjs +229 -11
  254. package/skills/artifact/scripts/document.mjs +29 -2
  255. package/skills/artifact/scripts/spreadsheet.mjs +1165 -0
  256. package/skills/data-report/SKILL.md +8 -1
  257. package/.next/server/chunks/[root-of-the-server]__0aijj66._.js +0 -3
  258. package/.next/server/chunks/[root-of-the-server]__0tvoct-._.js +0 -3
  259. package/.next/server/chunks/[root-of-the-server]__118qjk_._.js +0 -7
  260. package/.next/server/chunks/[root-of-the-server]__1b8tp42._.js +0 -5
  261. package/.next/server/chunks/[root-of-the-server]__1gzcbda._.js +0 -3
  262. package/.next/server/chunks/[root-of-the-server]__1qcn1ti._.js +0 -7
  263. package/.next/server/chunks/_0xx3ryc._.js +0 -7
  264. package/.next/server/chunks/ssr/[root-of-the-server]__1y5_1cv._.js +0 -3
  265. package/.next/server/chunks/ssr/_0-ou1b0._.js +0 -3
  266. package/.next/server/chunks/ssr/_1g48r6t._.js +0 -3
  267. package/.next/server/chunks/ssr/_1u5vsy-._.js +0 -3
  268. package/.next/server/chunks/ssr/features_bot_1s_-2vj._.js +0 -3
  269. package/.next/server/chunks/ssr/lib_utils_ts_0_f1xvm._.js +0 -3
  270. package/.next/static/chunks/00d54fcfm-lko.js +0 -1
  271. package/.next/static/chunks/0gjlsu6vrfzod.js +0 -1
  272. package/.next/static/chunks/17yqt1p_svv13.js +0 -1
  273. package/.next/static/chunks/203pbwecfs3tm.js +0 -1
  274. package/.next/static/chunks/3ghvoe_mlljzs.js +0 -15
  275. package/.next/static/chunks/3gn7dubb4-pwy.js +0 -1
  276. /package/.next/static/{RtLRT9EEaGn-OqwpMFdYg → SNCDmWKeIrXB6yqnwzClS}/_buildManifest.js +0 -0
  277. /package/.next/static/{RtLRT9EEaGn-OqwpMFdYg → SNCDmWKeIrXB6yqnwzClS}/_clientMiddlewareManifest.js +0 -0
  278. /package/.next/static/{RtLRT9EEaGn-OqwpMFdYg → SNCDmWKeIrXB6yqnwzClS}/_ssgManifest.js +0 -0
@@ -0,0 +1,1165 @@
1
+ #!/usr/bin/env node
2
+ // A sheet: a real .xlsx file — its formulas, number formats, a frozen header with a filter on it
3
+ // — and the page beside it that shows it in the app, with its tabs, sorting, filters, the sum of
4
+ // the picked cells, CSV and copy. Excel, Numbers and Google Sheets open the .xlsx; the page is
5
+ // its view. Both land in your folder under artifacts/, in a folder named after the sheet.
6
+ //
7
+ // node spreadsheet.mjs put <name> <book.json | data.csv> [--title "…"] [--over]
8
+ // write the workbook from a JSON description (references/sheet.md), or one sheet from
9
+ // a CSV whose first line names the columns
10
+ // node spreadsheet.mjs read <name | file.xlsx | file.csv> [--rows 20] [--csv <folder>] [--json <file>]
11
+ // what a workbook holds: each sheet's size, its first rows and its formulas; --csv
12
+ // writes every sheet as a CSV there, for chart.mjs or a script; --json writes the
13
+ // whole workbook as put takes it — formats, formulas and totals kept — to change and put;
14
+ // a CSV — a bank's export — prints its lines numbered, and with --json the table under
15
+ // the line --header names (1 unless said), its dates as dates
16
+ // A CSV, to read or to put: --encoding <euc-kr | shift_jis | gbk | windows-1252 | utf-16le …>
17
+ // when it is not UTF-8; --header <line> and --until <line> where its table starts and ends;
18
+ // --dates dmy | mdy when it writes a day or a month before the year
19
+ // node spreadsheet.mjs view <name | file.xlsx> [--name <name>]
20
+ // the page drawn again from the .xlsx as it is now (after it was changed in Excel), or
21
+ // a page for someone's .xlsx: it is copied into your folder beside its page
22
+ // node spreadsheet.mjs shots <name>
23
+ // the page as it opens, as a picture to look at
24
+ // node spreadsheet.mjs sync <edited.html> --page <page.html>
25
+ // the app's side of an edit made in the page: the .xlsx beside <page.html> written from
26
+ // the workbook <edited.html> holds, and <edited.html> made to name it (workspace.query
27
+ // savePage runs this before the edited page takes the old one's place); exit 3 when
28
+ // the .xlsx was changed since the page drew it
29
+ //
30
+ // A formula this sheet cannot work out, a number format it does not draw, a sheet name Excel
31
+ // refuses and a workbook changed in Excel since it was written all stop, rather than write
32
+ // something quietly wrong or over the user's changes.
33
+ import { spawnSync } from "node:child_process";
34
+ import { createHash } from "node:crypto";
35
+ import {
36
+ copyFileSync,
37
+ existsSync,
38
+ mkdirSync,
39
+ readFileSync,
40
+ renameSync,
41
+ rmSync,
42
+ writeFileSync,
43
+ } from "node:fs";
44
+ import { basename, dirname, extname, join, resolve } from "node:path";
45
+ import { fileURLToPath } from "node:url";
46
+ import {
47
+ checkFormat,
48
+ formatValue,
49
+ isDateFormat,
50
+ isoOf,
51
+ serialOf,
52
+ } from "../runtime/sheet/format.mjs";
53
+ import {
54
+ asColumnFormula,
55
+ colName,
56
+ FormulaError,
57
+ FUNCTIONS,
58
+ workOut,
59
+ } from "../runtime/sheet/formula.mjs";
60
+ import { readXlsx, sheetRef, writeXlsx } from "../runtime/sheet/xlsx.mjs";
61
+ import { revision } from "../runtime/shell/put.mjs";
62
+ import { wear } from "../runtime/shell/wear.mjs";
63
+ import {
64
+ ARTIFACTS,
65
+ NAME,
66
+ Stop,
67
+ shown,
68
+ WORKSPACE,
69
+ } from "../runtime/shell/workspace.mjs";
70
+
71
+ const SKILL = resolve(dirname(fileURLToPath(import.meta.url)), "..");
72
+ const RUNTIME = join(SKILL, "runtime", "sheet");
73
+ const SCRIPT = join(SKILL, "scripts", "spreadsheet.mjs");
74
+ const SKILLS = process.env.THURSDAY_SKILLS || resolve(SKILL, "..");
75
+
76
+ /** The most cells a workbook holds here; past it a bot works on the data with a script. */
77
+ const MOST_CELLS = 300_000;
78
+ /** How each totals function is written into the .xlsx: SUBTOTAL, so a filter in Excel is counted too. */
79
+ const TOTALS = { sum: 109, average: 101, count: 102, max: 104, min: 105 };
80
+
81
+ const usage = () => {
82
+ const lines = readFileSync(new URL(import.meta.url), "utf8")
83
+ .split("\n")
84
+ .slice(1);
85
+ const end = lines.findIndex((line) => !line.startsWith("//"));
86
+ return lines
87
+ .slice(0, end)
88
+ .map((line) => line.replace(/^\/\/ ?/, ""))
89
+ .join("\n");
90
+ };
91
+
92
+ function parseArgs(argv) {
93
+ const positional = [];
94
+ const flags = {};
95
+ for (let i = 0; i < argv.length; i++) {
96
+ if (!argv[i].startsWith("--")) {
97
+ positional.push(argv[i]);
98
+ continue;
99
+ }
100
+ const next = argv[i + 1];
101
+ flags[argv[i].slice(2)] =
102
+ next === undefined || next.startsWith("--") ? true : (i++, next);
103
+ }
104
+ return { positional, flags };
105
+ }
106
+
107
+ /** A sheet's folder, and its two files in it. */
108
+ function filesFor(name) {
109
+ if (!name || !NAME.test(name))
110
+ throw new Stop(
111
+ `${name ? `"${name}" is not` : "Give"} a sheet name: letters, numbers, - and _ only.`,
112
+ );
113
+ const folder = join(ARTIFACTS, name);
114
+ return {
115
+ folder,
116
+ xlsx: join(folder, `${name}.xlsx`),
117
+ page: join(folder, `${name}.html`),
118
+ };
119
+ }
120
+
121
+ const hashOf = (bytes) =>
122
+ createHash("sha256").update(bytes).digest("hex").slice(0, 16);
123
+
124
+ /** The .xlsx as the page last drew it; null for a page made before this was kept. */
125
+ const drawnHash = (page) =>
126
+ existsSync(page)
127
+ ? (/<meta name="sheet-xlsx" content="([0-9a-f]*)"/.exec(
128
+ readFileSync(page, "utf8"),
129
+ )?.[1] ?? null)
130
+ : null;
131
+
132
+ /** Whether the page was drawn from the user's own change — an edit in the app, or the file
133
+ * changed in Excel — rather than from a bot's put: a put over it would undo that change. */
134
+ const userChanged = (page) =>
135
+ existsSync(page) &&
136
+ /<meta name="sheet-xlsx" content="[0-9a-f]*" data-edited/.test(
137
+ readFileSync(page, "utf8"),
138
+ );
139
+ const EDITED = (hash) =>
140
+ `<meta name="sheet-xlsx" content="${hash}" data-edited`;
141
+
142
+ /** A width for a column in Excel's characters: its longest text, a Korean or Chinese one counted twice. */
143
+ const widthOf = (texts) => {
144
+ const longest = Math.max(
145
+ 0,
146
+ ...texts.map((text) =>
147
+ [...String(text)].reduce(
148
+ (w, ch) => w + (/[ᄀ-ᇿ⺀-鿿가-힯＀-￯]/.test(ch) ? 2 : 1),
149
+ 0,
150
+ ),
151
+ ),
152
+ );
153
+ return Math.min(50, Math.max(6, longest + 2));
154
+ };
155
+
156
+ // ── a workbook from a description ─────────────────────────────────────────
157
+
158
+ /** `book.json` read and checked into sheets of cells, row 0 each sheet's header. */
159
+ function fromDescription(spec) {
160
+ if (!spec || !Array.isArray(spec.sheets) || !spec.sheets.length)
161
+ throw new Stop(
162
+ 'The workbook needs "sheets": a list of { "name", "columns", "rows" } (references/sheet.md).',
163
+ );
164
+ const seen = new Set();
165
+ let cells = 0;
166
+ const sheets = spec.sheets.map((one, s) => {
167
+ const name = String(one?.name ?? "").trim();
168
+ if (
169
+ !name ||
170
+ name.length > 31 ||
171
+ /[[\]:*?/\\]/.test(name) ||
172
+ /^'|'$/.test(name)
173
+ )
174
+ throw new Stop(
175
+ `Sheet ${s + 1}'s name "${name}" is not one Excel takes: 1 to 31 characters, none of [ ] : * ? / \\, not starting or ending with '.`,
176
+ );
177
+ if (seen.has(name.toLowerCase()))
178
+ throw new Stop(`Two sheets are named "${name}".`);
179
+ seen.add(name.toLowerCase());
180
+ if (!Array.isArray(one.columns) || !one.columns.length)
181
+ throw new Stop(
182
+ `Sheet "${name}" needs "columns": a list of { "name" } and, where it has them, "format", "formula", "width".`,
183
+ );
184
+ const columns = one.columns.map((column, c) => {
185
+ const label = String(column?.name ?? "").trim();
186
+ if (!label)
187
+ throw new Stop(`Sheet "${name}", column ${colName(c)} has no name.`);
188
+ if (column.format !== undefined) {
189
+ const wrong = checkFormat(String(column.format));
190
+ if (wrong)
191
+ throw new Stop(`Sheet "${name}", column "${label}": ${wrong}.`);
192
+ }
193
+ return {
194
+ name: label,
195
+ format: column.format,
196
+ formula: column.formula,
197
+ width: column.width,
198
+ };
199
+ });
200
+ const rows = one.rows ?? [];
201
+ if (!Array.isArray(rows))
202
+ throw new Stop(
203
+ `Sheet "${name}": "rows" is a list of rows, each a list of cells.`,
204
+ );
205
+ const data = rows.map((row, i) => {
206
+ if (!Array.isArray(row))
207
+ throw new Stop(`Sheet "${name}", row ${i + 2} is not a list of cells.`);
208
+ if (row.length > columns.length)
209
+ throw new Stop(
210
+ `Sheet "${name}", row ${i + 2} has ${row.length} cells for ${columns.length} columns.`,
211
+ );
212
+ return columns.map((column, c) => {
213
+ const given = row[c];
214
+ const excelRow = String(i + 2);
215
+ if (column.formula !== undefined) {
216
+ if (given !== undefined && given !== null)
217
+ throw new Stop(
218
+ `Sheet "${name}", row ${excelRow}: column "${column.name}" is worked out by its formula; leave its cell null.`,
219
+ );
220
+ return { f: String(column.formula).replaceAll("{r}", excelRow) };
221
+ }
222
+ if (given && typeof given === "object") {
223
+ if (typeof given.f !== "string")
224
+ throw new Stop(
225
+ `Sheet "${name}", row ${excelRow}: a cell is a value or { "f": "=…" }.`,
226
+ );
227
+ return { f: given.f.replaceAll("{r}", excelRow) };
228
+ }
229
+ if (given === undefined || given === null || given === "")
230
+ return { v: null };
231
+ if (typeof given === "number" || typeof given === "boolean")
232
+ return { v: given };
233
+ // A date column holds dates: "2026-07-02" is that day, as Excel stores it
234
+ if (column.format !== undefined && isDateFormat(String(column.format)))
235
+ return { v: serialOf(given) ?? String(given) };
236
+ return { v: String(given) };
237
+ });
238
+ });
239
+ cells += (data.length + 2) * columns.length;
240
+ let totals = null;
241
+ if (one.totals) {
242
+ const { label = "Total", ...fns } = one.totals;
243
+ const byName = new Map(columns.map((column, c) => [column.name, c]));
244
+ totals = { label: String(label), cells: columns.map(() => null) };
245
+ for (const [key, fn] of Object.entries(fns)) {
246
+ if (!byName.has(key))
247
+ throw new Stop(
248
+ `Sheet "${name}": totals name "${key}", which is not a column (${columns.map((c) => c.name).join(", ")}).`,
249
+ );
250
+ if (!(fn in TOTALS))
251
+ throw new Stop(
252
+ `Sheet "${name}": total "${fn}" for "${key}" — use sum, average, count, min or max.`,
253
+ );
254
+ totals.cells[byName.get(key)] = fn;
255
+ }
256
+ if (totals.cells[0])
257
+ throw new Stop(
258
+ `Sheet "${name}": the first column holds the totals' label, so it cannot be totalled; put a name or a date first.`,
259
+ );
260
+ }
261
+ return { name, columns, data, totals };
262
+ });
263
+ if (cells > MOST_CELLS)
264
+ throw new Stop(
265
+ `That is ${cells.toLocaleString()} cells; a sheet here holds ${MOST_CELLS.toLocaleString()}. Work on the data with a script and put the result.`,
266
+ );
267
+ return { title: spec.title, sheets };
268
+ }
269
+
270
+ /**
271
+ * A CSV file's text: UTF-8, or the encoding it is said to be in. A file that is not UTF-8 and
272
+ * says nothing stops, since read as UTF-8 its words would come out as noise.
273
+ */
274
+ function csvText(file, flags = {}) {
275
+ const bytes = readFileSync(file);
276
+ const decode = (encoding) => {
277
+ try {
278
+ return new TextDecoder(encoding, { fatal: true }).decode(bytes);
279
+ } catch (failed) {
280
+ if (failed instanceof RangeError)
281
+ throw new Stop(
282
+ `"${encoding}" is not an encoding this reads: euc-kr, shift_jis, gbk, big5, windows-1252, iso-8859-1, utf-16le, utf-16be are.`,
283
+ );
284
+ throw new Stop(
285
+ `${shown(file)} is not written in ${encoding}: some of its bytes are not ${encoding} text. Try the next likely one.`,
286
+ );
287
+ }
288
+ };
289
+ if (typeof flags.encoding === "string") return decode(flags.encoding);
290
+ // A file that says what it is in its first bytes (a byte-order mark) is read as that
291
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return decode("utf-16le");
292
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return decode("utf-16be");
293
+ try {
294
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
295
+ } catch {
296
+ throw new Stop(
297
+ `${shown(file)} is not written in UTF-8. Run this again with the encoding it is in — --encoding euc-kr (Korean), shift_jis (Japanese), gbk or big5 (Chinese), windows-1252 (Western European), utf-16le — and look at its lines: words that do not read right mean another one.`,
298
+ );
299
+ }
300
+ }
301
+
302
+ /** A CSV's lines as cells, as written: quotes undone, nothing typed yet. */
303
+ function csvRows(text) {
304
+ const rows = [];
305
+ let row = [];
306
+ let field = "";
307
+ let quoted = false;
308
+ const body = text.replace(/^\uFEFF/, "");
309
+ for (let i = 0; i < body.length; i++) {
310
+ const ch = body[i];
311
+ if (quoted) {
312
+ if (ch === '"' && body[i + 1] === '"') {
313
+ field += '"';
314
+ i++;
315
+ } else if (ch === '"') quoted = false;
316
+ else field += ch;
317
+ } else if (ch === '"') quoted = true;
318
+ else if (ch === ",") {
319
+ row.push(field);
320
+ field = "";
321
+ } else if (ch === "\n" || ch === "\r") {
322
+ if (ch === "\r" && body[i + 1] === "\n") i++;
323
+ row.push(field);
324
+ rows.push(row);
325
+ row = [];
326
+ field = "";
327
+ } else field += ch;
328
+ }
329
+ if (field || row.length) {
330
+ row.push(field);
331
+ rows.push(row);
332
+ }
333
+ return rows;
334
+ }
335
+
336
+ /** A CSV cell as a number when it is written as one — 1234, 1,234.5, -5, (1,200) — else null. */
337
+ function csvNumber(cell) {
338
+ const minus = /^\((.*)\)$/.exec(cell);
339
+ const bare = minus ? minus[1].trim() : cell;
340
+ if (!/^-?(\d+|\d{1,3}(,\d{3})+)(\.\d+)?$/.test(bare)) return null;
341
+ const n = Number(bare.replaceAll(",", ""));
342
+ return minus ? -n : n;
343
+ }
344
+
345
+ /** Where a CSV's table is: `--header` (a line number, as read prints them), else its first
346
+ * line that holds something and is not a note (#); `--until` its last line. */
347
+ function csvTable(rows, flags) {
348
+ const line = (key) => {
349
+ if (flags[key] === undefined) return null;
350
+ if (typeof flags[key] !== "string" || !/^\d+$/.test(flags[key]))
351
+ throw new Stop(`--${key} takes a line number, as read prints them.`);
352
+ const n = Number(flags[key]);
353
+ if (n < 1 || n > rows.length)
354
+ throw new Stop(`--${key} is a line from 1 to ${rows.length}.`);
355
+ return n - 1;
356
+ };
357
+ const blank = (one) => !one.some((cell) => cell.trim());
358
+ const note = (one) => /^#/.test(one[0] ?? "");
359
+ let header = line("header");
360
+ if (header === null) {
361
+ header = rows.findIndex((one) => !blank(one) && !note(one));
362
+ if (header === -1) throw new Stop("The CSV has no lines.");
363
+ }
364
+ const until = line("until") ?? rows.length - 1;
365
+ if (until <= header)
366
+ throw new Stop("--until is a line under the one naming the columns.");
367
+ const dates = flags.dates ?? "ymd";
368
+ if (!["ymd", "dmy", "mdy"].includes(dates))
369
+ throw new Stop(
370
+ "--dates says how the file writes a day: ymd (2026-07-03), dmy (03.07.2026) or mdy (07/03/2026).",
371
+ );
372
+ return {
373
+ header,
374
+ dates,
375
+ body: rows
376
+ .map((cells, i) => ({ cells, line: i + 1 }))
377
+ .slice(header + 1, until + 1)
378
+ .filter(({ cells }) => !blank(cells) && !note(cells)),
379
+ };
380
+ }
381
+
382
+ /**
383
+ * One sheet from a CSV's lines, as `csvTable` finds its table: a number is a number, and a
384
+ * column whose every value is a date, written as `--dates` says, is a column of dates. A
385
+ * column that almost is — a line under it that is not a date, or dates written day or month
386
+ * first with no --dates — stays text, and a note says which line or what to give.
387
+ */
388
+ function describeCsv(rows, flags, name) {
389
+ const { header, dates, body } = csvTable(rows, flags);
390
+ let width = rows[header].length;
391
+ for (const { cells } of body) width = Math.max(width, cells.length);
392
+ const notes = [];
393
+ const columns = [];
394
+ const values = [];
395
+ for (let c = 0; c < width; c++) {
396
+ const name = (rows[header][c] ?? "").trim() || colName(c);
397
+ const cells = body.map(({ cells: one }) => (one[c] ?? "").trim());
398
+ const serials = cells.map((cell) => (cell ? serialOf(cell, dates) : null));
399
+ const filled = cells.filter(Boolean).length;
400
+ const dated = serials.filter((v) => v !== null).length;
401
+ const isDates = filled > 0 && dated === filled;
402
+ if (!isDates && dated > 0 && dated >= filled / 2) {
403
+ const off = body
404
+ .map(({ line }, r) => ({
405
+ line,
406
+ cell: cells[r],
407
+ bad: cells[r] && serials[r] === null,
408
+ }))
409
+ .filter((one) => one.bad)
410
+ .slice(0, 3)
411
+ .map(({ line, cell }) => `line ${line} ("${cell}")`);
412
+ notes.push(
413
+ `Column ${colName(c)} (${name}) is dates but for ${off.join(", ")}, so it stays text. A line under the table — a total — is left out with --until <its last line>.`,
414
+ );
415
+ }
416
+ if (
417
+ !dated &&
418
+ dates === "ymd" &&
419
+ filled &&
420
+ cells
421
+ .filter(Boolean)
422
+ .every((cell) => /^\d{1,2}[-/.]\d{1,2}[-/.]\d{4}/.test(cell))
423
+ )
424
+ notes.push(
425
+ `Column ${colName(c)} (${name}) writes its dates day or month first, which the file does not say; it stays text. Give --dates dmy (03.07.2026) or --dates mdy (07/03/2026), as the bank's country writes them.`,
426
+ );
427
+ const timed = cells.some(
428
+ (cell, r) => serials[r] !== null && /\d:\d/.test(cell),
429
+ );
430
+ const seconds = cells.some(
431
+ (cell, r) => serials[r] !== null && /\d:\d\d:\d/.test(cell),
432
+ );
433
+ columns.push({
434
+ name,
435
+ ...(isDates
436
+ ? {
437
+ format: seconds
438
+ ? "yyyy-mm-dd hh:mm:ss"
439
+ : timed
440
+ ? "yyyy-mm-dd hh:mm"
441
+ : "yyyy-mm-dd",
442
+ }
443
+ : {}),
444
+ });
445
+ values.push(
446
+ cells.map((cell, r) => {
447
+ if (!cell) return null;
448
+ // A date as put takes one: written YYYY-MM-DD, its time after it
449
+ if (isDates) return isoOf(serials[r]);
450
+ return csvNumber(cell) ?? cell;
451
+ }),
452
+ );
453
+ }
454
+ return {
455
+ notes,
456
+ header: header + 1,
457
+ spec: {
458
+ sheets: [
459
+ {
460
+ name: name.slice(0, 31),
461
+ columns,
462
+ rows: body.map((_, r) => columns.map((__, c) => values[c][r])),
463
+ },
464
+ ],
465
+ },
466
+ };
467
+ }
468
+
469
+ /** One sheet from a CSV, its table found as `read` finds it. */
470
+ function fromCsv(text, name, flags = {}) {
471
+ const rows = csvRows(text);
472
+ if (!rows.some((one) => one.some((cell) => cell.trim())))
473
+ throw new Stop("The CSV has no lines.");
474
+ return describeCsv(rows, flags, name);
475
+ }
476
+
477
+ /** Sheets of cells: header, rows, totals row; formulas worked out. */
478
+ function build(model, problems) {
479
+ const sheets = model.sheets.map((sheet) => {
480
+ const header = sheet.columns.map((column) => ({ v: column.name }));
481
+ const cells = [header, ...sheet.data];
482
+ let totals = null;
483
+ if (sheet.totals) {
484
+ const last = sheet.data.length + 1;
485
+ const row = sheet.columns.map((_, c) => {
486
+ const fn = sheet.totals.cells[c];
487
+ if (fn)
488
+ return {
489
+ f: `=SUBTOTAL(${TOTALS[fn]},${colName(c)}2:${colName(c)}${Math.max(2, last)})`,
490
+ };
491
+ return c === 0 ? { v: sheet.totals.label } : { v: null };
492
+ });
493
+ totals = cells.push(row) - 1;
494
+ }
495
+ return {
496
+ name: sheet.name,
497
+ columns: sheet.columns,
498
+ cells,
499
+ totals,
500
+ totalsSpec: sheet.totals,
501
+ };
502
+ });
503
+ try {
504
+ workOut(sheets, { problems });
505
+ } catch (failed) {
506
+ if (failed instanceof FormulaError)
507
+ throw new Stop(`A formula cannot be worked out — ${failed.message}.`);
508
+ throw failed;
509
+ }
510
+ for (const sheet of sheets)
511
+ sheet.columns = sheet.columns.map((column, c) => {
512
+ const values = sheet.cells
513
+ .slice(1)
514
+ .map((row) => row[c]?.v ?? null)
515
+ .filter((v) => v !== null);
516
+ const numbers = values.filter((v) => typeof v === "number").length;
517
+ return {
518
+ name: column.name,
519
+ format: column.format,
520
+ num: values.length > 0 && numbers >= values.length / 2,
521
+ width:
522
+ typeof column.width === "number"
523
+ ? column.width
524
+ : widthOf([
525
+ column.name,
526
+ ...sheet.cells
527
+ .slice(1, 200)
528
+ .map((row) => formatValue(row[c]?.v ?? null, column.format)),
529
+ ]),
530
+ };
531
+ });
532
+ return sheets;
533
+ }
534
+
535
+ // ── the page ───────────────────────────────────────────────────────────────
536
+
537
+ /** The page for a workbook, with the .xlsx's hash so a later put knows whether Excel changed it. */
538
+ function page({ title, sheets, xlsxName, hash }) {
539
+ const part = (file) => readFileSync(join(RUNTIME, file), "utf8").trim();
540
+ const data = {
541
+ title,
542
+ sheets: sheets.map((sheet) => {
543
+ const end = sheet.totals ?? sheet.cells.length;
544
+ return {
545
+ name: sheet.name,
546
+ columns: sheet.columns.map(({ name, format, num, width }) => ({
547
+ name,
548
+ format: format ?? null,
549
+ num,
550
+ width,
551
+ })),
552
+ rows: sheet.cells.slice(1, end).map((row) =>
553
+ sheet.columns.map((_, c) => {
554
+ const cell = row[c] ?? {};
555
+ return cell.f === undefined
556
+ ? { v: cell.v ?? null }
557
+ : { v: cell.v ?? null, f: cell.f };
558
+ }),
559
+ ),
560
+ totals: sheet.totalsSpec ?? null,
561
+ };
562
+ }),
563
+ };
564
+ const escape = (text) =>
565
+ String(text).replace(
566
+ /[&<>"]/g,
567
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c],
568
+ );
569
+ return wear(
570
+ part("sheet.html")
571
+ .replaceAll("{{title}}", escape(title))
572
+ .replace("{{xlsx.hash}}", hash)
573
+ .replace("{{xlsx.file}}", () => escape(encodeURIComponent(xlsxName)))
574
+ // The workbook in place of the template's empty one; `<` escaped, so no text closes the tag
575
+ .replace(
576
+ '<script type="application/json" id="sheet-data">null</script>',
577
+ () =>
578
+ `<script type="application/json" id="sheet-data">${JSON.stringify(data).replaceAll("<", "\\u003c")}</script>`,
579
+ )
580
+ .replace("/* sheet.css */", () => part("sheet.css"))
581
+ // The formula engine, whole, so an edit made in the page is worked out as the file will be
582
+ .replace(
583
+ "// formula.mjs",
584
+ () =>
585
+ `const Formula = (() => {\n${part("formula.mjs").replace(/^export /gm, "")}\nreturn { workOut, moveRefs, fillDown, parse, FormulaError, colName, referencesIn };\n})();`,
586
+ )
587
+ .replace("// format.mjs", () =>
588
+ part("format.mjs").replace(/^export /gm, ""),
589
+ )
590
+ .replace("// sheet.js", () => part("sheet.js")),
591
+ );
592
+ }
593
+
594
+ /** The .xlsx and its page written, over nothing the user changed since. */
595
+ function write(name, sheets, title, over) {
596
+ const { folder, xlsx, page: pagePath } = filesFor(name);
597
+ if (existsSync(xlsx) && !over) {
598
+ const kept = drawnHash(pagePath);
599
+ if (kept !== hashOf(readFileSync(xlsx)) || userChanged(pagePath))
600
+ throw new Stop(
601
+ `${shown(xlsx)} was changed after it was last written — in Excel, in the app, or by hand. Read it first (node ${SCRIPT} read ${name}), make your change from what it holds now, then put again with --over.`,
602
+ );
603
+ }
604
+ const bytes = writeXlsx({ sheets });
605
+ mkdirSync(folder, { recursive: true });
606
+ writeFileSync(xlsx, bytes);
607
+ const hash = hashOf(bytes);
608
+ writeFileSync(
609
+ pagePath,
610
+ page({ title: title || name, sheets, xlsxName: basename(xlsx), hash }),
611
+ );
612
+ return { xlsx, pagePath };
613
+ }
614
+
615
+ function put(name, from, flags) {
616
+ if (!from || !existsSync(from))
617
+ throw new Stop(
618
+ `No file ${from ?? ""}. Give a book.json or a CSV: node ${SCRIPT} put <name> <file>`,
619
+ );
620
+ filesFor(name);
621
+ let model;
622
+ let notes = [];
623
+ if (extname(from).toLowerCase() === ".csv") {
624
+ const made = fromCsv(csvText(from, flags), name, flags);
625
+ model = made.spec;
626
+ notes = made.notes;
627
+ } else {
628
+ let spec;
629
+ try {
630
+ spec = JSON.parse(readFileSync(from, "utf8"));
631
+ } catch (failed) {
632
+ throw new Stop(`${from} is not JSON: ${failed.message}`);
633
+ }
634
+ model = spec;
635
+ }
636
+ const described = fromDescription(model);
637
+ const sheets = build(described);
638
+ const title = typeof flags.title === "string" ? flags.title : described.title;
639
+ const { xlsx, pagePath } = write(name, sheets, title, Boolean(flags.over));
640
+ const rows = sheets
641
+ .map(
642
+ (s) =>
643
+ `${s.name} ${s.cells.length - 1 - (s.totals === null ? 0 : 1)} rows`,
644
+ )
645
+ .join(", ");
646
+ for (const line of notes) console.log(line);
647
+ console.log(
648
+ `Wrote ${shown(xlsx)} (${rows}) and its page ${shown(pagePath)}. Hand back both paths: the page opens in the app, the .xlsx in Excel. To see it: node ${SCRIPT} shots ${name}`,
649
+ );
650
+ }
651
+
652
+ // ── reading one ────────────────────────────────────────────────────────────
653
+
654
+ /** A workbook named or pointed at, and where its page goes. */
655
+ function workbookAt(arg, flags = {}) {
656
+ if (!arg) throw new Stop("Give a sheet's name or an .xlsx path.");
657
+ if (/\.xlsx$/i.test(arg)) {
658
+ const file = resolve(arg);
659
+ if (!existsSync(file)) throw new Stop(`No file ${arg}.`);
660
+ const name =
661
+ typeof flags.name === "string"
662
+ ? flags.name
663
+ : nameFromFile(file, 80, "sheet");
664
+ return { file, name };
665
+ }
666
+ if (/\.xls$/i.test(arg))
667
+ throw new Stop(
668
+ "An .xls is Excel's old format, which this cannot read: open it in Excel or Numbers and save it as .xlsx, or ask the user to.",
669
+ );
670
+ const { xlsx } = filesFor(arg);
671
+ if (!existsSync(xlsx))
672
+ throw new Stop(
673
+ `No sheet ${shown(xlsx)}. Make one: node ${SCRIPT} put ${arg} <book.json | data.csv>`,
674
+ );
675
+ return { file: xlsx, name: arg };
676
+ }
677
+
678
+ /**
679
+ * A workbook read back. A formula saved with no value beside it — a program other than Excel
680
+ * wrote the file — is worked out here; a value Excel stored stays as Excel had it. `unworked`
681
+ * says why none were worked out, when one of them is a formula this cannot work out.
682
+ */
683
+ function readBook(file) {
684
+ let book;
685
+ try {
686
+ book = readXlsx(readFileSync(file));
687
+ } catch (failed) {
688
+ throw new Stop(`${shown(file)}: ${failed.message}`);
689
+ }
690
+ const missing = book.sheets.some((sheet) =>
691
+ sheet.rows.some((row) => row.some((cell) => cell.f && cell.v === null)),
692
+ );
693
+ if (!missing) return book;
694
+ const copies = book.sheets.map((sheet) => ({
695
+ name: sheet.name,
696
+ cells: sheet.rows.map((row) =>
697
+ row.map((cell) => (cell.f ? { f: cell.f } : { v: cell.v })),
698
+ ),
699
+ }));
700
+ try {
701
+ workOut(copies);
702
+ } catch (failed) {
703
+ if (!(failed instanceof FormulaError)) throw failed;
704
+ return { ...book, unworked: failed.message };
705
+ }
706
+ book.sheets.forEach((sheet, s) =>
707
+ sheet.rows.forEach((row, r) =>
708
+ row.forEach((cell, c) => {
709
+ if (cell.f && cell.v === null) cell.v = copies[s].cells[r][c].v;
710
+ }),
711
+ ),
712
+ );
713
+ return book;
714
+ }
715
+
716
+ /** A value as text; a date, in a column written as dates, as YYYY-MM-DD. */
717
+ const text = (v, format) =>
718
+ v === null || v === undefined
719
+ ? ""
720
+ : typeof v === "number" && format && isDateFormat(format)
721
+ ? isoOf(v)
722
+ : typeof v === "object"
723
+ ? v.error
724
+ : typeof v === "boolean"
725
+ ? v
726
+ ? "TRUE"
727
+ : "FALSE"
728
+ : String(v);
729
+
730
+ /** How many rows `read` prints: --rows, 20 unless said. */
731
+ const mostRows = (flags) => Math.max(1, Number(flags.rows) || 20);
732
+
733
+ /** A name from a file's name, as a sheet or a workbook may take it. */
734
+ const nameFromFile = (file, most, fallback) =>
735
+ basename(file, extname(file))
736
+ .replace(/[^\p{L}\p{N}_-]+/gu, "-")
737
+ .replace(/^-+|-+$/g, "")
738
+ .slice(0, most) || fallback;
739
+
740
+ /** A workbook's description written as put takes it, a row on each line so the rows read as a table. */
741
+ function writeSpec(path, spec) {
742
+ const rows = [];
743
+ for (const sheet of spec.sheets)
744
+ sheet.rows = sheet.rows.map((row) => `\u0000${rows.push(row) - 1}`);
745
+ writeFileSync(
746
+ path,
747
+ `${JSON.stringify(spec, null, 2).replace(/"\\u0000(\d+)"/g, (_, n) =>
748
+ JSON.stringify(rows[Number(n)]),
749
+ )}\n`,
750
+ );
751
+ }
752
+
753
+ /**
754
+ * A CSV as it is written — a bank's export often has lines about the account over the table —
755
+ * its lines numbered, so the one naming the columns can be given as --header.
756
+ */
757
+ function readCsv(arg, flags) {
758
+ const file = resolve(arg);
759
+ if (!existsSync(file)) throw new Stop(`No file ${arg}.`);
760
+ const rows = csvRows(csvText(file, flags));
761
+ if (!rows.some((one) => one.some((cell) => cell.trim())))
762
+ throw new Stop(`${shown(file)} has no lines.`);
763
+ const most = mostRows(flags);
764
+ const out = [`${shown(file)}: ${rows.length} lines.`];
765
+ rows
766
+ .slice(0, most)
767
+ .forEach((row, i) => out.push(`${i + 1}\t${row.join("\t")}`));
768
+ if (rows.length > most) out.push(`… ${rows.length - most} more lines`);
769
+ const { notes, header, spec } = describeCsv(
770
+ rows,
771
+ flags,
772
+ nameFromFile(file, 31, "Sheet1"),
773
+ );
774
+ out.push(...notes);
775
+ if (typeof flags.json === "string") {
776
+ writeSpec(flags.json, spec);
777
+ out.push(
778
+ `Wrote ${shown(resolve(flags.json))}: line ${header} as the columns, the ${spec.sheets[0].rows.length} lines under it as rows${spec.sheets[0].columns.some((c) => c.format) ? ", dates as dates" : ""}. Change it there and put it: node ${SCRIPT} put <name> ${flags.json}`,
779
+ );
780
+ } else
781
+ out.push(
782
+ `Line ${header} names the columns (--header <line> for another); --json <file> writes the table under it as put takes it.`,
783
+ );
784
+ console.log(out.join("\n"));
785
+ }
786
+
787
+ function read(arg, flags) {
788
+ if (/\.csv$/i.test(arg ?? "")) return readCsv(arg, flags);
789
+ const { file } = workbookAt(arg, flags);
790
+ const { sheets, unworked } = readBook(file);
791
+ const most = mostRows(flags);
792
+ const out = [
793
+ `${shown(file)}: ${sheets.length} sheet${sheets.length === 1 ? "" : "s"}.`,
794
+ ];
795
+ if (unworked)
796
+ out.push(
797
+ `Formulas saved without their values are left empty: ${unworked}. Opening the file in Excel and saving it stores them.`,
798
+ );
799
+ for (const sheet of sheets) {
800
+ const width = sheet.rows[0]?.length ?? 0;
801
+ out.push(
802
+ "",
803
+ `## ${sheet.name} — ${Math.max(0, sheet.rows.length - 1)} rows under a header, ${width} columns (A–${colName(Math.max(0, width - 1))})`,
804
+ );
805
+ const cellText = (cell, r, c) =>
806
+ text(cell.v, r > 0 ? sheet.formats[c] : null);
807
+ sheet.rows.slice(0, most + 1).forEach((row, r) => {
808
+ out.push(row.map((cell, c) => cellText(cell, r, c)).join("\t"));
809
+ });
810
+ if (sheet.rows.length > most + 1)
811
+ out.push(`… ${sheet.rows.length - most - 1} more rows`);
812
+ const formulas = [];
813
+ sheet.rows.forEach((row, r) =>
814
+ row.forEach((cell, c) => {
815
+ if (cell.f) formulas.push(`${colName(c)}${r + 1} ${cell.f}`);
816
+ }),
817
+ );
818
+ if (formulas.length)
819
+ out.push(
820
+ `Formulas (${formulas.length}): ${formulas.slice(0, 12).join("; ")}${formulas.length > 12 ? "; …" : ""}`,
821
+ );
822
+ }
823
+ if (typeof flags.json === "string") {
824
+ const pagePath = /\.xlsx$/i.test(arg) ? null : filesFor(arg).page;
825
+ writeSpec(flags.json, describe(fromXlsx(sheets), titleOf(pagePath)));
826
+ out.push(
827
+ `Wrote ${shown(resolve(flags.json))}: the whole workbook as put takes it. Change it there and put it back${pagePath ? ` (node ${SCRIPT} put ${arg} ${flags.json} --over)` : ""}; a column worked out by one formula has it as its "formula".`,
828
+ );
829
+ }
830
+ if (typeof flags.csv === "string") {
831
+ mkdirSync(flags.csv, { recursive: true });
832
+ for (const sheet of sheets) {
833
+ const path = join(
834
+ flags.csv,
835
+ `${sheet.name.replace(/[\\/:*?"<>|]+/g, "-")}.csv`,
836
+ );
837
+ const csv = sheet.rows
838
+ .map((row, r) =>
839
+ row
840
+ .map((cell, c) => {
841
+ const t = text(cell.v, r > 0 ? sheet.formats[c] : null);
842
+ return /[",\n]/.test(t) ? `"${t.replaceAll('"', '""')}"` : t;
843
+ })
844
+ .join(","),
845
+ )
846
+ .join("\n");
847
+ writeFileSync(path, `${csv}\n`);
848
+ out.push(`Wrote ${path}`);
849
+ }
850
+ }
851
+ console.log(out.join("\n"));
852
+ }
853
+
854
+ /** A workbook read back into sheets the page draws: the SUBTOTAL row found again as the totals. */
855
+ function fromXlsx(sheets) {
856
+ const back = Object.fromEntries(
857
+ Object.entries(TOTALS).map(([fn, n]) => [n, fn]),
858
+ );
859
+ return sheets.map((sheet) => {
860
+ const [header = [], ...rest] = sheet.rows;
861
+ const width = header.length;
862
+ const columns = header.map((cell, c) => ({
863
+ name: text(cell.v) || colName(c),
864
+ }));
865
+ let totals = null;
866
+ const last = rest.at(-1);
867
+ if (last?.some((cell) => /^=SUBTOTAL\(/i.test(cell.f ?? ""))) {
868
+ totals = {
869
+ label: text(last[0]?.v) || "Total",
870
+ cells: last.map((cell) => {
871
+ const n = /^=SUBTOTAL\((\d+)/i.exec(cell.f ?? "")?.[1];
872
+ return n ? (back[Number(n)] ?? back[Number(n) + 100] ?? "sum") : null;
873
+ }),
874
+ };
875
+ }
876
+ const cells = [header, ...rest.slice(0, totals ? -1 : undefined)];
877
+ return {
878
+ name: sheet.name,
879
+ cells: totals ? [...cells, last] : cells,
880
+ totals: totals ? cells.length : null,
881
+ totalsSpec: totals,
882
+ columns: columns.map((column, c) => {
883
+ const format =
884
+ sheet.formats[c] && !checkFormat(sheet.formats[c])
885
+ ? sheet.formats[c]
886
+ : undefined;
887
+ const values = rest
888
+ .map((row) => row[c]?.v ?? null)
889
+ .filter((v) => v !== null);
890
+ return {
891
+ ...column,
892
+ format,
893
+ num:
894
+ values.length > 0 &&
895
+ values.filter((v) => typeof v === "number").length >=
896
+ values.length / 2,
897
+ width:
898
+ sheet.widths[c] ??
899
+ widthOf([
900
+ column.name,
901
+ ...rest
902
+ .slice(0, 200)
903
+ .map((row) => formatValue(row[c]?.v ?? null, format)),
904
+ ]),
905
+ };
906
+ }),
907
+ width,
908
+ };
909
+ });
910
+ }
911
+
912
+ /** The title a sheet's page carries, or null. */
913
+ function titleOf(pagePath) {
914
+ if (!pagePath || !existsSync(pagePath)) return null;
915
+ try {
916
+ return (
917
+ JSON.parse(DATA.exec(readFileSync(pagePath, "utf8"))?.[1] ?? "null")
918
+ ?.title ?? null
919
+ );
920
+ } catch {
921
+ return null;
922
+ }
923
+ }
924
+
925
+ /**
926
+ * A workbook read back as the description put takes (references/sheet.md): a column whose
927
+ * every row holds one formula filled down has it as its `formula`, other formulas stay in their
928
+ * cells, and the totals row is `totals` again. An error Excel saved in a cell is left empty.
929
+ */
930
+ function describe(drawn, title) {
931
+ return {
932
+ ...(title ? { title } : {}),
933
+ sheets: drawn.map((sheet) => {
934
+ const end = sheet.totals ?? sheet.cells.length;
935
+ const rows = sheet.cells.slice(1, end);
936
+ const width = sheet.columns.length;
937
+ const formulas = sheet.columns.map((_, c) => {
938
+ if (!rows.length || !rows.every((row) => row[c]?.f)) return null;
939
+ const template = asColumnFormula(rows[0][c].f, 2);
940
+ return template &&
941
+ rows.every(
942
+ (row, i) => template.replaceAll("{r}", String(i + 2)) === row[c].f,
943
+ )
944
+ ? template
945
+ : null;
946
+ });
947
+ const value = (cell, c) => {
948
+ const v = cell?.v ?? null;
949
+ if (v !== null && typeof v === "object") return null;
950
+ const format = sheet.columns[c].format;
951
+ return typeof v === "number" && format && isDateFormat(format)
952
+ ? isoOf(v)
953
+ : v;
954
+ };
955
+ return {
956
+ name: sheet.name,
957
+ columns: sheet.columns.map((column, c) => ({
958
+ name: column.name,
959
+ ...(column.format ? { format: column.format } : {}),
960
+ ...(formulas[c] ? { formula: formulas[c] } : {}),
961
+ })),
962
+ rows: rows.map((row) =>
963
+ Array.from({ length: width }, (_, c) =>
964
+ formulas[c] ? null : row[c]?.f ? { f: row[c].f } : value(row[c], c),
965
+ ),
966
+ ),
967
+ ...(sheet.totalsSpec
968
+ ? {
969
+ totals: {
970
+ label: sheet.totalsSpec.label,
971
+ ...Object.fromEntries(
972
+ sheet.totalsSpec.cells
973
+ .map((fn, c) => [sheet.columns[c]?.name, fn])
974
+ .filter(([, fn]) => fn),
975
+ ),
976
+ },
977
+ }
978
+ : {}),
979
+ };
980
+ }),
981
+ };
982
+ }
983
+
984
+ function view(arg, flags) {
985
+ const { file, name } = workbookAt(arg, flags);
986
+ const { sheets, unworked } = readBook(file);
987
+ const drawn = fromXlsx(sheets);
988
+ const { folder, xlsx, page: pagePath } = filesFor(name);
989
+ mkdirSync(folder, { recursive: true });
990
+ if (resolve(file) !== resolve(xlsx)) {
991
+ if (
992
+ existsSync(xlsx) &&
993
+ hashOf(readFileSync(xlsx)) !== hashOf(readFileSync(file))
994
+ )
995
+ throw new Stop(
996
+ `${shown(xlsx)} already holds another workbook. Give this one another name: --name <name>.`,
997
+ );
998
+ copyFileSync(file, xlsx);
999
+ }
1000
+ const hash = hashOf(readFileSync(xlsx));
1001
+ const title =
1002
+ typeof flags.title === "string" ? flags.title : (titleOf(pagePath) ?? name);
1003
+ writeFileSync(
1004
+ pagePath,
1005
+ page({ title, sheets: drawn, xlsxName: basename(xlsx), hash }),
1006
+ );
1007
+ console.log(
1008
+ `Drew ${shown(pagePath)} from ${shown(xlsx)}. Hand back the page; the .xlsx stays the file.${unworked ? ` Formulas saved without their values show empty: ${unworked}.` : ""}`,
1009
+ );
1010
+ }
1011
+
1012
+ // ── an edit made in the page ───────────────────────────────────────────────
1013
+
1014
+ const DATA =
1015
+ /<script type="application\/json" id="sheet-data">([\s\S]*?)<\/script>/;
1016
+
1017
+ /** A file written beside itself and moved into place, so it is never half written. */
1018
+ function writeAtomic(file, content) {
1019
+ const beside = `${file}.${process.pid}.saving`;
1020
+ writeFileSync(beside, content);
1021
+ try {
1022
+ renameSync(beside, file);
1023
+ } catch (failed) {
1024
+ rmSync(beside, { force: true });
1025
+ throw failed;
1026
+ }
1027
+ }
1028
+
1029
+ /** A sheet's page holding `sheets` and naming the .xlsx they are in, its head left as it is. */
1030
+ function withBook(html, sheets, xlsx, hash) {
1031
+ // Drawn from what the user changed: a bot's next put reads it first (userChanged)
1032
+ let title = basename(xlsx, ".xlsx");
1033
+ try {
1034
+ title = JSON.parse(DATA.exec(html)?.[1] ?? "null")?.title || title;
1035
+ } catch {}
1036
+ const fresh = page({ title, sheets, xlsxName: basename(xlsx), hash });
1037
+ return html
1038
+ .replace(
1039
+ /<meta name="sheet-xlsx" content="[0-9a-f]*"( data-edited)?/,
1040
+ EDITED(hash),
1041
+ )
1042
+ .replace(DATA, () => DATA.exec(fresh)[0]);
1043
+ }
1044
+
1045
+ /**
1046
+ * The workbook a page edited in the app holds, written into the .xlsx beside the page it
1047
+ * replaces. A formula that no longer works out keeps its error code in its cell, as Excel shows
1048
+ * it, rather than stop the save. The .xlsx changed since the page drew it — in Excel — stops.
1049
+ */
1050
+ function sync(edited, flags) {
1051
+ const pagePath = typeof flags.page === "string" ? resolve(flags.page) : null;
1052
+ if (!edited || !existsSync(edited) || !pagePath || !existsSync(pagePath))
1053
+ throw new Stop(`Give the edited page and --page <page.html>.`);
1054
+ const xlsx = join(
1055
+ dirname(pagePath),
1056
+ `${basename(pagePath, extname(pagePath))}.xlsx`,
1057
+ );
1058
+ // Changed since the page drew it: the page is drawn again from the file, under a new
1059
+ // revision, and exit 3 has the app tell the open page as it does of a page written since —
1060
+ // its Reload then shows the file as it is, not the page the edit came from
1061
+ if (existsSync(xlsx) && drawnHash(pagePath) !== hashOf(readFileSync(xlsx))) {
1062
+ const bytes = readFileSync(xlsx);
1063
+ const { sheets, unworked } = readBook(xlsx);
1064
+ const now = readFileSync(pagePath, "utf8");
1065
+ writeAtomic(
1066
+ pagePath,
1067
+ withBook(now, fromXlsx(sheets), xlsx, hashOf(bytes)).replace(
1068
+ /<meta name="revision" content="[^"]*">/,
1069
+ `<meta name="revision" content="${revision()}">`,
1070
+ ),
1071
+ );
1072
+ console.error(
1073
+ `${shown(xlsx)} was changed after this page drew it — in Excel, or by a bot.${unworked ? ` Formulas saved without their values show empty: ${unworked}.` : ""}`,
1074
+ );
1075
+ process.exitCode = 3;
1076
+ return;
1077
+ }
1078
+ const html = readFileSync(edited, "utf8");
1079
+ let data;
1080
+ try {
1081
+ data = JSON.parse(DATA.exec(html)?.[1] ?? "null");
1082
+ } catch {
1083
+ data = null;
1084
+ }
1085
+ if (!data || !Array.isArray(data.sheets))
1086
+ throw new Stop("The page holds no workbook to keep.");
1087
+ const described = fromDescription({
1088
+ title: data.title,
1089
+ sheets: data.sheets.map((sheet) => ({
1090
+ name: sheet?.name,
1091
+ columns: (sheet?.columns ?? []).map((column) => ({
1092
+ name: column?.name,
1093
+ format: column?.format ?? undefined,
1094
+ width: typeof column?.width === "number" ? column.width : undefined,
1095
+ })),
1096
+ rows: (sheet?.rows ?? []).map((row) =>
1097
+ (Array.isArray(row) ? row : []).map((cell) =>
1098
+ typeof cell?.f === "string" ? { f: cell.f } : (cell?.v ?? null),
1099
+ ),
1100
+ ),
1101
+ totals: sheet?.totals
1102
+ ? {
1103
+ label: sheet.totals.label,
1104
+ ...Object.fromEntries(
1105
+ (sheet.totals.cells ?? [])
1106
+ .map((fn, c) => [sheet.columns?.[c]?.name, fn])
1107
+ .filter(([, fn]) => fn),
1108
+ ),
1109
+ }
1110
+ : undefined,
1111
+ })),
1112
+ });
1113
+ const sheets = build(described, []);
1114
+ const bytes = writeXlsx({ sheets });
1115
+ writeAtomic(xlsx, bytes);
1116
+ // The edited page keeps its own head and shell; only what the .xlsx now holds is new
1117
+ writeFileSync(edited, withBook(html, sheets, xlsx, hashOf(bytes)));
1118
+ console.log(`Wrote ${shown(xlsx)}.`);
1119
+ }
1120
+
1121
+ function shots(name) {
1122
+ const { page: pagePath } = filesFor(name);
1123
+ if (!existsSync(pagePath)) throw new Stop(`No sheet ${shown(pagePath)}.`);
1124
+ const out = join(WORKSPACE, "scratch", `${name}-sheet-shots`);
1125
+ rmSync(out, { recursive: true, force: true });
1126
+ mkdirSync(out, { recursive: true });
1127
+ const done = spawnSync(
1128
+ process.execPath,
1129
+ [
1130
+ join(SKILLS, "artifact", "runtime", "render.mjs"),
1131
+ pagePath,
1132
+ "--out",
1133
+ out,
1134
+ "--size",
1135
+ "1280x800",
1136
+ "--most",
1137
+ "1",
1138
+ "--name",
1139
+ "sheet",
1140
+ "--apart",
1141
+ ],
1142
+ { stdio: "inherit" },
1143
+ );
1144
+ if (done.status !== 0)
1145
+ throw new Stop("Fix what it names above, then run this again.");
1146
+ console.log(`Look at it with look_at, from ${shown(out)}.`);
1147
+ }
1148
+
1149
+ const { positional, flags } = parseArgs(process.argv.slice(2));
1150
+ const [command, ...rest] = positional;
1151
+ try {
1152
+ if (command === "put") put(rest[0], rest[1], flags);
1153
+ else if (command === "read") read(rest[0], flags);
1154
+ else if (command === "view") view(rest[0], flags);
1155
+ else if (command === "shots") shots(rest[0]);
1156
+ else if (command === "sync") sync(rest[0], flags);
1157
+ else
1158
+ throw new Stop(
1159
+ `${usage()}\nFunctions a formula may use: ${FUNCTIONS.join(", ")}. A cell elsewhere: ${sheetRef("Other sheet")}!B2.`,
1160
+ );
1161
+ } catch (error) {
1162
+ if (!(error instanceof Stop)) throw error;
1163
+ console.error(error.message);
1164
+ process.exitCode = 1;
1165
+ }