@fastly/compute-js-static-publish 8.0.0 → 8.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/DOCUMENTATION.md +1984 -0
  2. package/README.md +11 -4
  3. package/README.short.md +11 -4
  4. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  5. package/build/cli/cli/commands/manage/clean.js +12 -7
  6. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  7. package/build/cli/cli/commands/manage/collections/delete.js +29 -13
  8. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  9. package/build/cli/cli/commands/manage/collections/index.js +6 -1
  10. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  11. package/build/cli/cli/commands/manage/collections/list.js +47 -7
  12. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  13. package/build/cli/cli/commands/manage/collections/promote.js +67 -20
  14. package/build/cli/cli/commands/manage/collections/update-expiration.d.ts.map +1 -1
  15. package/build/cli/cli/commands/manage/collections/update-expiration.js +10 -11
  16. package/build/cli/cli/commands/manage/deploy.d.ts +2 -0
  17. package/build/cli/cli/commands/manage/deploy.d.ts.map +1 -0
  18. package/build/cli/cli/commands/manage/deploy.js +194 -0
  19. package/build/cli/cli/commands/manage/dev.d.ts +2 -0
  20. package/build/cli/cli/commands/manage/dev.d.ts.map +1 -0
  21. package/build/cli/cli/commands/manage/dev.js +77 -0
  22. package/build/cli/cli/commands/manage/eject.d.ts +2 -0
  23. package/build/cli/cli/commands/manage/eject.d.ts.map +1 -0
  24. package/build/cli/cli/commands/manage/eject.js +155 -0
  25. package/build/cli/cli/commands/manage/index.d.ts.map +1 -1
  26. package/build/cli/cli/commands/manage/index.js +37 -1
  27. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  28. package/build/cli/cli/commands/manage/publish-content.js +85 -35
  29. package/build/cli/cli/commands/manage/status.d.ts +2 -0
  30. package/build/cli/cli/commands/manage/status.d.ts.map +1 -0
  31. package/build/cli/cli/commands/manage/status.js +162 -0
  32. package/build/cli/cli/commands/manage/template/index.d.ts +2 -0
  33. package/build/cli/cli/commands/manage/template/index.d.ts.map +1 -0
  34. package/build/cli/cli/commands/manage/template/index.js +42 -0
  35. package/build/cli/cli/commands/manage/template/init.d.ts +13 -0
  36. package/build/cli/cli/commands/manage/template/init.d.ts.map +1 -0
  37. package/build/cli/cli/commands/manage/template/init.js +172 -0
  38. package/build/cli/cli/commands/manage/upgrade.d.ts +2 -0
  39. package/build/cli/cli/commands/manage/upgrade.d.ts.map +1 -0
  40. package/build/cli/cli/commands/manage/upgrade.js +59 -0
  41. package/build/cli/cli/commands/run-dev-watch.d.ts +8 -0
  42. package/build/cli/cli/commands/run-dev-watch.d.ts.map +1 -0
  43. package/build/cli/cli/commands/run-dev-watch.js +41 -0
  44. package/build/cli/cli/commands/run-template-hook.d.ts +2 -0
  45. package/build/cli/cli/commands/run-template-hook.d.ts.map +1 -0
  46. package/build/cli/cli/commands/run-template-hook.js +28 -0
  47. package/build/cli/cli/commands/scaffold/app-template.d.ts +17 -0
  48. package/build/cli/cli/commands/scaffold/app-template.d.ts.map +1 -0
  49. package/build/cli/cli/commands/scaffold/app-template.js +54 -0
  50. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts +5 -0
  51. package/build/cli/cli/commands/scaffold/fastly-toml-sections.d.ts.map +1 -0
  52. package/build/cli/cli/commands/scaffold/fastly-toml-sections.js +154 -0
  53. package/build/cli/cli/commands/scaffold/generate-app.d.ts +47 -0
  54. package/build/cli/cli/commands/scaffold/generate-app.d.ts.map +1 -0
  55. package/build/cli/cli/commands/scaffold/generate-app.js +164 -0
  56. package/build/cli/cli/commands/scaffold/index.d.ts +6 -0
  57. package/build/cli/cli/commands/scaffold/index.d.ts.map +1 -1
  58. package/build/cli/cli/commands/scaffold/index.js +239 -300
  59. package/build/cli/cli/commands/scaffold/render.d.ts +7 -0
  60. package/build/cli/cli/commands/scaffold/render.d.ts.map +1 -0
  61. package/build/cli/cli/commands/scaffold/render.js +72 -0
  62. package/build/cli/cli/hono/build.d.ts +43 -0
  63. package/build/cli/cli/hono/build.d.ts.map +1 -0
  64. package/build/cli/cli/hono/build.js +297 -0
  65. package/build/cli/cli/index.js +98 -5
  66. package/build/cli/cli/managed/app.d.ts +21 -0
  67. package/build/cli/cli/managed/app.d.ts.map +1 -0
  68. package/build/cli/cli/managed/app.js +162 -0
  69. package/build/cli/cli/managed/command-helpers.d.ts +6 -0
  70. package/build/cli/cli/managed/command-helpers.d.ts.map +1 -0
  71. package/build/cli/cli/managed/command-helpers.js +81 -0
  72. package/build/cli/cli/managed/eject.d.ts +6 -0
  73. package/build/cli/cli/managed/eject.d.ts.map +1 -0
  74. package/build/cli/cli/managed/eject.js +68 -0
  75. package/build/cli/cli/managed/fastly-service.d.ts +8 -0
  76. package/build/cli/cli/managed/fastly-service.d.ts.map +1 -0
  77. package/build/cli/cli/managed/fastly-service.js +21 -0
  78. package/build/cli/cli/managed/fingerprint.d.ts +13 -0
  79. package/build/cli/cli/managed/fingerprint.d.ts.map +1 -0
  80. package/build/cli/cli/managed/fingerprint.js +60 -0
  81. package/build/cli/cli/managed/lockfile.d.ts +31 -0
  82. package/build/cli/cli/managed/lockfile.d.ts.map +1 -0
  83. package/build/cli/cli/managed/lockfile.js +62 -0
  84. package/build/cli/cli/managed/project-edit.d.ts +3 -0
  85. package/build/cli/cli/managed/project-edit.d.ts.map +1 -0
  86. package/build/cli/cli/managed/project-edit.js +35 -0
  87. package/build/cli/cli/managed/project-file.d.ts +16 -0
  88. package/build/cli/cli/managed/project-file.d.ts.map +1 -0
  89. package/build/cli/cli/managed/project-file.js +119 -0
  90. package/build/cli/cli/managed/template-init.d.ts +12 -0
  91. package/build/cli/cli/managed/template-init.d.ts.map +1 -0
  92. package/build/cli/cli/managed/template-init.js +120 -0
  93. package/build/cli/cli/managed/version-check.d.ts +25 -0
  94. package/build/cli/cli/managed/version-check.d.ts.map +1 -0
  95. package/build/cli/cli/managed/version-check.js +84 -0
  96. package/build/cli/cli/storage/kv-store-local-provider.d.ts +1 -0
  97. package/build/cli/cli/storage/kv-store-local-provider.d.ts.map +1 -1
  98. package/build/cli/cli/storage/kv-store-local-provider.js +6 -3
  99. package/build/cli/cli/storage/kv-store-provider.d.ts +2 -1
  100. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  101. package/build/cli/cli/storage/kv-store-provider.js +17 -6
  102. package/build/cli/cli/storage/s3-storage-provider.d.ts +1 -0
  103. package/build/cli/cli/storage/s3-storage-provider.d.ts.map +1 -1
  104. package/build/cli/cli/storage/s3-storage-provider.js +8 -2
  105. package/build/cli/cli/storage/storage-provider.d.ts +4 -0
  106. package/build/cli/cli/storage/storage-provider.d.ts.map +1 -1
  107. package/build/cli/cli/storage/storage-provider.js +32 -0
  108. package/build/cli/cli/util/api-token.d.ts +2 -1
  109. package/build/cli/cli/util/api-token.d.ts.map +1 -1
  110. package/build/cli/cli/util/api-token.js +38 -3
  111. package/build/cli/cli/util/collection-name.d.ts +3 -0
  112. package/build/cli/cli/util/collection-name.d.ts.map +1 -0
  113. package/build/cli/cli/util/collection-name.js +24 -0
  114. package/build/cli/cli/util/collection-selection-flags.d.ts +13 -0
  115. package/build/cli/cli/util/collection-selection-flags.d.ts.map +1 -0
  116. package/build/cli/cli/util/collection-selection-flags.js +131 -0
  117. package/build/cli/cli/util/config.d.ts +13 -0
  118. package/build/cli/cli/util/config.d.ts.map +1 -1
  119. package/build/cli/cli/util/config.js +172 -38
  120. package/build/cli/cli/util/data.d.ts.map +1 -1
  121. package/build/cli/cli/util/global-options.d.ts +13 -0
  122. package/build/cli/cli/util/global-options.d.ts.map +1 -0
  123. package/build/cli/cli/util/global-options.js +53 -0
  124. package/build/cli/cli/util/kv-store-items.d.ts +1 -0
  125. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  126. package/build/cli/cli/util/kv-store-items.js +16 -40
  127. package/build/cli/cli/util/kv-store-local-server.d.ts +1 -1
  128. package/build/cli/cli/util/kv-store-local-server.d.ts.map +1 -1
  129. package/build/cli/cli/util/kv-store-local-server.js +4 -2
  130. package/build/cli/cli/util/output.d.ts +31 -0
  131. package/build/cli/cli/util/output.d.ts.map +1 -0
  132. package/build/cli/cli/util/output.js +139 -0
  133. package/build/cli/cli/util/package.d.ts +3 -0
  134. package/build/cli/cli/util/package.d.ts.map +1 -1
  135. package/build/cli/cli/util/package.js +12 -0
  136. package/build/cli/cli/util/progress.d.ts +11 -0
  137. package/build/cli/cli/util/progress.d.ts.map +1 -0
  138. package/build/cli/cli/util/progress.js +32 -0
  139. package/build/cli/cli/util/purge.d.ts +15 -3
  140. package/build/cli/cli/util/purge.d.ts.map +1 -1
  141. package/build/cli/cli/util/purge.js +23 -10
  142. package/build/cli/cli/util/resources.d.ts +2 -0
  143. package/build/cli/cli/util/resources.d.ts.map +1 -0
  144. package/build/cli/cli/util/resources.js +8 -0
  145. package/build/cli/cli/util/service-id.d.ts +1 -0
  146. package/build/cli/cli/util/service-id.d.ts.map +1 -1
  147. package/build/cli/cli/util/service-id.js +5 -1
  148. package/build/cli/cli/util/variants.d.ts.map +1 -1
  149. package/build/cli/models/assets/index.d.ts +6 -0
  150. package/build/cli/models/assets/index.d.ts.map +1 -1
  151. package/build/cli/models/assets/index.js +24 -0
  152. package/build/cli/models/collections/index.d.ts +3 -0
  153. package/build/cli/models/collections/index.d.ts.map +1 -0
  154. package/build/cli/models/collections/index.js +15 -0
  155. package/build/cli/models/compression/index.d.ts +1 -1
  156. package/build/cli/models/compression/index.d.ts.map +1 -1
  157. package/build/cli/models/config/collection-selection.d.ts +55 -0
  158. package/build/cli/models/config/collection-selection.d.ts.map +1 -0
  159. package/build/cli/models/config/collection-selection.js +238 -0
  160. package/build/cli/models/config/item-patterns.d.ts +4 -0
  161. package/build/cli/models/config/item-patterns.d.ts.map +1 -0
  162. package/build/cli/models/config/item-patterns.js +43 -0
  163. package/build/cli/models/config/publish-content-config.d.ts +6 -1
  164. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  165. package/build/cli/models/config/static-publish-project.d.ts +23 -0
  166. package/build/cli/models/config/static-publish-project.d.ts.map +1 -0
  167. package/build/cli/models/config/static-publish-project.js +11 -0
  168. package/build/cli/models/config/static-publish-rc.d.ts +25 -0
  169. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  170. package/build/cli/models/config/static-publish-rc.js +31 -0
  171. package/build/cli/models/config/template-settings.d.ts +10 -0
  172. package/build/cli/models/config/template-settings.d.ts.map +1 -0
  173. package/build/cli/models/config/template-settings.js +72 -0
  174. package/build/cli/models/server/index.d.ts.map +1 -1
  175. package/build/cli/models/server/index.js +6 -2
  176. package/build/server/hono/extensions.d.ts +48 -0
  177. package/build/server/hono/extensions.d.ts.map +1 -0
  178. package/build/server/hono/extensions.js +65 -0
  179. package/build/server/hono/index.d.ts +30 -0
  180. package/build/server/hono/index.d.ts.map +1 -0
  181. package/build/server/hono/index.js +72 -0
  182. package/build/server/hono/path.d.ts +7 -0
  183. package/build/server/hono/path.d.ts.map +1 -0
  184. package/build/server/hono/path.js +32 -0
  185. package/build/server/models/assets/index.d.ts +6 -0
  186. package/build/server/models/assets/index.d.ts.map +1 -1
  187. package/build/server/models/assets/index.js +24 -0
  188. package/build/server/models/collections/index.d.ts +3 -0
  189. package/build/server/models/collections/index.d.ts.map +1 -0
  190. package/build/server/models/collections/index.js +15 -0
  191. package/build/server/models/compression/index.d.ts +1 -1
  192. package/build/server/models/compression/index.d.ts.map +1 -1
  193. package/build/server/models/config/collection-selection.d.ts +55 -0
  194. package/build/server/models/config/collection-selection.d.ts.map +1 -0
  195. package/build/server/models/config/collection-selection.js +238 -0
  196. package/build/server/models/config/item-patterns.d.ts +4 -0
  197. package/build/server/models/config/item-patterns.d.ts.map +1 -0
  198. package/build/server/models/config/item-patterns.js +43 -0
  199. package/build/server/models/config/publish-content-config.d.ts +6 -1
  200. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  201. package/build/server/models/config/static-publish-project.d.ts +23 -0
  202. package/build/server/models/config/static-publish-project.d.ts.map +1 -0
  203. package/build/server/models/config/static-publish-project.js +11 -0
  204. package/build/server/models/config/static-publish-rc.d.ts +25 -0
  205. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  206. package/build/server/models/config/static-publish-rc.js +31 -0
  207. package/build/server/models/server/index.d.ts.map +1 -1
  208. package/build/server/models/server/index.js +6 -2
  209. package/build/server/server/collection-selection/index.d.ts +11 -0
  210. package/build/server/server/collection-selection/index.d.ts.map +1 -0
  211. package/build/server/server/collection-selection/index.js +192 -0
  212. package/build/server/server/collection-selector/from-cookie.d.ts.map +1 -1
  213. package/build/server/server/collection-selector/from-cookie.js +6 -8
  214. package/build/server/server/collection-selector/from-request.d.ts.map +1 -1
  215. package/build/server/server/index.d.ts +4 -1
  216. package/build/server/server/index.d.ts.map +1 -1
  217. package/build/server/server/index.js +3 -1
  218. package/build/server/server/publisher-server/accept-html.d.ts +2 -0
  219. package/build/server/server/publisher-server/accept-html.d.ts.map +1 -0
  220. package/build/server/server/publisher-server/accept-html.js +50 -0
  221. package/build/server/server/publisher-server/index.d.ts +59 -6
  222. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  223. package/build/server/server/publisher-server/index.js +370 -131
  224. package/build/server/server/publisher-server/response-cache.d.ts +3 -0
  225. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  226. package/build/server/server/publisher-server/response-cache.js +24 -1
  227. package/build/server/server/storage/kv-store-provider.d.ts.map +1 -1
  228. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  229. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  230. package/build/server/server/util/body-length.d.ts.map +1 -1
  231. package/build/server/server/util/server-timing.d.ts.map +1 -1
  232. package/package.json +23 -4
  233. package/resources/app/fastly.toml.njk +58 -0
  234. package/resources/app/gitignore.njk +9 -0
  235. package/resources/app/publish-content.config.from-project.js.njk +9 -0
  236. package/resources/app/publish-content.config.js.njk +35 -0
  237. package/resources/app/static-publish.project.js.njk +83 -0
  238. package/resources/app/static-publish.rc.js.njk +43 -0
  239. package/resources/template-init/hono/_example.ts +22 -0
  240. package/resources/template-init/hono/tsconfig.json +17 -0
  241. package/resources/templates/hono/package-lock.json +4123 -0
  242. package/resources/templates/hono/package.json +15 -0
  243. package/resources/templates/hono/scripts/template_postinstall.js +10 -0
  244. package/resources/templates/hono/scripts/template_prebuild.js +8 -0
  245. package/resources/templates/hono/scripts/template_watch.js +15 -0
  246. package/resources/templates/hono/src/hono-extensions.generated.d.ts +5 -0
  247. package/resources/templates/hono/src/index.ts +53 -0
  248. package/resources/templates/hono/tsconfig.json +17 -0
  249. package/resources/templates/plain/package-lock.json +4088 -0
  250. package/resources/templates/plain/package.json +10 -0
  251. package/resources/templates/plain/src/index.js +34 -0
@@ -0,0 +1,1984 @@
1
+ # Static Publisher for JavaScript on Fastly Compute
2
+
3
+ > NOTE: `@fastly/compute-js-static-publish` is provided as a Fastly Labs product. Visit the [Fastly Labs](https://www.fastlylabs.com/) site for terms of use.
4
+
5
+ > [!NOTE]
6
+ > v8 adds Beta support for S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage). For more details, see the [S3-compatible storage](#-using-s3-compatible-storage-beta) section.
7
+
8
+ > [!NOTE]
9
+ > These docs are for v7 or newer, a major rewrite that adds powerful new features such as named collections.
10
+ > If you're looking for v6, please check out the [v6 branch](https://github.com/fastly/compute-js-static-publish/tree/v6).
11
+
12
+ > [!WARNING]
13
+ > v7 and newer no longer support module assets. If you require this feature, consider using [v6](https://github.com/fastly/compute-js-static-publish/tree/v6).
14
+
15
+ ## 📖 Table of Contents
16
+
17
+ - [✨ Key Features](#-key-features)
18
+ - [🏁 Quick Start](#-quick-start)
19
+ - [📦 Fastly KV Store](#-using-the-fastly-kv-store)
20
+ - [🎁 S3 Compatible Storage](#-using-s3-compatible-storage-beta) (Beta)
21
+ - [⚙️ Configuring `static-publish.rc.js`](#️-configuring-static-publishrcjs)
22
+ - [🧾 Config for Publishing and Server: `publish-content.config.js`](#-config-for-publishing-and-server-publish-contentconfigjs)
23
+ - [📦 Collections (Publish, Preview, Promote)](#-collections-publish-preview-promote)
24
+ - [🧹 Cleaning Up](#-cleaning-up)
25
+ - [🔄 Content Compression](#-content-compression)
26
+ - [🧩 Using PublisherServer in Custom Apps](#-using-publisherserver-in-custom-apps)
27
+ - [🔥 Using Hono](#-using-hono)
28
+ - [📥 Using Published Assets in Your Code](#-using-published-assets-in-your-code)
29
+ - [📚 CLI Reference](#-cli-reference)
30
+ - [📕 Appendix](#-appendix)
31
+ - [📚 Next Steps](#-next-steps)
32
+
33
+ Serve static websites and web apps at the edge — no backends and no CDN invalidation delays.
34
+
35
+ `@fastly/compute-js-static-publish` helps you deploy and serve static files using [Fastly Compute](https://developer.fastly.com/learning/compute/) for fast, cacheable, and content-addressed delivery. The library can be configured to store your data in either of the following:
36
+ * Fastly [Key Value Store](https://www.fastly.com/products/kv-store)
37
+ * S3-compatible storage, such as Fastly [Object Storage](https://www.fastly.com/products/storage) (Beta)
38
+
39
+ ## ✨ Key Features
40
+
41
+ - 📦 Easy to scaffold and deploy
42
+ - 🚀 Content stored using hashed keys, in Fastly KV Store or S3-compatible storage (Beta) including Fastly Object Storage
43
+ - 🔁 Publish new content without needing to deploy new Wasm binaries
44
+ - 🗂 Organize releases into named collections which can be previewed (e.g. `live`, `staging`, `preview-123`)
45
+ - 🧼 Cleanup tools to remove expired or orphaned files
46
+ - ⚙️ Configurable per-collection server configurations (e.g. fallback files)
47
+ - 🔒 Supports Brotli/gzip compression, conditional GET, and long cache TTLs
48
+
49
+ ---
50
+
51
+ ## 🏁 Quick Start
52
+
53
+ ### 📦 Using the Fastly KV Store
54
+
55
+ #### 1. Scaffold a Compute App
56
+
57
+ Create a directory for your project, place your static files in `./public`, then type:
58
+
59
+ ```sh
60
+ npx @fastly/compute-js-static-publish@beta \
61
+ --root-dir=./public \
62
+ --kv-store-name=site-content
63
+ ```
64
+
65
+ You get a Compute app in `./compute-js` with:
66
+
67
+ - `fastly.toml` (service config)
68
+ - `src/index.js` (entry point)
69
+ - `static-publish.rc.js` (app config)
70
+ - `publish-content.config.js` (publish-time / runtime behavior)
71
+
72
+ Once the application is scaffolded, install dependencies:
73
+
74
+ ```sh
75
+ cd compute-js
76
+ npm install
77
+ ```
78
+
79
+ #### 2. Preview Locally
80
+
81
+ Type the following — no Fastly account or service required yet!
82
+
83
+ ```sh
84
+ npm run dev:publish
85
+ npm run dev:start
86
+ ```
87
+
88
+ Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`, powered by a simulated KV Store.
89
+
90
+ #### 3. Deploy Your App
91
+
92
+ Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
93
+
94
+ ```sh
95
+ npm run fastly:deploy
96
+ ```
97
+
98
+ The command publishes your Compute app and creates the KV Store. (No content uploaded yet!)
99
+
100
+ #### 4. Publish Content
101
+
102
+ ```sh
103
+ npm run fastly:publish
104
+ ```
105
+
106
+ This command uploads your static files to the KV Store and applies the server config. Your website is now up and live!
107
+
108
+ `fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
109
+
110
+ ```sh
111
+ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
112
+ ```
113
+
114
+ ### 🎁 Using S3 Compatible Storage (Beta)
115
+
116
+ #### 1. Scaffold a Compute App
117
+
118
+ Create a directory for your project, place your static files in `./public`, then type:
119
+
120
+ ```sh
121
+ npx @fastly/compute-js-static-publish@beta \
122
+ --root-dir=./public \
123
+ --storage-mode=s3 \
124
+ --s3-region=<s3 region> \
125
+ --s3-bucket=<bucket name>
126
+ ```
127
+
128
+ > [!NOTE]
129
+ > If the storage requires a custom endpoint, such as is the case with Fastly Object Storage, specify it using `--s3-endpoint=<endpoint>`. For example:
130
+ >
131
+ > ```sh
132
+ > npx @fastly/compute-js-static-publish@beta \
133
+ > --root-dir=./public \
134
+ > --storage-mode=s3 \
135
+ > --s3-region=us-east-1 \
136
+ > --s3-bucket=my-static-content-bucket \
137
+ > --s3-endpoint=https://us-east-1.object.fastlystorage.app
138
+ > ```
139
+ >
140
+ > For the regions of Fastly Object Storage and their endpoints, see [Working with Object Storage](https://www.fastly.com/documentation/guides/platform/object-storage/working-with-object-storage/#managing-object-storage-buckets-and-objects).
141
+
142
+ You get a Compute app in `./compute-js` with:
143
+
144
+ - `fastly.toml` (service config)
145
+ - `src/index.js` (entry point)
146
+ - `static-publish.rc.js` (app config)
147
+ - `publish-content.config.js` (publish-time / runtime behavior)
148
+
149
+ Once the application is scaffolded, install dependencies:
150
+
151
+ ```sh
152
+ cd compute-js
153
+ npm install
154
+ ```
155
+
156
+ #### 2. Publish your content to S3-compatible storage
157
+
158
+ Before publishing your content, your S3-compatible bucket must already exist.
159
+
160
+ > [!TIP]
161
+ > If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
162
+
163
+ Type the following:
164
+
165
+ ```sh
166
+ npm run s3:publish
167
+ ```
168
+
169
+ #### 3. Preview Locally
170
+
171
+ Type the following to preview your site locally:
172
+
173
+ ```sh
174
+ npm run dev:start
175
+ ```
176
+
177
+ Fastly's [local development environment](https://www.fastly.com/documentation/guides/compute/testing/#running-a-local-testing-server) serves your static website at `http://127.0.0.1:7676`. Your content is fetched from S3-compatible storage.
178
+
179
+ #### 4. Deploy Your App
180
+
181
+ Ready to go live? All you need is a [free Fastly account](https://www.fastly.com/signup/?tier=free)!
182
+
183
+ ```sh
184
+ npm run fastly:deploy
185
+ ```
186
+
187
+ The app reads the S3 credentials from the Secret Store that has the resource link name `S3_CREDENTIALS` on your service.
188
+
189
+ When the Fastly CLI creates a new service, it creates a Secret Store named `S3_CREDENTIALS`, links it to the service with the same name, and prompts you for the values `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`.
190
+
191
+ ---
192
+
193
+ ## 🗂 Project Layout
194
+
195
+ Here's what your project might look like after scaffolding:
196
+
197
+ ```
198
+ my-project/
199
+ ├── public/ # Your static site files (HTML, CSS, JS, etc.)
200
+ │ ├── index.html
201
+ │ ├── scripts.js
202
+ │ ├── styles.css
203
+ │ └── (... other static files ...)
204
+ └── compute-js/ # The scaffolded Compute application
205
+ ├── fastly.toml # Fastly service configuration
206
+ ├── package.json # Scaffolded package metadata
207
+ ├── package-lock.json # Dependency lockfile
208
+ ├── .gitignore # Ignores build artifacts by default
209
+ ├── static-publish.rc.js # App config
210
+ ├── publish-content.config.js # Publishing / runtime config
211
+ ├── static-publisher/ # ⚠️ Do not commit - generated content for local dev and publishing
212
+ │ ├── kvstore.json # Simulates KV Store content for local preview
213
+ │ └── kv-store-content/ # Preprocessed and compressed files for KV upload
214
+ ├── scripts/ # Optional: template hooks (template_<hook>.js, template_watch.js)
215
+ └── src/
216
+ └── index.js # Your Compute app entry point
217
+ ```
218
+
219
+ ### Managed and ejected apps
220
+
221
+ From 8.1.0, a project can be **managed** or **ejected**:
222
+
223
+ | | Managed | Ejected |
224
+ |---|---|---|
225
+ | In the repo | One file, `static-publish.project.js`, in the project dir | The app dir (`compute-js/`) with `static-publish.rc.js` and `publish-content.config.js`, as above |
226
+ | Who owns the app code | This package: it generates the app | You |
227
+ | Upgrade this package | Run `upgrade`; the next `deploy` deploys the new app | Change the files by hand (see `MIGRATING.md`) |
228
+ | Deploy | `deploy`, only when the generated app changed | `npm run fastly:deploy` (or `deploy`) |
229
+ | Customize | The options of the project file | Anything |
230
+
231
+ An **ejected app** is in the repo, and you own its code. Every app that `scaffold` makes without `--managed`, and every app made before 8.1.0, is an ejected app. A **managed project** has only a project file in the repo, and this package generates the app when it needs it.
232
+
233
+ `scaffold` makes an ejected app, as before. `scaffold --managed` makes a managed project. `eject` converts a managed project into an ejected app. To move an existing app to managed mode, see `MIGRATING.md`.
234
+
235
+ #### Managed projects
236
+
237
+ `scaffold --managed` writes only one file, `static-publish.project.js`, in the current directory (the project dir), and adds `.static-publish/` and the working directory to the `.gitignore` there:
238
+
239
+ ```
240
+ my-site/
241
+ ├── static-publish.project.js # Commit this: the only config file
242
+ ├── public/ # Your static site files
243
+ ├── .gitignore # Ignores .static-publish/ and static-publisher/
244
+ └── static-publisher/ # ⚠️ Do not commit - the working directory
245
+ ```
246
+
247
+ The project file has the settings that an ejected app has in its two files:
248
+
249
+ - The top level has the fields of `static-publish.rc.js` (`storageMode`, `kvStore` or `s3`, `publishId`, `defaultCollectionName`, `staticPublisherWorkingDir`, `collectionSelection`), and the settings of the template (`build` and `templateOptions`, see [Hono extensions](#hono-extensions)).
250
+ - `publishContent` has the fields of `publish-content.config.js`. `publish-content --config <file>` replaces it for one run.
251
+ - `managed` has the settings of the generated app (`name`, `description`, `authors`, `serviceId`, `staticPublishVersion`, the version of this package that the project uses, and `fastlyToml`, see below).
252
+
253
+ Paths in the project file are relative to it. The name of the file marks the mode: a directory with `static-publish.project.js` is a managed project, and a directory with `static-publish.rc.js` is an ejected app. A directory with both is an error.
254
+
255
+ `publish-content`, `collections`, and `clean` run in the project dir (or with `--project-dir`), and read the project file. `publish-content` purges the service of `managed.serviceId`, after `--fastly-service-id` and `FASTLY_SERVICE_ID`.
256
+
257
+ To run the app on your computer:
258
+
259
+ ```sh
260
+ npx @fastly/compute-js-static-publish publish-content --local
261
+ npx @fastly/compute-js-static-publish dev
262
+ ```
263
+
264
+ `dev` generates the app in `.static-publish/app/`, installs its dependencies with `npm ci` if they changed, and runs `fastly compute serve` in it. Options after `--` go to `fastly compute serve`, for example `dev -- --addr=127.0.0.1:8080`. With `dev -- --watch`, a change in the app builds and restarts it, and the watch script of the template (`scripts/template_watch.js`, see [Template hooks](#-template-hooks)), if it has one, runs next to `fastly compute serve`. The app serves the content of the local KV Store, `kvstore.json` in the working directory.
265
+
266
+ **Local resources and setup in `fastly.toml`.** The CLI generates the `fastly.toml` of the app. To add resources for `fastly compute serve` (`[local_server]`) or for the first deploy, which makes the service (`[setup]`), add them to `managed.fastlyToml`, in the structure of [`fastly.toml`](https://www.fastly.com/documentation/reference/compute/fastly-toml/). For example, a local Secret Store and a local Config Store:
267
+
268
+ ```js
269
+ managed: {
270
+ // ...
271
+ fastlyToml: {
272
+ local_server: {
273
+ secret_stores: { oauth: [ { key: 'GITHUB_CLIENT_SECRET', env: 'GITHUB_CLIENT_SECRET' } ] },
274
+ config_stores: { site_config: { format: 'inline-toml', contents: { greeting: 'hello' } } },
275
+ },
276
+ setup: {
277
+ secret_stores: { oauth: { entries: { GITHUB_CLIENT_SECRET: { description: 'The client secret' } } } },
278
+ },
279
+ },
280
+ },
281
+ ```
282
+
283
+ - Only `local_server` and `setup` can be added. The CLI writes the other parts of `fastly.toml`.
284
+ - The CLI also writes some resources: the KV Store of the content, and in S3 mode, the `S3_CREDENTIALS` Secret Store and the `s3_storage` backend. A resource with one of these names is an error.
285
+ - Do not put a secret in the project file: in `local_server`, read it from an environment variable (`env`) or a file (`file`) that is not committed.
286
+ - `local_server` does not change the fingerprint, because it is only for `fastly compute serve`. `setup` changes it.
287
+ - `eject` writes the sections into the `fastly.toml` of the ejected app.
288
+
289
+ `managed.template` selects the template of the app: `plain` (the default) or `hono`. To switch, change it. The next `dev` or `deploy` generates the app again with the new template, and `npm ci` installs its dependencies. The fingerprint changes, so `deploy` deploys again. Files of the old template can stay in `.static-publish/app/`. They do not change the build. To remove them, delete `.static-publish/`: the next `dev` or `deploy` generates it again.
290
+
291
+ The same version of this package always generates the same app, with the same versions of all dependencies: this package has a lockfile for the app of each template. The app uses the copy of this package that runs the CLI, through a `file:` link. Thus, add this package as a dev dependency of your project, and run the CLI from it, so that the version is pinned:
292
+
293
+ ```sh
294
+ npm install --save-dev @fastly/compute-js-static-publish
295
+ ```
296
+
297
+ To deploy the app:
298
+
299
+ ```sh
300
+ npx @fastly/compute-js-static-publish deploy
301
+ ```
302
+
303
+ `deploy` generates the app, installs it if necessary, and runs `fastly compute build` and `fastly compute deploy`, only if the app changed. It needs a Fastly API token (`FASTLY_API_TOKEN` or `--fastly-api-token`).
304
+
305
+ - **The fingerprint** is a SHA-256 of the generated app and the version of this package. It does not depend on the content, on `publishContent`, on the Service ID, or on the path of this package on your computer. `deploy` writes it into the comment of the new service version (`static-publish <version> fp:<fingerprint>`, then ` | <text>` with `--comment <text>`, for example a commit SHA). The next `deploy` reads the comment of the active version, and does nothing if the fingerprint is the same. `--force` deploys anyway.
306
+ - **The first deploy** makes a new service (the Fastly CLI asks for its name and domain, unless `--non-interactive`), and writes its ID into `managed.serviceId`. Commit the project file then. To deploy to a service that exists, use `--fastly-service-id` or `FASTLY_SERVICE_ID`. With S3 storage, the first deploy must be done on your computer, because the Fastly CLI asks for the S3 credentials of the Secret Store; with `--non-interactive`, it is an error.
307
+ - `status` shows the fingerprint of the app, the fingerprint of the active version, and if a deploy is necessary, and the preview URLs of [collection selection](#-previews-collection-selection). Without an API token, the deployed fingerprint is unknown.
308
+
309
+ **The version of this package.** `managed.staticPublishVersion` records the version of this package that the project uses. `dev` and `deploy` compare it with the version that runs:
310
+
311
+ | The CLI that runs | Result |
312
+ |---|---|
313
+ | The same version | Continue. |
314
+ | A newer version | Stop. Run `upgrade` to move the project to the new version (and commit the project file), or use `--auto-upgrade`. |
315
+ | An older version | Stop. An older version never deploys over an app that a newer version made. |
316
+
317
+ Thus a new release of this package never changes your app by itself, also with `npx @fastly/compute-js-static-publish@latest`.
318
+
319
+ **Eject.** `eject` converts a managed project into an ejected app that you own:
320
+
321
+ - It writes the app that `deploy` would deploy into `./compute-js` (or `--dir`). It refuses a directory that exists, unless `--force`.
322
+ - It splits the project file into `compute-js/static-publish.rc.js` (with `generatedFrom`) and `compute-js/publish-content.config.js`, and writes the paths again, so that they point at the same directories (for example `staticPublisherWorkingDir: '../static-publisher'`). Then it deletes `static-publish.project.js`.
323
+ - `publishContent` must be data: eject cannot copy functions or regular expressions (for example `assetInclusionTest`). If it has them, eject stops before it writes anything. Remove them, eject, and add them to `compute-js/publish-content.config.js` by hand.
324
+ - `package.json` gets `"@fastly/compute-js-static-publish": "^<version>"`, and the lockfile has exactly `<version>`, so that the first ejected build is the same app. This needs a version that is published on npm, and one `npm install` (network access).
325
+ - After eject, run the commands in `compute-js/`. Run `publish-content --local` again before `npm run dev:start`. You can delete `.static-publish/`.
326
+
327
+ **API token scopes.** Give CI the least access that it needs. As far as we know (check the [Fastly documentation of API tokens](https://www.fastly.com/documentation/reference/api/auth-tokens/)):
328
+
329
+ | Command | Scope |
330
+ |---|---|
331
+ | `status` (the active version of the service) | `global:read` |
332
+ | `publish-content` and `collections` with the KV Store (writes) | `global` |
333
+ | The purge after `publish-content` (S3 storage) | `purge_select` |
334
+ | `deploy` | `global` |
335
+
336
+ Limit the token to the service of the project, where possible.
337
+
338
+
339
+ ### 🪝 Template hooks
340
+
341
+ The `package.json` of a scaffolded app has these scripts:
342
+
343
+ ```json
344
+ "prebuild": "compute-js-static-publish run-template-hook prebuild",
345
+ "build": "js-compute-runtime ./src/index.js ./bin/main.wasm",
346
+ "postbuild": "compute-js-static-publish run-template-hook postbuild",
347
+ "postinstall": "compute-js-static-publish run-template-hook postinstall"
348
+ ```
349
+
350
+ `run-template-hook <name>` runs `scripts/template_<name>.js` if that file exists, and otherwise does nothing. Thus, to run your own code before or after each build, or after each `npm install`, add one of these files:
351
+
352
+ - `scripts/template_prebuild.js`
353
+ - `scripts/template_postbuild.js`
354
+ - `scripts/template_postinstall.js`
355
+
356
+ The file runs with Node.js, in the directory of the app. If it fails, the build or the install fails. `fastly compute build`, `fastly compute serve`, and `fastly compute publish` run `npm run build`, so they also run the build hooks. `npm install --ignore-scripts` does not run the hooks.
357
+
358
+ The app also has a `dev:watch` script:
359
+
360
+ ```json
361
+ "dev:watch": "compute-js-static-publish run-dev-watch"
362
+ ```
363
+
364
+ `npm run dev:watch` runs `fastly compute serve --watch`, which builds and restarts the app when a file in the app directory changes. Options after `--` go to `fastly compute serve`, for example `npm run dev:watch -- --addr=127.0.0.1:8080`. If the app has `scripts/template_watch.js`, that file runs with Node.js next to the Fastly CLI, until the Fastly CLI stops. Use it to watch files outside the app directory: when they change, write a file in the app directory, and the Fastly CLI builds the app again.
365
+
366
+ ## ⚙️ Configuring `static-publish.rc.js`
367
+
368
+ This file defines your compute-js-static-publish application's settings. A copy of this is also baked into the Wasm binary and loaded when running your Compute app locally or on the edge.
369
+
370
+ > [!NOTE]
371
+ > Making changes to this file requires rebuilding the Compute app, since a copy of it is baked into the Wasm binary.
372
+
373
+ ### Using the Fastly KV Store
374
+
375
+ #### Fields:
376
+
377
+ All fields are required unless specified otherwise.
378
+
379
+ - `storageMode` - Specifies the storage mode. Set to `'kv-store'`.
380
+ - `kvStore.kvStoreName` - The name of the KV Store used for publishing.
381
+ - `defaultCollectionName` - Collection to serve when none is specified.
382
+ - `publishId` - Unique prefix for all keys in the KV Store. Override only for advanced setups (e.g., multiple apps sharing the same KV Store).
383
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish. The path is relative to the directory of `static-publish.rc.js`.
384
+ - `generatedFrom` - (optional) A record of how the app was made: the template, the version of this package, and the date. The scaffolder writes it. The app does not use it.
385
+
386
+ #### Example: `static-publish.rc.js`
387
+
388
+ ```js
389
+ const rc = {
390
+ storageMode: 'kv-store',
391
+ kvStore: {
392
+ kvStoreName: 'site-content',
393
+ },
394
+ defaultCollectionName: 'live',
395
+ publishId: 'default',
396
+ staticPublisherWorkingDir: './static-publisher',
397
+ };
398
+
399
+ export default rc;
400
+ ```
401
+
402
+ ### Using S3-compatible storage (BETA)
403
+
404
+ #### Fields:
405
+
406
+ All fields are required unless specified otherwise.
407
+
408
+ - `storageMode` - Specifies the storage mode. Set to `'s3'`.
409
+ - `s3.region` - The region of the S3-compatible bucket.
410
+ - `s3.bucket` - The name of the S3-compatible bucket.
411
+ - `s3.endpoint` - (optional) The custom endpoint for the S3-compatible bucket.
412
+ - `defaultCollectionName` - Collection to serve when none is specified.
413
+ - `publishId` - Unique prefix for all keys in the bucket. Override only for advanced setups (e.g., multiple apps sharing the same bucket).
414
+ - `staticPublisherWorkingDir` - Directory to hold working files during publish. The path is relative to the directory of `static-publish.rc.js`.
415
+ - `generatedFrom` - (optional) A record of how the app was made: the template, the version of this package, and the date. The scaffolder writes it. The app does not use it.
416
+
417
+ #### Example: `static-publish.rc.js`
418
+
419
+ ```js
420
+ const rc = {
421
+ storageMode: 's3',
422
+ s3: {
423
+ region: 'us-east-1',
424
+ bucket: 'my-site-content',
425
+ },
426
+ defaultCollectionName: 'live',
427
+ publishId: 'default',
428
+ staticPublisherWorkingDir: './static-publisher',
429
+ };
430
+
431
+ export default rc;
432
+ ```
433
+
434
+ ## 🧾 Config for Publishing and Server: `publish-content.config.js`
435
+
436
+ This file is included as part of the scaffolding. Every time you publish content, the publish settings in this file are used for publishing the content, and the server settings are taken from this file and saved as the settings used by the server for that collection.
437
+
438
+ ```js
439
+ const config = {
440
+ // these paths are relative to compute-js dir
441
+ rootDir: '../public',
442
+
443
+ // Include/exclude filters (optional):
444
+ excludeDirs: ['node_modules'],
445
+ excludeDotFiles: true,
446
+ includeWellKnown: true,
447
+
448
+ // Advanced filtering (optional):
449
+ assetInclusionTest: (key, contentType) => {
450
+ return true; // include everything by default
451
+ },
452
+
453
+ // Files to publish as hidden files (optional):
454
+ hiddenItems: ['/404.html', '/templates/'],
455
+
456
+ // Override which compressed variants to create for each asset during publish (optional):
457
+ contentCompression: ['br', 'gzip'],
458
+
459
+ // Brotli quality, 0 to 11 (optional, default 11):
460
+ brotliQuality: 11,
461
+
462
+ // Content type definitions/overrides (optional):
463
+ contentTypes: [
464
+ { test: /\.custom$/, contentType: 'application/x-custom', text: false },
465
+ ],
466
+
467
+ // Server settings
468
+ server: {
469
+ spaFile: '/spa.html',
470
+ notFoundPageFile: '/404.html',
471
+ autoIndex: ['index.html'],
472
+ autoExt: ['.html'],
473
+ staticItems: ['/static/', '/assets/'],
474
+ allowedEncodings: ['br', 'gzip'],
475
+ }
476
+ };
477
+
478
+ export default config;
479
+ ```
480
+
481
+ You can override this file for a single `publish-content` command by specifying an alternative using `--config` on the command line.
482
+
483
+ ### Fields:
484
+
485
+ - `rootDir` - Directory to scan for content, relative to this file (required).
486
+ - `excludeDirs` - Array of directory names or regex patterns to exclude (default: `['./node_modules']`).
487
+ - `excludeDotFiles` - Exclude dotfiles and dot-named directories (default: true).
488
+ - `includeWellKnown` - Always include `.well-known` even if dotfiles are excluded (default: true).
489
+ - `assetInclusionTest` - Function to determine inclusion and variant behavior per file. Return `false` to leave the file out, `true` to include it, or `{ hidden: true }` to include it as a [hidden file](#hidden-files).
490
+ - `hiddenItems` - The files to publish as [hidden files](#hidden-files). The same format as `server.staticItems`, tested against the asset key (the path relative to `rootDir`): a directory that ends with `/`, an exact path, a glob pattern, or `'re:/<regex>/<flags>'` (default: none).
491
+ - `contentCompression` - Array of compression formats to pre-generate (`['br', 'gzip']` by default).
492
+ - `brotliQuality` - Brotli quality for the `br` variants, an integer from 0 to 11 (default: 11). Quality 11 gives the smallest files but is the slowest. Quality 10 is approximately 3 times faster, and its files are approximately 2% larger. If you change this value, variants that are already in storage are not compressed again.
493
+ - `contentTypes` - Additional or override content type definitions.
494
+
495
+ - `server` - Server runtime config that contains the following fields:
496
+ - `publicDirPrefix` - **Deprecated.** A future version will remove it.
497
+ A prefix that the Publisher Server adds to the path of each
498
+ request, to get the asset key. Use it if the files to serve are in a subdirectory
499
+ of `rootDir`. For example, if `rootDir` is `'../site'` and the files to serve are in
500
+ `'../site/public'`, set it to `'/public'`. The value starts with `/` and does not
501
+ end with `/` (default: `''`). The scaffolder sets it from `--root-dir` and `--public-dir`.
502
+ - `spaFile` - Path to a file to be used to serve in a SPA application.
503
+ - `notFoundPageFile` - Path to a file to be used to serve as a 404 not found page.
504
+ The server serves `spaFile` or `notFoundPageFile` only to a request that accepts HTML: its `Accept`
505
+ header is missing or empty, or has `text/html`, `text/*`, or `*/*` with a q-value that is not 0.
506
+ For other requests, `serveRequest()` returns `null`.
507
+ - `autoIndex` - List of files to automatically use as index.
508
+ - `autoExt` - List of extensions to automatically apply to a path and retry when
509
+ the requested path is not found.
510
+ - `staticItems` - Directories to specify as containing 'static' files. The
511
+ Publisher Server will serve files from these directories with a long TTL.
512
+ - `allowedEncodings` - Specifies which compression formats the server is allowed
513
+ to serve based on the client's `Accept-Encoding` header.
514
+
515
+ ### Hidden files
516
+
517
+ A hidden file is published, but the Publisher Server does not serve it for a request, also not through `autoExt` or `autoIndex`. Use hidden files for:
518
+
519
+ - The 404 page: a request for `/404.html` must not get the 404 page with status `200`. If the `spaFile` or the `notFoundPageFile` is hidden, the server still serves it as the fallback page.
520
+ - Files that your code reads, for example templates. Get them with `getMatchingAsset(key, { includeHidden: true })` (see [Using Published Assets in Your Code](#-using-published-assets-in-your-code)).
521
+
522
+ A file is hidden if `hiddenItems` selects it, or if `assetInclusionTest` returns `{ hidden: true }` for it:
523
+
524
+ ```js
525
+ const config = {
526
+ rootDir: '../public',
527
+ hiddenItems: ['/404.html', '/templates/'],
528
+ assetInclusionTest: (key) => key.endsWith('.tpl') ? { hidden: true } : true,
529
+ server: {
530
+ notFoundPageFile: '/404.html',
531
+ },
532
+ };
533
+ ```
534
+
535
+ `publish-content` and `collections list` show the number of hidden files.
536
+
537
+ > [!WARNING]
538
+ > **Hidden is not access control.** Hidden files are in storage (the KV Store or the bucket), the same as the other files, and code that asks for hidden files can serve them. Do not use hidden files for secrets.
539
+
540
+ A collection that has hidden files requires the `hidden` feature. An app that is built with a version earlier than 8.1.0 does not serve such a collection (8.0), or does not find its hidden files (earlier versions). Build and deploy your app with 8.1.0 or later before you publish hidden files.
541
+
542
+ ## 📦 Collections (Publish, Preview, Promote)
543
+
544
+ Collections are a powerful feature that allow you to publish and manage multiple versions of your site simultaneously. Each collection is a named set of:
545
+
546
+ - Static files
547
+ - Server configuration (e.g., fallback file, static directories, etc.)
548
+ - An index file that maps paths to those hashes
549
+
550
+ Collections are published using a `--collection-name`, and can be reused, updated, or deleted independently. For example, you can create a staging version of your site using:
551
+
552
+ ```sh
553
+ npx @fastly/compute-js-static-publish publish-content \
554
+ --collection-name=staging \
555
+ --expires-in=7d \
556
+ --config=./publish-content.config.js
557
+ ```
558
+
559
+ You can overwrite or republish any collection at any time. Old file hashes will be reused automatically where contents match.
560
+
561
+ A collection name must be a DNS label: lowercase `a-z`, `0-9`, and `-`, from 1 to 63 characters, with no `-` at the start or the end (for example `live`, `staging`, `pr-42`). Thus a name is safe in storage keys, in cookies, and in hostnames. If a CI tool makes collection names from branch names, it must convert them to this form (for example `feature/Foo_bar` to `feature-foo-bar`). A collection that was published before this rule continues to work, with a warning, but new collections must follow it.
562
+
563
+ ### Expiration (Auto-cleanup)
564
+
565
+ Collections can expire automatically:
566
+
567
+ - Expired collections are ignored by the server and return 404s
568
+ - A request for a collection other than the default collection that is expired or not published gets a plain-text 404 that names the collection. The response cache does not store it, so the collection is served as soon as you publish it. If the default collection is not published, the server returns a 500.
569
+ - The default collection never expires
570
+ - Expiration limits can be modified (shortened, extended, reenstated) using `collections update-expiration`
571
+ - They are cleaned up by `clean --delete-expired-collections`
572
+
573
+ ```sh
574
+ --expires-in=3d # relative (e.g. 1h, 2d, 1w)
575
+ --expires-at=2025-05-01T12:00Z # absolute (ISO 8601)
576
+ --expires-never # the collection never expires
577
+ ```
578
+
579
+ *(Only one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified)*
580
+
581
+ ### Switching the active collection
582
+
583
+ By default, the server app serves assets from the "default collection", named in `static-publish.rc.js` under `defaultCollectionName`. To switch the active collection, you add custom code to your Compute app that calls `publisherServer.setActiveCollectionName(name)`:
584
+
585
+ ```js
586
+ publisherServer.setActiveCollectionName("preview-42");
587
+ ```
588
+
589
+ Pass `null` to select the default collection.
590
+
591
+ If the app turns on sandbox reuse, Compute can use a sandbox for more than one request (see [Sandbox lifecycle](https://www.fastly.com/documentation/guides/compute/developer-guides/sandbox-lifecycle/)), and the active collection stays set until you change it. Thus, call `setActiveCollectionName()` for each request, also when the request does not select a collection.
592
+
593
+ #### Example: Subdomain-based Routing
594
+
595
+ In the following example, assume that the Compute application is hosted using a wildcard domain `*.example.com`. A request for `preview-pr-123.example.com` would activate the collection `'pr-123'`.
596
+
597
+ ```js
598
+ import { PublisherServer, collectionSelector } from '@fastly/compute-js-static-publish';
599
+ import rc from '../static-publish.rc.js';
600
+
601
+ const publisherServer = PublisherServer.fromStaticPublishRc(rc);
602
+
603
+ addEventListener("fetch", event => {
604
+ const request = event.request;
605
+ const collectionName = collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
606
+ publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
607
+
608
+ event.respondWith(publisherServer.serveRequest(request));
609
+ });
610
+ ```
611
+
612
+ ### 👀 Previews: Collection Selection
613
+
614
+ `collectionSelection` in `static-publish.rc.js` chooses the collection that serves each request, for example to show a preview of a pull request. It is off by default: without it, every request gets the default collection.
615
+
616
+ ```js
617
+ const rc = {
618
+ // ...
619
+ collectionSelection: {
620
+ // Tried in order. The first source that gives a collection wins.
621
+ // If no source gives a collection, the default collection is used.
622
+ sources: [
623
+ { type: 'host', pattern: '{collection}.preview.example.com' },
624
+ { type: 'path', prefix: '/_preview/{collection}', sticky: 'cookie' },
625
+ { type: 'query', param: 'collection', sticky: 'cookie' },
626
+ { type: 'cookie', cookieName: 'publisher-collection',
627
+ activatePath: '/activate', resetPath: '/reset', maxAge: 604800 },
628
+ { type: 'header', name: 'x-publisher-collection' },
629
+ ],
630
+ // The collections that can be selected ('*' matches any characters). Default: any.
631
+ allow: ['pr-*', 'staging'],
632
+ // The selected collection does not exist or has expired:
633
+ // 'not-found' (default) gives a 404 response, 'default' serves the default collection.
634
+ onMissing: 'not-found',
635
+ // X-Robots-Tag: noindex on the responses of a selected collection. Default: true.
636
+ noindex: true,
637
+ },
638
+ };
639
+ ```
640
+
641
+ | Source | Reads | Notes |
642
+ |--------|-------|-------|
643
+ | `host` | The hostname, matched against `pattern` | Needs a wildcard domain and TLS for it. The pattern has one `{collection}` in one label, with fixed text around it if you want (`branch-{collection}.preview.example.com`). A host label has at most 63 characters. Make sure that your production hostname does not match the pattern. |
644
+ | `path` | A path prefix, which is removed before the file lookup | Works on `*.edgecompute.app`. Links that start with `/` lose the prefix, so use it with `sticky: 'cookie'`, or for a site with relative links. The links in HTML do not change. |
645
+ | `query` | A query parameter | Only the request that has it. Usually used with `sticky: 'cookie'`. |
646
+ | `cookie` | A cookie | Also serves the activate path (`/activate?collection=<name>&redirectTo=<path>`) and the reset path. |
647
+ | `header` | A request header | For tests, CI checks, and API clients. |
648
+
649
+ - `sticky: 'cookie'` on a `path` or `query` source: when the source matches, set the cookie of the `cookie` source, and redirect (`308`) to the URL without the prefix or the parameter. It needs a `cookie` source.
650
+ - A name must follow the [collection name rule](#-collections-publish-preview-promote) and match `allow`. Otherwise the source is skipped.
651
+ - Redirects go only to a path on the same site. `redirectTo` with another site redirects to `/`.
652
+ - The responses of a selected collection (not the default collection) get `X-Robots-Tag: noindex` (unless `noindex` is `false`). They get `Cache-Control: private` if the URL does not name the collection. See [Shared caches](#shared-caches).
653
+ - To find out if a selected collection exists, `PublisherServer` reads its index, also when the [response cache](#️-caching-responses-with-the-core-cache) has the response.
654
+
655
+ The `plain` app does this in `src/index.js`. Apps scaffolded before 8.1.0 do not. To add it to such an app, change `src/index.js`:
656
+
657
+ ```js
658
+ const selection = publisherServer.resolveCollection(request);
659
+ if (selection.response != null) {
660
+ return selection.response; // a redirect (sticky, activate, reset), or an error
661
+ }
662
+ const response = await publisherServer.serveRequest(request, {
663
+ collectionName: selection.collectionName, // null: the default collection
664
+ pathname: selection.pathname, // the path without the prefix of a path source
665
+ });
666
+ ```
667
+
668
+ To scaffold an app with collection selection, use the [`--collection-selection` flags](#options). To show a link to a collection, for example in CI, use `previewUrl()`. It uses the first source that can make a URL:
669
+
670
+ ```js
671
+ import { previewUrl } from '@fastly/compute-js-static-publish';
672
+ import rc from './static-publish.rc.js';
673
+
674
+ previewUrl('pr-42', 'https://example.edgecompute.app', rc.collectionSelection);
675
+ // with the sources above: 'https://pr-42.preview.example.com/'
676
+ ```
677
+
678
+ > [!WARNING]
679
+ > A preview is public to anyone who knows its name. Use `allow` to limit the collections that can be selected, and do not publish content that must stay private.
680
+
681
+ #### Shared caches
682
+
683
+ A shared cache, for example a CDN in front of your service, can store a response and give it to other visitors. The [response cache](#️-caching-responses-with-the-core-cache) of `PublisherServer` keeps the responses of each collection apart, so this section is only about shared caches. For a shared cache, the response of a collection that is not the default collection depends on how the request selects the collection:
684
+
685
+ | Source | Does the URL name the collection? | `Cache-Control` |
686
+ |--------|-----------------------------------|-----------------|
687
+ | `host`, `path`, `query` | Yes | As for the default collection. A shared cache can store the response. |
688
+ | `cookie`, `header` | No: the same URL can serve another collection | `private`. A shared cache does not store the response. |
689
+ | `path` or `query` with `sticky: 'cookie'` | No: after the redirect, the cookie selects the collection | `private` |
690
+
691
+ A response gets `private` also when your code gives `serveRequest()` a `collectionName` that the sources of the request do not select. For a `query` source, the shared cache must keep the query string in its cache key.
692
+
693
+ **Previews with a cookie or a header:** the default collection and the preview have the same URLs. A shared cache can store a response of the default collection, and give it to a visitor who has the preview cookie. That visitor then sees the default collection in place of the preview. If a shared cache is in front of your service, select previews with a `host` or `path` source.
694
+
695
+ **More than one site in one service:** you can serve one site from each collection. Select the collection with a `host` source, for example `{collection}.example.com`, so that a shared cache can store the responses of each site. Also set `noindex: false`, because otherwise each site that is not the default collection gets `X-Robots-Tag: noindex`. A collection that expires stops being served, so do not set an expiration time for these collections.
696
+
697
+ **Without `collectionSelection`:** if your code chooses the collection, for example with `collectionSelector.fromCookie()` and `setActiveCollectionName()`, or with the `collectionName` option, `PublisherServer` does not add `Cache-Control: private` or `X-Robots-Tag: noindex`. Your code must add them when the URL does not name the collection. Otherwise a shared cache can store a preview and give it to other visitors.
698
+
699
+ `serveRequest()` returns a normal `Response`. To use a different cache policy, change its headers in your code before you return it.
700
+
701
+ #### A preview for each pull request
702
+
703
+ A CI job can publish each pull request to its own collection, and remove it when the pull request closes. `--expires-in` stops serving a preview after that time, also if the second job does not run. But its index stays in storage until `clean --delete-expired-collections`, and its files stay until `clean`.
704
+
705
+ This GitHub Actions workflow publishes the collection `pr-<number>`, and, when the pull request closes, deletes the collection and runs `clean`. It needs the `FASTLY_API_TOKEN` secret (and, for the purge, the `FASTLY_SERVICE_ID` secret).
706
+
707
+ ```yaml
708
+ name: Preview
709
+ on:
710
+ pull_request:
711
+ types: [opened, synchronize, reopened, closed]
712
+
713
+ # clean must not run while a publish runs, so all jobs that change the same
714
+ # storage use one concurrency group. Use the same group in every workflow that
715
+ # publishes or cleans, for example the workflow that publishes `live`.
716
+ concurrency:
717
+ group: static-publish-storage
718
+ cancel-in-progress: false
719
+
720
+ jobs:
721
+ publish:
722
+ if: github.event.action != 'closed'
723
+ runs-on: ubuntu-latest
724
+ defaults:
725
+ run:
726
+ working-directory: compute-js
727
+ env:
728
+ FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }}
729
+ FASTLY_SERVICE_ID: ${{ secrets.FASTLY_SERVICE_ID }}
730
+ steps:
731
+ - uses: actions/checkout@v7
732
+ - uses: actions/setup-node@v7
733
+ with:
734
+ node-version: 24
735
+ - run: npm ci
736
+ - run: npx @fastly/compute-js-static-publish publish-content --collection-name=pr-${{ github.event.number }} --expires-in=7d
737
+
738
+ remove:
739
+ if: github.event.action == 'closed'
740
+ runs-on: ubuntu-latest
741
+ defaults:
742
+ run:
743
+ working-directory: compute-js
744
+ env:
745
+ FASTLY_API_TOKEN: ${{ secrets.FASTLY_API_TOKEN }}
746
+ FASTLY_SERVICE_ID: ${{ secrets.FASTLY_SERVICE_ID }}
747
+ steps:
748
+ - uses: actions/checkout@v7
749
+ - uses: actions/setup-node@v7
750
+ with:
751
+ node-version: 24
752
+ - run: npm ci
753
+ - run: npx @fastly/compute-js-static-publish collections delete --collection-name=pr-${{ github.event.number }}
754
+ - run: npx @fastly/compute-js-static-publish clean --delete-expired-collections
755
+ ```
756
+
757
+ For a pull request that never published, `collections delete` finds no collection and deletes nothing.
758
+
759
+ ### 🔀 Selecting a Collection at Runtime
760
+
761
+ For previews, use [collection selection](#-previews-collection-selection). To select a collection in your own code, the `collectionSelector` module provides helpers to extract a collection name from different parts of a request:
762
+
763
+ ```js
764
+ collectionSelector.fromHostDomain(request, /^preview-([^\.]*)\./);
765
+ ```
766
+
767
+ #### From the Request URL
768
+
769
+ ```js
770
+ collectionSelector.fromRequestUrl(request, url => url.pathname.split('/')[2]);
771
+ ```
772
+
773
+ #### With a Custom Request Matcher
774
+
775
+ ```js
776
+ collectionSelector.fromRequest(request, req => req.headers.get('x-collection') ?? 'live');
777
+ ```
778
+
779
+ #### From a Cookie
780
+
781
+ See [fromCookie](#fromcookie) for details on this feature.
782
+
783
+ ```js
784
+ const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
785
+ ```
786
+
787
+ #### From a Fastly Config Store
788
+
789
+ ```js
790
+ collectionSelector.fromConfigStore('my-config-store', 'collection-key');
791
+ ```
792
+
793
+ ### 🚀 Promoting a Collection
794
+
795
+ If you're happy with a preview or staging collection and want to make it live, use the `collections promote` command:
796
+
797
+ ```sh
798
+ npx @fastly/compute-js-static-publish collections promote \
799
+ --collection-name=staging
800
+ --to=live
801
+ ```
802
+
803
+ This copies all content and server settings from the `staging` collection to `live`.
804
+
805
+ You can also specify a new expiration:
806
+
807
+ ```sh
808
+ npx @fastly/compute-js-static-publish collections promote \
809
+ --collection-name=preview-42 \
810
+ --to=staging \
811
+ --expires-in=7d
812
+ ```
813
+
814
+ > [!NOTE]
815
+ > The collection denoted by `defaultCollectionName` is exempt from expiration.
816
+
817
+ ## 🛠 Development → Production Workflow
818
+
819
+ ### Using the KV Store
820
+
821
+ #### Local development
822
+
823
+ During development, the local development server (`npm run dev:start`) runs against assets loaded into the simulated KV Store provided by the local development environment.
824
+
825
+ Prior to starting the server, publish the content to the simulated KV Store:
826
+
827
+ ```sh
828
+ npm run dev:publish # 'publish' your files to the simulated local KV Store
829
+ npm run dev:start # preview locally
830
+ ```
831
+
832
+ This simulates publishing by writing to `kvstore.json` instead of uploading to the actual KV Store. You can preview your site at `http://127.0.0.1:7676` - no Fastly account or service required.
833
+
834
+ Note that for local development, you will have to stop and restart the local development server each time you publish updates to your content.
835
+
836
+ To publish to an alternative collection name, use the following command and then restart the local development server:
837
+
838
+ ```sh
839
+ npm run dev:publish -- --collection-name=preview-123
840
+ ```
841
+
842
+ #### Production
843
+
844
+ When you're ready for production:
845
+
846
+ 1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
847
+ 2. Run `npm run fastly:deploy`
848
+ - This builds your Compute app into a Wasm binary
849
+ - Deploys it to a new or existing Fastly Compute service
850
+ - If creating a new service:
851
+ - you'll be prompted for backend info - **you can skip this**, as no backend is needed (all content is served from KV)
852
+ - KV Store will be created if necessary and automatically linked to your new service.
853
+
854
+ Once deployed, publish content like so:
855
+
856
+ ```sh
857
+ npm run fastly:publish
858
+ ```
859
+
860
+ `fastly:publish` needs a Fastly API token that can write to the KV Store. Set the `FASTLY_API_TOKEN` environment variable, or add `-- --fastly-api-token=<token>`. The command does not read the token of your Fastly CLI profile. If you are logged in with the Fastly CLI, you can give it that token:
861
+
862
+ ```sh
863
+ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
864
+ ```
865
+
866
+ This:
867
+
868
+ - Uses the default collection name
869
+ - Uploads static files to the KV Store
870
+ - Stores server configuration for the collection
871
+
872
+ > [!TIP]
873
+ > Upload to a specific collection by specifying the collection name when publishing content:
874
+ > ```sh
875
+ > npm run fastly:publish -- --collection-name=preview-42
876
+ > ```
877
+
878
+ **No Wasm redeploy needed** unless you:
879
+
880
+ - Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
881
+ - Change `static-publish.rc.js`
882
+
883
+ If you do need to rebuild and redeploy the Compute app, simply run:
884
+
885
+ ```sh
886
+ npm run fastly:deploy
887
+ ```
888
+
889
+ ### Using S3-compatible storage (BETA)
890
+
891
+ #### Local development
892
+
893
+ During development, the local development server (`npm run dev:start`) runs against assets published to S3-compatible storage.
894
+
895
+ In this mode, the content in the S3-compatible storage can be updated independent of the Compute application running in the local development server.
896
+
897
+ Before publishing your content, your S3-compatible bucket must already exist.
898
+
899
+ > [!TIP]
900
+ > If you're using Fastly Object Storage, [create your Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already, and then follow the [Object Storage quick start](https://www.fastly.com/documentation/guides/platform/object-storage/object-storage-quick-start/) to set up your bucket.
901
+
902
+ Publish your content by typing:
903
+
904
+ ```sh
905
+ npm run s3:publish
906
+ ```
907
+
908
+ Then start the local development server:
909
+
910
+ ```sh
911
+ npm run dev:start
912
+ ```
913
+
914
+ #### Production
915
+
916
+ When you're ready for production:
917
+
918
+ 1. [Create a free Fastly account](https://www.fastly.com/signup/?tier=free) if you haven't already.
919
+ 2. Run `npm run fastly:deploy`
920
+ - This builds your Compute app into a Wasm binary
921
+ - Deploys it to a new or existing Fastly Compute service
922
+ - If creating a new service, the Fastly CLI uses the `[setup]` section of `fastly.toml`:
923
+ - It creates the backend `s3_storage`. It prompts you for the hostname and the port of the backend.
924
+ The default values are the hostname of your S3 endpoint and 443. Press Enter to accept them.
925
+ - It creates the Secret Store `S3_CREDENTIALS` and prompts you for the values of
926
+ `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. Use credentials that can read the bucket.
927
+ - It links the backend and the Secret Store to your new service.
928
+ - If you deploy to an existing service, the Fastly CLI does not use the `[setup]` section.
929
+ Add the backend and the Secret Store to the service yourself, with the same names.
930
+
931
+ Once deployed, publish content like so:
932
+
933
+ ```sh
934
+ npm run s3:publish
935
+ ```
936
+
937
+ After the deploy, `fastly.toml` has the service ID, so `s3:publish` also purges the service's cache. For this purge, set `FASTLY_API_TOKEN` (or add `-- --fastly-api-token=<token>`) in addition to the S3 credentials. Without it, `s3:publish` stops with an error before it uploads files.
938
+
939
+ This:
940
+
941
+ - Uses the default collection name
942
+ - Uploads static files to the S3-compatible bucket
943
+ - Stores server configuration for the collection
944
+
945
+ > [!TIP]
946
+ > Upload to a specific collection by specifying the collection name when publishing content:
947
+ > ```sh
948
+ > npm run s3:publish -- --collection-name=preview-42
949
+ > ```
950
+
951
+ **No Wasm redeploy needed** unless you:
952
+
953
+ - Modify `src/index.js` - such as when you update your custom routing logic (e.g. collection selection) or
954
+ - Change `static-publish.rc.js`
955
+
956
+ If you do need to rebuild and redeploy the Compute app, simply run:
957
+
958
+ ```sh
959
+ npm run fastly:deploy
960
+ ```
961
+
962
+ ## 🧹 Cleaning Up
963
+
964
+ Every time you publish, old files are left behind for safety. **However, files with the same content will be re-used across collections and publishing events.** They are only stored once in the KV Store using their content hash as a key. This ensures that unchanged files aren't duplicated, keeping storage efficient and deduplicated.
965
+
966
+ Over time, however, collections may expire, old versions of files will be left behind, and some assets in the KV Store will no longer be referenced by any live collection. To avoid bloat, use:
967
+
968
+ ```sh
969
+ npm run dev:clean
970
+ ```
971
+ and
972
+ ```sh
973
+ npm run fastly:clean
974
+ ```
975
+
976
+ These scripts run against the local and Fastly KV Stores respectively, and run the following command:
977
+ ```
978
+ npx @fastly/compute-js-static-publish clean --delete-expired-collections
979
+ ```
980
+
981
+ This removes:
982
+
983
+ - Expired collection index files (only if `--delete-expired-collections` is passed)
984
+ - Unused content blobs (no longer referenced)
985
+ - Orphaned server config files
986
+
987
+ > [!WARNING]
988
+ > Do not run `clean` while `publish-content` can run for the same storage. `publish-content` writes the index of a collection after it uploads the files, so `clean` can delete files that the new index then refers to. In CI, put the jobs that publish and the job that cleans in the same `concurrency` group (see [A preview for each pull request](#a-preview-for-each-pull-request)).
989
+
990
+ ### 🔍 Dry Run Mode
991
+
992
+ Preview what will be deleted without making changes:
993
+
994
+ ```sh
995
+ npx @fastly/compute-js-static-publish clean --dry-run
996
+ ```
997
+
998
+ > ⚠️ Cleanup never deletes the default collection and never deletes content that’s still in use.
999
+
1000
+ ## 🔄 Content Compression
1001
+
1002
+ This project supports pre-compressing and serving assets in Brotli and Gzip formats. Compression is controlled at two different stages:
1003
+
1004
+ - **During publishing**, the `contentCompression` field in the `publish` section of `publish-content.config.js` defines which compressed variants (e.g., `br`, `gzip`) should be generated and uploaded to storage.
1005
+
1006
+ Assets are stored in multiple formats (uncompressed + compressed) if configured. A compressed variant is uploaded and used only if it is smaller than the original. (For very small files, the compressed variant is often larger.) If a variant is already in storage, it is not compressed or uploaded again. Files are compressed in parallel on the Node.js thread pool. By default, the CLI sets `UV_THREADPOOL_SIZE` to the number of CPU cores (minimum 4, maximum 16). To use a different value, set `UV_THREADPOOL_SIZE` yourself. To make compression faster, you can also set a lower `brotliQuality`. The following file types are compressed by default:
1007
+
1008
+ - Text-based: `.html`, `.js`, `.css`, `.svg`, `.json`, `.txt`, `.xml`, `.map`
1009
+ - Certain binary formats: `.bmp`, `.tar`
1010
+
1011
+ - **At runtime**, the `allowedEncodings` field in the `server` section of `publish-content.config.js` specifies which compression formats the server is allowed to serve based on the client's `Accept-Encoding` header.
1012
+
1013
+ `PublisherServer` will serve the smallest appropriate version based on the `Accept-Encoding` header.
1014
+
1015
+ ## 🧩 Using PublisherServer in Custom Apps
1016
+
1017
+ You can combine PublisherServer with custom logic to support APIs, authentication, redirects, or A/B testing. `PublisherServer` returns `null` when it cannot handle a request, allowing you to chain in your own logic.
1018
+
1019
+ ```js
1020
+ import { PublisherServer } from '@fastly/compute-js-static-publish';
1021
+ import rc from '../static-publish.rc.js';
1022
+
1023
+ const publisherServer = PublisherServer.fromStaticPublishRc(rc);
1024
+
1025
+ addEventListener("fetch", event => {
1026
+ event.respondWith(handleRequest(event.request));
1027
+ });
1028
+
1029
+ async function handleRequest(request) {
1030
+ const response = await publisherServer.serveRequest(request);
1031
+ if (response) {
1032
+ return response;
1033
+ }
1034
+
1035
+ // Add your custom logic here
1036
+ const url = new URL(request.url);
1037
+ if (url.pathname === '/api/hello') {
1038
+ return new Response(JSON.stringify({ greeting: "hi" }), {
1039
+ headers: { 'content-type': 'application/json' }
1040
+ });
1041
+ }
1042
+
1043
+ return new Response("Not Found", { status: 404 });
1044
+ }
1045
+ ```
1046
+
1047
+ ### Options of `serveRequest()`
1048
+
1049
+ `serveRequest(request, options)` takes these options. Without options, it works as above.
1050
+
1051
+ | Option | Description | Default |
1052
+ |--------|-------------|---------|
1053
+ | `collectionName` | The collection to serve, for this call only. `null` selects the default collection. | The active collection (see [Switching the active collection](#switching-the-active-collection)) |
1054
+ | `pathname` | The path to look up, in place of the path of the request URL. It must be decoded, and it must start with `/`. | The decoded path of the request URL |
1055
+ | `fallback` | `false`: if no file matches, do not serve the SPA file or the 404 page. Return `null`. | `true` |
1056
+ | `healthCheck` | `false`: do not answer `/healthz`. | `true` |
1057
+
1058
+ `serveRequest()` returns `null` for a method other than `GET` and `HEAD`, and when there is no response (no file matches, and there is no fallback page or `fallback` is `false`). If the default collection has no settings in storage, the response is `500`. A collection other than the default collection that is not published, or that expired, gets a plain-text `404` that names it.
1059
+
1060
+ `serveFallback(request, { collectionName })` serves the SPA file (`200`) or the 404 page (`404`) of the collection, as `serveRequest()` does when no file matches. It returns `null` for a method other than `GET` and `HEAD`, for a client that does not accept HTML, or when the collection has no fallback page. Use it with `fallback: false`, to run your own logic between the files and the fallback page:
1061
+
1062
+ ```js
1063
+ async function handleRequest(request) {
1064
+ const response = await publisherServer.serveRequest(request, { fallback: false });
1065
+ if (response) {
1066
+ return response;
1067
+ }
1068
+
1069
+ const url = new URL(request.url);
1070
+ if (url.pathname === '/api/hello') {
1071
+ return new Response(JSON.stringify({ greeting: "hi" }), {
1072
+ headers: { 'content-type': 'application/json' }
1073
+ });
1074
+ }
1075
+
1076
+ return (await publisherServer.serveFallback(request)) ?? new Response("Not Found", { status: 404 });
1077
+ }
1078
+ ```
1079
+
1080
+ ### ⏱️ Measuring Performance with `Server-Timing`
1081
+
1082
+ `PublisherServer` can report how long it spends reading from storage. To turn this on, give it the name of a request header:
1083
+
1084
+ ```js
1085
+ publisherServer.setServerTimingRequestHeader('X-Publisher-Server-Timing');
1086
+ ```
1087
+
1088
+ A request that has this header gets a [`Server-Timing`](https://www.w3.org/TR/server-timing/) response header. Requests without it are not affected. This is off by default.
1089
+
1090
+ ```
1091
+ Server-Timing: settings;dur=12.3, index;dur=40.1, index-body;dur=31.0, index-parse;dur=24.2, asset;dur=11.4
1092
+ ```
1093
+
1094
+ | Name | Duration of |
1095
+ |------|-------------|
1096
+ | `settings` | Reading and parsing the collection's settings |
1097
+ | `index` | Reading the collection's index, until the response headers arrive |
1098
+ | `index-body` | Reading the body of the index |
1099
+ | `index-parse` | Parsing the index |
1100
+ | `asset` | Reading the file, until the response headers arrive. Can appear more than one time, one time for each variant that is tried. |
1101
+ | `cache` | Looking up the response cache, if it is on (see [Caching Responses with the Core Cache](#️-caching-responses-with-the-core-cache)). `desc` is `hit` (with the age of the cached response, for example `hit age=42s`), `miss`, or `bypass`. |
1102
+
1103
+ An entry is missing if `PublisherServer` did not read that item for this request, for example because the item is cached in memory, or because the response came from the response cache.
1104
+
1105
+ `serveRequest()` starts the measurements for each request. If you call `getMatchingAsset()` and `serveAsset()` directly, call `beginRequest()` first:
1106
+
1107
+ ```js
1108
+ publisherServer.beginRequest(request);
1109
+ const asset = await publisherServer.getMatchingAsset(pathname);
1110
+ if (asset != null) {
1111
+ return publisherServer.serveAsset(request, asset);
1112
+ }
1113
+ ```
1114
+
1115
+ Any client can send the request header. Choose a name that is not easy to guess if you do not want to show these timings to the public.
1116
+
1117
+ ### 🗄️ Caching Responses with the Core Cache
1118
+
1119
+ To serve a file, `PublisherServer` reads the collection's settings, the collection's index, and the file. Fastly can cache these reads, but `PublisherServer` must still parse the index for each request, and the index of a large site is large. To skip this work, `PublisherServer` can cache whole responses with the Fastly [Core Cache](https://www.fastly.com/documentation/guides/concepts/cache/) API:
1120
+
1121
+ ```js
1122
+ publisherServer.setResponseCache({ maxAge: 3600 });
1123
+ ```
1124
+
1125
+ `maxAge` is in seconds. This is off by default.
1126
+
1127
+ `maxBodySize` sets the largest response, in bytes, to cache. The default is 16 MiB (`16 * 1024 * 1024`). A larger response is served from storage each time:
1128
+
1129
+ ```js
1130
+ publisherServer.setResponseCache({ maxAge: 3600, maxBodySize: 4 * 1024 * 1024 });
1131
+ ```
1132
+
1133
+ - A response is cached by the publish ID, the collection, the path, and the client's `Accept-Encoding`. A cache hit does not read the settings, the index, or the file.
1134
+ - A path that does not match a file is cached, too, so a missing path does not read the index again.
1135
+ - With the options of `serveRequest()`, the path in the key is the `pathname` option, and the collection is the `collectionName` option. A response with `fallback: false` has its own key. `serveFallback()` caches one response for each collection, for all paths.
1136
+ - If several requests miss the same response at the same time, one request produces it, and the others wait for it.
1137
+ - Only `200` and `404` responses are cached. Conditional requests (`304`) and `HEAD` requests are answered from the cached response.
1138
+ - Each cached response has the surrogate key `<publishId>-<collectionName>`. After you publish, `publish-content` purges this key (see [`--fastly-service-id`](#publish-content)), so the next request gets the new content. `collections promote` and `collections delete` purge the key of the collection that they change.
1139
+
1140
+ `serveRequest()` uses the response cache automatically. If you call `getMatchingAsset()` and `serveAsset()` directly, wrap them in `serveCached()`. When a response is not cached yet, `serveCached()` calls your function to produce it, with a `GET` request that has no conditional headers:
1141
+
1142
+ ```js
1143
+ publisherServer.beginRequest(request);
1144
+ const response = await publisherServer.serveCached(request, pathname, async (fillRequest) => {
1145
+ const asset = await publisherServer.getMatchingAsset(pathname);
1146
+ if (asset == null) {
1147
+ return null; // not found; this result is cached, too
1148
+ }
1149
+ return publisherServer.serveAsset(fillRequest, asset);
1150
+ });
1151
+ ```
1152
+
1153
+ The second argument identifies the response in the collection. If anything other than the path and `Accept-Encoding` changes your response, include it in this value.
1154
+
1155
+ Notes:
1156
+
1157
+ - A response is read completely before it is cached. The request that caches it uses memory of about two times the body, up to two times `maxBodySize`. A Compute instance has a limit on its memory, so do not set `maxBodySize` larger than 48 MiB (`48 * 1024 * 1024`). Other requests that wait for the same response get it when it is cached.
1158
+ - A response is cached only if its body has the size in the file's metadata. If storage returns a different body, nothing is cached, the request gets an error, and the next request reads the file again.
1159
+ - With `--local`, `publish-content` cannot purge the local cache. Restart `fastly compute serve` to see newly published content, or leave the response cache off in local development.
1160
+ - On staging, a purge must include the `Fastly-Purge-Environment: staging` header to clear the staging cache. Without it, a purge clears only the production cache. Use `publish-content --purge-environment=production,staging` to purge both.
1161
+
1162
+ ## 🔥 Using Hono
1163
+
1164
+ `@fastly/compute-js-static-publish/hono` has middleware for [Hono](https://hono.dev/) apps. It serves the published files with `PublisherServer`, so a Hono app gets all the features of the server: `autoIndex`, `autoExt`, the compressed variants, `304` responses, the [response cache](#️-caching-responses-with-the-core-cache), `Server-Timing`, and [collection selection](#-previews-collection-selection).
1165
+
1166
+ ### The `hono` template
1167
+
1168
+ To scaffold a Hono app, add `--template hono` (in a managed project: `managed.template: 'hono'`):
1169
+
1170
+ ```sh
1171
+ npx @fastly/compute-js-static-publish@beta --template hono --root-dir=./public --kv-store-name=site-content
1172
+ ```
1173
+
1174
+ The app is TypeScript: `src/index.ts`, with code like the example below, and `tsconfig.json`. Add your own routes in `src/index.ts`. The build (`js-compute-runtime ./src/index.ts`) removes the types, but does not check them. To check the types, run `npx tsc` in the app. The app has `typescript` as a dev dependency.
1175
+
1176
+ ### Hono extensions
1177
+
1178
+ To add your own middleware and routes to the `hono` template, put modules in the extensions folder, `hono-extensions/`. In a managed project, this is the only way to add code, because the CLI generates the app. In an ejected app, you can also edit `src/index.ts`.
1179
+
1180
+ `scaffold --template hono` makes the folder next to the project file (managed) or next to `compute-js/` (ejected). To make it later, or to update it, run:
1181
+
1182
+ ```sh
1183
+ npx @fastly/compute-js-static-publish template init
1184
+ ```
1185
+
1186
+ ```
1187
+ hono-extensions/
1188
+ ├── package.json # Your dependencies, and the peer dependencies on the packages that the app provides
1189
+ ├── tsconfig.json # For your editor
1190
+ ├── 10-auth.ts # A module
1191
+ ├── api.ts # A module
1192
+ ├── _example.ts # An example, not a module (the name starts with _)
1193
+ └── lib/ # Your helpers (not modules)
1194
+ ```
1195
+
1196
+ - **Modules** are the files directly in the folder, with the extension `.ts`, `.mts`, `.js`, or `.mjs`. Files that start with `_` or `.`, and `.d.ts` files, are not modules. The build does not look in subfolders, so use them, for example `lib/`, for your helpers.
1197
+ - **The name** of a module is the file name without the number prefix and the extension: `10-auth.ts` is `auth`. Two modules with the same name are an error.
1198
+ - **The phases:** a module adds its handlers to the app in one or more phases. The app runs the phases in this order, and in each phase the modules in the order of the file names (add a number prefix to set the order):
1199
+
1200
+ ```
1201
+ selectCollection() → middleware → beforeFiles → serveStatic() → afterFiles → serveFallback()
1202
+ ```
1203
+
1204
+ - `middleware`: before all other phases. All modules add their middleware before any module adds its routes, so a middleware such as a login check also applies to the routes of the other modules.
1205
+ - `beforeFiles`: before the published files.
1206
+ - `afterFiles`: after the published files. These handlers get only the requests that no published file matches, for example to make a page for a path that has no file, before the 404 page. The published files are served only for `GET` and `HEAD`, so these handlers also get all other methods.
1207
+
1208
+ A module default-exports `defineExtension()`. Give it a function for each phase that the module uses. Each function gets the Hono app and the options of the module, and adds handlers with `app.use()`, `app.get()`, `app.post()`, and the other methods of Hono. With only a function in place of the object, the function is the `middleware` phase:
1209
+
1210
+ ```ts
1211
+ // hono-extensions/10-header.ts
1212
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1213
+
1214
+ export default defineExtension((app, options?: { value?: string }) => {
1215
+ app.use('*', async (c, next) => {
1216
+ await next();
1217
+ c.header('x-site', options?.value ?? 'default');
1218
+ });
1219
+ });
1220
+ ```
1221
+
1222
+ ```ts
1223
+ // hono-extensions/api.ts
1224
+ import { defineExtension } from '@fastly/compute-js-static-publish/hono';
1225
+
1226
+ export default defineExtension({ bindings: { config: 'ConfigStore:site_config' } }, {
1227
+ middleware: (app) => {
1228
+ app.use('/api/*', async (c, next) => {
1229
+ await next();
1230
+ c.header('cache-control', 'no-store');
1231
+ });
1232
+ },
1233
+ beforeFiles: (app) => {
1234
+ app.get('/api/greeting', async (c) => c.json({ greeting: await c.env.config?.get('greeting') }));
1235
+ },
1236
+ afterFiles: (app) => {
1237
+ app.get('/blog/:slug', (c) => c.redirect(`/archive/${c.req.param('slug')}/`, 301));
1238
+ },
1239
+ });
1240
+ ```
1241
+
1242
+ **Options** come from `templateOptions.hono.extensions` in the project file (or in `static-publish.rc.js`), with the name of the module as the key. Each phase of a module gets the same options. The build shows a warning for options of a module that does not exist:
1243
+
1244
+ ```js
1245
+ templateOptions: {
1246
+ hono: {
1247
+ bindings: { config: 'ConfigStore:site_config' },
1248
+ extensions: { header: { value: 'my-site' } },
1249
+ },
1250
+ },
1251
+ ```
1252
+
1253
+ **Bindings** put Fastly resources on `c.env`, as `buildFire()` of `@fastly/hono-fastly-compute` does. A module declares the bindings that it uses in the first argument of `defineExtension()`, and `c.env` in its handlers has their types, for example `ConfigStore | undefined` for `'ConfigStore:site_config'` (`undefined` if the resource does not exist or is not linked to the service). `templateOptions.hono.bindings` adds bindings for the app. The same name with the same resource in two places is allowed. The same name with two different resources stops the build, and the message names both places. `c.var` is not typed in a module, so that a module can set its own variables.
1254
+
1255
+ **Errors** in a module stop the build, and the message names the file: a default export that is not `defineExtension()`, an object with no phase, a key that is not a phase, or a phase that is not a function.
1256
+
1257
+ **The build** bundles the modules into `src/hono-extensions.generated.js` of the app (the `prebuild` [template hook](#-template-hooks)). The packages that the app provides stay imports, so that the app has one copy of each: the dependencies of the app (for example `hono` and `@fastly/hono-fastly-compute`), this package, and `fastly:*`. Thus, do not install them in the folder. `template init` writes them as peer dependencies in `hono-extensions/package.json`, with the versions that the app has. Install other packages in the folder (`npm install` in `hono-extensions/`), and the build bundles them.
1258
+
1259
+ - `build.hono.extensionsDir` sets another folder, relative to the project file (or to `static-publish.rc.js`). The default is `./hono-extensions`.
1260
+ - Without the folder, or without modules, the app has no extensions. `dev` and `deploy` of a managed project then show how to make the folder.
1261
+ - In a managed project, the files of the folder (without `node_modules/`) are part of the fingerprint, so a change to a module makes `deploy` deploy again.
1262
+ - Keep the code of the extensions in the folder. A module can import a file from outside the folder, and the build bundles it, but a change to that file does not change the fingerprint, and the watcher does not see it.
1263
+
1264
+ **`template init`** makes the folder with `package.json`, `tsconfig.json`, and the example. In a folder that exists, it updates only the peer dependencies, and adds the starter files that are missing. It never changes your modules. `--reset` writes the starter files again (it asks first, or needs `--force` with `--non-interactive`). `--check` changes nothing, and fails with `template-init-needed` if the folder is out of date, for example after an upgrade of this package; use it in CI.
1265
+
1266
+ **Watch:** `dev -- --watch` (managed) and `npm run dev:watch` (ejected) also watch the extensions folder, also if it does not exist yet. A change in the folder bundles the modules again, and then the Fastly CLI builds and restarts the app. If a module has an error, the watcher shows it and the app keeps the last modules that built.
1267
+
1268
+ **Examples** in [`examples/hono/`](https://github.com/fastly/compute-js-static-publish/tree/main/examples/hono) show complete extensions. They are not part of the npm package, and you cannot scaffold an app with them: for a new project, copy the `hono-extensions/` folder of an example into your project, and set it up as the README of the example shows. The README also shows how to add an example to a project that exists.
1269
+
1270
+ - [`grip`](https://github.com/fastly/compute-js-static-publish/tree/main/examples/hono/grip): realtime streams and Server-Sent Events with Fastly Fanout, and a publish endpoint with a shared key. One module with two phases: the `middleware` phase hands off only `/events/*` to Fanout, and the `beforeFiles` phase has the endpoints.
1271
+ - [`oauth`](https://github.com/fastly/compute-js-static-publish/tree/main/examples/hono/oauth): a login with GitHub or Google in front of some paths of the site (`protect`), with a signed session cookie.
1272
+
1273
+ Each example takes its secrets from a Secret Store. For `dev`, `managed.fastlyToml` adds a local Secret Store that reads environment variables.
1274
+
1275
+ ### Hono in your own app
1276
+
1277
+ Add `hono` and `@fastly/hono-fastly-compute` to your app:
1278
+
1279
+ ```sh
1280
+ npm install hono @fastly/hono-fastly-compute
1281
+ ```
1282
+
1283
+ Then serve the files from your Hono app. Add your own routes before `serveStatic()` or after it:
1284
+
1285
+ ```js
1286
+ import { Hono } from 'hono';
1287
+ import { fire } from '@fastly/hono-fastly-compute';
1288
+ import { fromStaticPublishRc } from '@fastly/compute-js-static-publish/hono';
1289
+ import rc from '../static-publish.rc.js';
1290
+
1291
+ const { serveStatic, serveFallback, selectCollection } = fromStaticPublishRc(rc);
1292
+
1293
+ const app = new Hono();
1294
+
1295
+ // Select the collection of each request with collectionSelection in
1296
+ // static-publish.rc.js, for example for previews.
1297
+ app.use('*', selectCollection());
1298
+
1299
+ app.get('/api/hello', (c) => c.json({ hello: 'world' }));
1300
+
1301
+ // Serve the published files. If no file matches, the request goes to the next handler.
1302
+ app.use('*', serveStatic());
1303
+
1304
+ // When nothing matches, serve the SPA file or the 404 page.
1305
+ app.notFound(serveFallback());
1306
+
1307
+ fire(app);
1308
+ ```
1309
+
1310
+ `fire()` from [`@fastly/hono-fastly-compute`](https://hono.dev/docs/getting-started/fastly) runs the app on Fastly Compute. Use version 0.4.0 or later with `@fastly/js-compute` v4. To use a KV Store, a Config Store, or other resources from `c.env`, use `buildFire()` with bindings. Do not use `hono/service-worker`: by default, it sends each 404 response to `fetch()`, and Compute has no default backend.
1311
+
1312
+ `fromStaticPublishRc(rc)` returns:
1313
+
1314
+ - `serveStatic(options?)`: middleware that serves the file that matches the request. If no file matches, or the method is not `GET` or `HEAD`, it calls the next handler, so a route after it gets the request. It does not serve the SPA file or the 404 page, and it does not answer `/healthz`.
1315
+ - `serveFallback(options?)`: for `app.notFound()`. It serves the SPA file or the 404 page. If there is neither, or the client does not accept HTML, it gives Hono's default 404 response.
1316
+ - `selectCollection()`: middleware that selects the collection of each request with the [`collectionSelection`](#-previews-collection-selection) of `static-publish.rc.js`. It returns the redirects of the selection (a `sticky` source, and the activate and reset paths of the `cookie` source), and sets `c.var.staticPublisher`. Then `serveStatic()` and `serveFallback()` use the selected collection. For a `path` source, `serveStatic()` looks up the path without the prefix.
1317
+ - `publisherServer`: the `PublisherServer`, to configure it. For example, `publisherServer.setResponseCache({ maxAge: 3600 })`.
1318
+
1319
+ If you make the `PublisherServer` yourself, use `fromPublisherServer(publisherServer)` in place of `fromStaticPublishRc(rc)`.
1320
+
1321
+ `serveStatic()` takes options like the `serveStatic()` of Hono:
1322
+
1323
+ | Option | Description |
1324
+ |---|---|
1325
+ | `root` | The directory that request paths are relative to, in the published files (after `publicDirPrefix`, if it is set). The default is `./`. A path that resolves outside `root` is not served. |
1326
+ | `path` | The path to serve, in place of the request path. For example, `./favicon.ico`. |
1327
+ | `rewriteRequestPath` | `(path, c) => string`. Changes the request path before it is resolved against `root`. |
1328
+ | `collectionName` | The collection: a string, `null` for the default collection, or `(c) => string \| null \| undefined`. Without it, or if the function returns `undefined`, the collection is the one that `selectCollection()` selected, or else the active collection. |
1329
+
1330
+ For example, to serve `/assets/*` from the `static` directory:
1331
+
1332
+ ```js
1333
+ app.use('/assets/*', serveStatic({ root: './static', rewriteRequestPath: (path) => path.replace(/^\/assets/, '') }));
1334
+ ```
1335
+
1336
+ `serveFallback()` takes the `collectionName` option, too. To give a default to all the middleware, pass it to `fromStaticPublishRc(rc, { collectionName })`. An option in a call replaces the default.
1337
+
1338
+ In TypeScript, use `StaticPublisherVariables` for the variables of the app, so that `c.var.staticPublisher` has a type:
1339
+
1340
+ ```ts
1341
+ import { fromStaticPublishRc, type StaticPublisherVariables } from '@fastly/compute-js-static-publish/hono';
1342
+
1343
+ const app = new Hono<{ Variables: StaticPublisherVariables }>();
1344
+ app.get('/api/collection', (c) => c.json({ collection: c.var.staticPublisher.collectionName }));
1345
+ ```
1346
+
1347
+ The middleware imports only types from `hono`, so it does not add `hono` to your bundle. `hono` (v4) is an optional peer dependency of this package.
1348
+
1349
+ To move from `@fastly/hono-compute-js-static-publish`, see [MIGRATING.md](./MIGRATING.md).
1350
+
1351
+ ## 📥 Using Published Assets in Your Code
1352
+
1353
+ To access files you've published, use the `getMatchingAsset()` and `loadAssetVariant()` methods on `publisherServer`.
1354
+
1355
+ ### Access Metadata for a File:
1356
+
1357
+ ```js
1358
+ const asset = await publisherServer.getMatchingAsset('/index.html');
1359
+ if (asset != null) {
1360
+ // Asset exists with that path
1361
+ asset.contentType; // e.g., 'text/html'
1362
+ asset.lastModifiedTime; // Unix timestamp
1363
+ asset.size; // Size in bytes of the base version
1364
+ asset.hash; // SHA256 hash of base version
1365
+ asset.variants; // Available variants (e.g., ['gzip'])
1366
+ }
1367
+ ```
1368
+
1369
+ `getMatchingAsset(key, options)` takes these options:
1370
+
1371
+ - `applyAuto` - Also try `autoExt` and `autoIndex`, as for a request (default: `false`). The second argument can also be a boolean, the value of `applyAuto`.
1372
+ - `includeHidden` - Also find [hidden files](#hidden-files) (default: `false`).
1373
+
1374
+ ```js
1375
+ const template = await publisherServer.getMatchingAsset('/templates/email.html', { includeHidden: true });
1376
+ ```
1377
+
1378
+ `getAssetEntryMap()` returns the whole index. The key of a hidden file in it is `hidden:` and then the asset key, for example `hidden:/404.html`.
1379
+
1380
+ ### Load the File from KV Store:
1381
+
1382
+ ```js
1383
+ const assetVariant = await publisherServer.loadAssetVariant(asset, null); // pass 'gzip' or 'br' for compressed
1384
+
1385
+ assetVariant.storageEntry; // Storage entry (type StorageEntry defined in './src/storage/storage-provider.ts')
1386
+ assetVariant.size; // Size of the variant
1387
+ assetVariant.hash; // SHA256 of the variant
1388
+ assetVariant.contentEncoding; // 'gzip', 'br', or null
1389
+ assetVariant.numChunks; // Number of chunks (for large files)
1390
+ ```
1391
+
1392
+ You can stream `assetVariant.storageEntry.body` directly to a `Response`, or read it using `.text()`, `.json()`, or `.arrayBuffer()` depending on its content type.
1393
+
1394
+ ---
1395
+
1396
+ ## 📚 CLI Reference
1397
+
1398
+ ### Available Commands
1399
+
1400
+ #### Outside a Compute App Directory
1401
+ - `npx @fastly/compute-js-static-publish@beta [options]` - Scaffold a new Compute app
1402
+
1403
+ #### Inside a Compute App Directory
1404
+ - `publish-content` - Publish static files to storage (KV Store or S3-compatible storage) under a named collection
1405
+ - `clean` - Delete expired and unreferenced entries in storage
1406
+ - `collections list` - List all published collections
1407
+ - `collections delete` - Delete a specific collection index
1408
+ - `collections promote` - Copy a collection to another name
1409
+ - `collections update-expiration` - Modify expiration time for an existing collection
1410
+
1411
+ ### 🤖 Using the CLI in CI
1412
+
1413
+ These rules are for tools that run the CLI with no person present, for example a GitHub Actions workflow. They are part of the contract of the CLI: a change that breaks them comes only in a major release.
1414
+
1415
+ **Exit codes:**
1416
+
1417
+ | Code | Meaning |
1418
+ |------|---------|
1419
+ | `0` | Success. Also when there is nothing to do, for example when you publish the same content again, promote to a collection again, or delete a collection that does not exist. A failed purge after a successful publish is only a warning (see `purge.ok` in the JSON). |
1420
+ | `1` | The operation failed, for example storage cannot be reached, or the deploy failed. A retry can help. |
1421
+ | `2` | A usage or config error, for example an unknown option, a missing option, a collection name that breaks the rule, or a config file that cannot be loaded. A retry cannot help. |
1422
+
1423
+ **`--json`:** `publish-content`, `collections list`, `collections delete`, `collections promote`, `status`, `deploy` (in a managed project), and `--version` can write their result as one JSON object to stdout, at the end. All log lines then go to stderr, so that they still show in the CI log. With another command, `--json` is an error (`json-not-supported`).
1424
+
1425
+ ```sh
1426
+ npx @fastly/compute-js-static-publish publish-content \
1427
+ --project-dir=./compute-js --collection-name=pr-42 --json > result.json
1428
+ ```
1429
+
1430
+ Each object has `schemaVersion` (now `1`). A new field keeps the version. A field is removed or changed only in a major release, with a new `schemaVersion`.
1431
+
1432
+ `publish-content --json`:
1433
+
1434
+ ```json
1435
+ {
1436
+ "schemaVersion": 1,
1437
+ "collection": "pr-42",
1438
+ "publishId": "default",
1439
+ "files": { "total": 352, "hidden": 2 },
1440
+ "storageItems": { "uploaded": 12, "reused": 340 },
1441
+ "expiresAt": "2026-12-01T00:00:00.000Z",
1442
+ "purge": {
1443
+ "ok": true,
1444
+ "serviceId": "SERVICE_ID",
1445
+ "environments": [ { "environment": "production", "result": "purged" } ]
1446
+ }
1447
+ }
1448
+ ```
1449
+
1450
+ - `files` counts the files in the index. `storageItems` counts the items in storage: each file, and each compressed variant that is kept. Thus `storageItems.uploaded` can be larger than `files.total`.
1451
+ - `expiresAt` is `null` if the collection does not expire.
1452
+ - `purge` is `null` if there was no purge (`--local`, or no Service ID). `purge.ok` is `false` if a purge failed. Then the visitors can get the old content from the cache until it expires. Each item of `environments` has a `result`: `purged`, `not-staged` (a `staging` purge, and the service has no staged version), or `failed` (with a `reason`).
1453
+
1454
+ `collections list --json`:
1455
+
1456
+ ```json
1457
+ {
1458
+ "schemaVersion": 1,
1459
+ "publishId": "default",
1460
+ "defaultCollection": "live",
1461
+ "collections": [
1462
+ {
1463
+ "name": "live", "isDefault": true,
1464
+ "publishedAt": "2026-11-01T00:00:00.000Z", "expiresAt": null, "expired": false,
1465
+ "requires": [ "hidden" ], "unsupported": [], "files": 352, "hidden": 2
1466
+ }
1467
+ ]
1468
+ }
1469
+ ```
1470
+
1471
+ `collections delete --json`. `deleted` is `false` with `"reason": "not-found"` if the collection does not exist (also exit `0`). `purge` is as in `publish-content`:
1472
+
1473
+ ```json
1474
+ { "schemaVersion": 1, "collection": "pr-42", "publishId": "default", "deleted": true, "purge": null }
1475
+ ```
1476
+
1477
+ `collections promote --json`. `expiresAt` is the expiration time of the target after the promote, or `null`:
1478
+
1479
+ ```json
1480
+ { "schemaVersion": 1, "from": "staging", "to": "live", "publishId": "default", "expiresAt": null }
1481
+ ```
1482
+
1483
+ `status --json` in a managed project. `needsDeploy` is `null` if it is not known (no API token):
1484
+
1485
+ ```json
1486
+ {
1487
+ "schemaVersion": 1,
1488
+ "mode": "managed",
1489
+ "serviceId": "SERVICE_ID",
1490
+ "staticPublishVersion": { "recorded": "8.1.0", "running": "8.1.0", "check": "same" },
1491
+ "fingerprint": { "current": "3f…", "deployed": "3f…", "deployedStaticPublishVersion": "8.1.0" },
1492
+ "activeVersion": 12,
1493
+ "domain": "example.edgecompute.app",
1494
+ "needsDeploy": false,
1495
+ "reasons": [],
1496
+ "previewUrls": [ { "type": "query", "url": "https://example.edgecompute.app/?collection={collection}" } ],
1497
+ "template": {
1498
+ "name": "hono",
1499
+ "provides": {
1500
+ "@fastly/hono-fastly-compute": "0.4.0",
1501
+ "@fastly/js-compute": "4.0.0",
1502
+ "hono": "4.13.14",
1503
+ "@fastly/compute-js-static-publish": "8.1.0"
1504
+ }
1505
+ }
1506
+ }
1507
+ ```
1508
+
1509
+ `template.provides` lists the packages that the app of the template provides to the folder of the template (for example `hono-extensions/`), with their versions.
1510
+
1511
+ In an ejected app, `status --json` gives `{ "schemaVersion": 1, "mode": "ejected", "serviceId": "SERVICE_ID" }`.
1512
+
1513
+ `deploy --json`. `deployed` is `false` with `"reason": "up-to-date"` if the active version already has this app:
1514
+
1515
+ ```json
1516
+ {
1517
+ "schemaVersion": 1,
1518
+ "deployed": true,
1519
+ "serviceId": "SERVICE_ID",
1520
+ "version": 13,
1521
+ "domain": "example.edgecompute.app",
1522
+ "fingerprint": "3f…",
1523
+ "staticPublishVersion": "8.1.0"
1524
+ }
1525
+ ```
1526
+
1527
+ `--version --json` gives `{ "schemaVersion": 1, "version": "8.1.0" }`.
1528
+
1529
+ **Errors:** with `--json`, stdout has one object, `{ "schemaVersion": 1, "error": { "code": "…", "message": "…" } }`. The error also goes to stderr. `message` is for people and can change. `code` is one of these values. A script can use it:
1530
+
1531
+ | Code | Exit code | Meaning |
1532
+ |------|-----------|---------|
1533
+ | `usage` | `2` | An unknown command or option, or a missing or incorrect option value |
1534
+ | `config-invalid` | `2` | `static-publish.rc.js`, `static-publish.project.js`, or `publish-content.config.js` cannot be loaded, or is not valid |
1535
+ | `collection-name-invalid` | `2` | A collection name breaks the [rule](#-collections-publish-preview-promote) |
1536
+ | `collection-not-found` | `2` | The command needs a collection that does not exist |
1537
+ | `project-dir-not-found` | `2` | `--project-dir` is not a directory, or has no config file |
1538
+ | `json-not-supported` | `2` | `--json` with a command that does not support it |
1539
+ | `credentials-missing` | `2` | An API token or S3 credentials are necessary, but not given |
1540
+ | `version-mismatch` | `2` | `managed.staticPublishVersion` is not the version of the CLI that runs |
1541
+ | `first-deploy-manual` | `2` | The first deploy of a managed project with S3 storage, with `--non-interactive` |
1542
+ | `version-not-published` | `2` | `eject` needs a version of this package that is on npm |
1543
+ | `template-init-needed` | `2` | `template init --check`: the folder of the template (for example `hono-extensions/`) is out of date. Run `template init` |
1544
+ | `deploy-failed` | `1` | The build or the deploy of the app failed |
1545
+ | `failed` | `1` | The operation failed, for example storage cannot be reached |
1546
+
1547
+ New codes can come in a minor release. Treat a code that you do not know by its exit code.
1548
+
1549
+ **Secrets:** give the Fastly API token in `FASTLY_API_TOKEN`, and S3 credentials in `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. The CLI replaces the values of the token and the S3 secret access key with `[REDACTED]` in its output, also in errors and in the JSON.
1550
+
1551
+ ### 🛠 App Scaffolding
1552
+
1553
+ Run outside an existing Compute app directory:
1554
+
1555
+ #### Minimum required options
1556
+
1557
+ ```sh
1558
+ # Using KV store storage
1559
+ npx @fastly/compute-js-static-publish@beta \
1560
+ --root-dir=./public \
1561
+ --kv-store-name=<site-content>
1562
+
1563
+ # Using S3 storage (BETA)
1564
+ npx @fastly/compute-js-static-publish@beta \
1565
+ --root-dir=./public \
1566
+ --storage-mode=s3 \
1567
+ --s3-region=<s3 region> \
1568
+ --s3-bucket=<bucket name> \
1569
+ [--s3-endpoint=<endpoint>]
1570
+ ```
1571
+
1572
+ #### Full options list
1573
+
1574
+ ```sh
1575
+ npx @fastly/compute-js-static-publish@beta \
1576
+ --root-dir=./public \
1577
+ { [--storage-mode=kv-store] --kv-store-name=<site-content> | \
1578
+ --storage-mode=s3 --s3-region=<s3 region> --s3-bucket=<bucket name> [--s3-endpoint=<endpoint>] } \
1579
+ [--output=./compute-js] \
1580
+ [--static-publisher-working-dir=<output>/static-publisher] \
1581
+ [--publish-id=<prefix>] \
1582
+ [--default-collection-name=live] \
1583
+ [--template=plain|hono] \
1584
+ [--static-dir=./public/static] \
1585
+ [--spa=./public/spa.html] \
1586
+ [--not-found-page=./public/404.html] \
1587
+ [--auto-index=index.html,index.htm] \
1588
+ [--auto-ext=.html,.htm] \
1589
+ [--name=my-site] \
1590
+ [--description='My Compute static site'] \
1591
+ [--author='you@example.com'] \
1592
+ [--service-id=your-fastly-service-id]
1593
+ ```
1594
+
1595
+ #### Options:
1596
+
1597
+ **Used to generate the Compute app:**
1598
+ - `--storage-mode`: Specifies the storage mode. Must be either `kv-store` or `s3` (default: `kv-store`).
1599
+
1600
+ If `--storage-mode=kv-store`:
1601
+ - `--kv-store-name`: Required. Name of KV Store to use.
1602
+
1603
+ If `--storage-mode=s3`:
1604
+ - `--s3-region`: Required. Region of the S3-compatible bucket.
1605
+ - `--s3-bucket`: Required. Name of the S3-compatible bucket.
1606
+ - `--s3-endpoint`: Optional. Custom endpoint of the S3-compatible bucket, if necessary.
1607
+
1608
+ - `--output`: Compute app destination (default: `./compute-js`)
1609
+ - `--static-publisher-working-dir`: Directory to hold working files (default: `<output>/static-publisher`).
1610
+ - `--name`: Application name to insert into `fastly.toml`
1611
+ - `--description`: Application description to insert into `fastly.toml`
1612
+ - `--author`: Author to insert into `fastly.toml`
1613
+ - `--service-id`: Optional existing Fastly Compute service ID
1614
+ - `--template`: The template of the app's code (default: `plain`). `plain` is a JavaScript app that calls `PublisherServer.serveRequest()` from a fetch event listener. `hono` is a TypeScript [Hono](https://hono.dev/) app (see [Using Hono](#-using-hono)).
1615
+ - `--managed`: Write only `static-publish.project.js` (a [managed project](#managed-projects)) in the current directory, in place of the app. `--output` is not used.
1616
+
1617
+ **Used in building config files:**
1618
+ - `--root-dir`: Required. Directory of static site content.
1619
+ - `--publish-id`: Optional key prefix for KV entries (default: `'default'`).
1620
+ - `--default-collection-name`: The collection to serve when no collection is selected (default: `'live'`).
1621
+ - `--public-dir`: **Deprecated.** A future version will remove it. Public files base directory, under `--root-dir` (default: same as `--root-dir`). Files that are under `--root-dir` but not under `--public-dir` are published, but requests cannot get them.
1622
+ - `--static-dir`: One or more directories to serve with long cache TTLs.
1623
+ - `--spa`: SPA fallback file path, from the current directory (e.g., `./public/spa.html`). The file must exist under `--root-dir`.
1624
+ - `--not-found-page`: 404 fallback file path, from the current directory (e.g., `./public/404.html`). The file must exist under `--root-dir`. If you do not set it, the scaffolder uses `404.html` in `--root-dir` if that file exists.
1625
+ - `--auto-index`: List of filenames to use as index files.
1626
+ - `--auto-ext`: Extensions to try when resolving URLs.
1627
+
1628
+ **Collection selection** (written as `collectionSelection` in `static-publish.rc.js`; see [Previews: Collection Selection](#-previews-collection-selection)):
1629
+ - `--collection-selection`: A source. Can be repeated; the sources are tried in the order of the flags.
1630
+ - `host:<pattern>`, for example `host:{collection}.preview.example.com`
1631
+ - `path:<prefix>[,sticky]`, for example `path:/_preview/{collection},sticky`
1632
+ - `query:<param>[,sticky]`, for example `query:collection,sticky`
1633
+ - `cookie[:<cookieName>][,maxAge=<seconds>][,activatePath=<path>][,resetPath=<path>]`
1634
+ - `header:<name>`, for example `header:x-publisher-collection`
1635
+ - `--collection-allow`: The collections that can be selected, for example `pr-*,staging`.
1636
+ - `--collection-on-missing`: `not-found` (default) or `default`.
1637
+ - `--collection-noindex`: `true` (default) or `false`.
1638
+
1639
+ ### 🚀 Inside a Compute App Directory
1640
+
1641
+ Once you're in the scaffolded Compute app directory (with `static-publish.rc.js` present), you can run these subcommands.
1642
+
1643
+ To run a subcommand from another directory, for example the root of your repo in CI, give the app directory with `--project-dir`:
1644
+
1645
+ ```sh
1646
+ npx @fastly/compute-js-static-publish publish-content \
1647
+ --project-dir=./compute-js \
1648
+ --collection-name=staging
1649
+ ```
1650
+
1651
+ With `--project-dir`, all relative paths are relative to that directory: the paths in `static-publish.rc.js` and `publish-content.config.js`, and also the paths in the other options (for example `--config` and `--root-dir`). The directory must have a `static-publish.rc.js` (an app) or a `static-publish.project.js` (a [managed project](#managed-projects)). To scaffold an app in another directory, use `--output`.
1652
+
1653
+ To print the version of this package, run `npx @fastly/compute-js-static-publish --version`. It works in any directory.
1654
+
1655
+ With `--non-interactive`, or when the `CI` environment variable is set, the CLI never asks for input: missing input is an error. `deploy` then also runs the Fastly CLI with `--non-interactive`. The output never shows the values of `--fastly-api-token`, `--s3-secret-access-key`, `FASTLY_API_TOKEN`, and `S3_SECRET_ACCESS_KEY`.
1656
+
1657
+ For `--json`, the exit codes, and the error codes, see [Using the CLI in CI](#-using-the-cli-in-ci).
1658
+
1659
+ #### `publish-content`
1660
+
1661
+ ```sh
1662
+ npx @fastly/compute-js-static-publish publish-content \
1663
+ [--root-dir=./public] \
1664
+ [--collection-name=preview-42] \
1665
+ [--config=./publish-content.config.js] \
1666
+ [--expires-in=7d | --expires-at=2025-05-01T12:00Z | --expires-never] \
1667
+ [--overwrite-existing] \
1668
+ [--brotli-quality=<0-11>] \
1669
+ [--local] \
1670
+ [--fastly-api-token=...] \
1671
+ [--fastly-service-id=...] \
1672
+ [--purge-environment=production,staging] \
1673
+ [--s3-access-key-id=... --s3-secret-access-key=...] \
1674
+ [--verbose]
1675
+ ```
1676
+
1677
+ Publishes static files from your local root directory into a named collection, in the storage that `static-publish.rc.js` specifies: the Fastly KV Store, S3-compatible storage (BETA), or a local dev directory (`--local`, KV Store mode only).
1678
+
1679
+ Before it scans your files, the command lists the files that are already in storage. Files that already exist with the same hash are not compressed or uploaded again. With the KV Store, a file larger than 20 MiB is stored in chunks, and the command uploads a chunk again if the chunk in storage does not have the correct size. Then the command uploads the remaining files in batches.
1680
+
1681
+ After this process is complete, the PublisherServer object in the Compute application will see the updated index of files and updated server settings from the `publish-content.config.js` file.
1682
+
1683
+ ##### Options:
1684
+
1685
+ - `--collection-name`: Name of the collection to create/update (default: value in `static-publish.rc.js`)
1686
+ - `--config`: Path to a config file to configure server behavior for this collection (default: `./publish-content.config.js`)
1687
+ - `--root-dir`: Source directory to read files from (overrides value in `publish-content.config.js`)
1688
+ - `--overwrite-existing`: Always upload all files, even if they are already in storage. `--kv-overwrite` is an alias.
1689
+ - `--brotli-quality`: Brotli quality for the `br` variants, an integer from 0 to 11. Overrides `brotliQuality` in `publish-content.config.js`. This is useful in CI, where the config file is generated at each run.
1690
+ - `--fastly-service-id`: The Fastly Service ID to purge after publishing. The command purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached copies of the collection's settings, index, files, and responses (see [response cache](#️-caching-responses-with-the-core-cache)). If not set, the tool will check:
1691
+ - **`FASTLY_SERVICE_ID` environment variable**
1692
+ - `service_id` in `fastly.toml`
1693
+
1694
+ If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the content is already published.
1695
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list (`--purge-environment=production,staging`). You can also repeat the option. Purge `staging` if you test the collection on a [staged service version](https://www.fastly.com/documentation/guides/getting-started/services/working-with-staging/), because a purge without it does not clear the staging cache. If the service has no staged version, there is nothing to purge in `staging`. The API then gives the same error as for a service ID that is not correct, so the command shows a message for both causes, not a warning.
1696
+ - `--verbose`: Verbose mode. When enabled, the command logs a line for each file that the command scans, and for each upload. Without this option, the command logs the progress after each 1,000 files or uploads.
1697
+
1698
+ **Expiration:**
1699
+
1700
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
1701
+ - `--expires-at`: Absolute expiration time (ISO format: `2025-05-01T12:00Z`)
1702
+ - `--expires-never`: Collection never expires
1703
+
1704
+ *At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*
1705
+
1706
+ **KV Store Options:**
1707
+
1708
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1709
+
1710
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1711
+
1712
+ **S3 Storage Options (BETA):**
1713
+
1714
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1715
+ - `--s3-upload-concurrency`: Number of objects to upload at the same time, from 1 to 256 (default: 64). Each upload keeps its file in memory, so a site with many large files can need a lower value.
1716
+
1717
+ #### `clean`
1718
+
1719
+ ```sh
1720
+ npx @fastly/compute-js-static-publish clean \
1721
+ [--delete-expired-collections] \
1722
+ [--dry-run]
1723
+ ```
1724
+
1725
+ Cleans up expired or unreferenced items in storage (KV Store or S3-compatible storage).
1726
+ This can include expired collection indexes and orphaned content assets.
1727
+
1728
+ ##### Options:
1729
+
1730
+ - `--delete-expired-collections`: If set, expired collection index files will be deleted.
1731
+ - `--dry-run`: Show what would be deleted without performing any deletions.
1732
+
1733
+ **KV Store Options:**
1734
+
1735
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1736
+
1737
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1738
+
1739
+ **S3 Storage Options (BETA):**
1740
+
1741
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1742
+
1743
+ #### `collections list`
1744
+
1745
+ ```sh
1746
+ npx @fastly/compute-js-static-publish collections list
1747
+ ```
1748
+ Lists all collections currently published in storage.
1749
+
1750
+ ##### Options:
1751
+
1752
+ **KV Store Options:**
1753
+
1754
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1755
+
1756
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1757
+
1758
+ **S3 Storage Options (BETA):**
1759
+
1760
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1761
+
1762
+ #### `collections promote`
1763
+
1764
+ ```sh
1765
+ npx @fastly/compute-js-static-publish collections promote \
1766
+ --collection-name=preview-42 \
1767
+ --to=live \
1768
+ [--expires-in=7d | --expires-at=2025-06-01T00:00Z | --expires-never]
1769
+ ```
1770
+ Copies an existing collection (content + config) to a new collection name.
1771
+
1772
+ If a Service ID is found, the command then purges the surrogate key `<publishId>-<collectionName>` of the target collection, so that the service stops serving cached responses of the old content. This uses the same options as [`publish-content`](#publish-content).
1773
+
1774
+ ##### Options:
1775
+
1776
+ - `--collection-name`: The name of the source collection to promote (required)
1777
+ - `--to`: The name of the new (target) collection to create or overwrite (required)
1778
+
1779
+ **Expiration:**
1780
+
1781
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
1782
+ - `--expires-at`: Absolute expiration time (ISO format)
1783
+ - `--expires-never`: Collection never expires
1784
+
1785
+ *At most one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** may be specified*. If not provided, then the existing expiration rule of the collection being promoted is used.
1786
+
1787
+ **KV Store Options:**
1788
+
1789
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1790
+
1791
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1792
+
1793
+ **Purge Options:**
1794
+
1795
+ - `--fastly-service-id`: The Fastly Service ID to purge after promoting. If not set, the tool checks the `FASTLY_SERVICE_ID` environment variable, then `service_id` in `fastly.toml`. If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`), also in S3 mode. With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the collection is already promoted.
1796
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
1797
+
1798
+ **S3 Storage Options (BETA):**
1799
+
1800
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1801
+
1802
+ #### `collections update-expiration`
1803
+
1804
+ ```sh
1805
+ npx @fastly/compute-js-static-publish collections update-expiration \
1806
+ --collection-name=preview-42 \
1807
+ --expires-in=3d | --expires-at=2025-06-01T00:00Z | --expires-never
1808
+ ```
1809
+ Sets or updates the expiration time of an existing collection.
1810
+
1811
+ ##### Options:
1812
+ - `--collection-name`: The name of the collection to update (required)
1813
+
1814
+ **Expiration:**
1815
+
1816
+ - `--expires-in`: Time-to-live from now (e.g. `1h`, `2d`, `1w`)
1817
+ - `--expires-at`: Absolute expiration time (ISO format)
1818
+ - `--expires-never`: Collection never expires
1819
+
1820
+ *Exactly one of **`--expires-in`**, **`--expires-at`**, or **`--expires-never`** must be specified*
1821
+
1822
+ **KV Store Options:**
1823
+
1824
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1825
+
1826
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1827
+
1828
+ **S3 Storage Options (BETA):**
1829
+
1830
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1831
+
1832
+ #### `collections delete`
1833
+
1834
+ ```sh
1835
+ npx @fastly/compute-js-static-publish collections delete \
1836
+ --collection-name=preview-42
1837
+ ```
1838
+
1839
+ Deletes a collection index from storage. The content files will remain as they may still be referenced by other collection indexes.
1840
+
1841
+ Use the `npx @fastly/compute-js-static-publish clean` command afterward to remove content files that are no longer referenced by any collection.
1842
+
1843
+ If a Service ID is found, the command then purges the surrogate key `<publishId>-<collectionName>`, so that the service stops serving cached responses of the deleted collection. This uses the same options as [`publish-content`](#publish-content).
1844
+
1845
+ ##### Options:
1846
+
1847
+ - `--collection-name`: The name of the collection to delete (required)
1848
+
1849
+ - `--fastly-service-id`: The Fastly Service ID to purge after deleting. If not set, the tool checks the `FASTLY_SERVICE_ID` environment variable, then `service_id` in `fastly.toml`. If none is found, the command skips the purge. The purge also needs an API token (see `--fastly-api-token`). With `--local`, there is no purge. If the purge fails, the command shows a warning and completes, because the collection is already deleted.
1850
+
1851
+ - `--purge-environment`: The environments to purge: `production` (the default), `staging`, or both, as a comma-separated list. You can also repeat the option.
1852
+
1853
+ **KV Store Options:**
1854
+
1855
+ - `--local`: Instead of working with the Fastly KV Store, operate on local files that will be used to simulate the KV Store with the local development environment. KV Store mode only. In S3 mode, `--local` is an error, because there is no local simulation of S3 storage.
1856
+
1857
+ - `--fastly-api-token`: API token to use when publishing. If not set, the tool uses the **`FASTLY_API_TOKEN` environment variable**.
1858
+
1859
+ **S3 Storage Options (BETA):**
1860
+
1861
+ - `--s3-access-key-id`, `--s3-secret-access-key`: Access key ID and secret access key for S3-compatible storage. If not set, the tool will check the `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY` environment variables.
1862
+
1863
+ ---
1864
+
1865
+ ## 📕 Appendix
1866
+
1867
+ ### fromCookie
1868
+
1869
+ `collectionSelector.fromCookie` is a utility function that enables the use of a browser
1870
+ cookie to select the active collection.
1871
+
1872
+ ```js
1873
+ import { collectionSelector } from '@fastly/compute-js-static-publish';
1874
+
1875
+ const { collectionName, redirectResponse } =
1876
+ collectionSelector.fromCookie(request, {
1877
+ // Everything here is optional – these are just examples
1878
+ cookieName: 'publisher-collection', // default
1879
+ activatePath: '/activate', // default
1880
+ resetPath: '/reset', // default
1881
+ cookieHttpOnly: true, // default
1882
+ cookieMaxAge: 60 * 60 * 24 * 7, // 7-days. default is `null`, never expires.
1883
+ cookiePath: '/', // default
1884
+ });
1885
+
1886
+ if (redirectResponse) {
1887
+ // honor the redirect
1888
+ return redirectResponse;
1889
+ }
1890
+
1891
+ // `collectionName` now holds the active collection (or `null` if none)
1892
+ ```
1893
+
1894
+ #### What it does, in plain English
1895
+
1896
+ 1. Reads a cookie
1897
+
1898
+ It looks for a cookie named cookieName (default `publisher-collection`) and hands you the value as `collectionName`.
1899
+
1900
+ 2. Handles two helper endpoints for you
1901
+
1902
+ | Endpoint | Purpose | Query params | Result |
1903
+ |------------------------------------|------------------|------------------------------------------------------------------------------------------------|-------------------------------------------|
1904
+ | activatePath (default `/activate`) | Set the cookie | `collection` (required) - name of the collection<br /> `redirectTo` (optional, `/` by default) | `308` redirect with a `Set-Cookie` header |
1905
+ | resetPath (default `/reset`) | Clear the cookie | `redirectTo` (optional, `/` by default) | `308` redirect that expires the cookie |
1906
+
1907
+ If a visitor accesses `/activate?collection=blue&redirectTo=/preview`, the helper will issue a redirect and drop `publisher-collection=blue` into their cookie jar.
1908
+ - If someone forgets `?collection=?`? Then `/activate` replies with HTTP `400`.
1909
+
1910
+ When the visitor hits `/reset`, the cookie is deleted.
1911
+
1912
+ > [!NOTE]
1913
+ > The collection that the cookie selects is not in the URL. Add `Cache-Control: private` to the responses of a preview, so that a shared cache does not store them. See [Shared caches](#shared-caches). With [`collectionSelection`](#-previews-collection-selection), `PublisherServer` does this for you.
1914
+
1915
+ 3. Safety flags are baked in
1916
+
1917
+ - `HttpOnly` is on by default (configurable), to help avoid XSS issues.
1918
+ - `Secure` is automatically added on HTTPS requests.
1919
+ - `SameSite=Lax` is always set – reasonable default for previews.
1920
+
1921
+ #### Option reference
1922
+
1923
+ | Option | Type | Default | Notes |
1924
+ |------------------|-------------------|--------------------------|------------------------------------------------|
1925
+ | `cookieName` | string | `'publisher-collection'` | Name of the cookie to read/write |
1926
+ | `activatePath` | string | `'/activate'` | Path that sets the cookie |
1927
+ | `resetPath` | string | `'/reset'` | Path that clears the cookie |
1928
+ | `cookieHttpOnly` | boolean | `true` | Turn off if the client-side needs to read it |
1929
+ | `cookieMaxAge` | number\|undefined | `undefined` | Seconds until expiry; omit for session cookies |
1930
+ | `cookiePath` | string | `'/'` | Path attribute in the cookie |
1931
+
1932
+ #### Example
1933
+
1934
+ `fromCookie` can be dropped into a Fastly Compute app:
1935
+
1936
+ ```js
1937
+ async function handleRequest(event) {
1938
+ const request = event.request;
1939
+
1940
+ // --- Cookie handling starts here
1941
+ const { collectionName, redirectResponse } = collectionSelector.fromCookie(request);
1942
+ if (redirectResponse) {
1943
+ // obey redirect first
1944
+ return redirectResponse;
1945
+ }
1946
+ publisherServer.setActiveCollectionName(collectionName); // null selects the default collection
1947
+ // --- Cookie handling ends here
1948
+
1949
+ // Regular routing follows...
1950
+ const response = await publisherServer.serveRequest(request);
1951
+ if (response != null) {
1952
+ return response;
1953
+ }
1954
+ return new Response('Not found', { status: 404 });
1955
+ }
1956
+ ```
1957
+
1958
+ ---
1959
+
1960
+ ## 📚 Next Steps
1961
+
1962
+ - View CLI command help: `npx @fastly/compute-js-static-publish --help`
1963
+ - Use in CI to automate branch previews
1964
+ - Visit [https://developer.fastly.com](https://developer.fastly.com) for Compute platform docs
1965
+
1966
+ ## Development
1967
+
1968
+ To build the package, run `npm run build`. To run the tests, see [test/README.md](./test/README.md).
1969
+
1970
+ In the code, its comments, and the docs for developers of this package, a **customer** is a developer who uses this package to publish a site, and a **visitor** is a person who opens the customer's site.
1971
+
1972
+ ## Issues
1973
+
1974
+ If you encounter any non-security-related bug or unexpected behavior, please [file an issue][bug] using the bug report template.
1975
+
1976
+ [bug]: https://github.com/fastly/compute-js-static-publish/issues/new?labels=bug
1977
+
1978
+ ### Security issues
1979
+
1980
+ Please see our [SECURITY.md](SECURITY.md) for guidance on reporting security-related issues.
1981
+
1982
+ ## License
1983
+
1984
+ [MIT](./LICENSE).