@jant/core 0.7.0 → 0.8.0

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