@jant/core 0.11.0 → 0.12.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 (183) hide show
  1. package/bin/commands/deploy.js +179 -0
  2. package/bin/lib/cloudflare-setup.js +499 -0
  3. package/bin/lib/d1-query.js +26 -1
  4. package/bin/lib/r2-query.js +2 -2
  5. package/dist/{app-jQI4OPRe.js → app-DSwsDBD0.js} +28623 -635
  6. package/dist/client/.vite/manifest.json +2 -2
  7. package/dist/client/_assets/{client-52vQhZAv.js → client-DPByjWoU.js} +1 -1
  8. package/dist/client/_assets/{client-auth-BDcCR6u1.js → client-auth-CPqPTX1B.js} +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/node.js +2 -2
  11. package/package.json +31 -31
  12. package/src/__tests__/bin/deploy.test.ts +163 -0
  13. package/src/__tests__/export-hugo-build.test.ts +5 -5
  14. package/src/__tests__/export-import-roundtrip.test.ts +1 -1
  15. package/src/__tests__/export-service.test.ts +2 -2
  16. package/src/__tests__/fixtures/releases/0.11.0/site-export/README.md +130 -0
  17. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/297kg/_index.md +14 -0
  18. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/2thjq/_index.md +25 -0
  19. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/2u5e5/_index.md +33 -0
  20. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/0x4nv/index.md +18 -0
  21. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/_index.md +42 -0
  22. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/faqyt/index.md +28 -0
  23. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/41q27/the-potting-mix-guide-i-keep-rereading/index.md +20 -0
  24. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5kayp/_index.md +23 -0
  25. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5ynfs/_index.md +31 -0
  26. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/5ynfs/hu597/index.md +21 -0
  27. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/_index.md +5 -0
  28. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/a-night-heron-field-guide-for-my-walk-folder/_index.md +31 -0
  29. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/a-quiet-saturday-after-a-busy-week/_index.md +36 -0
  30. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/archive/_index.md +8 -0
  31. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/are-na-is-the-only-bookmark-pile-i-still-revisit/_index.md +30 -0
  32. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/bought-too-many-lemons-again/_index.md +35 -0
  33. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/city-walks/_index.md +14 -0
  34. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/cleanshot-for-screenshots-ocr-and-screen-recording-on-the-mac/_index.md +33 -0
  35. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/cleanshotmac-shang-de-jie-tu-ocr-lu-ping-gong-ju/_index.md +32 -0
  36. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/co344/_index.md +25 -0
  37. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/collections/_index.md +5 -0
  38. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/current-tea-rotation/_index.md +34 -0
  39. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/derek-sivers-still-writes-the-kind-of-internet-i-want-more-of/_index.md +30 -0
  40. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/desk-but-better/_index.md +25 -0
  41. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/e0kcg/_index.md +22 -0
  42. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/egi3c/_index.md +24 -0
  43. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/evf9j/_index.md +129 -0
  44. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/featured/_index.md +8 -0
  45. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-draft/_index.md +17 -0
  46. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-quotes/_index.md +13 -0
  47. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/fixture-text-attachment/_index.md +29 -0
  48. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-basho/_index.md +25 -0
  49. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-epictetus/_index.md +25 -0
  50. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-marcus-aurelius/_index.md +25 -0
  51. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-seneca/_index.md +26 -0
  52. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/from-thoreau/_index.md +25 -0
  53. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/2cl6d/index.md +18 -0
  54. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/3zqv7/index.md +28 -0
  55. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/5oxsv/index.md +18 -0
  56. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gkbvv/_index.md +37 -0
  57. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/gwob9/_index.md +25 -0
  58. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/home-cooking/_index.md +12 -0
  59. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/hz729/_index.md +24 -0
  60. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/inaturalist-ai-zi-ran-she-qu/_index.md +42 -0
  61. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/j4v0q/_index.md +33 -0
  62. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k278t/_index.md +25 -0
  63. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k4eee/_index.md +22 -0
  64. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/_index.md +32 -0
  65. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/a-reading-log-idea-i-might-steal/index.md +20 -0
  66. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/a83qu/index.md +18 -0
  67. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/k5vh8/from-seneca-5hibo/index.md +21 -0
  68. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/kan-qi-lai-bi-jiao-ku-de-gong-si-men/_index.md +41 -0
  69. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/l2m7y/_index.md +29 -0
  70. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/lan-ya-yao-kong-qi-chuang-shang-yue-du-de-fan-ye-shen-qi/_index.md +52 -0
  71. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/mynoise-for-rainy-afternoons/_index.md +30 -0
  72. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/n09le/_index.md +23 -0
  73. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/ni-fu-jin-de-wei-ji-bai-ke-tiao-mu/_index.md +40 -0
  74. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/nts-archives-are-good-cleaning-music/_index.md +30 -0
  75. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/_index.md +32 -0
  76. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/c91j0/index.md +18 -0
  77. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/qyucy/index.md +18 -0
  78. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/qgfcu/wsgck/index.md +18 -0
  79. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/rain-makes-my-neighborhood-look-better/_index.md +44 -0
  80. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/reading-notes/_index.md +12 -0
  81. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/s4r3e/_index.md +25 -0
  82. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/serious-eats-on-tomato-and-egg-soup/_index.md +30 -0
  83. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/_index.md +42 -0
  84. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/cxiu6/index.md +18 -0
  85. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/t77ms/index.md +18 -0
  86. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/te812/the-soup-trick-i-always-forget/index.md +20 -0
  87. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/telk3/_index.md +30 -0
  88. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/telk3/from-thoreau-pawt2/index.md +21 -0
  89. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-five-minute-reset-is-still-the-best-habit-i-have/_index.md +36 -0
  90. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-hallway-light-took-12-minutes-and-3-months/_index.md +32 -0
  91. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/the-recurse-center-manual-is-weirdly-calming/_index.md +30 -0
  92. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tiny-projects/_index.md +12 -0
  93. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tong-wang-xing-fu-zhi-lu/_index.md +68 -0
  94. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/tou-ma-yan-jiang-ju-le-bu-chu-ti-yan/_index.md +62 -0
  95. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/useful-links/_index.md +12 -0
  96. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/weekend-notes/_index.md +12 -0
  97. package/src/__tests__/fixtures/releases/0.11.0/site-export/content/what-i-actually-use-my-notebook-for/_index.md +50 -0
  98. package/src/__tests__/fixtures/releases/0.11.0/site-export/data/jant.toml +155 -0
  99. package/src/__tests__/fixtures/releases/0.11.0/site-export/hugo.toml +45 -0
  100. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/_redirects +30 -0
  101. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/3c46a9ea6fe0-med_01kn8jtq3penf98tfq4gzmh9g9.png +0 -0
  102. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jtx8qenf98tm9ahxr48sw.webp +0 -0
  103. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jv0jdenf98tp6qr9zgjjc.webp +0 -0
  104. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jv452enf98trbkwrvhvgd.webp +0 -0
  105. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvb16enf98txp7p0pf5ge.webp +0 -0
  106. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jve5nenf98tzap11gpxzr.webp +0 -0
  107. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvq58enf98v538w5vsqp4.webp +0 -0
  108. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jvsaeenf98v6ct4gjzppc.webp +0 -0
  109. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01kn8jw26cenf98vc7k0ppz5k8.webp +0 -0
  110. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q1hme4e8cmby77dn66yy.webp +0 -0
  111. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q2w7e4e8cmc20036yh66.webp +0 -0
  112. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q7d2e4e8cmdeqjmyafby.webp +0 -0
  113. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m313q887e4e8cmdjssych7yh.webp +0 -0
  114. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp-poster.webp +0 -0
  115. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167jx2f6ct88pkz45j3ycp.mp4 +0 -0
  116. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf-poster.webp +0 -0
  117. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167mbdf6ct88pr4ga1b9kf.mp4 +0 -0
  118. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb-poster.webp +0 -0
  119. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167nsvf6ct88q1anhz4svb.mp4 +0 -0
  120. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83-poster.webp +0 -0
  121. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167qaxf6ct88qfndwzxx83.mp4 +0 -0
  122. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167sm0f6ct88qw5brtsgcw.webp +0 -0
  123. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167tf8f6ct88r169s51j49.webp +0 -0
  124. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167vaaf6ct88rbx5ztenwb.webp +0 -0
  125. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167w51f6ct88rp19pybkw1.webp +0 -0
  126. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167x0nf6ct88rzajb84tw3.webp +0 -0
  127. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167xxbf6ct88s5t2300bjk.webp +0 -0
  128. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167yq5f6ct88s9pjwt5fxg.webp +0 -0
  129. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m3167zg4f6ct88sge8jp28ja.webp +0 -0
  130. package/src/__tests__/fixtures/releases/0.11.0/site-export/static/media/med_01m50607a6e8h8gfpa8byqtt7h.md +3 -0
  131. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/apple-touch-icon.png +0 -0
  132. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/custom.css +0 -0
  133. package/src/__tests__/fixtures/releases/0.11.0/site-export/themes/jant/static/favicon.ico +0 -0
  134. package/src/__tests__/fixtures/releases/0.11.0/site-export/wrangler.jsonc +24 -0
  135. package/src/__tests__/fixtures/releases/0.11.0/snapshot/db.sql +339 -0
  136. package/src/__tests__/fixtures/releases/0.11.0/snapshot/meta.json +11 -0
  137. package/src/__tests__/helpers/d1-round-trips.ts +213 -0
  138. package/src/__tests__/package-dependencies.test.ts +123 -0
  139. package/src/__tests__/public-page-round-trips.test.ts +203 -0
  140. package/src/__tests__/template-deploy-workflow.test.ts +33 -77
  141. package/src/__tests__/vite-config.test.ts +32 -0
  142. package/src/app.tsx +7 -1
  143. package/src/client/icons.ts +5 -6
  144. package/src/db/__tests__/d1-query.test.ts +29 -0
  145. package/src/db/__tests__/migration-rehearsal.test.ts +2 -2
  146. package/src/lib/__tests__/icons.test.ts +21 -10
  147. package/src/lib/api-posts.ts +4 -2
  148. package/src/lib/api-public-posts.ts +4 -2
  149. package/src/lib/constants.ts +20 -0
  150. package/src/lib/icons.ts +96 -34
  151. package/src/lib/post-display.ts +13 -9
  152. package/src/lib/timeline.ts +23 -21
  153. package/src/lib/view.ts +3 -2
  154. package/src/middleware/__tests__/onboarding.test.ts +5 -3
  155. package/src/middleware/__tests__/secure-headers.test.ts +40 -42
  156. package/src/middleware/config.ts +44 -2
  157. package/src/middleware/onboarding.ts +12 -3
  158. package/src/middleware/secure-headers.ts +25 -36
  159. package/src/node/__tests__/cli-deploy-setup.test.ts +373 -0
  160. package/src/node/__tests__/cli-deploy.test.ts +55 -0
  161. package/src/routes/feed/feed.ts +4 -2
  162. package/src/routes/pages/__tests__/post-page-round-trips.test.ts +10 -10
  163. package/src/routes/pages/archive.tsx +36 -17
  164. package/src/routes/pages/collection.tsx +72 -35
  165. package/src/routes/pages/page.tsx +46 -25
  166. package/src/routes/pages/search.tsx +3 -1
  167. package/src/services/__tests__/collection.test.ts +2 -4
  168. package/src/services/collection.ts +95 -71
  169. package/src/services/export.ts +2 -1
  170. package/src/services/post.ts +150 -205
  171. package/src/services/settings.ts +4 -8
  172. package/src/types/app-context.ts +5 -0
  173. package/src/ui/pages/ArchivePage.tsx +34 -34
  174. package/src/ui/pages/CollectionPage.tsx +1 -1
  175. package/src/ui/pages/SmartCollectionPage.tsx +2 -2
  176. package/src/ui/pages/SubscribePage.tsx +2 -4
  177. package/src/ui/shared/CollectionDirectory.tsx +2 -2
  178. package/src/ui/shared/CollectionsManager.tsx +1 -1
  179. package/src/ui/shared/CopyField.tsx +1 -1
  180. package/src/ui/shared/Icon.tsx +5 -5
  181. package/src/ui/shared/IconSprite.tsx +10 -11
  182. package/src/ui/shared/custom-icons.ts +38 -7
  183. package/src/ui/shared/icon-collector.ts +7 -5
@@ -136,17 +136,25 @@ describe("secureHeadersMiddleware", () => {
136
136
  expect(csp).toContain("frame-ancestors 'none'");
137
137
  });
138
138
 
139
+ /** Stand in for `withConfig()`, which sets the config a page renders with. */
140
+ function withCodeInjection(head: string, bodyEnd = "") {
141
+ return async (
142
+ c: Parameters<Parameters<Hono<Env>["use"]>[1]>[0],
143
+ next: () => Promise<void>,
144
+ ) => {
145
+ c.set("appConfig", {
146
+ customHeadHtml: head,
147
+ customBodyEndHtml: bodyEnd,
148
+ } as AppVariables["appConfig"]);
149
+ await next();
150
+ };
151
+ }
152
+
139
153
  it("does not relax script-src when no code injection is configured", async () => {
140
154
  const app = new Hono<Env>();
141
- const settings = {
142
- get: vi.fn(async () => null as string | null),
143
- };
144
155
 
145
- app.use("*", async (c, next) => {
146
- c.set("services", { settings } as AppVariables["services"]);
147
- await next();
148
- });
149
156
  app.use("*", secureHeadersMiddleware());
157
+ app.use("*", withCodeInjection(" "));
150
158
  app.get("/", (c) => c.text("ok"));
151
159
 
152
160
  const response = await app.request("/");
@@ -156,21 +164,13 @@ describe("secureHeadersMiddleware", () => {
156
164
  expect(csp).toContain("script-src 'self' 'unsafe-eval' blob: https:");
157
165
  });
158
166
 
167
+ // Registered ahead of the config middleware, as in `createApp()`: the
168
+ // policy follows what the page rendered with, read after the route ran.
159
169
  it("relaxes script-src with 'unsafe-inline' when code injection is set", async () => {
160
170
  const app = new Hono<Env>();
161
- const settings = {
162
- get: vi.fn(async (key: string) => {
163
- if (key === "CUSTOM_HEAD_HTML")
164
- return "<script>console.log('hi')</script>";
165
- return null;
166
- }),
167
- };
168
171
 
169
- app.use("*", async (c, next) => {
170
- c.set("services", { settings } as AppVariables["services"]);
171
- await next();
172
- });
173
172
  app.use("*", secureHeadersMiddleware());
173
+ app.use("*", withCodeInjection("", "<script>console.log('hi')</script>"));
174
174
  app.get("/", (c) => c.text("ok"));
175
175
 
176
176
  const response = await app.request("/");
@@ -183,45 +183,43 @@ describe("secureHeadersMiddleware", () => {
183
183
 
184
184
  it("keeps script-src tight on frame-protected paths regardless of injection", async () => {
185
185
  const app = new Hono<Env>();
186
- const settings = {
187
- get: vi.fn(async (key: string) => {
188
- if (key === "CUSTOM_HEAD_HTML") return "<script>x()</script>";
189
- return null;
190
- }),
191
- };
192
186
 
193
- app.use("*", async (c, next) => {
194
- c.set("services", { settings } as AppVariables["services"]);
195
- await next();
196
- });
197
187
  app.use("*", secureHeadersMiddleware());
188
+ app.use("*", withCodeInjection("<script>x()</script>"));
198
189
  app.get("/settings", (c) => c.text("ok"));
199
190
 
200
191
  const response = await app.request("/settings");
201
192
  const csp = response.headers.get("content-security-policy") ?? "";
202
193
 
203
194
  expect(csp).not.toMatch(/script-src[^;]*'unsafe-inline'/);
204
- // Settings lookup should be skipped entirely on frame-protected paths.
205
- expect(settings.get).not.toHaveBeenCalled();
206
195
  });
207
196
 
208
- it("skips the settings lookup on static asset paths", async () => {
197
+ it("keeps script-src tight on a response rendered without the site config", async () => {
209
198
  const app = new Hono<Env>();
210
- const settings = {
211
- get: vi.fn(async () => null as string | null),
212
- };
213
199
 
214
- app.use("*", async (c, next) => {
215
- c.set("services", { settings } as AppVariables["services"]);
216
- await next();
217
- });
218
200
  app.use("*", secureHeadersMiddleware());
219
201
  app.get("/media/foo.jpg", (c) => c.text("ok"));
220
- app.get("/favicon.ico", (c) => c.text("ok"));
221
202
 
222
- await app.request("/media/foo.jpg");
223
- await app.request("/favicon.ico");
203
+ const response = await app.request("/media/foo.jpg");
204
+ const csp = response.headers.get("content-security-policy") ?? "";
205
+
206
+ expect(csp).not.toMatch(/script-src[^;]*'unsafe-inline'/);
207
+ });
208
+
209
+ it("sets its headers on an error page too", async () => {
210
+ const app = new Hono<Env>();
224
211
 
225
- expect(settings.get).not.toHaveBeenCalled();
212
+ app.onError((_error, c) => c.text("failed", 500));
213
+ app.use("*", secureHeadersMiddleware());
214
+ app.get("/", () => {
215
+ throw new Error("boom");
216
+ });
217
+
218
+ const response = await app.request("/");
219
+
220
+ expect(response.status).toBe(500);
221
+ expect(response.headers.get("content-security-policy")).toContain(
222
+ "default-src 'self'",
223
+ );
226
224
  });
227
225
  });
@@ -6,7 +6,7 @@
6
6
  * skip for /healthz, /media/*, /favicon.ico, /api/auth/*, etc.
7
7
  */
8
8
 
9
- import type { MiddlewareHandler } from "hono";
9
+ import type { Context, MiddlewareHandler } from "hono";
10
10
  import type { Bindings } from "../types.js";
11
11
  import type { AppVariables } from "../types/app-context.js";
12
12
  import { resolveConfig } from "../lib/resolve-config.js";
@@ -23,6 +23,48 @@ import {
23
23
 
24
24
  type Env = { Bindings: Bindings; Variables: AppVariables };
25
25
 
26
+ /**
27
+ * The site's settings for this request, read once.
28
+ *
29
+ * The first caller starts the read and every later one shares it, so the
30
+ * onboarding gate and `withConfig()` cost one query between them. Nothing
31
+ * between the first middleware that asks and the route handler writes a
32
+ * setting, so a request sees one consistent snapshot, as it would if
33
+ * `withConfig()` read them itself.
34
+ *
35
+ * @param c - Hono context
36
+ * @returns Every stored setting, by key
37
+ * @example
38
+ * const allSettings = await loadRequestSettings(c);
39
+ */
40
+ export function loadRequestSettings(
41
+ c: Context<Env>,
42
+ ): Promise<Record<string, string>> {
43
+ const pending = c.var.settingsLoad;
44
+ if (pending) return pending;
45
+ const load = c.var.services.settings.getAll();
46
+ c.set("settingsLoad", load);
47
+ return load;
48
+ }
49
+
50
+ /**
51
+ * Start reading the site's settings without waiting for them.
52
+ *
53
+ * On Workers each read the middleware chain waits on is one more trip to
54
+ * D1, and the reads here are independent: the stored-redirect lookup needs a
55
+ * path, not the settings. Registered ahead of that middleware, this puts the
56
+ * settings read in flight alongside the lookup instead of after it.
57
+ */
58
+ export function prefetchSettings(): MiddlewareHandler<Env> {
59
+ return async (c, next) => {
60
+ // A redirect can answer before `withConfig()` awaits the read; a failure
61
+ // nobody awaits must not surface as an unhandled rejection. Whoever does
62
+ // await it still sees the error.
63
+ loadRequestSettings(c).catch(() => {});
64
+ await next();
65
+ };
66
+ }
67
+
26
68
  /**
27
69
  * Middleware that loads settings, resolves app config, and builds theme CSS.
28
70
  *
@@ -30,7 +72,7 @@ type Env = { Bindings: Bindings; Variables: AppVariables };
30
72
  */
31
73
  export function withConfig(): MiddlewareHandler<Env> {
32
74
  return async (c, next) => {
33
- const allSettings = await c.var.services.settings.getAll();
75
+ const allSettings = await loadRequestSettings(c);
34
76
  c.set("allSettings", allSettings);
35
77
  const publicRequestOrigin = new URL(c.var.publicRequestUrl).origin;
36
78
  const siteUrlOverride =
@@ -4,7 +4,9 @@
4
4
  * Redirects key page routes to /setup while first-run setup is unfinished.
5
5
  * Uses an allowlist approach: only explicitly listed page routes are redirected,
6
6
  * so static assets, API endpoints, feeds, and other resources always pass through.
7
- * Caches the result in memory so the DB is only queried once per isolate lifetime.
7
+ * Caches the result in memory so the DB is only queried once per isolate lifetime,
8
+ * and reads the status from the request's settings, which `withConfig()` needs
9
+ * anyway, rather than asking for it on its own.
8
10
  *
9
11
  * How much is gated depends on how far setup has got:
10
12
  *
@@ -22,7 +24,12 @@
22
24
  import type { MiddlewareHandler } from "hono";
23
25
  import type { Bindings } from "../types.js";
24
26
  import type { AppVariables } from "../types/app-context.js";
25
- import { ONBOARDING_STATUS } from "../lib/constants.js";
27
+ import {
28
+ ONBOARDING_STATUS,
29
+ SETTINGS_KEYS,
30
+ parseOnboardingStatus,
31
+ } from "../lib/constants.js";
32
+ import { loadRequestSettings } from "./config.js";
26
33
  import { getRuntimeSitePathPrefix } from "../lib/site-resolution.js";
27
34
  import { toPublicPath } from "../lib/url.js";
28
35
 
@@ -48,7 +55,9 @@ export function requireOnboarding(): MiddlewareHandler<Env> {
48
55
  return next();
49
56
  }
50
57
 
51
- const status = await c.var.services.settings.getOnboardingStatus();
58
+ const status = parseOnboardingStatus(
59
+ (await loadRequestSettings(c))[SETTINGS_KEYS.ONBOARDING_STATUS],
60
+ );
52
61
  if (status === ONBOARDING_STATUS.COMPLETED) {
53
62
  completedOnboardingSites.add(c.var.currentSite.id);
54
63
  return next();
@@ -48,20 +48,6 @@ function shouldBlockFraming(path: string): boolean {
48
48
  );
49
49
  }
50
50
 
51
- /**
52
- * Paths whose responses are not HTML rendered by `BaseLayout` and therefore
53
- * never carry author-pasted `customHeadHtml` / `customBodyEndHtml`. Skipping
54
- * the settings lookup for these avoids two DB roundtrips on every static
55
- * asset request.
56
- */
57
- function couldRenderCodeInjection(path: string): boolean {
58
- if (shouldBlockFraming(path)) return false;
59
- if (path === "/favicon.ico" || path === "/apple-touch-icon.png") return false;
60
- if (path === "/healthz" || path === "/readyz") return false;
61
- if (isPublicStoragePath(path)) return false;
62
- return true;
63
- }
64
-
65
51
  function tryGetOrigin(value: string | undefined): string | null {
66
52
  if (!value) return null;
67
53
  try {
@@ -157,37 +143,40 @@ function buildSecureHeadersOptions(
157
143
  }
158
144
 
159
145
  /**
160
- * Probe the settings service for any author-saved code injection. Resolves to
161
- * `false` whenever the lookup is unavailable (e.g. in unit tests that skip the
162
- * runtime middleware) or the path can't render `BaseLayout`.
146
+ * Whether the page this request rendered carries author-pasted code injection.
147
+ *
148
+ * Decided after the route has run, from the configuration it rendered with:
149
+ * `BaseLayout` emits `customHeadHtml` / `customBodyEndHtml` from
150
+ * `c.var.appConfig`, and a request that never loaded that configuration
151
+ * cannot have rendered them. Reading the settings again up front cost every
152
+ * public page a round trip of its own before routing could start.
163
153
  *
164
- * Costs two settings reads on public HTML routes; static asset and
165
- * frame-protected paths are short-circuited above.
154
+ * Authoring and auth pages keep a tight policy whatever is configured: an
155
+ * analytics snippet has no business running next to the settings forms.
166
156
  */
167
- async function detectInlineScriptOptIn(
157
+ function rendersCodeInjection(
168
158
  path: string,
169
- settings: { get(key: string): Promise<string | null> } | undefined,
170
- ): Promise<boolean> {
171
- if (!settings) return false;
172
- if (!couldRenderCodeInjection(path)) return false;
173
- const [head, bodyEnd] = await Promise.all([
174
- settings.get("CUSTOM_HEAD_HTML"),
175
- settings.get("CUSTOM_BODY_END_HTML"),
176
- ]);
177
- return Boolean(head?.trim() || bodyEnd?.trim());
159
+ appConfig: AppVariables["appConfig"] | undefined,
160
+ ): boolean {
161
+ if (!appConfig || shouldBlockFraming(path)) return false;
162
+ return Boolean(
163
+ appConfig.customHeadHtml.trim() || appConfig.customBodyEndHtml.trim(),
164
+ );
178
165
  }
179
166
 
180
167
  export function secureHeadersMiddleware(): MiddlewareHandler<Env> {
181
168
  return async (c, next) => {
182
- // `services` is set by the runtime bootstrap middleware. Cast through
183
- // `undefined` so unit tests that skip that middleware still work.
184
- const services = c.var.services as AppVariables["services"] | undefined;
185
- const allowInlineScript = await detectInlineScriptOptIn(
169
+ await next();
170
+ // Headers go on the response the route produced — Hono's middleware sets
171
+ // them after its own `next()` too — so the route runs first and the policy
172
+ // follows what it rendered. `appConfig` is set by `withConfig()`, which
173
+ // some routes never reach; cast through `undefined` for those.
174
+ const allowInlineScript = rendersCodeInjection(
186
175
  c.req.path,
187
- services?.settings,
176
+ c.var.appConfig as AppVariables["appConfig"] | undefined,
188
177
  );
189
- return secureHeaders(
178
+ await secureHeaders(
190
179
  buildSecureHeadersOptions(c.req.path, c.env, allowInlineScript),
191
- )(c, next);
180
+ )(c, async () => {});
192
181
  };
193
182
  }
@@ -0,0 +1,373 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+ import {
7
+ needsFirstDeploySetup,
8
+ runFirstDeploySetup,
9
+ setAccountId,
10
+ setD1DatabaseId,
11
+ } from "../../../bin/lib/cloudflare-setup.js";
12
+
13
+ /** `wrangler.toml` the way `npm create jant my-blog` writes it. */
14
+ const SCAFFOLDED_CONFIG = `name = "my-blog"
15
+ main = "index.js"
16
+ compatibility_date = "2026-01-20"
17
+
18
+ [vars]
19
+ # SITE_ORIGIN = "https://my-blog.example.com"
20
+
21
+ [[d1_databases]]
22
+ binding = "DB"
23
+ database_name = "my-blog-db"
24
+ database_id = "local"
25
+ migrations_dir = "node_modules/@jant/core/src/db/migrations"
26
+
27
+ [[r2_buckets]]
28
+ binding = "R2"
29
+ bucket_name = "my-blog-media"
30
+ `;
31
+
32
+ const DATABASE_ID = "7c1e5f0a-2b3c-4d5e-8f90-123456789abc";
33
+
34
+ type WranglerCall = { args: string[]; options?: { stdio?: string } };
35
+
36
+ class WranglerError extends Error {
37
+ stdout: string;
38
+ stderr: string;
39
+
40
+ constructor(stderr: string, stdout = "") {
41
+ super("Command failed: wrangler");
42
+ this.stdout = stdout;
43
+ this.stderr = stderr;
44
+ }
45
+ }
46
+
47
+ const notFoundBucket = () =>
48
+ new WranglerError(
49
+ "✘ [ERROR] A request to the Cloudflare API (/accounts/x/r2/buckets/my-blog-media) failed.\n\n The specified bucket does not exist. [code: 10006]\n",
50
+ );
51
+ const notFoundWorker = () =>
52
+ new WranglerError(
53
+ '✘ [ERROR] Worker "my-blog" not found.\n\n If this is a new Worker, run `wrangler deploy` first to create it.\n',
54
+ );
55
+
56
+ /**
57
+ * A stand-in for Wrangler with an account that starts out empty. Creating a
58
+ * database or bucket adds it, the way the real API would.
59
+ */
60
+ function fakeCloudflare(
61
+ state: {
62
+ loggedIn?: boolean;
63
+ accounts?: { id: string; name: string }[];
64
+ databases?: { name: string; uuid: string }[];
65
+ buckets?: string[];
66
+ secrets?: string[];
67
+ r2Enabled?: boolean;
68
+ } = {},
69
+ ) {
70
+ const account = {
71
+ loggedIn: state.loggedIn ?? true,
72
+ accounts: state.accounts ?? [{ id: "acc1", name: "Owen's Account" }],
73
+ databases: [...(state.databases ?? [])],
74
+ buckets: [...(state.buckets ?? [])],
75
+ secrets: state.secrets ?? null,
76
+ r2Enabled: state.r2Enabled ?? true,
77
+ };
78
+ const calls: WranglerCall[] = [];
79
+
80
+ const wrangler = (args: string[], options?: { stdio?: string }) => {
81
+ calls.push({ args, options });
82
+ const command = args.slice(0, 3).join(" ");
83
+
84
+ if (args[0] === "whoami") {
85
+ const body = JSON.stringify(
86
+ account.loggedIn
87
+ ? { loggedIn: true, accounts: account.accounts }
88
+ : { loggedIn: false },
89
+ );
90
+ if (!account.loggedIn) throw new WranglerError("", body);
91
+ return body;
92
+ }
93
+ if (args[0] === "login") {
94
+ account.loggedIn = true;
95
+ return "";
96
+ }
97
+ if (command === "d1 list --json") {
98
+ return JSON.stringify(account.databases);
99
+ }
100
+ if (command.startsWith("d1 create")) {
101
+ account.databases.push({ name: args[2]!, uuid: DATABASE_ID });
102
+ return "Successfully created DB";
103
+ }
104
+ if (command === "r2 bucket info" || command === "r2 bucket create") {
105
+ if (!account.r2Enabled) {
106
+ throw new WranglerError(
107
+ "✘ [ERROR] A request to the Cloudflare API failed.\n\n Please enable R2 through the Cloudflare Dashboard. [code: 10042]\n",
108
+ );
109
+ }
110
+ if (command === "r2 bucket create") {
111
+ account.buckets.push(args[3]!);
112
+ return "Created bucket";
113
+ }
114
+ if (!account.buckets.includes(args[3]!)) throw notFoundBucket();
115
+ return JSON.stringify({ name: args[3] });
116
+ }
117
+ if (command === "secret list --format") {
118
+ if (account.secrets === null) throw notFoundWorker();
119
+ return JSON.stringify(
120
+ account.secrets.map((name) => ({ name, type: "secret_text" })),
121
+ );
122
+ }
123
+ throw new Error(`Unexpected wrangler call: ${args.join(" ")}`);
124
+ };
125
+
126
+ return { account, calls, wrangler };
127
+ }
128
+
129
+ const terminal = { stdin: { isTTY: true }, stdout: { isTTY: true } };
130
+ const pipe = { stdin: { isTTY: false }, stdout: { isTTY: false } };
131
+
132
+ describe("first-deploy setup", () => {
133
+ let root: string;
134
+ const originalCwd = process.cwd();
135
+ const cleanups: (() => void)[] = [];
136
+
137
+ beforeEach(async () => {
138
+ root = await mkdtemp(join(tmpdir(), "jant-deploy-setup-"));
139
+ await writeFile(join(root, "wrangler.toml"), SCAFFOLDED_CONFIG);
140
+ process.chdir(root);
141
+ // A developer's shell or CI may set these; the tests decide them.
142
+ vi.stubEnv("CI", "");
143
+ vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "");
144
+ });
145
+
146
+ afterEach(async () => {
147
+ for (const cleanup of cleanups.splice(0)) cleanup();
148
+ process.chdir(originalCwd);
149
+ vi.unstubAllEnvs();
150
+ await rm(root, { recursive: true, force: true });
151
+ });
152
+
153
+ async function setUp(
154
+ cloudflare: ReturnType<typeof fakeCloudflare>,
155
+ deps: { io?: object; ask?: (question: string) => Promise<string> } = {},
156
+ ) {
157
+ const log = vi.fn();
158
+ const setup = await runFirstDeploySetup(
159
+ { configPath: "wrangler.toml", database: "DB" },
160
+ {
161
+ io: deps.io ?? pipe,
162
+ log,
163
+ ask: deps.ask,
164
+ wrangler: cloudflare.wrangler,
165
+ },
166
+ );
167
+ cleanups.push(setup.cleanup);
168
+ return { setup, log };
169
+ }
170
+
171
+ const readConfig = () => readFile(join(root, "wrangler.toml"), "utf8");
172
+
173
+ it("runs only while database_id is the scaffold placeholder", async () => {
174
+ expect(needsFirstDeploySetup({ configPath: "wrangler.toml" })).toBe(true);
175
+
176
+ await writeFile(
177
+ join(root, "wrangler.toml"),
178
+ SCAFFOLDED_CONFIG.replace('"local"', `"${DATABASE_ID}"`),
179
+ );
180
+ expect(needsFirstDeploySetup({ configPath: "wrangler.toml" })).toBe(false);
181
+
182
+ await writeFile(join(root, "wrangler.toml"), '[assets]\ndirectory = "x"\n');
183
+ expect(needsFirstDeploySetup({ configPath: "wrangler.toml" })).toBe(false);
184
+ });
185
+
186
+ it("creates the database, the bucket, and AUTH_SECRET on an empty account", async () => {
187
+ const cloudflare = fakeCloudflare();
188
+ const { setup } = await setUp(cloudflare);
189
+
190
+ expect(cloudflare.account.databases).toEqual([
191
+ { name: "my-blog-db", uuid: DATABASE_ID },
192
+ ]);
193
+ expect(cloudflare.account.buckets).toEqual(["my-blog-media"]);
194
+ expect(await readConfig()).toBe(
195
+ SCAFFOLDED_CONFIG.replace('"local"', `"${DATABASE_ID}"`),
196
+ );
197
+
198
+ const secretsFile = setup.secretsFile!;
199
+ const secrets = JSON.parse(readFileSync(secretsFile, "utf8"));
200
+ expect(Object.keys(secrets)).toEqual(["AUTH_SECRET"]);
201
+ expect(secrets.AUTH_SECRET).toHaveLength(44);
202
+ expect(statSync(secretsFile).mode & 0o777).toBe(0o600);
203
+
204
+ setup.cleanup();
205
+ expect(existsSync(secretsFile)).toBe(false);
206
+ });
207
+
208
+ it("reuses what already exists and keeps the Worker's AUTH_SECRET", async () => {
209
+ const cloudflare = fakeCloudflare({
210
+ databases: [{ name: "my-blog-db", uuid: DATABASE_ID }],
211
+ buckets: ["my-blog-media"],
212
+ secrets: ["AUTH_SECRET"],
213
+ });
214
+ const { setup } = await setUp(cloudflare);
215
+
216
+ const commands = cloudflare.calls.map((call) => call.args.slice(0, 3));
217
+ expect(commands).not.toContainEqual(["d1", "create", "my-blog-db"]);
218
+ expect(commands).not.toContainEqual(["r2", "bucket", "create"]);
219
+ expect(setup.secretsFile).toBeNull();
220
+ expect(await readConfig()).toContain(`database_id = "${DATABASE_ID}"`);
221
+ });
222
+
223
+ it("puts the placeholder back when the deploy fails", async () => {
224
+ const { setup } = await setUp(fakeCloudflare());
225
+ setup.restore();
226
+ expect(await readConfig()).toBe(SCAFFOLDED_CONFIG);
227
+ });
228
+
229
+ it("tells a script how to sign in instead of opening a browser", async () => {
230
+ const cloudflare = fakeCloudflare({ loggedIn: false });
231
+ await expect(setUp(cloudflare)).rejects.toThrow("npx wrangler login");
232
+ expect(cloudflare.calls.map((call) => call.args[0])).not.toContain("login");
233
+ expect(await readConfig()).toBe(SCAFFOLDED_CONFIG);
234
+ });
235
+
236
+ it("signs in through the browser when a person is at the terminal", async () => {
237
+ const cloudflare = fakeCloudflare({ loggedIn: false });
238
+ await setUp(cloudflare, { io: terminal });
239
+ expect(cloudflare.calls).toContainEqual({
240
+ args: ["login"],
241
+ options: { stdio: "inherit" },
242
+ });
243
+ });
244
+
245
+ it("lists the accounts for a script when the sign-in reaches several", async () => {
246
+ const cloudflare = fakeCloudflare({
247
+ accounts: [
248
+ { id: "acc1", name: "Personal" },
249
+ { id: "acc2", name: "Work" },
250
+ ],
251
+ });
252
+ await expect(setUp(cloudflare)).rejects.toThrow(
253
+ /Personal \(acc1\)[\s\S]*Work \(acc2\)/,
254
+ );
255
+ expect(cloudflare.calls.map((call) => call.args[0])).not.toContain("d1");
256
+ });
257
+
258
+ it("asks a person which account to use and remembers it", async () => {
259
+ const cloudflare = fakeCloudflare({
260
+ accounts: [
261
+ { id: "acc1", name: "Personal" },
262
+ { id: "acc2", name: "Work" },
263
+ ],
264
+ });
265
+ const ask = vi.fn(async () => "2");
266
+ const { setup } = await setUp(cloudflare, { io: terminal, ask });
267
+
268
+ expect(ask).toHaveBeenCalledOnce();
269
+ const config = await readConfig();
270
+ expect(config).toMatch(/^name = "my-blog"\naccount_id = "acc2"\n/);
271
+
272
+ // A failed deploy keeps the choice.
273
+ setup.restore();
274
+ expect(await readConfig()).toContain('account_id = "acc2"');
275
+ expect(await readConfig()).toContain('database_id = "local"');
276
+ });
277
+
278
+ it("skips the account question when wrangler.toml names one", async () => {
279
+ await writeFile(
280
+ join(root, "wrangler.toml"),
281
+ setAccountId(SCAFFOLDED_CONFIG, "acc2"),
282
+ );
283
+ const cloudflare = fakeCloudflare({
284
+ accounts: [
285
+ { id: "acc1", name: "Personal" },
286
+ { id: "acc2", name: "Work" },
287
+ ],
288
+ });
289
+ const ask = vi.fn(async () => "1");
290
+ await setUp(cloudflare, { io: terminal, ask });
291
+ expect(ask).not.toHaveBeenCalled();
292
+ });
293
+
294
+ it("says where to enable R2 when the account hasn't", async () => {
295
+ const cloudflare = fakeCloudflare({ r2Enabled: false });
296
+ await expect(setUp(cloudflare)).rejects.toThrow(
297
+ /R2 isn't enabled[\s\S]*dash\.cloudflare\.com/,
298
+ );
299
+ expect(await readConfig()).toBe(SCAFFOLDED_CONFIG);
300
+ });
301
+
302
+ it("leaves R2 alone in a project without buckets", async () => {
303
+ await writeFile(
304
+ join(root, "wrangler.toml"),
305
+ SCAFFOLDED_CONFIG.replace(/\n\[\[r2_buckets\]\][^[]*/s, "\n"),
306
+ );
307
+ const cloudflare = fakeCloudflare();
308
+ await setUp(cloudflare);
309
+ expect(cloudflare.calls.map((call) => call.args[0])).not.toContain("r2");
310
+ });
311
+ });
312
+
313
+ describe("setD1DatabaseId", () => {
314
+ it("replaces the binding's database_id and keeps the rest of the file", () => {
315
+ const raw = `# Site config
316
+ [[d1_databases]]
317
+ binding = "OTHER"
318
+ database_name = "other"
319
+ database_id = "keep-me"
320
+
321
+ [[d1_databases]]
322
+ binding = "DB"
323
+ database_name = "my-blog-db"
324
+ database_id = "local" # set on first deploy
325
+ `;
326
+ expect(setD1DatabaseId(raw, { binding: "DB", databaseId: "new-id" })).toBe(
327
+ raw.replace('"local"', '"new-id"'),
328
+ );
329
+ });
330
+
331
+ it("adds database_id after database_name when the entry has none", () => {
332
+ const raw = `[[d1_databases]]
333
+ binding = "DB"
334
+ database_name = "my-blog-db"
335
+ migrations_dir = "migrations"
336
+ `;
337
+ expect(setD1DatabaseId(raw, { binding: "DB", databaseId: "new-id" })).toBe(
338
+ `[[d1_databases]]
339
+ binding = "DB"
340
+ database_name = "my-blog-db"
341
+ database_id = "new-id"
342
+ migrations_dir = "migrations"
343
+ `,
344
+ );
345
+ });
346
+
347
+ it("writes into the named environment's entry", () => {
348
+ const raw = `[[d1_databases]]
349
+ binding = "DB"
350
+ database_id = "local"
351
+
352
+ [[env.staging.d1_databases]]
353
+ binding = "DB"
354
+ database_id = "local"
355
+ `;
356
+ expect(
357
+ setD1DatabaseId(raw, {
358
+ binding: "DB",
359
+ databaseId: "staging-id",
360
+ env: "staging",
361
+ }),
362
+ ).toBe(raw.replace(/"local"\n$/, '"staging-id"\n'));
363
+ });
364
+
365
+ it("fails when no entry has the binding", () => {
366
+ expect(() =>
367
+ setD1DatabaseId('[[d1_databases]]\nbinding = "OTHER"\n', {
368
+ binding: "DB",
369
+ databaseId: "x",
370
+ }),
371
+ ).toThrow('No [[d1_databases]] entry for binding "DB"');
372
+ });
373
+ });