@jant/core 0.7.1 → 0.8.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 (329) hide show
  1. package/bin/commands/assets/prepare.js +3 -3
  2. package/bin/commands/db/export.js +115 -2
  3. package/bin/commands/deploy.js +11 -3
  4. package/bin/commands/{search-reindex.js → search/reindex.js} +5 -5
  5. package/bin/commands/site/export.js +48 -36
  6. package/bin/commands/site/import.js +3074 -2
  7. package/bin/commands/site/snapshot/import.js +2 -0
  8. package/bin/commands/telegram/register-webhooks.js +48 -23
  9. package/bin/jant.js +16 -11
  10. package/bin/lib/command-registry.js +120 -0
  11. package/bin/lib/migration-artifacts.js +19 -0
  12. package/bin/lib/renamed-arguments.js +56 -0
  13. package/bin/lib/site-snapshot.js +83 -1
  14. package/dist/{app-ZcaI1kPN.js → app--uxnaIRV.js} +8339 -740
  15. package/dist/client/.vite/manifest.json +3 -3
  16. package/dist/client/_assets/{client-DAhoqPdr.css → client-BCumu1-D.css} +1 -1
  17. package/dist/client/_assets/{client-knSEyUJO.js → client-BT6kpcuG.js} +1 -1
  18. package/dist/client/_assets/{client-auth-CAMfTrKW.js → client-auth-begiT1tq.js} +1 -1
  19. package/dist/index.js +2 -3
  20. package/dist/node.js +2 -3
  21. package/dist/url-CKlGzvdN.js +428 -0
  22. package/package.json +1 -5
  23. package/src/__tests__/cli-commands.test.ts +144 -0
  24. package/src/__tests__/config-docs.test.ts +148 -0
  25. package/src/__tests__/export-import-roundtrip.test.ts +1 -1
  26. package/src/__tests__/feed-docs.test.ts +36 -0
  27. package/src/__tests__/fixtures/releases/0.7.0/site-export/README.md +89 -0
  28. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/41q27/0x4nv/index.md +16 -0
  29. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/41q27/_index.md +41 -0
  30. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/41q27/faqyt/index.md +28 -0
  31. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +18 -0
  32. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/_index.md +4 -0
  33. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +27 -0
  34. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +32 -0
  35. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/archive/_index.md +7 -0
  36. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +27 -0
  37. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/bought-too-many-lemons-again/_index.md +34 -0
  38. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/city-walks/_index.md +11 -0
  39. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/collections/_index.md +4 -0
  40. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/current-tea-rotation/_index.md +31 -0
  41. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +27 -0
  42. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/desk-but-better/_index.md +22 -0
  43. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/e0kcg/_index.md +19 -0
  44. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/featured/_index.md +7 -0
  45. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/from-basho/_index.md +22 -0
  46. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/from-epictetus/_index.md +22 -0
  47. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/from-marcus-aurelius/_index.md +22 -0
  48. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/from-seneca/_index.md +22 -0
  49. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/from-thoreau/_index.md +22 -0
  50. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/gkbvv/2cl6d/index.md +16 -0
  51. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/gkbvv/3zqv7/index.md +28 -0
  52. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/gkbvv/5oxsv/index.md +16 -0
  53. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/gkbvv/_index.md +36 -0
  54. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/home-cooking/_index.md +11 -0
  55. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/k5vh8/_index.md +29 -0
  56. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +18 -0
  57. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/k5vh8/a83qu/index.md +16 -0
  58. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +19 -0
  59. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +27 -0
  60. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +27 -0
  61. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/qgfcu/_index.md +29 -0
  62. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/qgfcu/c91j0/index.md +16 -0
  63. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/qgfcu/qyucy/index.md +16 -0
  64. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/qgfcu/wsgck/index.md +16 -0
  65. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +43 -0
  66. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/reading-notes/_index.md +11 -0
  67. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +27 -0
  68. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/te812/_index.md +41 -0
  69. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/te812/cxiu6/index.md +16 -0
  70. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/te812/t77ms/index.md +16 -0
  71. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +18 -0
  72. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/telk3/_index.md +27 -0
  73. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/telk3/from-thoreau-pawt2/index.md +17 -0
  74. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +32 -0
  75. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +29 -0
  76. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +27 -0
  77. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/tiny-projects/_index.md +11 -0
  78. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/useful-links/_index.md +11 -0
  79. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/weekend-notes/_index.md +11 -0
  80. package/src/__tests__/fixtures/releases/0.7.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +49 -0
  81. package/src/__tests__/fixtures/releases/0.7.0/site-export/data/jant.toml +119 -0
  82. package/src/__tests__/fixtures/releases/0.7.0/site-export/hugo.toml +43 -0
  83. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/021801c20ab3-med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  84. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/0f868ce9ac84-med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  85. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/50c2ad911bad-med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  86. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/7a91f0960491-med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  87. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/8714116d3c8e-med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  88. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/8a0b4277443f-med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  89. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/a7d1c8a1afd9-med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  90. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/e25570b405f5-med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  91. package/src/__tests__/fixtures/releases/0.7.0/site-export/static/media/e89ea4eabf01-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  92. package/src/__tests__/fixtures/releases/0.7.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  93. package/src/__tests__/fixtures/releases/0.7.0/site-export/themes/jant/static/custom.css +0 -0
  94. package/src/__tests__/fixtures/releases/0.7.0/site-export/themes/jant/static/favicon.ico +0 -0
  95. package/src/__tests__/fixtures/releases/0.7.0/snapshot/db.sql +218 -0
  96. package/src/__tests__/fixtures/releases/0.7.0/snapshot/meta.json +9 -0
  97. package/src/__tests__/fixtures/releases/0.7.1/site-export/README.md +89 -0
  98. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/41q27/0x4nv/index.md +16 -0
  99. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/41q27/_index.md +41 -0
  100. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/41q27/faqyt/index.md +28 -0
  101. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +18 -0
  102. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/_index.md +4 -0
  103. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +27 -0
  104. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +32 -0
  105. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/archive/_index.md +7 -0
  106. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +27 -0
  107. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/bought-too-many-lemons-again/_index.md +34 -0
  108. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/city-walks/_index.md +11 -0
  109. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/collections/_index.md +4 -0
  110. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/current-tea-rotation/_index.md +31 -0
  111. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +27 -0
  112. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/desk-but-better/_index.md +22 -0
  113. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/e0kcg/_index.md +19 -0
  114. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/featured/_index.md +7 -0
  115. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/from-basho/_index.md +22 -0
  116. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/from-epictetus/_index.md +22 -0
  117. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/from-marcus-aurelius/_index.md +22 -0
  118. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/from-seneca/_index.md +22 -0
  119. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/from-thoreau/_index.md +22 -0
  120. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/gkbvv/2cl6d/index.md +16 -0
  121. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/gkbvv/3zqv7/index.md +28 -0
  122. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/gkbvv/5oxsv/index.md +16 -0
  123. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/gkbvv/_index.md +36 -0
  124. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/home-cooking/_index.md +11 -0
  125. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/k5vh8/_index.md +29 -0
  126. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +18 -0
  127. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/k5vh8/a83qu/index.md +16 -0
  128. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/k5vh8/from-seneca-5hibo/index.md +19 -0
  129. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/mynoise-for-rainy-afternoons/_index.md +27 -0
  130. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/nts-archives-are-good-cleaning-music/_index.md +27 -0
  131. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/qgfcu/_index.md +29 -0
  132. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/qgfcu/c91j0/index.md +16 -0
  133. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/qgfcu/qyucy/index.md +16 -0
  134. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/qgfcu/wsgck/index.md +16 -0
  135. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +43 -0
  136. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/reading-notes/_index.md +11 -0
  137. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +27 -0
  138. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/te812/_index.md +41 -0
  139. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/te812/cxiu6/index.md +16 -0
  140. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/te812/t77ms/index.md +16 -0
  141. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/te812/the-soup-trick-i-always-forget/index.md +18 -0
  142. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/telk3/_index.md +27 -0
  143. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/telk3/from-thoreau-pawt2/index.md +17 -0
  144. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +32 -0
  145. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +29 -0
  146. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +27 -0
  147. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/tiny-projects/_index.md +11 -0
  148. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/useful-links/_index.md +11 -0
  149. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/weekend-notes/_index.md +11 -0
  150. package/src/__tests__/fixtures/releases/0.7.1/site-export/content/what-i-actually-use-my-notebook-for/_index.md +49 -0
  151. package/src/__tests__/fixtures/releases/0.7.1/site-export/data/jant.toml +119 -0
  152. package/src/__tests__/fixtures/releases/0.7.1/site-export/hugo.toml +43 -0
  153. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/021801c20ab3-med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  154. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/0f868ce9ac84-med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  155. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/50c2ad911bad-med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  156. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/7a91f0960491-med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  157. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/8714116d3c8e-med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  158. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/8a0b4277443f-med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  159. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/a7d1c8a1afd9-med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  160. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/e25570b405f5-med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  161. package/src/__tests__/fixtures/releases/0.7.1/site-export/static/media/e89ea4eabf01-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  162. package/src/__tests__/fixtures/releases/0.7.1/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  163. package/src/__tests__/fixtures/releases/0.7.1/site-export/themes/jant/static/custom.css +0 -0
  164. package/src/__tests__/fixtures/releases/0.7.1/site-export/themes/jant/static/favicon.ico +0 -0
  165. package/src/__tests__/fixtures/releases/0.7.1/snapshot/db.sql +322 -0
  166. package/src/__tests__/fixtures/releases/0.7.1/snapshot/meta.json +9 -0
  167. package/src/__tests__/fixtures/releases/0.8.0/site-export/README.md +130 -0
  168. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/2thjq/_index.md +25 -0
  169. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/2u5e5/_index.md +35 -0
  170. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/0x4nv/index.md +18 -0
  171. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/_index.md +44 -0
  172. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/faqyt/index.md +30 -0
  173. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +20 -0
  174. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5kayp/_index.md +23 -0
  175. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5ynfs/_index.md +31 -0
  176. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/5ynfs/hu597/index.md +21 -0
  177. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/_index.md +5 -0
  178. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +31 -0
  179. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +36 -0
  180. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/archive/_index.md +8 -0
  181. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +30 -0
  182. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/bought-too-many-lemons-again/_index.md +37 -0
  183. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/city-walks/_index.md +12 -0
  184. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/cleanshot-for-screenshots-ocr-and-screen-recording-on-the-mac/_index.md +33 -0
  185. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/cleanshotmac-shang-de-jie-tu-ocr-lu-ping-gong-ju/_index.md +32 -0
  186. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/co344/_index.md +25 -0
  187. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/collections/_index.md +5 -0
  188. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/current-tea-rotation/_index.md +34 -0
  189. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +30 -0
  190. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/desk-but-better/_index.md +25 -0
  191. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/e0kcg/_index.md +22 -0
  192. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/egi3c/_index.md +24 -0
  193. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/evf9j/_index.md +152 -0
  194. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/featured/_index.md +8 -0
  195. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-basho/_index.md +25 -0
  196. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-epictetus/_index.md +25 -0
  197. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-marcus-aurelius/_index.md +25 -0
  198. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-seneca/_index.md +26 -0
  199. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/from-thoreau/_index.md +25 -0
  200. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/2cl6d/index.md +18 -0
  201. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/3zqv7/index.md +30 -0
  202. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/5oxsv/index.md +18 -0
  203. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gkbvv/_index.md +39 -0
  204. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/gwob9/_index.md +25 -0
  205. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/home-cooking/_index.md +12 -0
  206. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/hz729/_index.md +24 -0
  207. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/inaturalist-ai-zi-ran-she-qu/_index.md +44 -0
  208. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/j4v0q/_index.md +35 -0
  209. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k278t/_index.md +25 -0
  210. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k4eee/_index.md +22 -0
  211. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/_index.md +32 -0
  212. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +20 -0
  213. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/a83qu/index.md +18 -0
  214. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +21 -0
  215. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/kan-qi-lai-bi-jiao-ku-de-gong-si-men/_index.md +41 -0
  216. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/l2m7y/_index.md +29 -0
  217. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/lan-ya-yao-kong-qi-chuang-shang-yue-du-de-fan-ye-shen-qi/_index.md +57 -0
  218. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +30 -0
  219. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/n09le/_index.md +23 -0
  220. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/ni-fu-jin-de-wei-ji-bai-ke-tiao-mu/_index.md +42 -0
  221. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +30 -0
  222. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/_index.md +32 -0
  223. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/c91j0/index.md +18 -0
  224. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/qyucy/index.md +18 -0
  225. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/qgfcu/wsgck/index.md +18 -0
  226. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +46 -0
  227. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/reading-notes/_index.md +12 -0
  228. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/s4r3e/_index.md +25 -0
  229. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +30 -0
  230. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/_index.md +44 -0
  231. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/cxiu6/index.md +18 -0
  232. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/t77ms/index.md +18 -0
  233. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +20 -0
  234. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/telk3/_index.md +30 -0
  235. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/telk3/from-thoreau-pawt2/index.md +21 -0
  236. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +36 -0
  237. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +32 -0
  238. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +30 -0
  239. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tiny-projects/_index.md +12 -0
  240. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tong-wang-xing-fu-zhi-lu/_index.md +68 -0
  241. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/tou-ma-yan-jiang-ju-le-bu-chu-ti-yan/_index.md +62 -0
  242. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/useful-links/_index.md +12 -0
  243. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/weekend-notes/_index.md +12 -0
  244. package/src/__tests__/fixtures/releases/0.8.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +52 -0
  245. package/src/__tests__/fixtures/releases/0.8.0/site-export/data/jant.toml +124 -0
  246. package/src/__tests__/fixtures/releases/0.8.0/site-export/hugo.toml +45 -0
  247. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/_redirects +25 -0
  248. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/15d51730a4f7-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  249. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  250. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  251. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  252. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  253. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  254. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  255. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  256. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  257. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q1hme4e8cmby77dn66yy.webp +0 -0
  258. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q2w7e4e8cmc20036yh66.webp +0 -0
  259. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q7d2e4e8cmdeqjmyafby.webp +0 -0
  260. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m313q887e4e8cmdjssych7yh.webp +0 -0
  261. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp-poster.webp +0 -0
  262. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp.mp4 +0 -0
  263. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf-poster.webp +0 -0
  264. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf.mp4 +0 -0
  265. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb-poster.webp +0 -0
  266. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb.mp4 +0 -0
  267. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83-poster.webp +0 -0
  268. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83.mp4 +0 -0
  269. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167sm0f6ct88qw5brtsgcw.webp +0 -0
  270. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167tf8f6ct88r169s51j49.webp +0 -0
  271. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167vaaf6ct88rbx5ztenwb.webp +0 -0
  272. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167w51f6ct88rp19pybkw1.webp +0 -0
  273. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167x0nf6ct88rzajb84tw3.webp +0 -0
  274. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167xxbf6ct88s5t2300bjk.webp +0 -0
  275. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167yq5f6ct88s9pjwt5fxg.webp +0 -0
  276. package/src/__tests__/fixtures/releases/0.8.0/site-export/static/media/med_01m3167zg4f6ct88sge8jp28ja.webp +0 -0
  277. package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  278. package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/custom.css +0 -0
  279. package/src/__tests__/fixtures/releases/0.8.0/site-export/themes/jant/static/favicon.ico +0 -0
  280. package/src/__tests__/fixtures/releases/0.8.0/site-export/wrangler.jsonc +24 -0
  281. package/src/__tests__/fixtures/releases/0.8.0/snapshot/db.sql +322 -0
  282. package/src/__tests__/fixtures/releases/0.8.0/snapshot/meta.json +11 -0
  283. package/src/__tests__/helpers/cursor-walk.ts +52 -0
  284. package/src/__tests__/helpers/site-export-import.ts +97 -0
  285. package/src/__tests__/import-site-command.test.ts +27 -1
  286. package/src/__tests__/release-fixtures.test.ts +136 -0
  287. package/src/__tests__/site-export-canonical-import.test.ts +11 -47
  288. package/src/__tests__/theme-docs.test.ts +109 -0
  289. package/src/app.tsx +1 -5
  290. package/src/db/rehearsal-fixtures/pg-demo-current.json +55 -0
  291. package/src/db/rehearsal-fixtures/pg-demo-current.sql +431 -0
  292. package/src/i18n/locales/public/en.po +0 -2
  293. package/src/i18n/locales/public/zh-Hans.po +0 -2
  294. package/src/i18n/locales/public/zh-Hant.po +0 -2
  295. package/src/index.ts +6 -77
  296. package/src/lib/__tests__/post-list-cursor.test.ts +105 -0
  297. package/src/lib/__tests__/timeline.test.ts +14 -14
  298. package/src/lib/__tests__/view.test.ts +0 -46
  299. package/src/lib/feed.ts +0 -6
  300. package/src/lib/post-list-cursor.ts +211 -0
  301. package/src/lib/view.ts +0 -27
  302. package/src/node/__tests__/cli-export.test.ts +2 -2
  303. package/src/node/__tests__/cli-site-snapshot.test.ts +6 -0
  304. package/src/node/__tests__/cli-site-token-env.test.ts +4 -1
  305. package/src/node/__tests__/cli-snapshot-meta.test.ts +64 -0
  306. package/src/routes/api/__tests__/mcp.test.ts +58 -0
  307. package/src/routes/api/__tests__/posts.test.ts +79 -0
  308. package/src/routes/api/internal/search-reindex.ts +1 -1
  309. package/src/routes/api/posts.ts +5 -9
  310. package/src/routes/api/public/__tests__/archive.test.ts +261 -0
  311. package/src/routes/api/public/__tests__/posts.test.ts +344 -19
  312. package/src/routes/api/public/archive.ts +18 -16
  313. package/src/routes/api/public/posts.ts +15 -16
  314. package/src/services/__tests__/media.test.ts +0 -271
  315. package/src/services/__tests__/post.test.ts +342 -36
  316. package/src/services/export.ts +13 -5
  317. package/src/services/mcp.ts +6 -11
  318. package/src/services/media.ts +1 -219
  319. package/src/services/post.ts +513 -319
  320. package/src/styles/ui.css +0 -118
  321. package/src/ui/shared/Pagination.tsx +1 -1
  322. package/bin/commands/export.js +0 -120
  323. package/bin/commands/import-site.js +0 -3034
  324. package/bin/commands/migrate-text-attachments.js +0 -181
  325. package/dist/github-sync-Gw4orAHk.js +0 -8398
  326. package/src/client/multipart-upload.ts +0 -206
  327. package/src/routes/api/__tests__/upload-multipart.test.ts +0 -739
  328. package/src/routes/api/internal/text-attachments.ts +0 -60
  329. package/src/routes/api/upload-multipart.ts +0 -366
@@ -1,5 +1,3077 @@
1
- import { run as runSiteImport } from "../import-site.js";
1
+ import { openAsBlob } from "node:fs";
2
+ import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises";
3
+ import { resolve, join, extname, dirname, basename } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { parseArgs } from "node:util";
6
+ import {
7
+ CLI_API_TOKEN_ENV_VAR,
8
+ getCliApiToken,
9
+ } from "../../lib/cli-api-token.js";
10
+ import {
11
+ extractAttachmentBlocks,
12
+ findImageUrls,
13
+ normalizeImportedBody,
14
+ rewriteMediaReferences,
15
+ } from "../../lib/site-media-parser.js";
16
+ import { parseFrontMatter as parseFrontMatterShared } from "../../lib/hugo-markdown.js";
17
+ import { extractZipFile } from "../../lib/zip-archive.js";
18
+ import { findPositionalUrl } from "../../lib/renamed-arguments.js";
19
+
20
+ /**
21
+ * Parse front matter from a Markdown file.
22
+ * Delegates to the shared hugo-markdown module.
23
+ */
24
+ const parseFrontMatter = parseFrontMatterShared;
25
+
26
+ /**
27
+ * Newest `data/jant.toml` format version this importer reads. `site export`
28
+ * writes `SITE_EXPORT_FORMAT_VERSION` from `src/services/export.ts`; a test
29
+ * keeps the two equal.
30
+ */
31
+ export const SUPPORTED_SITE_EXPORT_VERSION = 1;
32
+
33
+ /**
34
+ * Refuse an export written in a format newer than this importer reads.
35
+ *
36
+ * An export from before the version field, or from any version up to
37
+ * {@link SUPPORTED_SITE_EXPORT_VERSION}, is accepted.
38
+ *
39
+ * @param {{ extra?: { jant_export?: { format?: string, version?: unknown } } } | null} siteConfig
40
+ * The merged config from `loadSiteConfig`
41
+ * @returns {string | null} An error message, or null when the export can be read
42
+ * @example
43
+ * ```js
44
+ * checkSiteExportVersion({ extra: { jant_export: { format: "jant-site", version: 2 } } });
45
+ * // "This export uses format version 2, …"
46
+ * ```
47
+ */
48
+ function checkSiteExportVersion(siteConfig) {
49
+ const version = siteConfig?.extra?.jant_export?.version;
50
+ if (typeof version !== "number" || version <= SUPPORTED_SITE_EXPORT_VERSION) {
51
+ return null;
52
+ }
53
+ return `This export uses format version ${version}, and this Jant reads up to version ${SUPPORTED_SITE_EXPORT_VERSION}. Upgrade @jant/core, then import again.`;
54
+ }
55
+
56
+ async function parseToml(content) {
57
+ const { parse } = await import("smol-toml");
58
+ return parse(content);
59
+ }
60
+
61
+ /**
62
+ * Static directories of a Jant Hugo export, in Hugo's lookup order: the root
63
+ * `static/` (user overrides) before `themes/jant/static/`, where Jant writes
64
+ * `custom.css`, `favicon.ico`, and `apple-touch-icon.png`.
65
+ */
66
+ const IMPORT_STATIC_DIRS = [["static"], ["themes", "jant", "static"]];
67
+
68
+ /**
69
+ * Read custom.css from the first static directory of a Jant Hugo export that
70
+ * has one.
71
+ */
72
+ async function readImportCustomCss(rootDir) {
73
+ for (const staticDir of IMPORT_STATIC_DIRS) {
74
+ const css = await readFile(
75
+ join(rootDir, ...staticDir, "custom.css"),
76
+ "utf-8",
77
+ ).catch(() => null);
78
+ if (css !== null) {
79
+ return css;
80
+ }
81
+ }
82
+ return "";
83
+ }
84
+
85
+ function resolveImportUrl(url, siteConfig) {
86
+ if (typeof url !== "string" || url.trim() === "" || url.startsWith("data:")) {
87
+ return url;
88
+ }
89
+
90
+ const baseUrl =
91
+ typeof siteConfig?.base_url === "string" ? siteConfig.base_url : "";
92
+ if (!baseUrl) {
93
+ return url;
94
+ }
95
+
96
+ try {
97
+ return new URL(url, baseUrl).toString();
98
+ } catch {
99
+ return url;
100
+ }
101
+ }
102
+
103
+ function resolveImportSiteAssetUrl(path, siteConfig) {
104
+ if (typeof path !== "string" || path.trim() === "") {
105
+ return path;
106
+ }
107
+
108
+ const baseUrl =
109
+ typeof siteConfig?.base_url === "string" ? siteConfig.base_url : "";
110
+ if (!baseUrl) {
111
+ return path;
112
+ }
113
+
114
+ try {
115
+ const parsedBaseUrl = new URL(baseUrl);
116
+ const sitePathPrefix = getImportSitePathPrefix(siteConfig);
117
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
118
+ const publicPath =
119
+ sitePathPrefix &&
120
+ normalizedPath !== sitePathPrefix &&
121
+ !normalizedPath.startsWith(`${sitePathPrefix}/`)
122
+ ? `${sitePathPrefix}${normalizedPath}`
123
+ : normalizedPath;
124
+ return new URL(publicPath, parsedBaseUrl.origin).toString();
125
+ } catch {
126
+ return resolveImportUrl(path, siteConfig);
127
+ }
128
+ }
129
+
130
+ function getImportSitePathPrefix(siteConfig) {
131
+ const baseUrl =
132
+ typeof siteConfig?.base_url === "string" ? siteConfig.base_url : "";
133
+ if (!baseUrl) {
134
+ return "";
135
+ }
136
+
137
+ try {
138
+ const pathname = new URL(baseUrl).pathname.replace(/\/+$/, "");
139
+ return pathname === "/" ? "" : pathname;
140
+ } catch {
141
+ return "";
142
+ }
143
+ }
144
+
145
+ async function resolveImportLocalAssetPath(rawUrl, siteConfig, sourceRootDir) {
146
+ if (
147
+ !sourceRootDir ||
148
+ typeof rawUrl !== "string" ||
149
+ rawUrl.trim() === "" ||
150
+ rawUrl.startsWith("data:")
151
+ ) {
152
+ return null;
153
+ }
154
+
155
+ const resolvedUrl = resolveImportUrl(rawUrl, siteConfig);
156
+ if (typeof resolvedUrl !== "string" || resolvedUrl.trim() === "") {
157
+ return null;
158
+ }
159
+
160
+ let pathname = "";
161
+ try {
162
+ pathname = new URL(
163
+ resolvedUrl,
164
+ typeof siteConfig?.base_url === "string" && siteConfig.base_url
165
+ ? siteConfig.base_url
166
+ : "https://jant.invalid",
167
+ ).pathname;
168
+ } catch {
169
+ return null;
170
+ }
171
+
172
+ const sitePathPrefix = getImportSitePathPrefix(siteConfig);
173
+ if (sitePathPrefix && pathname.startsWith(`${sitePathPrefix}/`)) {
174
+ pathname = pathname.slice(sitePathPrefix.length + 1);
175
+ } else {
176
+ pathname = pathname.replace(/^\/+/, "");
177
+ }
178
+
179
+ if (!pathname) {
180
+ return null;
181
+ }
182
+
183
+ for (const staticDir of IMPORT_STATIC_DIRS) {
184
+ const fullPath = join(sourceRootDir, ...staticDir, pathname);
185
+ const fileStat = await stat(fullPath).catch(() => null);
186
+ if (fileStat?.isFile()) {
187
+ return fullPath;
188
+ }
189
+ }
190
+
191
+ return null;
192
+ }
193
+
194
+ /**
195
+ * Read one asset as a Blob, from the export's files or its URL.
196
+ *
197
+ * A local file comes back file-backed (`openAsBlob`): an upload streams it
198
+ * from disk. Reading every file into memory first held gigabytes during the
199
+ * import of a real site, since Node does not count Blob memory toward the
200
+ * garbage collector's pressure.
201
+ *
202
+ * @param {{ sourceUrl?: string, sourceFilePath?: string | null, mimeType?: string, originalName?: string }} options
203
+ * @returns {Promise<{ blob: Blob, filename: string, contentType: string } | null>}
204
+ * The asset, or null when a remote source is missing or unreachable
205
+ */
206
+ async function readImportAsset(options) {
207
+ const { sourceUrl, sourceFilePath, mimeType, originalName } = options;
208
+
209
+ if (sourceFilePath) {
210
+ const filename =
211
+ originalName || basename(sourceFilePath) || getFilenameFromUrl(sourceUrl);
212
+ const contentType = mimeType || guessMimeType(filename);
213
+ return {
214
+ blob: await openAsBlob(sourceFilePath, { type: contentType }),
215
+ filename,
216
+ contentType,
217
+ };
218
+ }
219
+
220
+ if (!sourceUrl) {
221
+ return null;
222
+ }
223
+
224
+ const response = await fetch(sourceUrl);
225
+ if (!response.ok) {
226
+ return null;
227
+ }
228
+
229
+ const bytes = new Uint8Array(await response.arrayBuffer());
230
+ const filename = originalName || getFilenameFromUrl(sourceUrl) || "file";
231
+ const contentType =
232
+ mimeType ||
233
+ response.headers.get("content-type")?.split(";")[0] ||
234
+ guessMimeType(filename);
235
+ return {
236
+ blob: new Blob([bytes], { type: contentType }),
237
+ filename,
238
+ contentType,
239
+ };
240
+ }
241
+
242
+ async function readMediaSpecAsset(media, field = "src") {
243
+ if (field === "poster") {
244
+ return readImportAsset({
245
+ sourceUrl: media.poster,
246
+ sourceFilePath: media.posterFilePath,
247
+ });
248
+ }
249
+
250
+ return readImportAsset({
251
+ sourceUrl: media.src,
252
+ sourceFilePath: media.srcFilePath,
253
+ mimeType: media.mimeType,
254
+ originalName: media.originalName,
255
+ });
256
+ }
257
+
258
+ function normalizeImportPathKey(value) {
259
+ if (typeof value !== "string") {
260
+ return null;
261
+ }
262
+
263
+ const trimmed = value.trim();
264
+ if (!trimmed) {
265
+ return null;
266
+ }
267
+
268
+ return trimmed
269
+ .toLowerCase()
270
+ .replace(/^\/+|\/+$/g, "")
271
+ .replace(/\/+/g, "/");
272
+ }
273
+
274
+ function normalizeImportAliasPath(value) {
275
+ const pathKey = normalizeImportPathKey(value);
276
+ return pathKey ? `/${pathKey}` : null;
277
+ }
278
+
279
+ /**
280
+ * Resolve the historical root slugs that should become custom-URL aliases
281
+ * pointing at the current root post. Hugo's `aliases:` on a root also
282
+ * contains every reply slug; we strip those (reply slugs are claimed by
283
+ * their own bundles) and keep only entries that aren't the root itself.
284
+ *
285
+ * `root_aliases:` is the authoritative record of the root's own historical
286
+ * slugs (the exporter writes it for round-trip), so when present we prefer
287
+ * it. Otherwise we fall back to `aliases:` minus reply slugs.
288
+ */
289
+ function getRootAliasPathsForImport(
290
+ aliases,
291
+ rootAliases,
292
+ postSlug,
293
+ replySlugPaths,
294
+ ) {
295
+ const rootSlugPath = normalizeImportAliasPath(postSlug);
296
+ const aliasPaths = [];
297
+ const seen = new Set();
298
+
299
+ // Prefer the explicit `root_aliases:` list when the exporter wrote it.
300
+ const source =
301
+ Array.isArray(rootAliases) && rootAliases.length > 0
302
+ ? rootAliases
303
+ : Array.isArray(aliases)
304
+ ? aliases
305
+ : [];
306
+
307
+ for (const alias of source) {
308
+ const aliasPath = normalizeImportAliasPath(alias);
309
+ if (!aliasPath) {
310
+ continue;
311
+ }
312
+ if (aliasPath === rootSlugPath) {
313
+ continue;
314
+ }
315
+ if (replySlugPaths.has(aliasPath)) {
316
+ // Reply slugs live in their own bundles — never route their URL back
317
+ // to the root as a custom alias.
318
+ continue;
319
+ }
320
+ if (seen.has(aliasPath)) {
321
+ continue;
322
+ }
323
+ seen.add(aliasPath);
324
+ aliasPaths.push(aliasPath);
325
+ }
326
+
327
+ return aliasPaths;
328
+ }
329
+
330
+ async function assertImportSlugAvailable(target, slug, label, kind) {
331
+ if (!slug) {
332
+ return;
333
+ }
334
+
335
+ const available = await target.checkPostSlugAvailability(slug);
336
+ if (!available) {
337
+ console.error(
338
+ `Import conflict: ${kind} slug "${slug}" for ${label} is already in use. Import into an empty site or remove the existing content first.`,
339
+ );
340
+ process.exit(1);
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Download a media file and upload it to the Jant API.
346
+ * Returns the new URL, or null on failure.
347
+ */
348
+ /**
349
+ * Upload one media file through the site's API.
350
+ *
351
+ * Throws when the file can't be read or the site refuses it, so a caller
352
+ * decides whether that is fatal (the export's own media) or leaves a link in
353
+ * place (an image in the body). It used to return null for either, and a
354
+ * post was created without the file and without a word.
355
+ *
356
+ * @param {Record<string, unknown>} media - A normalized media spec
357
+ * @param {string} apiUrl - Target site URL
358
+ * @param {string} token - API token
359
+ * @returns {Promise<{ url: string, id: string }>} The uploaded media
360
+ */
361
+ async function uploadRemoteMedia(media, apiUrl, token) {
362
+ const asset = await readMediaSpecAsset(media);
363
+ if (!asset) {
364
+ throw new Error(`Couldn't read ${media.src}`);
365
+ }
366
+
367
+ const formData = new FormData();
368
+ formData.append("file", asset.blob, asset.filename);
369
+ if (media.alt) formData.append("alt", media.alt);
370
+ if (media.summary) formData.append("summary", media.summary);
371
+ if (media.width) formData.append("width", String(media.width));
372
+ if (media.height) formData.append("height", String(media.height));
373
+ if (media.blurhash) formData.append("blurhash", media.blurhash);
374
+ if (media.waveform) formData.append("waveform", media.waveform);
375
+ if (media.durationSeconds) {
376
+ formData.append("durationSeconds", String(media.durationSeconds));
377
+ }
378
+
379
+ if (media.poster) {
380
+ const posterAsset = await readMediaSpecAsset(media, "poster");
381
+ if (posterAsset) {
382
+ formData.append("poster", posterAsset.blob, posterAsset.filename);
383
+ } else {
384
+ console.warn(`Warning: couldn't read the poster ${media.poster}`);
385
+ }
386
+ }
387
+
388
+ const uploadResponse = await fetch(`${apiUrl}/api/upload`, {
389
+ method: "POST",
390
+ headers: { Authorization: `Bearer ${token}` },
391
+ body: formData,
392
+ });
393
+
394
+ if (!uploadResponse.ok) {
395
+ const detail = (await uploadResponse.text().catch(() => "")).slice(0, 300);
396
+ throw new Error(
397
+ `The site refused ${media.src}: HTTP ${uploadResponse.status}${detail ? ` ${detail}` : ""}`,
398
+ );
399
+ }
400
+ const data = await uploadResponse.json();
401
+ return { url: data.url, id: data.id };
402
+ }
403
+
404
+ function getFilenameFromUrl(fileUrl) {
405
+ try {
406
+ const pathname = new URL(fileUrl).pathname;
407
+ return pathname.split("/").pop() || "file";
408
+ } catch {
409
+ return fileUrl.split("/").pop() || "file";
410
+ }
411
+ }
412
+
413
+ function guessMimeType(filename) {
414
+ const ext = extname(filename).toLowerCase();
415
+ switch (ext) {
416
+ case ".jpg":
417
+ case ".jpeg":
418
+ return "image/jpeg";
419
+ case ".png":
420
+ return "image/png";
421
+ case ".gif":
422
+ return "image/gif";
423
+ case ".webp":
424
+ return "image/webp";
425
+ case ".svg":
426
+ return "image/svg+xml";
427
+ case ".avif":
428
+ return "image/avif";
429
+ case ".bmp":
430
+ return "image/bmp";
431
+ case ".ico":
432
+ return "image/x-icon";
433
+ case ".mp4":
434
+ return "video/mp4";
435
+ case ".mp3":
436
+ return "audio/mpeg";
437
+ case ".pdf":
438
+ return "application/pdf";
439
+ case ".json":
440
+ return "application/json";
441
+ case ".md":
442
+ return "text/markdown";
443
+ case ".csv":
444
+ return "text/csv";
445
+ case ".txt":
446
+ return "text/plain";
447
+ default:
448
+ return "application/octet-stream";
449
+ }
450
+ }
451
+
452
+ function normalizeImportedBodySegment(markdown) {
453
+ const extracted = extractAttachmentBlocks(markdown);
454
+ const normalized = normalizeImportedBody(extracted.markdown);
455
+
456
+ return {
457
+ markdown: normalized.markdown,
458
+ attachments: [...extracted.attachments, ...normalized.attachments],
459
+ };
460
+ }
461
+
462
+ function isAbsoluteUrl(value) {
463
+ return typeof value === "string" && /^https?:\/\//i.test(value);
464
+ }
465
+
466
+ /**
467
+ * True when `url` points to a different location than the import target —
468
+ * i.e. has a scheme (`https://`, `data:`) or is protocol-relative (`//cdn…`).
469
+ * False for relative paths (`/media/x`, `./x`, `x`), which always belong to
470
+ * the source site and must be rehosted. Used to filter the body-fallback
471
+ * upload when `--skip-remote-media` is set.
472
+ */
473
+ function isAbsoluteImportUrl(value) {
474
+ if (typeof value !== "string") return false;
475
+ return /^([a-z][a-z0-9+.\-]*:|\/\/)/i.test(value);
476
+ }
477
+
478
+ /**
479
+ * Resolve a `media:` entry's `src` or `poster` reference to a local disk
480
+ * path when the export bundled the bytes under `static/`. Absolute URLs
481
+ * (remote-linked media) skip the disk lookup — the uploader fetches them
482
+ * directly.
483
+ */
484
+ async function resolveJantMediaDiskPath(ref, sourceRootDir) {
485
+ if (typeof ref !== "string" || !ref.trim()) return null;
486
+ if (isAbsoluteUrl(ref)) return null;
487
+ const normalized = ref.startsWith("/") ? ref.slice(1) : ref;
488
+ const fullPath = join(sourceRootDir, "static", normalized);
489
+ const fileStat = await stat(fullPath).catch(() => null);
490
+ return fileStat?.isFile() ? fullPath : null;
491
+ }
492
+
493
+ /**
494
+ * Build a media spec for upload from a flat `media:` front-matter entry.
495
+ *
496
+ * The entry's `src` is either a site-relative path
497
+ * (`/media/{id}.webp` — bytes live under `static/` in the exported site)
498
+ * or an absolute public URL (the exporter linked to an existing
499
+ * R2/S3/local-proxy host rather than re-bundling the bytes). Poster
500
+ * frames follow the same rule. The import uploader already knows how
501
+ * to handle both forms via `readImportAsset`.
502
+ */
503
+ async function mediaSpecFromJantMedia(entry, sourceRootDir) {
504
+ if (!entry || typeof entry.src !== "string" || !entry.src.trim()) {
505
+ return null;
506
+ }
507
+
508
+ const srcFilePath = await resolveJantMediaDiskPath(entry.src, sourceRootDir);
509
+ if (!srcFilePath && !isAbsoluteUrl(entry.src)) {
510
+ // Relative src but file not on disk — can't upload.
511
+ return null;
512
+ }
513
+
514
+ const poster =
515
+ typeof entry.poster === "string" && entry.poster.trim()
516
+ ? entry.poster
517
+ : null;
518
+ const posterFilePath = poster
519
+ ? await resolveJantMediaDiskPath(poster, sourceRootDir)
520
+ : null;
521
+
522
+ const originalName =
523
+ typeof entry.original_name === "string" && entry.original_name.trim()
524
+ ? entry.original_name
525
+ : srcFilePath
526
+ ? basename(srcFilePath)
527
+ : undefined;
528
+
529
+ return {
530
+ kind: typeof entry.kind === "string" ? entry.kind : undefined,
531
+ src: entry.src,
532
+ srcFilePath,
533
+ poster,
534
+ posterFilePath,
535
+ mimeType: typeof entry.mime_type === "string" ? entry.mime_type : undefined,
536
+ originalName,
537
+ size: typeof entry.size === "number" ? entry.size : undefined,
538
+ width: typeof entry.width === "number" ? entry.width : undefined,
539
+ height: typeof entry.height === "number" ? entry.height : undefined,
540
+ alt: typeof entry.alt === "string" ? entry.alt : undefined,
541
+ position: typeof entry.position === "string" ? entry.position : undefined,
542
+ blurhash: typeof entry.blurhash === "string" ? entry.blurhash : undefined,
543
+ waveform: typeof entry.waveform === "string" ? entry.waveform : undefined,
544
+ summary: typeof entry.summary === "string" ? entry.summary : undefined,
545
+ chars: typeof entry.chars === "number" ? entry.chars : undefined,
546
+ durationSeconds:
547
+ typeof entry.duration_seconds === "number"
548
+ ? entry.duration_seconds
549
+ : undefined,
550
+ };
551
+ }
552
+
553
+ async function normalizeMediaSpec(spec, siteConfig, sourceRootDir) {
554
+ if (!spec || typeof spec.src !== "string" || spec.src.trim() === "") {
555
+ return null;
556
+ }
557
+
558
+ const src = resolveImportUrl(spec.src, siteConfig);
559
+ const poster =
560
+ typeof spec.poster === "string"
561
+ ? resolveImportUrl(spec.poster, siteConfig)
562
+ : null;
563
+
564
+ return {
565
+ kind: spec.kind,
566
+ src,
567
+ srcFilePath:
568
+ spec.srcFilePath ??
569
+ (await resolveImportLocalAssetPath(spec.src, siteConfig, sourceRootDir)),
570
+ poster,
571
+ posterFilePath:
572
+ spec.posterFilePath ??
573
+ (typeof spec.poster === "string"
574
+ ? await resolveImportLocalAssetPath(
575
+ spec.poster,
576
+ siteConfig,
577
+ sourceRootDir,
578
+ )
579
+ : null),
580
+ mimeType: spec.mimeType || undefined,
581
+ originalName: spec.originalName || undefined,
582
+ size: typeof spec.size === "number" ? spec.size : undefined,
583
+ width: typeof spec.width === "number" ? spec.width : undefined,
584
+ height: typeof spec.height === "number" ? spec.height : undefined,
585
+ alt: typeof spec.alt === "string" ? spec.alt : undefined,
586
+ position: typeof spec.position === "string" ? spec.position : undefined,
587
+ blurhash: typeof spec.blurhash === "string" ? spec.blurhash : undefined,
588
+ waveform: typeof spec.waveform === "string" ? spec.waveform : undefined,
589
+ summary: typeof spec.summary === "string" ? spec.summary : undefined,
590
+ chars: typeof spec.chars === "number" ? spec.chars : undefined,
591
+ };
592
+ }
593
+
594
+ /**
595
+ * Coerce a `<figure data-jant-node="attachment" data-jant-kind="text">` meta
596
+ * block into the shape `createTextAttachment` wants on import.
597
+ *
598
+ * Two source shapes are supported:
599
+ *
600
+ * 1. Inline (legacy exports): the meta JSON carries the markdown itself under
601
+ * `contentFormat: "markdown"` + `content: "..."`. Used before text
602
+ * attachments got their own public URL.
603
+ * 2. Reference (current exports): the meta JSON only carries `kind: "text"`
604
+ * + `src: <url>` pointing at the `.md` artifact. We fetch that URL
605
+ * (falling back to `--pull-media` local disk via
606
+ * `resolveImportLocalAssetPath`, same as images) and use the bytes as
607
+ * the markdown body.
608
+ *
609
+ * Returns `null` when the spec isn't a text attachment or we can't get
610
+ * usable content (unreachable URL, empty body, etc.) — caller drops the
611
+ * attachment rather than creating an empty one.
612
+ */
613
+ async function normalizeTextAttachmentSpec(spec, siteConfig, sourceRootDir) {
614
+ if (!spec || spec.kind !== "text") {
615
+ return null;
616
+ }
617
+
618
+ const summary = typeof spec.summary === "string" ? spec.summary : undefined;
619
+
620
+ // Legacy inline content path — no network fetch needed.
621
+ if (
622
+ spec.contentFormat === "markdown" &&
623
+ typeof spec.content === "string" &&
624
+ spec.content.trim() !== ""
625
+ ) {
626
+ return {
627
+ type: "text",
628
+ contentFormat: "markdown",
629
+ content: spec.content,
630
+ summary,
631
+ };
632
+ }
633
+
634
+ // Reference path — fetch the markdown from the stored `src` URL.
635
+ if (typeof spec.src !== "string" || spec.src.trim() === "") {
636
+ return null;
637
+ }
638
+
639
+ const sourceUrl = resolveImportUrl(spec.src, siteConfig);
640
+ if (typeof sourceUrl !== "string" || sourceUrl.trim() === "") {
641
+ return null;
642
+ }
643
+
644
+ const asset = await readImportAsset({
645
+ sourceUrl,
646
+ sourceFilePath: await resolveImportLocalAssetPath(
647
+ spec.src,
648
+ siteConfig,
649
+ sourceRootDir,
650
+ ),
651
+ });
652
+
653
+ if (!asset) {
654
+ return null;
655
+ }
656
+
657
+ let markdown;
658
+ try {
659
+ markdown = await asset.blob.text();
660
+ } catch {
661
+ return null;
662
+ }
663
+
664
+ if (markdown.trim() === "") {
665
+ return null;
666
+ }
667
+
668
+ return {
669
+ type: "text",
670
+ contentFormat: "markdown",
671
+ content: markdown,
672
+ summary,
673
+ };
674
+ }
675
+
676
+ async function buildImportedAttachments(
677
+ attachmentSpecs,
678
+ target,
679
+ siteConfig,
680
+ sourceRootDir,
681
+ ) {
682
+ const attachments = [];
683
+ let uploaded = 0;
684
+
685
+ for (const spec of attachmentSpecs) {
686
+ const textAttachment = await normalizeTextAttachmentSpec(
687
+ spec,
688
+ siteConfig,
689
+ sourceRootDir,
690
+ );
691
+ if (textAttachment) {
692
+ attachments.push(textAttachment);
693
+ continue;
694
+ }
695
+
696
+ const normalized = await normalizeMediaSpec(
697
+ spec,
698
+ siteConfig,
699
+ sourceRootDir,
700
+ );
701
+ if (!normalized || normalized.src.startsWith("data:")) continue;
702
+ let result;
703
+ try {
704
+ result = await target.uploadMedia(normalized);
705
+ } catch (err) {
706
+ // The post's own attachment: creating the post without it would lose
707
+ // the file quietly.
708
+ throw new Error(`Couldn't upload ${spec.src}: ${err.message}`, {
709
+ cause: err,
710
+ });
711
+ }
712
+ if (!result) continue;
713
+ attachments.push({
714
+ type: "media",
715
+ mediaId: result.id,
716
+ ...(typeof normalized.alt === "string" ? { alt: normalized.alt } : {}),
717
+ });
718
+ uploaded += 1;
719
+ }
720
+
721
+ return { attachments, uploaded };
722
+ }
723
+
724
+ async function uploadMediaList(mediaSpecs, target, siteConfig, sourceRootDir) {
725
+ const urlMap = new Map();
726
+ const mediaIds = [];
727
+ let uploaded = 0;
728
+
729
+ for (const spec of mediaSpecs) {
730
+ const normalized = await normalizeMediaSpec(
731
+ spec,
732
+ siteConfig,
733
+ sourceRootDir,
734
+ );
735
+ if (!normalized || normalized.src.startsWith("data:")) continue;
736
+ let result;
737
+ try {
738
+ result = await target.uploadMedia(normalized);
739
+ } catch (err) {
740
+ // A body image may be a third party's; the Markdown keeps its URL.
741
+ console.warn(`Warning: kept ${spec.src} as a link. ${err.message}`);
742
+ continue;
743
+ }
744
+ if (!result) continue;
745
+ // Key the rewrite map by the *original* URL as it appears in the body
746
+ // (e.g. `/media/...`). `normalized.src` has been resolved against
747
+ // `siteConfig.base_url` and becomes absolute, which would never match
748
+ // `node.url` from the markdown AST during `rewriteMediaReferences`.
749
+ if (typeof spec.src === "string" && spec.src.trim() !== "") {
750
+ urlMap.set(spec.src, result.url);
751
+ }
752
+ if (normalized.src !== spec.src) {
753
+ urlMap.set(normalized.src, result.url);
754
+ }
755
+ mediaIds.push(result.id);
756
+ uploaded += 1;
757
+ }
758
+
759
+ return { urlMap, mediaIds, uploaded };
760
+ }
761
+
762
+ /**
763
+ * Upload each media spec referenced by a bundle's front matter. Accepts
764
+ * both site-relative entries (bytes on disk under `static/`, via
765
+ * `srcFilePath`) and absolute-URL entries (remote-linked media — the
766
+ * uploader fetches the URL). Returns a `urlMap` (for rewriting in-body
767
+ * references) and an ordered `mediaIds` list for post attachment.
768
+ */
769
+ async function uploadBundleResources(resourceSpecs, target) {
770
+ const urlMap = new Map();
771
+ const mediaIds = [];
772
+ let uploaded = 0;
773
+
774
+ for (const spec of resourceSpecs) {
775
+ if (!spec) continue;
776
+ if (!spec.srcFilePath && !isAbsoluteUrl(spec.src)) continue;
777
+ let result;
778
+ try {
779
+ result = await target.uploadMedia(spec);
780
+ } catch (err) {
781
+ // The post's own attachment: creating the post without it would lose
782
+ // the file quietly.
783
+ throw new Error(`Couldn't upload ${spec.src}: ${err.message}`, {
784
+ cause: err,
785
+ });
786
+ }
787
+ if (!result) continue;
788
+ urlMap.set(spec.src, result.url);
789
+ mediaIds.push(result.id);
790
+ uploaded += 1;
791
+ }
792
+
793
+ return { urlMap, mediaIds, uploaded };
794
+ }
795
+
796
+ function coerceBoolean(value) {
797
+ if (typeof value === "boolean") return value;
798
+ if (typeof value === "string") {
799
+ const normalized = value.trim().toLowerCase();
800
+ return normalized === "true" || normalized === "1" || normalized === "yes";
801
+ }
802
+ return false;
803
+ }
804
+
805
+ /**
806
+ * Build a unified "site config" object from Hugo's split config files.
807
+ *
808
+ * Hugo writes two sources of truth:
809
+ * - `hugo.toml`: baseURL, title, languageCode, theme params
810
+ * - `data/jant.toml`: everything Jant owns — nav items, branding modes,
811
+ * site_footer, avatar urls, display preferences, and the ordered
812
+ * collections directory under `[[directory]]`.
813
+ *
814
+ * This merger normalizes them into a single shape that downstream helpers
815
+ * (`buildSettingsUpdatesFromConfig`, `normalizeImportedNavItems`,
816
+ * `normalizeImportedCollectionDirectory`, `buildSiteAvatarImport`) already
817
+ * know how to read. The shape is intentionally a superset — nothing
818
+ * depends on `hugo.toml`-only vs `data/jant.toml`-only fields, so extra
819
+ * keys are harmless if they leak through.
820
+ */
821
+ async function loadSiteConfig(rootDir) {
822
+ const hugoTomlText = await readFile(
823
+ join(rootDir, "hugo.toml"),
824
+ "utf-8",
825
+ ).catch(() => null);
826
+ const jantDataText = await readFile(
827
+ join(rootDir, "data", "jant.toml"),
828
+ "utf-8",
829
+ ).catch(() => null);
830
+
831
+ if (!hugoTomlText && !jantDataText) {
832
+ return null;
833
+ }
834
+
835
+ const hugoToml = hugoTomlText ? await parseToml(hugoTomlText) : {};
836
+ const jantData = jantDataText ? await parseToml(jantDataText) : {};
837
+
838
+ const params = hugoToml.params ?? {};
839
+
840
+ const title =
841
+ (typeof hugoToml.title === "string" && hugoToml.title) ||
842
+ (typeof jantData.site_name === "string" ? jantData.site_name : "");
843
+ const description =
844
+ (typeof params.description === "string" && params.description) ||
845
+ (typeof jantData.site_description === "string"
846
+ ? jantData.site_description
847
+ : "");
848
+ const baseUrl =
849
+ typeof hugoToml.baseURL === "string"
850
+ ? hugoToml.baseURL
851
+ : typeof hugoToml.baseurl === "string"
852
+ ? hugoToml.baseurl
853
+ : "";
854
+ const language =
855
+ (typeof hugoToml.languageCode === "string" && hugoToml.languageCode) ||
856
+ (typeof hugoToml.defaultContentLanguage === "string" &&
857
+ hugoToml.defaultContentLanguage) ||
858
+ (typeof jantData.site_language === "string"
859
+ ? jantData.site_language
860
+ : "en");
861
+
862
+ const directoryItems = Array.isArray(jantData.directory)
863
+ ? jantData.directory
864
+ : [];
865
+ const directoryExported = Array.isArray(jantData.directory);
866
+
867
+ return {
868
+ // Public base URL (used for resolving relative media URLs).
869
+ base_url: baseUrl,
870
+ title,
871
+ description,
872
+ default_language: language,
873
+ extra: {
874
+ jant: {
875
+ theme_id:
876
+ (typeof params.theme_id === "string" && params.theme_id) ||
877
+ (typeof jantData.theme_id === "string" ? jantData.theme_id : ""),
878
+ default_theme_id:
879
+ (typeof params.default_theme_id === "string" &&
880
+ params.default_theme_id) ||
881
+ (typeof jantData.default_theme_id === "string"
882
+ ? jantData.default_theme_id
883
+ : ""),
884
+ font_theme_id:
885
+ (typeof params.font_theme_id === "string" && params.font_theme_id) ||
886
+ (typeof jantData.font_theme_id === "string"
887
+ ? jantData.font_theme_id
888
+ : ""),
889
+ theme_mode:
890
+ (typeof params.theme_mode === "string" && params.theme_mode) ||
891
+ (typeof jantData.theme_mode === "string" ? jantData.theme_mode : ""),
892
+ show_jant_branding_on_home: coerceBoolean(
893
+ params.show_jant_branding_on_home ??
894
+ jantData.show_jant_branding_on_home,
895
+ ),
896
+ show_header_avatar: coerceBoolean(
897
+ params.show_header_avatar ?? jantData.show_header_avatar,
898
+ ),
899
+ noindex: coerceBoolean(params.noindex ?? jantData.noindex),
900
+ public_api_enabled:
901
+ params.public_api_enabled === undefined &&
902
+ jantData.public_api_enabled === undefined
903
+ ? true
904
+ : coerceBoolean(
905
+ params.public_api_enabled ?? jantData.public_api_enabled,
906
+ ),
907
+ rss_feeds_enabled:
908
+ params.rss_feeds_enabled === undefined &&
909
+ jantData.rss_feeds_enabled === undefined
910
+ ? true
911
+ : coerceBoolean(
912
+ params.rss_feeds_enabled ?? jantData.rss_feeds_enabled,
913
+ ),
914
+ site_footer_markdown:
915
+ typeof jantData.site_footer_markdown === "string"
916
+ ? jantData.site_footer_markdown
917
+ : "",
918
+ site_avatar_mode:
919
+ typeof jantData.site_avatar_mode === "string"
920
+ ? jantData.site_avatar_mode
921
+ : "none",
922
+ site_avatar_url:
923
+ typeof jantData.site_avatar_url === "string"
924
+ ? jantData.site_avatar_url
925
+ : typeof params.site_avatar_url === "string"
926
+ ? params.site_avatar_url
927
+ : "",
928
+ favicon_mode:
929
+ typeof jantData.favicon_mode === "string"
930
+ ? jantData.favicon_mode
931
+ : "default",
932
+ favicon_url:
933
+ typeof jantData.favicon_path === "string"
934
+ ? jantData.favicon_path
935
+ : "/favicon.ico",
936
+ apple_touch_mode:
937
+ typeof jantData.apple_touch_mode === "string"
938
+ ? jantData.apple_touch_mode
939
+ : "default",
940
+ apple_touch_icon_url:
941
+ typeof jantData.apple_touch_icon_path === "string"
942
+ ? jantData.apple_touch_icon_path
943
+ : "/apple-touch-icon.png",
944
+ nav: Array.isArray(jantData.nav) ? jantData.nav : [],
945
+ nav_exported: Array.isArray(jantData.nav),
946
+ collections_directory: directoryItems,
947
+ collections_directory_exported: directoryExported,
948
+ custom_urls: Array.isArray(jantData.custom_url)
949
+ ? jantData.custom_url
950
+ : [],
951
+ },
952
+ jant_export: {
953
+ format:
954
+ typeof jantData.format === "string" ? jantData.format : "jant-site",
955
+ version: jantData.version,
956
+ },
957
+ },
958
+ };
959
+ }
960
+
961
+ function buildSettingsUpdatesFromConfig(siteConfig, customCss = "") {
962
+ const jant = siteConfig?.extra?.jant || {};
963
+ const themeId = String(jant.theme_id || "");
964
+ const defaultThemeId = String(jant.default_theme_id || "");
965
+ const fontThemeId = String(jant.font_theme_id || "");
966
+ const themeMode = String(jant.theme_mode || "");
967
+ return {
968
+ SITE_NAME: String(siteConfig?.title || ""),
969
+ SITE_DESCRIPTION: String(siteConfig?.description || ""),
970
+ SITE_LANGUAGE: String(siteConfig?.default_language || "en"),
971
+ SITE_FOOTER: String(jant.site_footer_markdown || ""),
972
+ SHOW_JANT_BRANDING_ON_HOME: jant.show_jant_branding_on_home
973
+ ? "true"
974
+ : "false",
975
+ NOINDEX: jant.noindex ? "true" : "false",
976
+ PUBLIC_API_ENABLED: jant.public_api_enabled === false ? "false" : "true",
977
+ RSS_FEEDS_ENABLED: jant.rss_feeds_enabled === false ? "false" : "true",
978
+ SHOW_HEADER_AVATAR: jant.show_header_avatar ? "true" : "",
979
+ THEME: themeId && themeId !== defaultThemeId ? themeId : "",
980
+ FONT_THEME: fontThemeId && fontThemeId !== "default" ? fontThemeId : "",
981
+ THEME_MODE: themeMode === "light" || themeMode === "dark" ? themeMode : "",
982
+ CUSTOM_CSS: customCss,
983
+ };
984
+ }
985
+
986
+ /**
987
+ * Internal config keys that the site importer restores via the dedicated
988
+ * `/api/settings/import` route. Must stay in sync with
989
+ * `importableInternalSettingKeys` in `src/lib/api-settings.ts`.
990
+ */
991
+ const IMPORTABLE_INTERNAL_SETTING_KEYS = new Set([
992
+ "THEME",
993
+ "FONT_THEME",
994
+ "THEME_MODE",
995
+ "CUSTOM_CSS",
996
+ "SHOW_HEADER_AVATAR",
997
+ ]);
998
+
999
+ function splitSettingsUpdatesForImport(updates) {
1000
+ const editable = {};
1001
+ const internal = {};
1002
+ for (const [key, value] of Object.entries(updates)) {
1003
+ if (IMPORTABLE_INTERNAL_SETTING_KEYS.has(key)) {
1004
+ internal[key] = value;
1005
+ } else {
1006
+ editable[key] = value;
1007
+ }
1008
+ }
1009
+ return { editable, internal };
1010
+ }
1011
+
1012
+ const NAV_PLACEMENTS = new Set(["header", "more"]);
1013
+ const NAV_ITEM_TYPES = new Set([
1014
+ "system",
1015
+ "link",
1016
+ "collection",
1017
+ "smart_collection",
1018
+ "page",
1019
+ ]);
1020
+
1021
+ /**
1022
+ * The slug a nav URL names, for exports older than `collection_slug` and
1023
+ * `post_slug`: `/now` or `/now/` → `now`. Anything else names no slug.
1024
+ *
1025
+ * @param {unknown} url - The exported nav URL
1026
+ * @returns {string | null} The slug, or null
1027
+ */
1028
+ function getSlugFromNavUrl(url) {
1029
+ if (typeof url !== "string") return null;
1030
+ const match = url.match(/^\/([^/?#]+)\/?$/);
1031
+ return match ? decodeURIComponent(match[1]) : null;
1032
+ }
1033
+
1034
+ function normalizeImportedNavItems(siteConfig) {
1035
+ const jant = siteConfig?.extra?.jant || {};
1036
+ const navItems = jant.nav;
1037
+ if (!Array.isArray(navItems)) {
1038
+ return {
1039
+ exported: Boolean(jant.nav_exported),
1040
+ items: [],
1041
+ };
1042
+ }
1043
+
1044
+ return {
1045
+ exported: true,
1046
+ items: navItems
1047
+ .map((item) => {
1048
+ if (!item || typeof item !== "object") return null;
1049
+ const type = NAV_ITEM_TYPES.has(item.type) ? item.type : "link";
1050
+ const placement = NAV_PLACEMENTS.has(item.placement)
1051
+ ? item.placement
1052
+ : "header";
1053
+ const label = typeof item.label === "string" ? item.label : "";
1054
+ const url = typeof item.url === "string" ? item.url : "";
1055
+ const customLabel =
1056
+ typeof item.custom_label === "string" && item.custom_label.trim()
1057
+ ? item.custom_label
1058
+ : null;
1059
+
1060
+ if (type === "system") {
1061
+ if (typeof item.system_key !== "string" || !item.system_key) {
1062
+ return null;
1063
+ }
1064
+ return { type, systemKey: item.system_key, customLabel, placement };
1065
+ }
1066
+ if (type === "collection") {
1067
+ const slug =
1068
+ typeof item.collection_slug === "string"
1069
+ ? item.collection_slug
1070
+ : getSlugFromNavUrl(url);
1071
+ return { type, slug, customLabel, label, url, placement };
1072
+ }
1073
+ if (type === "page") {
1074
+ const slug =
1075
+ typeof item.post_slug === "string"
1076
+ ? item.post_slug
1077
+ : getSlugFromNavUrl(url);
1078
+ return { type, slug, customLabel, label, url, placement };
1079
+ }
1080
+ if (type === "smart_collection") {
1081
+ const slug =
1082
+ typeof item.smart_collection_slug === "string"
1083
+ ? item.smart_collection_slug
1084
+ : getSlugFromNavUrl(url);
1085
+ return { type, slug, customLabel, label, url, placement };
1086
+ }
1087
+ if (!label || !url) return null;
1088
+ return { type: "link", label: customLabel ?? label, url, placement };
1089
+ })
1090
+ .filter(Boolean),
1091
+ };
1092
+ }
1093
+
1094
+ /**
1095
+ * The custom URLs an export lists that name no post or collection: redirects,
1096
+ * and legacy archive URLs the importer reports but can't recreate.
1097
+ *
1098
+ * @param {Record<string, unknown>} siteConfig - From `loadSiteConfig`
1099
+ * @returns {Array<{ path: string, kind: "redirect" | "archive", to?: string, status?: 301 | 302, archiveQuery?: string }>}
1100
+ */
1101
+ function normalizeImportedCustomUrls(siteConfig) {
1102
+ const entries = siteConfig?.extra?.jant?.custom_urls;
1103
+ if (!Array.isArray(entries)) return [];
1104
+
1105
+ return entries
1106
+ .map((entry) => {
1107
+ if (!entry || typeof entry !== "object") return null;
1108
+ const path =
1109
+ typeof entry.path === "string" ? entry.path.replace(/^\/+/, "") : "";
1110
+ if (!path) return null;
1111
+ if (entry.kind === "redirect" && typeof entry.to === "string") {
1112
+ return {
1113
+ path,
1114
+ kind: "redirect",
1115
+ to: entry.to,
1116
+ status: entry.status === 302 ? 302 : 301,
1117
+ };
1118
+ }
1119
+ if (entry.kind === "archive") {
1120
+ return {
1121
+ path,
1122
+ kind: "archive",
1123
+ archiveQuery:
1124
+ typeof entry.archive_query === "string"
1125
+ ? entry.archive_query
1126
+ : undefined,
1127
+ };
1128
+ }
1129
+ return null;
1130
+ })
1131
+ .filter(Boolean);
1132
+ }
1133
+
1134
+ /**
1135
+ * The create request for one imported nav item, once the posts and
1136
+ * collections it may point at exist. A target that didn't come across stays
1137
+ * in the navigation as a plain link to the same address.
1138
+ *
1139
+ * @param {Record<string, unknown>} item - From `normalizeImportedNavItems`
1140
+ * @param {{ collectionSlugToId: Map<string, string>, smartCollectionSlugToId: Map<string, string>, postSlugToId: Map<string, string> }} targets
1141
+ * @returns {{ payload: Record<string, unknown>, customLabel: string | null, warning: string | null }}
1142
+ */
1143
+ function buildNavItemCreateRequest(item, targets) {
1144
+ const { placement, customLabel } = item;
1145
+
1146
+ if (item.type === "system") {
1147
+ return {
1148
+ payload: { type: "system", systemKey: item.systemKey, placement },
1149
+ customLabel,
1150
+ warning: null,
1151
+ };
1152
+ }
1153
+ if (item.type === "link") {
1154
+ return {
1155
+ payload: { type: "link", label: item.label, url: item.url, placement },
1156
+ customLabel: null,
1157
+ warning: null,
1158
+ };
1159
+ }
1160
+
1161
+ const targetId =
1162
+ item.type === "collection"
1163
+ ? targets.collectionSlugToId.get(item.slug)
1164
+ : item.type === "smart_collection"
1165
+ ? targets.smartCollectionSlugToId.get(item.slug)
1166
+ : item.type === "page"
1167
+ ? targets.postSlugToId.get(item.slug)
1168
+ : undefined;
1169
+ if (targetId) {
1170
+ const targetField =
1171
+ item.type === "collection"
1172
+ ? "collectionId"
1173
+ : item.type === "smart_collection"
1174
+ ? "smartCollectionId"
1175
+ : "postId";
1176
+ return {
1177
+ payload: {
1178
+ type: item.type,
1179
+ [targetField]: targetId,
1180
+ ...(customLabel ? { label: customLabel } : {}),
1181
+ placement,
1182
+ },
1183
+ customLabel: null,
1184
+ warning: null,
1185
+ };
1186
+ }
1187
+
1188
+ return {
1189
+ payload: {
1190
+ type: "link",
1191
+ label: customLabel ?? item.label,
1192
+ url: item.url,
1193
+ placement,
1194
+ },
1195
+ customLabel: null,
1196
+ warning: `The ${item.type.replace("_", " ")} behind "${item.label}" wasn't imported; it stays in the navigation as a link to ${item.url}.`,
1197
+ };
1198
+ }
1199
+
1200
+ /**
1201
+ * The create request for one exported smart collection.
1202
+ *
1203
+ * The conditions arrive as the export spells them, with the collection one
1204
+ * naming a slug; it becomes this site's ID. When that collection didn't come
1205
+ * across, the smart collection is skipped rather than created without the
1206
+ * condition, which would widen it to posts it never held.
1207
+ *
1208
+ * @param {{ slug: string, frontMatter: Record<string, unknown> }} bundle - A `type: smart_collection` section
1209
+ * @param {Map<string, string>} collectionSlugToId - Imported collections
1210
+ * @returns {{ payload: Record<string, unknown> | null, warning: string | null }}
1211
+ * @example
1212
+ * buildSmartCollectionCreateRequest(bundle, new Map([["ideas", "col_01…"]]));
1213
+ */
1214
+ function buildSmartCollectionCreateRequest(bundle, collectionSlugToId) {
1215
+ const frontMatter = bundle.frontMatter;
1216
+ const exported = frontMatter.selection;
1217
+ const selection =
1218
+ exported && typeof exported === "object" && !Array.isArray(exported)
1219
+ ? { ...exported }
1220
+ : {};
1221
+
1222
+ if (selection.collection !== undefined) {
1223
+ const collectionId =
1224
+ typeof selection.collection === "string"
1225
+ ? collectionSlugToId.get(selection.collection)
1226
+ : undefined;
1227
+ if (!collectionId) {
1228
+ return {
1229
+ payload: null,
1230
+ warning: `skipped the smart collection /${bundle.slug}: the collection it filters by, "${selection.collection}", wasn't imported.`,
1231
+ };
1232
+ }
1233
+ selection.collection = [collectionId];
1234
+ }
1235
+
1236
+ const title =
1237
+ typeof frontMatter.title === "string" && frontMatter.title.trim()
1238
+ ? frontMatter.title
1239
+ : bundle.slug;
1240
+ return {
1241
+ payload: {
1242
+ slug: bundle.slug,
1243
+ title,
1244
+ ...(typeof frontMatter.summary_text === "string" &&
1245
+ frontMatter.summary_text.trim()
1246
+ ? { description: frontMatter.summary_text }
1247
+ : {}),
1248
+ selection,
1249
+ ...(typeof frontMatter.sort_order === "string"
1250
+ ? { sort: frontMatter.sort_order }
1251
+ : {}),
1252
+ ...(typeof frontMatter.display_layout === "string"
1253
+ ? { layout: frontMatter.display_layout }
1254
+ : {}),
1255
+ },
1256
+ warning: null,
1257
+ };
1258
+ }
1259
+
1260
+ function normalizeImportedCollectionDirectory(siteConfig) {
1261
+ const jant = siteConfig?.extra?.jant || {};
1262
+ const directoryItems = jant.collections_directory;
1263
+ if (!Array.isArray(directoryItems)) {
1264
+ return {
1265
+ exported: Boolean(jant.collections_directory_exported),
1266
+ items: [],
1267
+ };
1268
+ }
1269
+
1270
+ return {
1271
+ exported: true,
1272
+ items: directoryItems
1273
+ .map((item) => {
1274
+ if (!item || typeof item !== "object") return null;
1275
+
1276
+ if (
1277
+ (item.type === "collection" || item.type === "smart_collection") &&
1278
+ typeof item.slug === "string" &&
1279
+ item.slug.trim()
1280
+ ) {
1281
+ return {
1282
+ type: item.type,
1283
+ slug: item.slug.trim(),
1284
+ };
1285
+ }
1286
+
1287
+ if (item.type === "divider") {
1288
+ return {
1289
+ type: "divider",
1290
+ label: typeof item.label === "string" ? item.label : null,
1291
+ };
1292
+ }
1293
+
1294
+ if (
1295
+ item.type === "link" &&
1296
+ typeof item.label === "string" &&
1297
+ typeof item.url === "string"
1298
+ ) {
1299
+ return {
1300
+ type: "link",
1301
+ label: item.label,
1302
+ url: item.url,
1303
+ description:
1304
+ typeof item.description === "string" && item.description.trim()
1305
+ ? item.description
1306
+ : null,
1307
+ };
1308
+ }
1309
+
1310
+ return null;
1311
+ })
1312
+ .filter(Boolean),
1313
+ };
1314
+ }
1315
+
1316
+ async function buildSiteAvatarImport(siteConfig, sourceRootDir) {
1317
+ const exportInfo = siteConfig?.extra?.jant_export || {};
1318
+ if (exportInfo.format !== "jant-site") {
1319
+ return null;
1320
+ }
1321
+
1322
+ const jant = siteConfig?.extra?.jant || {};
1323
+ const siteAvatarMode =
1324
+ jant.site_avatar_mode === "custom" ||
1325
+ (typeof jant.site_avatar_url === "string" && jant.site_avatar_url.trim())
1326
+ ? "custom"
1327
+ : "none";
1328
+ const faviconMode = jant.favicon_mode === "custom" ? "custom" : "default";
1329
+ const appleTouchMode =
1330
+ jant.apple_touch_mode === "custom" ||
1331
+ (typeof jant.apple_touch_icon_url === "string" &&
1332
+ jant.apple_touch_icon_url.trim())
1333
+ ? "custom"
1334
+ : "default";
1335
+
1336
+ if (siteAvatarMode !== "custom") {
1337
+ return { mode: "remove" };
1338
+ }
1339
+
1340
+ if (!jant.site_avatar_url || typeof jant.site_avatar_url !== "string") {
1341
+ throw new Error(
1342
+ 'Jant export marked site_avatar_mode="custom" but site_avatar_url is missing',
1343
+ );
1344
+ }
1345
+
1346
+ const faviconRawUrl =
1347
+ faviconMode === "custom"
1348
+ ? typeof jant.favicon_url === "string" && jant.favicon_url.trim()
1349
+ ? jant.favicon_url
1350
+ : "/favicon.ico"
1351
+ : null;
1352
+ const appleTouchRawUrl =
1353
+ appleTouchMode === "custom"
1354
+ ? typeof jant.apple_touch_icon_url === "string" &&
1355
+ jant.apple_touch_icon_url.trim()
1356
+ ? jant.apple_touch_icon_url
1357
+ : "/apple-touch-icon.png"
1358
+ : null;
1359
+
1360
+ return {
1361
+ mode: "set",
1362
+ avatarUrl: resolveImportUrl(jant.site_avatar_url, siteConfig),
1363
+ avatarFilePath: await resolveImportLocalAssetPath(
1364
+ jant.site_avatar_url,
1365
+ siteConfig,
1366
+ sourceRootDir,
1367
+ ),
1368
+ faviconUrl: faviconRawUrl
1369
+ ? resolveImportSiteAssetUrl(faviconRawUrl, siteConfig)
1370
+ : null,
1371
+ faviconFilePath: faviconRawUrl
1372
+ ? await resolveImportLocalAssetPath(
1373
+ faviconRawUrl,
1374
+ siteConfig,
1375
+ sourceRootDir,
1376
+ )
1377
+ : null,
1378
+ appleTouchUrl: appleTouchRawUrl
1379
+ ? resolveImportSiteAssetUrl(appleTouchRawUrl, siteConfig)
1380
+ : null,
1381
+ appleTouchFilePath: appleTouchRawUrl
1382
+ ? await resolveImportLocalAssetPath(
1383
+ appleTouchRawUrl,
1384
+ siteConfig,
1385
+ sourceRootDir,
1386
+ )
1387
+ : null,
1388
+ };
1389
+ }
1390
+
1391
+ async function reorderCollectionDirectoryItems(target, orderedIds) {
1392
+ const dedupedIds = [];
1393
+ const seenIds = new Set();
1394
+ for (const id of orderedIds) {
1395
+ if (typeof id !== "string" || !id || seenIds.has(id)) continue;
1396
+ seenIds.add(id);
1397
+ dedupedIds.push(id);
1398
+ }
1399
+
1400
+ let moves = 0;
1401
+
1402
+ for (let index = 0; index < dedupedIds.length; index += 1) {
1403
+ const itemId = dedupedIds[index];
1404
+ const currentItems = await target.listCollectionDirectoryItems();
1405
+ const currentIds = currentItems.map((item) => item.id);
1406
+ const currentIndex = currentIds.indexOf(itemId);
1407
+ if (currentIndex === -1) continue;
1408
+
1409
+ if (index === 0) {
1410
+ if (currentIndex === 0) continue;
1411
+ const beforeId = currentIds.find((id) => id !== itemId) ?? null;
1412
+ await target.moveCollectionDirectoryItem(itemId, null, beforeId);
1413
+ moves += 1;
1414
+ continue;
1415
+ }
1416
+
1417
+ const afterId = dedupedIds[index - 1];
1418
+ const afterIndex = currentIds.indexOf(afterId);
1419
+ if (afterIndex === -1) continue;
1420
+ if (currentIds[afterIndex + 1] === itemId) continue;
1421
+
1422
+ const beforeId =
1423
+ currentIds.slice(afterIndex + 1).find((id) => id !== itemId) ?? null;
1424
+ await target.moveCollectionDirectoryItem(itemId, afterId, beforeId);
1425
+ moves += 1;
1426
+ }
1427
+
1428
+ return moves;
1429
+ }
1430
+
1431
+ async function syncImportedCollectionDirectory(
1432
+ target,
1433
+ importedDirectory,
1434
+ collectionSlugToId,
1435
+ smartCollectionSlugToId,
1436
+ ) {
1437
+ if (!importedDirectory.exported) {
1438
+ return { created: 0, deleted: 0, moved: 0 };
1439
+ }
1440
+
1441
+ let deleted = 0;
1442
+ const existingItems = await target.listCollectionDirectoryItems();
1443
+ // Collections and smart collections get their row when they are created;
1444
+ // dividers and links exist only in the directory and are rebuilt from it.
1445
+ for (const item of existingItems) {
1446
+ if (item.type === "collection" || item.type === "smart_collection") {
1447
+ continue;
1448
+ }
1449
+ const removed = await target.deleteCollectionDirectoryItem(item.id);
1450
+ if (removed !== false) {
1451
+ deleted += 1;
1452
+ }
1453
+ }
1454
+
1455
+ let currentItems = await target.listCollectionDirectoryItems();
1456
+ // Directory rows by what they list: `collection:<id>` or
1457
+ // `smart_collection:<id>`.
1458
+ const rowIdsByTarget = new Map();
1459
+ for (const item of currentItems) {
1460
+ if (item.type === "collection" && item.collectionId) {
1461
+ rowIdsByTarget.set(`collection:${item.collectionId}`, item.id);
1462
+ } else if (item.type === "smart_collection" && item.smartCollectionId) {
1463
+ rowIdsByTarget.set(`smart_collection:${item.smartCollectionId}`, item.id);
1464
+ }
1465
+ }
1466
+
1467
+ const desiredIds = [];
1468
+ const seenTargets = new Set();
1469
+ let created = 0;
1470
+
1471
+ for (const item of importedDirectory.items) {
1472
+ if (item.type === "collection" || item.type === "smart_collection") {
1473
+ const targetId =
1474
+ item.type === "collection"
1475
+ ? collectionSlugToId.get(item.slug)
1476
+ : smartCollectionSlugToId.get(item.slug);
1477
+ const key = `${item.type}:${targetId}`;
1478
+ if (!targetId || seenTargets.has(key)) {
1479
+ continue;
1480
+ }
1481
+ seenTargets.add(key);
1482
+ const directoryItemId = rowIdsByTarget.get(key);
1483
+ if (directoryItemId) {
1484
+ desiredIds.push(directoryItemId);
1485
+ }
1486
+ continue;
1487
+ }
1488
+
1489
+ const createdItem = await target.createCollectionDirectoryItem(
1490
+ item.type === "divider"
1491
+ ? {
1492
+ type: "divider",
1493
+ ...(item.label !== null ? { label: item.label } : {}),
1494
+ }
1495
+ : {
1496
+ type: "link",
1497
+ label: item.label,
1498
+ url: item.url,
1499
+ ...(item.description ? { description: item.description } : {}),
1500
+ },
1501
+ );
1502
+ desiredIds.push(createdItem.id);
1503
+ created += 1;
1504
+ }
1505
+
1506
+ currentItems = await target.listCollectionDirectoryItems();
1507
+ const currentIds = currentItems.map((item) => item.id);
1508
+ const desiredIdSet = new Set(desiredIds);
1509
+ const moved = await reorderCollectionDirectoryItems(target, [
1510
+ ...desiredIds,
1511
+ ...currentIds.filter((id) => !desiredIdSet.has(id)),
1512
+ ]);
1513
+
1514
+ return { created, deleted, moved };
1515
+ }
1516
+
1517
+ function buildIncompleteSetupError(targetLabel) {
1518
+ return [
1519
+ `${targetLabel} has not completed setup.`,
1520
+ "Finish /setup first to create the site and admin account, then run the import again.",
1521
+ "Until setup is finished, imports cannot write site settings, navigation, collections, or posts.",
1522
+ ].join("\n");
1523
+ }
1524
+
1525
+ async function detectRemoteSetupStatus(apiUrl) {
1526
+ try {
1527
+ const response = await fetch(`${apiUrl}/setup`, {
1528
+ redirect: "manual",
1529
+ });
1530
+
1531
+ if (response.status === 200) {
1532
+ return false;
1533
+ }
1534
+
1535
+ if (response.status >= 300 && response.status < 400) {
1536
+ return true;
1537
+ }
1538
+ } catch {
1539
+ return null;
1540
+ }
1541
+
1542
+ return null;
1543
+ }
1544
+
1545
+ async function getIncompleteSetupError(target, targetLabel) {
1546
+ const isSetupComplete = await target.getSetupStatus();
1547
+ if (isSetupComplete !== false) {
1548
+ return null;
1549
+ }
1550
+
1551
+ return buildIncompleteSetupError(targetLabel);
1552
+ }
1553
+
1554
+ class ApiError extends Error {
1555
+ constructor(status, text) {
1556
+ super(`HTTP ${status}: ${text}`);
1557
+ this.status = status;
1558
+ }
1559
+ }
1560
+
1561
+ async function apiCall(method, path, apiUrl, token, body) {
1562
+ const headers = {
1563
+ Authorization: `Bearer ${token}`,
1564
+ "Content-Type": "application/json",
1565
+ };
1566
+
1567
+ let response;
1568
+ try {
1569
+ response = await fetch(`${apiUrl}${path}`, {
1570
+ method,
1571
+ headers,
1572
+ body: body ? JSON.stringify(body) : undefined,
1573
+ });
1574
+ } catch (err) {
1575
+ const cause = err.cause?.code || err.cause?.message || err.message;
1576
+ if (
1577
+ cause === "UNABLE_TO_VERIFY_LEAF_SIGNATURE" ||
1578
+ cause?.includes("certificate")
1579
+ ) {
1580
+ console.error(`\nCertificate error connecting to ${apiUrl}`);
1581
+ console.error(
1582
+ "The certificate is not signed by a CA that Node trusts. For a local",
1583
+ );
1584
+ console.error("or self-signed target, trust this machine's CA store:");
1585
+ console.error(" NODE_OPTIONS=--use-system-ca jant site import ...");
1586
+ process.exit(1);
1587
+ }
1588
+ throw new Error(
1589
+ `Network error calling ${method} ${apiUrl}${path}: ${cause}`,
1590
+ );
1591
+ }
1592
+
1593
+ if (!response.ok) {
1594
+ const text = await response.text();
1595
+ throw new ApiError(response.status, text);
1596
+ }
1597
+
1598
+ return response.json();
1599
+ }
1600
+
1601
+ function toRemotePostPayload(data) {
1602
+ if (data?.format !== "quote") {
1603
+ return data;
1604
+ }
1605
+
1606
+ const { title, url, ...rest } = data;
1607
+ return {
1608
+ ...rest,
1609
+ ...(typeof title === "string" && title.trim() ? { sourceName: title } : {}),
1610
+ ...(typeof url === "string" && url.trim() ? { sourceUrl: url } : {}),
1611
+ };
1612
+ }
1613
+
1614
+ function createRemoteTarget(apiUrl, token) {
1615
+ return {
1616
+ async close() {},
1617
+ async getSetupStatus() {
1618
+ return detectRemoteSetupStatus(apiUrl);
1619
+ },
1620
+ async updateSettings(updates) {
1621
+ return apiCall("PUT", "/api/settings", apiUrl, token, updates);
1622
+ },
1623
+ async updateImportSettings(updates) {
1624
+ return apiCall("PUT", "/api/settings/import", apiUrl, token, updates);
1625
+ },
1626
+ async listNavItems() {
1627
+ const result = await apiCall("GET", "/api/nav-items", apiUrl, token);
1628
+ return result.navItems || [];
1629
+ },
1630
+ async createNavItem(data) {
1631
+ return apiCall("POST", "/api/nav-items", apiUrl, token, data);
1632
+ },
1633
+ async deleteNavItem(id) {
1634
+ return apiCall("DELETE", `/api/nav-items/${id}`, apiUrl, token);
1635
+ },
1636
+ async updateNavItem(id, data) {
1637
+ return apiCall("PUT", `/api/nav-items/${id}`, apiUrl, token, data);
1638
+ },
1639
+ async createCustomUrl(data) {
1640
+ return apiCall("POST", "/api/custom-urls", apiUrl, token, data);
1641
+ },
1642
+ async removeSiteAvatar() {
1643
+ return apiCall("DELETE", "/api/settings/avatar", apiUrl, token);
1644
+ },
1645
+ async uploadSiteAvatar(data) {
1646
+ const avatarAsset = await readImportAsset({
1647
+ sourceUrl: data.avatarUrl,
1648
+ sourceFilePath: data.avatarFilePath,
1649
+ });
1650
+ if (!avatarAsset) {
1651
+ throw new Error(`Failed to read site avatar: ${data.avatarUrl}`);
1652
+ }
1653
+
1654
+ const formData = new FormData();
1655
+ formData.append("file", avatarAsset.blob, avatarAsset.filename);
1656
+
1657
+ if (data.faviconUrl || data.faviconFilePath) {
1658
+ const faviconAsset = await readImportAsset({
1659
+ sourceUrl: data.faviconUrl,
1660
+ sourceFilePath: data.faviconFilePath,
1661
+ mimeType: "image/x-icon",
1662
+ originalName: "favicon.ico",
1663
+ });
1664
+ if (faviconAsset) {
1665
+ formData.append("favicon", faviconAsset.blob, faviconAsset.filename);
1666
+ }
1667
+ }
1668
+
1669
+ if (data.appleTouchUrl) {
1670
+ const appleTouchAsset = await readImportAsset({
1671
+ sourceUrl: data.appleTouchUrl,
1672
+ sourceFilePath: data.appleTouchFilePath,
1673
+ });
1674
+ if (appleTouchAsset) {
1675
+ formData.append(
1676
+ "appleTouch",
1677
+ appleTouchAsset.blob,
1678
+ appleTouchAsset.filename,
1679
+ );
1680
+ }
1681
+ }
1682
+
1683
+ const response = await fetch(`${apiUrl}/api/settings/avatar`, {
1684
+ method: "POST",
1685
+ headers: { Authorization: `Bearer ${token}` },
1686
+ body: formData,
1687
+ });
1688
+
1689
+ if (!response.ok) {
1690
+ throw new Error(`HTTP ${response.status}: ${await response.text()}`);
1691
+ }
1692
+
1693
+ return response.json();
1694
+ },
1695
+ async syncSiteAvatar(data) {
1696
+ await this.removeSiteAvatar();
1697
+ if (!data) {
1698
+ return { success: true };
1699
+ }
1700
+ return this.uploadSiteAvatar(data);
1701
+ },
1702
+ async listCollections() {
1703
+ const existing = await apiCall("GET", "/api/collections", apiUrl, token);
1704
+ return existing.collections || [];
1705
+ },
1706
+ async listCollectionDirectoryItems() {
1707
+ const existing = await apiCall("GET", "/api/collections", apiUrl, token);
1708
+ return existing.directoryItems || [];
1709
+ },
1710
+ async createCollection(data) {
1711
+ return apiCall("POST", "/api/collections", apiUrl, token, data);
1712
+ },
1713
+ async listSmartCollections() {
1714
+ const result = await apiCall(
1715
+ "GET",
1716
+ "/api/smart-collections",
1717
+ apiUrl,
1718
+ token,
1719
+ );
1720
+ return result.smartCollections || [];
1721
+ },
1722
+ async createSmartCollection(data) {
1723
+ const result = await apiCall(
1724
+ "POST",
1725
+ "/api/smart-collections",
1726
+ apiUrl,
1727
+ token,
1728
+ data,
1729
+ );
1730
+ return result.smartCollection;
1731
+ },
1732
+ async createCollectionDirectoryItem(data) {
1733
+ return apiCall(
1734
+ "POST",
1735
+ "/api/collections/directory-items",
1736
+ apiUrl,
1737
+ token,
1738
+ data,
1739
+ );
1740
+ },
1741
+ async moveCollectionDirectoryItem(id, after, before) {
1742
+ return apiCall(
1743
+ "PUT",
1744
+ `/api/collections/directory-items/${id}/move`,
1745
+ apiUrl,
1746
+ token,
1747
+ { after, before },
1748
+ );
1749
+ },
1750
+ async deleteCollectionDirectoryItem(id) {
1751
+ return apiCall(
1752
+ "DELETE",
1753
+ `/api/collections/directory-items/${id}`,
1754
+ apiUrl,
1755
+ token,
1756
+ );
1757
+ },
1758
+ async createPost(data) {
1759
+ return apiCall(
1760
+ "POST",
1761
+ "/api/posts",
1762
+ apiUrl,
1763
+ token,
1764
+ toRemotePostPayload(data),
1765
+ );
1766
+ },
1767
+ async linkTranslation(postId, otherPostId) {
1768
+ return apiCall(
1769
+ "POST",
1770
+ `/api/posts/${postId}/translations`,
1771
+ apiUrl,
1772
+ token,
1773
+ { postId: otherPostId },
1774
+ );
1775
+ },
1776
+ async createAlias(path, targetSlug) {
1777
+ return apiCall("POST", "/api/custom-urls", apiUrl, token, {
1778
+ path,
1779
+ targetType: "post",
1780
+ targetId: targetSlug,
1781
+ });
1782
+ },
1783
+ async uploadMedia(media) {
1784
+ return uploadRemoteMedia(media, apiUrl, token);
1785
+ },
1786
+ async checkPostSlugAvailability(slug) {
1787
+ const result = await apiCall(
1788
+ "GET",
1789
+ `/api/posts/slug?mode=check&slug=${encodeURIComponent(slug)}`,
1790
+ apiUrl,
1791
+ token,
1792
+ );
1793
+ return Boolean(result.available);
1794
+ },
1795
+ };
1796
+ }
1797
+
1798
+ function getBundleTimestamp(bundle) {
1799
+ return parseImportTimestamp(bundle.frontMatter.date);
1800
+ }
1801
+
1802
+ function getBundleSourceId(bundle) {
1803
+ return typeof bundle.frontMatter.id === "string" ? bundle.frontMatter.id : "";
1804
+ }
1805
+
1806
+ /**
1807
+ * Order bundles by `date`, then by the original TypeID (time-sortable, so it
1808
+ * breaks a same-second tie the way the source site did), then by directory.
1809
+ *
1810
+ * @param {{ frontMatter: Record<string, unknown>, dir: string }} a
1811
+ * @param {{ frontMatter: Record<string, unknown>, dir: string }} b
1812
+ * @returns {number} Negative when `a` comes first
1813
+ */
1814
+ function compareBundlesByDateThenId(a, b) {
1815
+ const aDate = getBundleTimestamp(a);
1816
+ const bDate = getBundleTimestamp(b);
1817
+ if (aDate !== null && bDate !== null && aDate !== bDate) return aDate - bDate;
1818
+ if (aDate !== null && bDate === null) return -1;
1819
+ if (aDate === null && bDate !== null) return 1;
1820
+
1821
+ const aId = getBundleSourceId(a);
1822
+ const bId = getBundleSourceId(b);
1823
+ if (aId && bId && aId !== bId) return aId < bId ? -1 : 1;
1824
+
1825
+ return basename(a.dir).localeCompare(basename(b.dir));
1826
+ }
1827
+
1828
+ /**
1829
+ * Order reply bundles by their exported `weight` (position in the Thread),
1830
+ * falling back to {@link compareBundlesByDateThenId} for older exports.
1831
+ *
1832
+ * @param {{ frontMatter: Record<string, unknown>, dir: string }} a
1833
+ * @param {{ frontMatter: Record<string, unknown>, dir: string }} b
1834
+ * @returns {number} Negative when `a` comes first
1835
+ */
1836
+ function compareReplyBundles(a, b) {
1837
+ const aWeight = a.frontMatter.weight;
1838
+ const bWeight = b.frontMatter.weight;
1839
+ if (
1840
+ typeof aWeight === "number" &&
1841
+ typeof bWeight === "number" &&
1842
+ aWeight !== bWeight
1843
+ ) {
1844
+ return aWeight - bWeight;
1845
+ }
1846
+ return compareBundlesByDateThenId(a, b);
1847
+ }
1848
+
1849
+ /**
1850
+ * Walk `content/` and classify each `_index.md` / `index.md` bundle by its
1851
+ * front-matter `type`. Returns ordered root-post bundles (with child reply
1852
+ * bundles attached), collection landing pages, and smart collection pages.
1853
+ *
1854
+ * Algorithm:
1855
+ * 1. Recurse into `content/` collecting every directory that has either
1856
+ * `_index.md` (branch bundle / section) or `index.md` (leaf bundle).
1857
+ * 2. For each `_index.md`, read front matter. `type: "post"` (or a
1858
+ * missing `type` with post-shaped keys) → root bundle. `type:
1859
+ * "collection"` → collection landing page, `type: "smart_collection"` →
1860
+ * smart collection conditions. Other known section types
1861
+ * (`home`, `featured`, `archive`, `collections`) are recorded and
1862
+ * skipped for post import.
1863
+ * 3. For each root bundle, enumerate immediate child directories; any
1864
+ * child dir containing `index.md` becomes a reply leaf bundle.
1865
+ * 4. Reply bundles are sorted by `weight` (Thread position), then `date`,
1866
+ * then the original ID; root bundles by `date`, then the original ID.
1867
+ * Creating posts in that order keeps same-second ties as they were.
1868
+ */
1869
+ async function walkHugoContent(rootDir) {
1870
+ const contentDir = join(rootDir, "content");
1871
+ const contentStat = await stat(contentDir).catch(() => null);
1872
+ if (!contentStat?.isDirectory()) {
1873
+ console.error(`No content/ directory found in ${rootDir}`);
1874
+ process.exit(1);
1875
+ }
1876
+
1877
+ // Map of absolute dir → { frontMatter, body, kind, slug, dir, children[] }
1878
+ const dirs = new Map();
1879
+
1880
+ async function readBundle(dir, fileName) {
1881
+ const filePath = join(dir, fileName);
1882
+ const content = await readFile(filePath, "utf-8").catch(() => null);
1883
+ if (content === null) return null;
1884
+ const { frontMatter, body } = await parseFrontMatter(content);
1885
+ return { frontMatter, body };
1886
+ }
1887
+
1888
+ async function walk(dir) {
1889
+ const entries = await readdir(dir, { withFileTypes: true }).catch(
1890
+ () => null,
1891
+ );
1892
+ if (!entries) return;
1893
+
1894
+ const hasIndex = entries.some(
1895
+ (entry) => entry.isFile() && entry.name === "_index.md",
1896
+ );
1897
+ const hasLeaf = entries.some(
1898
+ (entry) => entry.isFile() && entry.name === "index.md",
1899
+ );
1900
+
1901
+ if (hasIndex) {
1902
+ const parsed = await readBundle(dir, "_index.md");
1903
+ if (parsed) {
1904
+ const type =
1905
+ typeof parsed.frontMatter.type === "string"
1906
+ ? parsed.frontMatter.type
1907
+ : null;
1908
+ const slug =
1909
+ typeof parsed.frontMatter.slug === "string"
1910
+ ? parsed.frontMatter.slug
1911
+ : basename(dir);
1912
+ dirs.set(dir, {
1913
+ kind: type || "post",
1914
+ slug,
1915
+ dir,
1916
+ frontMatter: parsed.frontMatter,
1917
+ body: parsed.body,
1918
+ file: "_index.md",
1919
+ children: [],
1920
+ });
1921
+ }
1922
+ } else if (hasLeaf) {
1923
+ const parsed = await readBundle(dir, "index.md");
1924
+ if (parsed) {
1925
+ const slug =
1926
+ typeof parsed.frontMatter.slug === "string"
1927
+ ? parsed.frontMatter.slug
1928
+ : basename(dir);
1929
+ dirs.set(dir, {
1930
+ kind: "leaf",
1931
+ slug,
1932
+ dir,
1933
+ frontMatter: parsed.frontMatter,
1934
+ body: parsed.body,
1935
+ file: "index.md",
1936
+ children: [],
1937
+ });
1938
+ }
1939
+ }
1940
+
1941
+ for (const entry of entries) {
1942
+ if (entry.isDirectory()) {
1943
+ await walk(join(dir, entry.name));
1944
+ }
1945
+ }
1946
+ }
1947
+
1948
+ await walk(contentDir);
1949
+
1950
+ // Attach leaf children to their parent root bundles.
1951
+ const rootBundles = [];
1952
+ const collectionBundles = [];
1953
+ const smartCollectionBundles = [];
1954
+
1955
+ for (const record of dirs.values()) {
1956
+ if (record.kind === "leaf") {
1957
+ const parentDir = dirname(record.dir);
1958
+ const parent = dirs.get(parentDir);
1959
+ if (parent && (parent.kind === "post" || parent.kind === null)) {
1960
+ parent.children.push(record);
1961
+ }
1962
+ continue;
1963
+ }
1964
+ if (record.kind === "collection") {
1965
+ collectionBundles.push(record);
1966
+ continue;
1967
+ }
1968
+ if (record.kind === "smart_collection") {
1969
+ smartCollectionBundles.push(record);
1970
+ continue;
1971
+ }
1972
+ if (record.kind === "post") {
1973
+ rootBundles.push(record);
1974
+ continue;
1975
+ }
1976
+ // home / featured / archive / collections / anything else — skip.
1977
+ }
1978
+
1979
+ // Replies in Thread order: the exported `weight`, which follows Jant's own
1980
+ // order (creation time, then ID). Older exports have no weight; `date` then
1981
+ // the original ID come next, since replies written in one second tie on
1982
+ // `date`, and the directory name last.
1983
+ for (const root of rootBundles) {
1984
+ root.children.sort(compareReplyBundles);
1985
+ }
1986
+
1987
+ // Roots in creation order, oldest first, so the new IDs keep the original
1988
+ // order among posts that share a second: lists break those ties by ID.
1989
+ rootBundles.sort(compareBundlesByDateThenId);
1990
+
1991
+ return { rootBundles, collectionBundles, smartCollectionBundles };
1992
+ }
1993
+
1994
+ /**
1995
+ * Resolve the collection memberships listed in a post bundle's top-level
1996
+ * `collections:` front-matter array into `{collectionId, createdAt,
1997
+ * position, pinnedAt}` records the post-create APIs expect.
1998
+ *
1999
+ * Drops entries whose slug doesn't map to a known collection — the
2000
+ * importer prints no warning (collections without slugs are already
2001
+ * filtered by the exporter).
2002
+ */
2003
+ function resolveCollectionMemberships(frontMatter, collectionSlugToId) {
2004
+ const collections = Array.isArray(frontMatter.collections)
2005
+ ? frontMatter.collections
2006
+ : [];
2007
+ const entries = [];
2008
+ const ids = [];
2009
+ for (const raw of collections) {
2010
+ if (!raw || typeof raw.slug !== "string") continue;
2011
+ const id = collectionSlugToId.get(raw.slug);
2012
+ if (!id) continue;
2013
+ const entry = { collectionId: id };
2014
+ const createdAt = parseImportTimestamp(raw.collected_at);
2015
+ if (createdAt !== null) {
2016
+ entry.createdAt = createdAt;
2017
+ }
2018
+ if (typeof raw.position === "number" && Number.isFinite(raw.position)) {
2019
+ entry.position = raw.position;
2020
+ }
2021
+ const pinnedAt = parseImportTimestamp(raw.pinned_at);
2022
+ if (pinnedAt !== null) {
2023
+ entry.pinnedAt = pinnedAt;
2024
+ }
2025
+ entries.push(entry);
2026
+ ids.push(id);
2027
+ }
2028
+ return { entries, ids };
2029
+ }
2030
+
2031
+ /**
2032
+ * Resolve one Thread's collection memberships from its root and every reply.
2033
+ *
2034
+ * Current exports write `collections:` only on the root bundle. Older exports
2035
+ * wrote it per post, so import must take the union before creating the root.
2036
+ * Duplicate memberships retain all historical information by taking the
2037
+ * greatest collected/pinned timestamps and the smallest position.
2038
+ */
2039
+ function resolveThreadCollectionMemberships(rootBundle, collectionSlugToId) {
2040
+ const byCollectionId = new Map();
2041
+ const bundles = [rootBundle, ...(rootBundle.children ?? [])];
2042
+
2043
+ for (const bundle of bundles) {
2044
+ const { entries } = resolveCollectionMemberships(
2045
+ bundle.frontMatter,
2046
+ collectionSlugToId,
2047
+ );
2048
+
2049
+ for (const entry of entries) {
2050
+ const current = byCollectionId.get(entry.collectionId);
2051
+ if (!current) {
2052
+ byCollectionId.set(entry.collectionId, { ...entry });
2053
+ continue;
2054
+ }
2055
+
2056
+ if (entry.createdAt !== undefined) {
2057
+ current.createdAt =
2058
+ current.createdAt === undefined
2059
+ ? entry.createdAt
2060
+ : Math.max(current.createdAt, entry.createdAt);
2061
+ }
2062
+ if (entry.position !== undefined) {
2063
+ current.position =
2064
+ current.position === undefined
2065
+ ? entry.position
2066
+ : Math.min(current.position, entry.position);
2067
+ }
2068
+ if (entry.pinnedAt !== undefined) {
2069
+ current.pinnedAt =
2070
+ current.pinnedAt === undefined
2071
+ ? entry.pinnedAt
2072
+ : Math.max(current.pinnedAt, entry.pinnedAt);
2073
+ }
2074
+ }
2075
+ }
2076
+
2077
+ const entries = [...byCollectionId.values()];
2078
+ return {
2079
+ entries,
2080
+ ids: entries.map((entry) => entry.collectionId),
2081
+ };
2082
+ }
2083
+
2084
+ function parseImportTimestamp(value) {
2085
+ if (typeof value !== "string" || value.trim() === "") return null;
2086
+ const timestamp = Date.parse(value);
2087
+ return Number.isFinite(timestamp) ? Math.floor(timestamp / 1000) : null;
2088
+ }
2089
+
2090
+ function getImportedRootLastActivityAt(frontMatter) {
2091
+ return (
2092
+ parseImportTimestamp(frontMatter.last_activity_at) ??
2093
+ parseImportTimestamp(frontMatter.date)
2094
+ );
2095
+ }
2096
+
2097
+ function getImportedPostStatus(frontMatter) {
2098
+ if (frontMatter.status === "draft" || frontMatter.status === "published") {
2099
+ return frontMatter.status;
2100
+ }
2101
+ return frontMatter.draft ? "draft" : "published";
2102
+ }
2103
+
2104
+ function shouldImportReplyQuietly(rootFrontMatter, replyFrontMatter) {
2105
+ if (getImportedPostStatus(replyFrontMatter) !== "published") return false;
2106
+
2107
+ // Exports since quiet_reply became a stored column say so explicitly.
2108
+ if (typeof replyFrontMatter.quiet_reply === "boolean") {
2109
+ return replyFrontMatter.quiet_reply;
2110
+ }
2111
+
2112
+ // Older bundles: a reply published after the root's recorded last activity
2113
+ // can only have gotten there by skipping the bump, so it was quiet.
2114
+ const rootLastActivityAt = getImportedRootLastActivityAt(rootFrontMatter);
2115
+ const replyPublishedAt = parseImportTimestamp(replyFrontMatter.date);
2116
+ return (
2117
+ rootLastActivityAt !== null &&
2118
+ replyPublishedAt !== null &&
2119
+ replyPublishedAt > rootLastActivityAt
2120
+ );
2121
+ }
2122
+
2123
+ /**
2124
+ * The post a Thread's next reply has to answer: the site's rule, the last post
2125
+ * in Thread order. The root comes first whatever its creation time, so the
2126
+ * first reply always ends the Thread; after that the newest reply by creation
2127
+ * time, then by ID, does.
2128
+ *
2129
+ * @param {{ id: string, createdAt: number, replyToId?: string | null }} tail - The current end
2130
+ * @param {{ id: string, createdAt: number, replyToId?: string | null } | null | undefined} created - The post just created
2131
+ * @returns {{ id: string, createdAt: number, replyToId?: string | null }} The new end
2132
+ * @example
2133
+ * getNextThreadTail(
2134
+ * { id: "root", createdAt: 20, replyToId: null },
2135
+ * { id: "r1", createdAt: 10, replyToId: "root" },
2136
+ * );
2137
+ * // r1: a reply older than the root still ends the Thread
2138
+ */
2139
+ function getNextThreadTail(tail, created) {
2140
+ if (!created?.id) return tail;
2141
+ return compareThreadOrder(created, tail) > 0 ? created : tail;
2142
+ }
2143
+
2144
+ /**
2145
+ * Compare two posts of one Thread the way the site orders them (`threadOrder`
2146
+ * in the post service): the root first, then creation time, then ID.
2147
+ *
2148
+ * @param {{ id: string, createdAt: number, replyToId?: string | null }} a
2149
+ * @param {{ id: string, createdAt: number, replyToId?: string | null }} b
2150
+ * @returns {number} Negative when `a` comes first, positive when `b` does
2151
+ * @example
2152
+ * compareThreadOrder({ id: "r1", createdAt: 10, replyToId: "root" },
2153
+ * { id: "root", createdAt: 20, replyToId: null }); // 1
2154
+ */
2155
+ function compareThreadOrder(a, b) {
2156
+ const rank = (post) => (post.replyToId ? 1 : 0);
2157
+ if (rank(a) !== rank(b)) return rank(a) - rank(b);
2158
+ if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
2159
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
2160
+ }
2161
+
2162
+ /**
2163
+ * Build the payload for `target.createPost()` from a parsed bundle. Works
2164
+ * for both root bundles (`forReply: false`) and reply leaf bundles — the
2165
+ * front-matter shape is identical aside from `build:` and the parent link.
2166
+ */
2167
+ function buildPostPayloadFromBundle(bundle, options) {
2168
+ const { frontMatter } = bundle;
2169
+ const format =
2170
+ typeof frontMatter.format === "string" ? frontMatter.format : "note";
2171
+ const slug =
2172
+ typeof frontMatter.slug === "string" ? frontMatter.slug : undefined;
2173
+ const status =
2174
+ frontMatter.status === "draft" || frontMatter.status === "published"
2175
+ ? frontMatter.status
2176
+ : frontMatter.draft
2177
+ ? "draft"
2178
+ : "published";
2179
+ // Accept every canonical visibility value (see `VISIBILITIES` in
2180
+ // `src/types/constants.ts`). Anything else — or missing — falls back to
2181
+ // the service default (`public`).
2182
+ const visibility =
2183
+ frontMatter.visibility === "public" ||
2184
+ frontMatter.visibility === "latest_hidden" ||
2185
+ frontMatter.visibility === "private"
2186
+ ? frontMatter.visibility
2187
+ : undefined;
2188
+ const { entries: collectionEntries, ids: collectionIds } =
2189
+ options.memberships;
2190
+
2191
+ const data = {
2192
+ format,
2193
+ title:
2194
+ format === "quote"
2195
+ ? typeof frontMatter.source_name === "string"
2196
+ ? frontMatter.source_name
2197
+ : undefined
2198
+ : typeof frontMatter.title === "string"
2199
+ ? frontMatter.title
2200
+ : undefined,
2201
+ bodyMarkdown: options.bodyMarkdown || undefined,
2202
+ slug,
2203
+ status,
2204
+ visibility,
2205
+ collectionIds:
2206
+ collectionEntries.length === 0 && collectionIds.length > 0
2207
+ ? collectionIds
2208
+ : undefined,
2209
+ collectionEntries:
2210
+ collectionEntries.length > 0 ? collectionEntries : undefined,
2211
+ attachments:
2212
+ options.attachments.length > 0 ? options.attachments : undefined,
2213
+ publishedAt:
2214
+ status === "published" && typeof frontMatter.date === "string"
2215
+ ? Math.floor(new Date(frontMatter.date).getTime() / 1000)
2216
+ : undefined,
2217
+ // `date` holds the publish time of a published post and the creation
2218
+ // time of a draft; `created` and `updated` are written when they differ.
2219
+ createdAt:
2220
+ parseImportTimestamp(frontMatter.created) ??
2221
+ parseImportTimestamp(frontMatter.date) ??
2222
+ undefined,
2223
+ updatedAt:
2224
+ parseImportTimestamp(frontMatter.updated) ??
2225
+ parseImportTimestamp(frontMatter.date) ??
2226
+ undefined,
2227
+ featuredAt:
2228
+ typeof frontMatter.featured_at === "string" && frontMatter.featured_at
2229
+ ? Math.floor(new Date(frontMatter.featured_at).getTime() / 1000)
2230
+ : undefined,
2231
+ pinnedAt:
2232
+ typeof frontMatter.pinned_at === "string" && frontMatter.pinned_at
2233
+ ? Math.floor(new Date(frontMatter.pinned_at).getTime() / 1000)
2234
+ : undefined,
2235
+ rating:
2236
+ typeof frontMatter.rating === "number" ? frontMatter.rating : undefined,
2237
+ // Roots only: replies take the root's language from the service, and a
2238
+ // reply bundle has no language of its own in the export.
2239
+ language:
2240
+ !options.replyToId && typeof frontMatter.language === "string"
2241
+ ? frontMatter.language
2242
+ : undefined,
2243
+ quietReply: options.quietReply ? true : undefined,
2244
+ };
2245
+
2246
+ if (options.replyToId) {
2247
+ data.replyToId = options.replyToId;
2248
+ }
2249
+
2250
+ if (format === "link" && typeof frontMatter.link_url === "string") {
2251
+ data.url = frontMatter.link_url;
2252
+ }
2253
+ if (format === "quote") {
2254
+ if (typeof frontMatter.quote_text === "string") {
2255
+ data.quoteText = frontMatter.quote_text;
2256
+ }
2257
+ if (
2258
+ typeof frontMatter.source_url === "string" &&
2259
+ frontMatter.source_url.trim()
2260
+ ) {
2261
+ data.url = frontMatter.source_url;
2262
+ }
2263
+ }
2264
+
2265
+ return data;
2266
+ }
2267
+
2268
+ export const __test__ = {
2269
+ isAbsoluteImportUrl,
2270
+ resolveImportUrl,
2271
+ readMediaSpecAsset,
2272
+ normalizeMediaSpec,
2273
+ normalizeTextAttachmentSpec,
2274
+ extractAttachmentBlocks,
2275
+ buildImportedAttachments,
2276
+ uploadMediaList,
2277
+ uploadBundleResources,
2278
+ buildSettingsUpdatesFromConfig,
2279
+ splitSettingsUpdatesForImport,
2280
+ normalizeImportedNavItems,
2281
+ buildNavItemCreateRequest,
2282
+ buildSmartCollectionCreateRequest,
2283
+ normalizeImportedCustomUrls,
2284
+ normalizeImportedCollectionDirectory,
2285
+ buildSiteAvatarImport,
2286
+ reorderCollectionDirectoryItems,
2287
+ syncImportedCollectionDirectory,
2288
+ getRootAliasPathsForImport,
2289
+ toRemotePostPayload,
2290
+ buildIncompleteSetupError,
2291
+ detectRemoteSetupStatus,
2292
+ getIncompleteSetupError,
2293
+ loadSiteConfig,
2294
+ checkSiteExportVersion,
2295
+ walkHugoContent,
2296
+ mediaSpecFromJantMedia,
2297
+ resolveCollectionMemberships,
2298
+ resolveThreadCollectionMemberships,
2299
+ buildPostPayloadFromBundle,
2300
+ shouldImportReplyQuietly,
2301
+ getNextThreadTail,
2302
+ };
2303
+
2304
+ function printImportUsage() {
2305
+ console.log("Usage: jant site import --url <url> [options]");
2306
+ console.log("");
2307
+ console.log("Import a Hugo export directory or ZIP into a Jant site.");
2308
+ console.log("");
2309
+ console.log("Options:");
2310
+ console.log(" --url Jant site URL (required)");
2311
+ console.log(
2312
+ " --path Path to export directory or ZIP file (default: .)",
2313
+ );
2314
+ console.log(" --dry-run Parse and validate without making API calls");
2315
+ console.log(
2316
+ " --skip-remote-media Skip uploading absolute-URL images found in body (relative paths and declared media still import)",
2317
+ );
2318
+ console.log(" --token API token (overrides JANT_API_TOKEN)");
2319
+ console.log("");
2320
+ console.log(
2321
+ "Import expects an empty target site and fails on slug or alias conflicts.",
2322
+ );
2323
+ console.log("");
2324
+ console.log("Authentication:");
2325
+ console.log(` export ${CLI_API_TOKEN_ENV_VAR}=jnt_your_token`);
2326
+ console.log(
2327
+ " jant site import --url https://your-site.example --path ./export",
2328
+ );
2329
+ console.log("");
2330
+ console.log("Examples:");
2331
+ console.log(
2332
+ " jant site import --url https://your-site.example --path ./jant-site",
2333
+ );
2334
+ console.log(
2335
+ " jant site import --url https://your-site.example --path ./jant-site-export.zip",
2336
+ );
2337
+ }
2
2338
 
3
2339
  export async function run(argv) {
4
- return runSiteImport(argv);
2340
+ const { values, positionals } = parseArgs({
2341
+ args: argv,
2342
+ allowPositionals: true,
2343
+ options: {
2344
+ url: { type: "string" },
2345
+ token: { type: "string" },
2346
+ path: { type: "string", default: "." },
2347
+ "dry-run": { type: "boolean", default: false },
2348
+ "skip-remote-media": { type: "boolean", default: false },
2349
+ help: { type: "boolean", short: "h" },
2350
+ },
2351
+ });
2352
+
2353
+ if (values.help) {
2354
+ printImportUsage();
2355
+ process.exit(0);
2356
+ }
2357
+
2358
+ const positionalError = findPositionalUrl("site import", positionals);
2359
+ if (positionalError) {
2360
+ console.error(`Error: ${positionalError}`);
2361
+ process.exit(1);
2362
+ }
2363
+
2364
+ const url = values.url?.trim();
2365
+ if (!url) {
2366
+ console.error("Error: --url is required");
2367
+ console.error("");
2368
+ printImportUsage();
2369
+ process.exit(1);
2370
+ }
2371
+
2372
+ const dryRun = values["dry-run"];
2373
+ const token = getCliApiToken(process.env, values.token);
2374
+ if (!token && !dryRun) {
2375
+ console.error(
2376
+ `Error: site import requires ${CLI_API_TOKEN_ENV_VAR} or --token (unless using --dry-run)`,
2377
+ );
2378
+ console.error("");
2379
+ console.error(` export ${CLI_API_TOKEN_ENV_VAR}=jnt_your_token`);
2380
+ process.exit(1);
2381
+ }
2382
+
2383
+ const apiUrl = url.replace(/\/$/, "");
2384
+ const skipRemoteMedia = values["skip-remote-media"];
2385
+ const target = dryRun ? null : createRemoteTarget(apiUrl, token);
2386
+ /** Exported translation-group ID → IDs of the posts created for it. */
2387
+ const translationGroups = new Map();
2388
+
2389
+ // 1. Read source — directory or ZIP
2390
+ const inputPath = resolve(process.cwd(), values.path);
2391
+ const inputStat = await stat(inputPath).catch(() => null);
2392
+
2393
+ if (!inputStat) {
2394
+ console.error(`Path not found: ${inputPath}`);
2395
+ process.exit(1);
2396
+ }
2397
+
2398
+ let sourceRootDir = inputPath;
2399
+ let tempSourceRootDir = null;
2400
+
2401
+ if (inputStat.isFile()) {
2402
+ console.log(`Reading ZIP ${inputPath}...`);
2403
+ tempSourceRootDir = await mkdtemp(join(tmpdir(), "jant-site-import-"));
2404
+ sourceRootDir = tempSourceRootDir;
2405
+ await extractZipFile(inputPath, sourceRootDir);
2406
+ } else {
2407
+ console.log(`Reading directory ${inputPath}...`);
2408
+ }
2409
+
2410
+ const { rootBundles, collectionBundles, smartCollectionBundles } =
2411
+ await walkHugoContent(sourceRootDir);
2412
+ const siteConfig = await loadSiteConfig(sourceRootDir);
2413
+ const versionError = checkSiteExportVersion(siteConfig);
2414
+ if (versionError) {
2415
+ console.error(`Error: ${versionError}`);
2416
+ if (tempSourceRootDir) {
2417
+ await rm(tempSourceRootDir, { recursive: true, force: true });
2418
+ }
2419
+ process.exit(1);
2420
+ }
2421
+ const customCss = await readImportCustomCss(sourceRootDir);
2422
+
2423
+ try {
2424
+ const replyCount = rootBundles.reduce(
2425
+ (sum, root) => sum + root.children.length,
2426
+ 0,
2427
+ );
2428
+ console.log(
2429
+ `Found ${rootBundles.length} posts (+${replyCount} replies), ${collectionBundles.length} collections, and ${smartCollectionBundles.length} smart collections`,
2430
+ );
2431
+ const importedCollectionDirectory = siteConfig
2432
+ ? normalizeImportedCollectionDirectory(siteConfig)
2433
+ : { exported: false, items: [] };
2434
+ const importedNav = siteConfig
2435
+ ? normalizeImportedNavItems(siteConfig)
2436
+ : { exported: false, items: [] };
2437
+ const importedCustomUrls = siteConfig
2438
+ ? normalizeImportedCustomUrls(siteConfig)
2439
+ : [];
2440
+
2441
+ if (target) {
2442
+ const setupError = await getIncompleteSetupError(
2443
+ target,
2444
+ `Target site at ${apiUrl}`,
2445
+ );
2446
+ if (setupError) {
2447
+ console.error("");
2448
+ console.error(setupError);
2449
+ console.error("");
2450
+ process.exit(1);
2451
+ }
2452
+ }
2453
+
2454
+ if (siteConfig) {
2455
+ const settingsUpdates = buildSettingsUpdatesFromConfig(
2456
+ siteConfig,
2457
+ customCss,
2458
+ );
2459
+ const avatarImport = await buildSiteAvatarImport(
2460
+ siteConfig,
2461
+ sourceRootDir,
2462
+ );
2463
+
2464
+ if (dryRun) {
2465
+ console.log("[dry-run] Would apply exported site settings");
2466
+ if (importedNav.exported) {
2467
+ console.log(
2468
+ `[dry-run] Would replace navigation with ${importedNav.items.length} items`,
2469
+ );
2470
+ }
2471
+ if (avatarImport) {
2472
+ if (avatarImport.mode === "remove") {
2473
+ console.log("[dry-run] Would remove existing site avatar");
2474
+ } else {
2475
+ console.log("[dry-run] Would import exported site avatar");
2476
+ }
2477
+ }
2478
+ } else {
2479
+ const { editable, internal } =
2480
+ splitSettingsUpdatesForImport(settingsUpdates);
2481
+ try {
2482
+ const result = await target.updateSettings(editable);
2483
+ if (result?.rejectedKeys?.length) {
2484
+ console.warn(
2485
+ `Warning: Some site settings were rejected: ${result.rejectedKeys.join(", ")}`,
2486
+ );
2487
+ }
2488
+ } catch (err) {
2489
+ console.error(
2490
+ `Error applying exported site settings: ${err.message}`,
2491
+ );
2492
+ process.exit(1);
2493
+ }
2494
+
2495
+ if (Object.keys(internal).length > 0) {
2496
+ try {
2497
+ const result = await target.updateImportSettings(internal);
2498
+ if (result?.rejectedKeys?.length) {
2499
+ console.warn(
2500
+ `Warning: Some internal site settings were rejected: ${result.rejectedKeys.join(", ")}`,
2501
+ );
2502
+ }
2503
+ } catch (err) {
2504
+ console.error(
2505
+ `Error applying exported internal site settings: ${err.message}`,
2506
+ );
2507
+ process.exit(1);
2508
+ }
2509
+ }
2510
+
2511
+ if (avatarImport) {
2512
+ try {
2513
+ await target.syncSiteAvatar(
2514
+ avatarImport.mode === "set" ? avatarImport : null,
2515
+ );
2516
+ } catch (err) {
2517
+ // Non-fatal: continue the rest of the import even if the avatar
2518
+ // source asset is unreachable (e.g. unreadable file, stale URL).
2519
+ // The rest of the site data is far more valuable than losing the
2520
+ // entire import over a single image.
2521
+ console.warn(
2522
+ `Warning: Could not import site avatar — continuing without it. (${err.message})`,
2523
+ );
2524
+ }
2525
+ }
2526
+ }
2527
+ }
2528
+
2529
+ // 3. Fetch existing collections and create missing ones
2530
+ const collectionSlugToId = new Map();
2531
+ // Root posts by slug, for navigation entries that point at a page.
2532
+ const postSlugToId = new Map();
2533
+
2534
+ if (!dryRun) {
2535
+ try {
2536
+ const existingCollections = await target.listCollections();
2537
+ for (const col of existingCollections) {
2538
+ collectionSlugToId.set(col.slug, col.id);
2539
+ }
2540
+ } catch (err) {
2541
+ console.error(`Error fetching existing collections: ${err.message}`);
2542
+ process.exit(1);
2543
+ }
2544
+ }
2545
+
2546
+ for (const bundle of collectionBundles) {
2547
+ const slug = bundle.slug;
2548
+
2549
+ if (collectionSlugToId.has(slug)) {
2550
+ console.error(
2551
+ `Import conflict: collection slug "${slug}" is already in use. Import into an empty site or remove the existing collection first.`,
2552
+ );
2553
+ process.exit(1);
2554
+ }
2555
+
2556
+ if (dryRun) {
2557
+ console.log(
2558
+ `[dry-run] Would create collection: ${bundle.frontMatter.title || slug}`,
2559
+ );
2560
+ collectionSlugToId.set(slug, `dry-run-${slug}`);
2561
+ continue;
2562
+ }
2563
+
2564
+ try {
2565
+ const result = await target.createCollection({
2566
+ title: bundle.frontMatter.title || slug,
2567
+ slug,
2568
+ description:
2569
+ typeof bundle.frontMatter.summary_text === "string"
2570
+ ? bundle.frontMatter.summary_text
2571
+ : undefined,
2572
+ sortOrder:
2573
+ typeof bundle.frontMatter.sort_order === "string"
2574
+ ? bundle.frontMatter.sort_order
2575
+ : undefined,
2576
+ });
2577
+ collectionSlugToId.set(slug, result.id);
2578
+ console.log(`Created collection: ${bundle.frontMatter.title || slug}`);
2579
+ } catch (err) {
2580
+ console.error(`Error creating collection "${slug}": ${err.message}`);
2581
+ process.exit(1);
2582
+ }
2583
+ }
2584
+
2585
+ // Smart collections after collections, which their conditions may name.
2586
+ // They hold no posts, so nothing about them waits for the posts below.
2587
+ const smartCollectionSlugToId = new Map();
2588
+ if (!dryRun) {
2589
+ try {
2590
+ for (const existing of await target.listSmartCollections()) {
2591
+ smartCollectionSlugToId.set(existing.slug, existing.id);
2592
+ }
2593
+ } catch (err) {
2594
+ console.error(
2595
+ `Error fetching existing smart collections: ${err.message}`,
2596
+ );
2597
+ process.exit(1);
2598
+ }
2599
+ }
2600
+
2601
+ for (const bundle of smartCollectionBundles) {
2602
+ const slug = bundle.slug;
2603
+ if (smartCollectionSlugToId.has(slug)) {
2604
+ console.error(
2605
+ `Import conflict: smart collection slug "${slug}" is already in use. Import into an empty site or remove the existing smart collection first.`,
2606
+ );
2607
+ process.exit(1);
2608
+ }
2609
+
2610
+ const request = buildSmartCollectionCreateRequest(
2611
+ bundle,
2612
+ collectionSlugToId,
2613
+ );
2614
+ if (!request.payload) {
2615
+ console.warn(`Warning: ${request.warning}`);
2616
+ continue;
2617
+ }
2618
+
2619
+ if (dryRun) {
2620
+ console.log(
2621
+ `[dry-run] Would create smart collection: ${request.payload.title}`,
2622
+ );
2623
+ smartCollectionSlugToId.set(slug, `dry-run-${slug}`);
2624
+ continue;
2625
+ }
2626
+
2627
+ try {
2628
+ const created = await target.createSmartCollection(request.payload);
2629
+ smartCollectionSlugToId.set(slug, created.id);
2630
+ console.log(`Created smart collection: ${request.payload.title}`);
2631
+ } catch (err) {
2632
+ console.error(
2633
+ `Error creating smart collection "${slug}": ${err.message}`,
2634
+ );
2635
+ process.exit(1);
2636
+ }
2637
+ }
2638
+
2639
+ if (importedCollectionDirectory.exported) {
2640
+ if (dryRun) {
2641
+ console.log(
2642
+ `[dry-run] Would restore collection directory with ${importedCollectionDirectory.items.length} items`,
2643
+ );
2644
+ } else {
2645
+ try {
2646
+ await syncImportedCollectionDirectory(
2647
+ target,
2648
+ importedCollectionDirectory,
2649
+ collectionSlugToId,
2650
+ smartCollectionSlugToId,
2651
+ );
2652
+ } catch (err) {
2653
+ console.error(
2654
+ `Error restoring collections directory: ${err.message}`,
2655
+ );
2656
+ process.exit(1);
2657
+ }
2658
+ }
2659
+ }
2660
+
2661
+ // 4. Process posts — root bundle first, then each reply leaf, then aliases.
2662
+ let postsCreated = 0;
2663
+ let repliesCreated = 0;
2664
+ let mediaUploaded = 0;
2665
+ let aliasesCreated = 0;
2666
+
2667
+ for (const rootBundle of rootBundles) {
2668
+ const { frontMatter: rootFm } = rootBundle;
2669
+ const postSlug = rootBundle.slug;
2670
+ const format = typeof rootFm.format === "string" ? rootFm.format : "note";
2671
+ const postLabel =
2672
+ (format === "quote"
2673
+ ? typeof rootFm.source_name === "string"
2674
+ ? rootFm.source_name
2675
+ : null
2676
+ : typeof rootFm.title === "string"
2677
+ ? rootFm.title
2678
+ : null) ||
2679
+ postSlug ||
2680
+ "(untitled)";
2681
+
2682
+ if (!dryRun) {
2683
+ await assertImportSlugAvailable(target, postSlug, postLabel, "post");
2684
+ }
2685
+
2686
+ // Normalize body + extract embedded attachment blocks.
2687
+ const normalizedRoot = normalizeImportedBodySegment(rootBundle.body);
2688
+ let rootBody = normalizedRoot.markdown;
2689
+ let importedAttachments = [];
2690
+
2691
+ // Upload media declared in flat `media:` front matter. Each entry's
2692
+ // `src` is either a site-relative path (bytes under `static/`) or an
2693
+ // absolute URL (media still served by the original provider).
2694
+ // Text attachments (`kind: "text"`) live under the same `media:` key
2695
+ // but must be imported via `normalizeTextAttachmentSpec` so the body
2696
+ // is decoded and stored as a text attachment rather than uploaded as
2697
+ // a generic media file.
2698
+ const rootResourceSpecs = [];
2699
+ const rootTextAttachmentEntries = [];
2700
+ if (Array.isArray(rootFm.media)) {
2701
+ for (const entry of rootFm.media) {
2702
+ if (entry && typeof entry === "object" && entry.kind === "text") {
2703
+ rootTextAttachmentEntries.push(entry);
2704
+ continue;
2705
+ }
2706
+ const spec = await mediaSpecFromJantMedia(entry, sourceRootDir);
2707
+ if (spec) rootResourceSpecs.push(spec);
2708
+ }
2709
+ }
2710
+
2711
+ const rootResourceIds = [];
2712
+ if (!dryRun && rootResourceSpecs.length > 0) {
2713
+ const result = await uploadBundleResources(rootResourceSpecs, target);
2714
+ mediaUploaded += result.uploaded;
2715
+ if (result.urlMap.size > 0) {
2716
+ rootBody = rewriteMediaReferences(rootBody, result.urlMap);
2717
+ }
2718
+ rootResourceIds.push(...result.mediaIds);
2719
+ }
2720
+
2721
+ // Fallback: rewrite any leftover in-body image URLs (covers hand-
2722
+ // authored Hugo content where the exporter didn't declare resources).
2723
+ // `--skip-remote-media` filters out absolute URLs here so we only
2724
+ // rehost relative paths (the source site's own files).
2725
+ if (!dryRun) {
2726
+ const fallbackUrls = findImageUrls(rootBody).filter(
2727
+ (url) => !skipRemoteMedia || !isAbsoluteImportUrl(url),
2728
+ );
2729
+ const imageMedia = fallbackUrls.map((src) => ({ src }));
2730
+ const uploadResult = await uploadMediaList(
2731
+ imageMedia,
2732
+ target,
2733
+ siteConfig,
2734
+ sourceRootDir,
2735
+ );
2736
+ mediaUploaded += uploadResult.uploaded;
2737
+ if (uploadResult.urlMap.size > 0) {
2738
+ rootBody = rewriteMediaReferences(rootBody, uploadResult.urlMap);
2739
+ }
2740
+ }
2741
+
2742
+ if (!dryRun) {
2743
+ const attachmentResult = await buildImportedAttachments(
2744
+ normalizedRoot.attachments,
2745
+ target,
2746
+ siteConfig,
2747
+ sourceRootDir,
2748
+ );
2749
+ importedAttachments = attachmentResult.attachments;
2750
+ mediaUploaded += attachmentResult.uploaded;
2751
+ }
2752
+
2753
+ // Also attach every uploaded root page-resource as a media attachment
2754
+ // so the post record carries them even when none appear in body text.
2755
+ for (const mediaId of rootResourceIds) {
2756
+ importedAttachments.push({ type: "media", mediaId });
2757
+ }
2758
+
2759
+ // Build text attachments declared in the flat `media:` front matter.
2760
+ // These reference a `.md` artifact that holds the full body; the
2761
+ // normalizer fetches the bytes (local disk first, then remote URL)
2762
+ // and decodes them.
2763
+ if (!dryRun) {
2764
+ for (const textEntry of rootTextAttachmentEntries) {
2765
+ const textAttachment = await normalizeTextAttachmentSpec(
2766
+ textEntry,
2767
+ siteConfig,
2768
+ sourceRootDir,
2769
+ );
2770
+ if (textAttachment) importedAttachments.push(textAttachment);
2771
+ }
2772
+ }
2773
+
2774
+ const memberships = resolveThreadCollectionMemberships(
2775
+ rootBundle,
2776
+ collectionSlugToId,
2777
+ );
2778
+ const postData = buildPostPayloadFromBundle(rootBundle, {
2779
+ bodyMarkdown: rootBody,
2780
+ attachments: importedAttachments,
2781
+ memberships,
2782
+ replyToId: null,
2783
+ });
2784
+
2785
+ if (dryRun) {
2786
+ console.log(`[dry-run] Would create post: ${postLabel} (${format})`);
2787
+ if (rootBundle.children.length > 0) {
2788
+ console.log(` [dry-run] With ${rootBundle.children.length} replies`);
2789
+ }
2790
+ postsCreated++;
2791
+ repliesCreated += rootBundle.children.length;
2792
+ continue;
2793
+ }
2794
+
2795
+ const progress = `[${postsCreated + 1}/${rootBundles.length}]`;
2796
+ let post;
2797
+ try {
2798
+ post = await target.createPost(postData);
2799
+ postsCreated++;
2800
+ if (post?.id && post.slug) postSlugToId.set(post.slug, post.id);
2801
+ // Translation groups are rebuilt after every post exists: the group ID
2802
+ // in the export is opaque and its members can appear in any order, so
2803
+ // there is nothing to link to until the whole run is done.
2804
+ const groupKey =
2805
+ typeof rootFm.translation_group === "string"
2806
+ ? rootFm.translation_group.trim()
2807
+ : "";
2808
+ if (groupKey && post?.id) {
2809
+ const members = translationGroups.get(groupKey) ?? [];
2810
+ members.push(post.id);
2811
+ translationGroups.set(groupKey, members);
2812
+ }
2813
+ const replyInfo =
2814
+ rootBundle.children.length > 0
2815
+ ? ` (+${rootBundle.children.length} replies)`
2816
+ : "";
2817
+ console.log(`${progress} Created: ${postLabel}${replyInfo}`);
2818
+ } catch (err) {
2819
+ console.error(`Error creating post "${postLabel}": ${err.message}`);
2820
+ process.exit(1);
2821
+ }
2822
+
2823
+ // Create replies before aliases so reply slugs can claim their paths.
2824
+ if (!post) continue;
2825
+ const replySlugPaths = new Set();
2826
+ // Jant threads are linear: a reply must point at the current end of the
2827
+ // thread, which the site reads as its last post in Thread order — the
2828
+ // root first, then replies by creation time, then ID. Creation times
2829
+ // are restored from the export (or taken from `date` in an older one),
2830
+ // so a reply sent after another can carry the earlier time; the end is
2831
+ // then the one with the later time, not the one sent last. Track it by
2832
+ // the site's rule.
2833
+ let threadTail = post;
2834
+ for (const replyBundle of rootBundle.children) {
2835
+ const replyFm = replyBundle.frontMatter;
2836
+ const replySlug = replyBundle.slug;
2837
+ const replyFormat =
2838
+ typeof replyFm.format === "string" ? replyFm.format : "note";
2839
+ const replyLabel =
2840
+ (replyFormat === "quote"
2841
+ ? typeof replyFm.source_name === "string"
2842
+ ? replyFm.source_name
2843
+ : null
2844
+ : typeof replyFm.title === "string"
2845
+ ? replyFm.title
2846
+ : null) ||
2847
+ replySlug ||
2848
+ "(untitled reply)";
2849
+
2850
+ const replySlugPath = normalizeImportAliasPath(replySlug);
2851
+ if (replySlugPath) replySlugPaths.add(replySlugPath);
2852
+
2853
+ await assertImportSlugAvailable(
2854
+ target,
2855
+ replySlug,
2856
+ `${replyLabel} in ${postLabel}`,
2857
+ "reply",
2858
+ );
2859
+
2860
+ const normalizedReply = normalizeImportedBodySegment(replyBundle.body);
2861
+ let replyBody = normalizedReply.markdown;
2862
+ let replyAttachments = [];
2863
+
2864
+ const replyResourceSpecs = [];
2865
+ const replyTextAttachmentEntries = [];
2866
+ if (Array.isArray(replyFm.media)) {
2867
+ for (const entry of replyFm.media) {
2868
+ if (entry && typeof entry === "object" && entry.kind === "text") {
2869
+ replyTextAttachmentEntries.push(entry);
2870
+ continue;
2871
+ }
2872
+ const spec = await mediaSpecFromJantMedia(entry, sourceRootDir);
2873
+ if (spec) replyResourceSpecs.push(spec);
2874
+ }
2875
+ }
2876
+
2877
+ const replyResourceIds = [];
2878
+ if (replyResourceSpecs.length > 0) {
2879
+ const result = await uploadBundleResources(
2880
+ replyResourceSpecs,
2881
+ target,
2882
+ );
2883
+ mediaUploaded += result.uploaded;
2884
+ if (result.urlMap.size > 0) {
2885
+ replyBody = rewriteMediaReferences(replyBody, result.urlMap);
2886
+ }
2887
+ replyResourceIds.push(...result.mediaIds);
2888
+ }
2889
+
2890
+ {
2891
+ const fallbackUrls = findImageUrls(replyBody).filter(
2892
+ (url) => !skipRemoteMedia || !isAbsoluteImportUrl(url),
2893
+ );
2894
+ const imageMedia = fallbackUrls.map((src) => ({ src }));
2895
+ const uploadResult = await uploadMediaList(
2896
+ imageMedia,
2897
+ target,
2898
+ siteConfig,
2899
+ sourceRootDir,
2900
+ );
2901
+ mediaUploaded += uploadResult.uploaded;
2902
+ if (uploadResult.urlMap.size > 0) {
2903
+ replyBody = rewriteMediaReferences(replyBody, uploadResult.urlMap);
2904
+ }
2905
+ }
2906
+
2907
+ const attachmentResult = await buildImportedAttachments(
2908
+ normalizedReply.attachments,
2909
+ target,
2910
+ siteConfig,
2911
+ sourceRootDir,
2912
+ );
2913
+ replyAttachments = attachmentResult.attachments;
2914
+ mediaUploaded += attachmentResult.uploaded;
2915
+ for (const mediaId of replyResourceIds) {
2916
+ replyAttachments.push({ type: "media", mediaId });
2917
+ }
2918
+
2919
+ for (const textEntry of replyTextAttachmentEntries) {
2920
+ const textAttachment = await normalizeTextAttachmentSpec(
2921
+ textEntry,
2922
+ siteConfig,
2923
+ sourceRootDir,
2924
+ );
2925
+ if (textAttachment) replyAttachments.push(textAttachment);
2926
+ }
2927
+
2928
+ const replyData = buildPostPayloadFromBundle(replyBundle, {
2929
+ bodyMarkdown: replyBody,
2930
+ attachments: replyAttachments,
2931
+ memberships: { entries: [], ids: [] },
2932
+ replyToId: threadTail.id,
2933
+ quietReply: shouldImportReplyQuietly(rootFm, replyFm),
2934
+ });
2935
+
2936
+ try {
2937
+ const createdReply = await target.createPost(replyData);
2938
+ repliesCreated++;
2939
+ threadTail = getNextThreadTail(threadTail, createdReply);
2940
+ } catch (err) {
2941
+ console.error(` Error creating reply: ${err.message}`);
2942
+ process.exit(1);
2943
+ }
2944
+ }
2945
+
2946
+ // Create exported root aliases after replies. Historical root slugs
2947
+ // round-trip via `root_aliases:`; reply slugs are handled by their
2948
+ // own bundles so we strip them from the alias list.
2949
+ const rootTargetSlug = postSlug || post.slug;
2950
+ const aliases = Array.isArray(rootFm.aliases) ? rootFm.aliases : [];
2951
+ const rootAliases = Array.isArray(rootFm.root_aliases)
2952
+ ? rootFm.root_aliases
2953
+ : [];
2954
+ const aliasPaths = getRootAliasPathsForImport(
2955
+ aliases,
2956
+ rootAliases,
2957
+ rootTargetSlug,
2958
+ replySlugPaths,
2959
+ );
2960
+ for (const aliasPath of aliasPaths) {
2961
+ try {
2962
+ await target.createAlias(aliasPath, rootTargetSlug);
2963
+ aliasesCreated++;
2964
+ } catch (err) {
2965
+ console.error(
2966
+ `Error creating alias "${aliasPath}" for "${postLabel}": ${err.message}`,
2967
+ );
2968
+ process.exit(1);
2969
+ }
2970
+ }
2971
+ }
2972
+
2973
+ // Rebuild translation groups. Each member is linked to the first one, so a
2974
+ // group of N takes N-1 calls and never asks the server to merge two groups
2975
+ // — which it refuses, on purpose.
2976
+ let translationsLinked = 0;
2977
+ for (const [groupKey, members] of translationGroups) {
2978
+ if (members.length < 2) continue;
2979
+ const [anchor, ...rest] = members;
2980
+ for (const memberId of rest) {
2981
+ try {
2982
+ await target.linkTranslation(anchor, memberId);
2983
+ translationsLinked++;
2984
+ } catch (err) {
2985
+ // A clash here means the export itself held two posts in the same
2986
+ // language for one group. Say so and keep going: the posts are
2987
+ // imported either way, they are just not linked.
2988
+ console.warn(
2989
+ `Warning: could not link a translation in group "${groupKey}": ${err.message}`,
2990
+ );
2991
+ }
2992
+ }
2993
+ }
2994
+
2995
+ // Navigation and custom URLs go last: they point at posts and
2996
+ // collections, which exist by now.
2997
+ let customUrlsCreated = 0;
2998
+ if (!dryRun && target) {
2999
+ if (importedNav.exported) {
3000
+ try {
3001
+ const existingNavItems = await target.listNavItems();
3002
+ for (const item of existingNavItems) {
3003
+ await target.deleteNavItem(item.id);
3004
+ }
3005
+ for (const item of importedNav.items) {
3006
+ const request = buildNavItemCreateRequest(item, {
3007
+ collectionSlugToId,
3008
+ smartCollectionSlugToId,
3009
+ postSlugToId,
3010
+ });
3011
+ if (request.warning) console.warn(`Warning: ${request.warning}`);
3012
+ const created = await target.createNavItem(request.payload);
3013
+ if (request.customLabel && created?.id) {
3014
+ await target.updateNavItem(created.id, {
3015
+ label: request.customLabel,
3016
+ });
3017
+ }
3018
+ }
3019
+ } catch (err) {
3020
+ console.error(`Error importing navigation: ${err.message}`);
3021
+ process.exit(1);
3022
+ }
3023
+ }
3024
+
3025
+ for (const customUrl of importedCustomUrls) {
3026
+ if (customUrl.kind === "archive") {
3027
+ console.warn(
3028
+ `Warning: skipped /${customUrl.path}, an archive URL (${customUrl.archiveQuery ?? "no filter"}). Archive URLs can no longer be created. Create a smart collection at /${customUrl.path} with the same conditions, here or on the source site before exporting.`,
3029
+ );
3030
+ continue;
3031
+ }
3032
+ try {
3033
+ await target.createCustomUrl({
3034
+ path: customUrl.path,
3035
+ targetType: "redirect",
3036
+ toPath: customUrl.to,
3037
+ redirectType: String(customUrl.status),
3038
+ });
3039
+ customUrlsCreated++;
3040
+ } catch (err) {
3041
+ console.warn(
3042
+ `Warning: couldn't recreate the redirect /${customUrl.path} → ${customUrl.to}: ${err.message}`,
3043
+ );
3044
+ }
3045
+ }
3046
+ } else if (dryRun && importedCustomUrls.length > 0) {
3047
+ console.log(
3048
+ `[dry-run] Would recreate ${importedCustomUrls.length} custom URLs`,
3049
+ );
3050
+ }
3051
+
3052
+ await target?.close();
3053
+
3054
+ // 5. Summary
3055
+ console.log("");
3056
+ console.log("Import complete:");
3057
+ console.log(` Posts created: ${postsCreated}`);
3058
+ console.log(` Replies created: ${repliesCreated}`);
3059
+ console.log(` Media uploaded: ${mediaUploaded}`);
3060
+ if (translationsLinked > 0) {
3061
+ console.log(` Translations linked: ${translationsLinked}`);
3062
+ }
3063
+ if (aliasesCreated > 0) {
3064
+ console.log(` Aliases created: ${aliasesCreated}`);
3065
+ }
3066
+ if (customUrlsCreated > 0) {
3067
+ console.log(` Redirects created: ${customUrlsCreated}`);
3068
+ }
3069
+ if (dryRun) {
3070
+ console.log(" (dry-run mode — no changes were made)");
3071
+ }
3072
+ } finally {
3073
+ if (tempSourceRootDir) {
3074
+ await rm(tempSourceRootDir, { recursive: true, force: true });
3075
+ }
3076
+ }
5
3077
  }