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