@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
@@ -10,14 +10,25 @@ import * as child_process from 'node:child_process';
10
10
  import * as path from 'node:path';
11
11
  import * as fs from 'node:fs';
12
12
  import { parseCommandLine } from '../../util/args.js';
13
- import { dotRelative, rootRelative } from '../../util/files.js';
14
- import { findComputeJsStaticPublisherVersion } from '../../util/package.js';
13
+ import { fail, recordFailure } from '../../util/output.js';
14
+ import { rootRelative } from '../../util/files.js';
15
+ import { findComputeJsStaticPublisherVersion, getOwnVersion } from '../../util/package.js';
16
+ import { runTemplateInit } from '../manage/template/init.js';
17
+ import { templateHasInit } from '../../managed/template-init.js';
15
18
  import { findHostnameForAwsS3RegionAndBucket } from '../../util/s3.js';
19
+ import { APP_TEMPLATE_NAMES, DEFAULT_APP_TEMPLATE_NAME, isAppTemplateName, loadAppTemplate, } from './app-template.js';
20
+ import { COLLECTION_SELECTION_FLAGS_HELP, collectionSelectionFromFlags } from '../../util/collection-selection-flags.js';
21
+ import { generateApp } from './generate-app.js';
22
+ import { renderProjectFile } from '../../managed/project-file.js';
23
+ import { dotRelative } from '../../util/files.js';
24
+ import { checkStaticPublisherWorkingDir } from '../../../models/config/static-publish-rc.js';
25
+ import { MANAGED_APP_DIR, PROJECT_FILE_NAME } from '../../../models/config/static-publish-project.js';
26
+ import { COLLECTION_NAME_RULE, isValidCollectionName } from '../../../models/collections/index.js';
16
27
  function help() {
17
28
  console.log(`\
18
29
 
19
30
  Usage:
20
- npx @fastly/compute-js-static-publish@latest [options]
31
+ npx @fastly/compute-js-static-publish@beta [options]
21
32
 
22
33
  Description:
23
34
  Scaffold a new Compute app configured for static publishing.
@@ -42,6 +53,13 @@ Options:
42
53
  --static-publisher-working-dir <dir> Working directory for build artifacts (default: <output>/static-publisher)
43
54
  (default: ./compute-js/static-publisher)
44
55
  --publish-id <id> Advanced. Prefix for KV keys (default: "default")
56
+ --default-collection-name <name> Collection to serve when none is selected (default: "live")
57
+ --template <name> The template of the app's code (default: "plain")
58
+ Valid templates: ${APP_TEMPLATE_NAMES.join(', ')}
59
+
60
+ --managed Write only static-publish.project.js (a managed project) in the
61
+ current directory, and add .static-publish/ and the working
62
+ directory to .gitignore. The CLI generates the app when it needs it.
45
63
 
46
64
  Compute Service Metadata:
47
65
  --name <name> App name (for fastly.toml)
@@ -52,12 +70,18 @@ Compute Service Metadata:
52
70
  Server Config:
53
71
  --public-dir <path> Deprecated. Base dir for content (default: root-dir)
54
72
  --static-dir <path>,<path...> Directory served with long TTL (can repeat)
55
- --spa <file> SPA fallback file (e.g., /index.html)
56
- --not-found-page <file> 404 fallback file (e.g., /404.html)
73
+ --spa <file> SPA fallback file, under --root-dir (e.g., ./public/index.html)
74
+ --not-found-page <file> 404 fallback file, under --root-dir (e.g., ./public/404.html)
75
+ (default: 404.html in --root-dir, if the file exists)
57
76
  --auto-index <name>,<name...> Index filename (e.g., index.html,index.htm)
58
77
  --auto-ext <ext>,<ext...> Automatic extensions (e.g., .html,.htm)
59
78
 
79
+ Collection Selection (previews):
80
+ ${COLLECTION_SELECTION_FLAGS_HELP}
81
+
60
82
  Other:
83
+ --version Print the version of this package and exit
84
+ --non-interactive Never ask a question (also on when CI is set)
61
85
  --verbose Enable verbose output
62
86
  -h, --help Show help
63
87
  `);
@@ -69,7 +93,7 @@ const defaultOptions = {
69
93
  staticDirs: [],
70
94
  staticPublisherWorkingDir: undefined,
71
95
  spa: undefined,
72
- notFoundPage: '[public-dir]/404.html',
96
+ notFoundPage: undefined,
73
97
  autoIndex: ['index.html', 'index.htm'],
74
98
  autoExt: ['.html', '.htm'],
75
99
  author: 'you@example.com',
@@ -77,11 +101,13 @@ const defaultOptions = {
77
101
  description: 'Fastly Compute static site',
78
102
  serviceId: undefined,
79
103
  publishId: undefined,
104
+ defaultCollectionName: undefined,
80
105
  storageMode: undefined,
81
106
  kvStoreName: undefined,
82
107
  s3Region: undefined,
83
108
  s3Bucket: undefined,
84
109
  s3Endpoint: undefined,
110
+ template: DEFAULT_APP_TEMPLATE_NAME,
85
111
  };
86
112
  function buildOptions(packageJson, commandLineOptions) {
87
113
  // Applied in this order for proper overriding
@@ -252,6 +278,18 @@ function buildOptions(packageJson, commandLineOptions) {
252
278
  options.description = description;
253
279
  }
254
280
  }
281
+ {
282
+ const defaultCollectionNameValue = commandLineOptions['default-collection-name'];
283
+ if (typeof defaultCollectionNameValue === 'string') {
284
+ options.defaultCollectionName = defaultCollectionNameValue;
285
+ }
286
+ }
287
+ {
288
+ const templateValue = commandLineOptions['template'];
289
+ if (typeof templateValue === 'string') {
290
+ options.template = templateValue;
291
+ }
292
+ }
255
293
  {
256
294
  let serviceId;
257
295
  const serviceIdValue = commandLineOptions['service-id'];
@@ -358,6 +396,11 @@ export async function action(actionArgs) {
358
396
  { name: 'author', type: String, },
359
397
  // Fastly Service ID to be added to the fastly.toml that is generated.
360
398
  { name: 'service-id', type: String },
399
+ // The template of the app's code.
400
+ { name: 'template', type: String, },
401
+ // The collection to serve when no collection is selected.
402
+ // If not provided, the default value of 'live' is used.
403
+ { name: 'default-collection-name', type: String, },
361
404
  // Required. The 'root' directory for the publishing.
362
405
  // All assets are expected to exist under this root. Required.
363
406
  // For backwards compatibility, if this value is not provided,
@@ -398,13 +441,20 @@ export async function action(actionArgs) {
398
441
  // List of extensions to apply to a path name, for example, if
399
442
  // http://example.com/about is requested, we can respond with http://example.com/about.html
400
443
  { name: 'auto-ext', type: String, multiple: true, },
444
+ // Collection selection. See util/collection-selection-flags.ts.
445
+ { name: 'collection-selection', type: String, multiple: true, },
446
+ { name: 'collection-allow', type: String, multiple: true, },
447
+ { name: 'collection-on-missing', type: String, },
448
+ { name: 'collection-noindex', type: String, },
449
+ // Write static-publish.project.js (a managed project) in place of the app.
450
+ { name: 'managed', type: Boolean, },
401
451
  ];
402
452
  const parsed = parseCommandLine(actionArgs, optionDefinitions);
403
453
  if (parsed.needHelp) {
404
454
  if (parsed.error != null) {
405
455
  console.error(String(parsed.error));
406
456
  console.error();
407
- process.exitCode = 1;
457
+ recordFailure('usage', String(parsed.error));
408
458
  }
409
459
  help();
410
460
  return;
@@ -419,25 +469,44 @@ export async function action(actionArgs) {
419
469
  packageJson = null;
420
470
  }
421
471
  const options = buildOptions(packageJson, parsed.commandLineOptions);
422
- const COMPUTE_JS_DIR = options.outputDir;
472
+ if (!isAppTemplateName(options.template)) {
473
+ fail('usage', `Unknown template '${options.template}'.`);
474
+ console.error(` * Valid templates: ${APP_TEMPLATE_NAMES.join(', ')}`);
475
+ return;
476
+ }
477
+ const { collectionSelection, errors: collectionSelectionErrors } = collectionSelectionFromFlags({
478
+ sources: parsed.commandLineOptions['collection-selection'],
479
+ allow: parsed.commandLineOptions['collection-allow'],
480
+ onMissing: parsed.commandLineOptions['collection-on-missing'],
481
+ noindex: parsed.commandLineOptions['collection-noindex'],
482
+ });
483
+ if (collectionSelectionErrors.length > 0) {
484
+ for (const error of collectionSelectionErrors) {
485
+ console.error(`❌ ${error}`);
486
+ }
487
+ recordFailure('usage', collectionSelectionErrors.join(' '));
488
+ return;
489
+ }
490
+ // A managed project: the project dir is the current directory. The CLI
491
+ // generates the app in .static-publish/app when it needs it.
492
+ const managed = parsed.commandLineOptions['managed'] === true;
493
+ const projectDir = path.resolve();
494
+ const COMPUTE_JS_DIR = managed ? MANAGED_APP_DIR : options.outputDir;
423
495
  if (COMPUTE_JS_DIR == null) {
424
- console.error("❌ required parameter --output not provided.");
425
- process.exitCode = 1;
496
+ fail('usage', "required parameter --output not provided.");
426
497
  return;
427
498
  }
428
499
  const computeJsDir = path.resolve(COMPUTE_JS_DIR);
429
500
  // Resolve the root dir, relative to current directory, and make sure it exists.
430
501
  const ROOT_DIR = options.rootDir;
431
502
  if (ROOT_DIR == null) {
432
- console.error("❌ required parameter --root-dir not provided.");
433
- process.exitCode = 1;
503
+ fail('usage', "required parameter --root-dir not provided.");
434
504
  return;
435
505
  }
436
506
  const rootDir = path.resolve(ROOT_DIR);
437
507
  if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
438
- console.error(`❌ Specified root directory '${ROOT_DIR}' does not exist.`);
508
+ fail('usage', `Specified root directory '${ROOT_DIR}' does not exist.`);
439
509
  console.error(` * ${rootRelative(rootDir)} must exist and be a directory.`);
440
- process.exitCode = 1;
441
510
  return;
442
511
  }
443
512
  if (options.publicDir != null) {
@@ -448,16 +517,14 @@ export async function action(actionArgs) {
448
517
  const PUBLIC_DIR = options.publicDir ?? ROOT_DIR;
449
518
  const publicDir = path.resolve(PUBLIC_DIR);
450
519
  if (!fs.existsSync(publicDir) || !fs.statSync(publicDir).isDirectory()) {
451
- console.error(`❌ Specified public directory '${PUBLIC_DIR}' does not exist.`);
520
+ fail('usage', `Specified public directory '${PUBLIC_DIR}' does not exist.`);
452
521
  console.error(` * ${rootRelative(publicDir)} must exist and be a directory.`);
453
- process.exitCode = 1;
454
522
  return;
455
523
  }
456
524
  // Public dir must be inside the root dir.
457
525
  if (!publicDir.startsWith(rootDir)) {
458
- console.error(`❌ Specified public directory '${PUBLIC_DIR}' is not under the asset root directory.`);
526
+ fail('usage', `Specified public directory '${PUBLIC_DIR}' is not under the asset root directory.`);
459
527
  console.error(` * ${rootRelative(publicDir)} must be under ${rootRelative(rootDir)}`);
460
- process.exitCode = 1;
461
528
  return;
462
529
  }
463
530
  // Static dirs must be inside the public dir.
@@ -481,17 +548,25 @@ export async function action(actionArgs) {
481
548
  // Static Publisher Working Root Dir must be under the current dir
482
549
  // This comes in relative to cwd.
483
550
  const STATIC_PUBLISHER_WORKING_DIR = options.staticPublisherWorkingDir ??
484
- path.resolve(computeJsDir, './static-publisher');
551
+ path.resolve(managed ? projectDir : computeJsDir, './static-publisher');
485
552
  const staticPublisherWorkingDir = path.resolve(STATIC_PUBLISHER_WORKING_DIR);
486
- if (!staticPublisherWorkingDir.startsWith(computeJsDir) ||
553
+ if (managed) {
554
+ // In a managed project, the working dir is relative to the project file.
555
+ const workingDirError = checkStaticPublisherWorkingDir(dotRelative(projectDir, staticPublisherWorkingDir).split(path.sep).join('/'));
556
+ if (workingDirError != null || staticPublisherWorkingDir.startsWith(path.resolve(projectDir, '.static-publish') + path.sep)) {
557
+ fail('usage', `Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' is not valid.`);
558
+ console.error(` * It must not be the project directory, a directory above it, or in .static-publish.`);
559
+ return;
560
+ }
561
+ }
562
+ else if (!staticPublisherWorkingDir.startsWith(computeJsDir) ||
487
563
  staticPublisherWorkingDir === computeJsDir ||
488
564
  staticPublisherWorkingDir === path.resolve(computeJsDir, './bin') ||
489
565
  staticPublisherWorkingDir === path.resolve(computeJsDir, './pkg') ||
490
566
  staticPublisherWorkingDir === path.resolve(computeJsDir, './src') ||
491
567
  staticPublisherWorkingDir === path.resolve(computeJsDir, './node_modules')) {
492
- console.error(`❌ Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' must be under ${rootRelative(computeJsDir)}.`);
568
+ fail('usage', `Specified static publisher working directory '${rootRelative(staticPublisherWorkingDir)}' must be under ${rootRelative(computeJsDir)}.`);
493
569
  console.error(` It also must not be bin, pkg, src, or node_modules.`);
494
- process.exitCode = 1;
495
570
  return;
496
571
  }
497
572
  // SPA and Not Found are relative to the asset root dir.
@@ -502,14 +577,15 @@ export async function action(actionArgs) {
502
577
  spaFilename = processPublicDirToken(SPA, publicDir);
503
578
  // At any rate it must exist under the root directory
504
579
  if (!spaFilename.startsWith(rootDir)) {
505
- console.log(`⚠️ Ignoring specified SPA file '${SPA}' as is not under the asset root directory.`);
506
- console.log(` * ${rootRelative(spaFilename)} is not under ${rootRelative(rootDir)}`);
507
- spaFilename = undefined;
580
+ fail('usage', `Specified SPA file '${SPA}' is not under the asset root directory.`);
581
+ console.error(` * ${rootRelative(spaFilename)} must be under ${rootRelative(rootDir)}`);
582
+ console.error(` Give the path from the current directory, for example ${rootRelative(rootDir)}/index.html.`);
583
+ return;
508
584
  }
509
- else if (!fs.existsSync(spaFilename)) {
510
- console.log(`⚠️ Warning: Ignoring specified SPA file '${SPA}' does not exist.`);
511
- console.log(` * ${rootRelative(spaFilename)} does not exist.`);
512
- spaFilename = undefined;
585
+ if (!fs.existsSync(spaFilename)) {
586
+ fail('usage', `Specified SPA file '${SPA}' does not exist.`);
587
+ console.error(` * ${rootRelative(spaFilename)} does not exist.`);
588
+ return;
513
589
  }
514
590
  }
515
591
  const NOT_FOUND_PAGE = options.notFoundPage;
@@ -519,26 +595,33 @@ export async function action(actionArgs) {
519
595
  notFoundPageFilename = processPublicDirToken(NOT_FOUND_PAGE, publicDir);
520
596
  // At any rate it must exist under the root directory
521
597
  if (!notFoundPageFilename.startsWith(rootDir)) {
522
- console.log(`⚠️ Ignoring specified Not Found file '${NOT_FOUND_PAGE}' as is not under the asset root directory.`);
523
- console.log(` * ${rootRelative(notFoundPageFilename)} is not under ${rootRelative(rootDir)}`);
524
- notFoundPageFilename = undefined;
598
+ fail('usage', `Specified Not Found file '${NOT_FOUND_PAGE}' is not under the asset root directory.`);
599
+ console.error(` * ${rootRelative(notFoundPageFilename)} must be under ${rootRelative(rootDir)}`);
600
+ console.error(` Give the path from the current directory, for example ${rootRelative(rootDir)}/404.html.`);
601
+ return;
525
602
  }
526
- else if (!fs.existsSync(notFoundPageFilename)) {
527
- console.log(`⚠️ Warning: Ignoring specified Not Found file '${NOT_FOUND_PAGE}' as it does not exist.`);
528
- console.log(` * ${rootRelative(notFoundPageFilename)} does not exist.`);
529
- notFoundPageFilename = undefined;
603
+ if (!fs.existsSync(notFoundPageFilename)) {
604
+ fail('usage', `Specified Not Found file '${NOT_FOUND_PAGE}' does not exist.`);
605
+ console.error(` * ${rootRelative(notFoundPageFilename)} does not exist.`);
606
+ return;
607
+ }
608
+ }
609
+ else {
610
+ // Without --not-found-page, use 404.html in the public directory if it exists.
611
+ const defaultNotFoundPageFilename = processPublicDirToken('[public-dir]/404.html', publicDir);
612
+ if (fs.existsSync(defaultNotFoundPageFilename)) {
613
+ notFoundPageFilename = defaultNotFoundPageFilename;
530
614
  }
531
615
  }
532
616
  const autoIndex = options.autoIndex;
533
617
  const autoExt = options.autoExt;
534
- const exists = fs.existsSync(computeJsDir);
618
+ const exists = !managed && fs.existsSync(computeJsDir);
535
619
  if (exists) {
536
- console.error(`❌ '${COMPUTE_JS_DIR}' directory already exists!`);
620
+ fail('usage', `'${COMPUTE_JS_DIR}' directory already exists!`);
537
621
  console.error(` You should not run this command if this directory exists.`);
538
622
  console.error(` If you need to re-scaffold the static publisher Compute App,`);
539
623
  console.error(` delete the following directory and then try again:`);
540
624
  console.error(` ${rootRelative(computeJsDir)}`);
541
- process.exitCode = 1;
542
625
  return;
543
626
  }
544
627
  const author = options.author;
@@ -547,8 +630,7 @@ export async function action(actionArgs) {
547
630
  const fastlyServiceId = options.serviceId;
548
631
  const storageMode = options.storageMode;
549
632
  if (!(storageMode === 'kv-store' || storageMode === 's3')) {
550
- console.error(`❌ parameter --storage-mode must be set to 'kv-store' or 's3'.`);
551
- process.exitCode = 1;
633
+ fail('usage', `parameter --storage-mode must be set to 'kv-store' or 's3'.`);
552
634
  return;
553
635
  }
554
636
  const kvStoreName = options.kvStoreName;
@@ -558,20 +640,17 @@ export async function action(actionArgs) {
558
640
  let s3EndpointGenerated = false;
559
641
  if (storageMode === 'kv-store') {
560
642
  if (kvStoreName == null) {
561
- console.error(`❌ required parameter --kv-store-name not provided.`);
562
- process.exitCode = 1;
643
+ fail('usage', `required parameter --kv-store-name not provided.`);
563
644
  return;
564
645
  }
565
646
  }
566
647
  else if (storageMode === 's3') {
567
648
  if (s3Region == null) {
568
- console.error(`❌ required parameter --s3-region not provided.`);
569
- process.exitCode = 1;
649
+ fail('usage', `required parameter --s3-region not provided.`);
570
650
  return;
571
651
  }
572
652
  if (s3Bucket == null) {
573
- console.error(`❌ required parameter --s3-bucket not provided.`);
574
- process.exitCode = 1;
653
+ fail('usage', `required parameter --s3-bucket not provided.`);
575
654
  return;
576
655
  }
577
656
  let s3Endpoint = options.s3Endpoint;
@@ -585,8 +664,7 @@ export async function action(actionArgs) {
585
664
  console.log('✅ S3 endpoint resolved:', s3Endpoint);
586
665
  }
587
666
  else {
588
- console.error(`❌ Unable to resolve S3 endpoint from region '${s3Region}' and bucket '${s3Bucket}.`);
589
- process.exitCode = 1;
667
+ fail('failed', `Unable to resolve S3 endpoint from region '${s3Region}' and bucket '${s3Bucket}'.`);
590
668
  return;
591
669
  }
592
670
  s3EndpointUrl = new URL(`https://${s3Endpoint}/`);
@@ -601,8 +679,7 @@ export async function action(actionArgs) {
601
679
  s3EndpointUrl = new URL(s3Endpoint);
602
680
  }
603
681
  catch {
604
- console.error(`❌ Unable to parse '${s3Endpoint}' as a valid URL.`);
605
- process.exitCode = 1;
682
+ fail('usage', `Unable to parse '${s3Endpoint}' as a valid URL.`);
606
683
  return;
607
684
  }
608
685
  }
@@ -611,7 +688,12 @@ export async function action(actionArgs) {
611
688
  if (publishId == null) {
612
689
  publishId = 'default';
613
690
  }
614
- const defaultCollectionName = 'live';
691
+ const defaultCollectionName = options.defaultCollectionName ?? 'live';
692
+ if (!isValidCollectionName(defaultCollectionName)) {
693
+ fail('collection-name-invalid', `parameter --default-collection-name is not a valid collection name: '${defaultCollectionName}'.`);
694
+ console.error(` * ${COLLECTION_NAME_RULE}`);
695
+ return;
696
+ }
615
697
  console.log('');
616
698
  console.log('Compute Application Settings');
617
699
  console.log('----------------------------');
@@ -620,6 +702,7 @@ export async function action(actionArgs) {
620
702
  console.log('author :', author);
621
703
  console.log('description :', description);
622
704
  console.log('Service ID :', fastlyServiceId ?? '(None)');
705
+ console.log('Template :', options.template);
623
706
  if (storageMode === 'kv-store') {
624
707
  console.log('Storage Mode : Fastly KV Store');
625
708
  console.log('KV Store Name :', kvStoreName);
@@ -649,257 +732,52 @@ export async function action(actionArgs) {
649
732
  console.log('Auto-Index :', autoIndex.length > 0 ? autoIndex : '(None)');
650
733
  console.log('Auto-Ext :', autoExt.length > 0 ? autoExt : '(None)');
651
734
  console.log('Static Files Dir :', staticDirs.length > 0 ? staticDirs.map(rootRelative) : '(None)');
735
+ console.log('Collection Selection :', collectionSelection != null ? collectionSelection.sources.map(x => x.type).join(', ') : '(None)');
652
736
  console.log('');
653
- console.log("Initializing Compute Application in " + computeJsDir + "...");
654
- fs.mkdirSync(computeJsDir);
655
- fs.mkdirSync(path.resolve(computeJsDir, './src'));
656
- const resourceFiles = {};
657
- // .gitignore
658
- resourceFiles['.gitignore'] = `\
659
- /node_modules
660
- /bin
661
- /pkg
662
- /${path.relative(computeJsDir, staticPublisherWorkingDir)}
663
- `;
664
- // package.json
665
- const computeJsStaticPublisherVersion = findComputeJsStaticPublisherVersion(packageJson);
666
- const packageJsonScripts = {
667
- 'dev:start': 'fastly compute serve',
668
- 'fastly:deploy': 'fastly compute publish',
669
- 'build': 'js-compute-runtime ./src/index.js ./bin/main.wasm',
670
- };
671
- if (storageMode === 'kv-store') {
672
- packageJsonScripts['dev:publish'] = 'npx @fastly/compute-js-static-publish publish-content --local';
673
- packageJsonScripts['fastly:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
674
- }
675
- else if (storageMode === 's3') {
676
- packageJsonScripts['s3:publish'] = 'npx @fastly/compute-js-static-publish publish-content';
677
- }
678
- resourceFiles['package.json'] = JSON.stringify({
737
+ const appConfig = {
738
+ appDir: computeJsDir,
679
739
  name,
680
- version: '0.1.0',
681
- description,
682
740
  author,
683
- type: 'module',
684
- devDependencies: {
685
- "@fastly/cli": "^16.0.0",
686
- '@fastly/compute-js-static-publish': computeJsStaticPublisherVersion,
687
- },
688
- dependencies: {
689
- '@fastly/js-compute': '^4.0.0',
690
- },
691
- engines: {
692
- node: '>=20.11.0',
741
+ description,
742
+ serviceId: fastlyServiceId,
743
+ storage: storageMode === 'kv-store' ?
744
+ { mode: 'kv-store', kvStoreName: kvStoreName } :
745
+ { mode: 's3', region: s3Region, bucket: s3Bucket, endpointUrl: String(s3EndpointUrl), endpointGenerated: s3EndpointGenerated },
746
+ publishId,
747
+ defaultCollectionName,
748
+ staticPublisherWorkingDir,
749
+ rootDir,
750
+ publicDir,
751
+ staticDirs,
752
+ spaFilename,
753
+ notFoundPageFilename,
754
+ autoIndex,
755
+ autoExt,
756
+ staticPublishVersionSpec: findComputeJsStaticPublisherVersion(packageJson),
757
+ template: loadAppTemplate(options.template),
758
+ // The hono template: the extensions folder is in the directory where
759
+ // scaffold runs (next to the app, or next to the project file).
760
+ ...(options.template === 'hono' ? { build: { hono: { extensionsDir: path.resolve('hono-extensions') } } } : {}),
761
+ generatedFrom: {
762
+ template: options.template,
763
+ staticPublishVersion: getOwnVersion(),
764
+ generatedAt: new Date().toISOString().slice(0, 10),
693
765
  },
694
- private: true,
695
- scripts: packageJsonScripts,
696
- }, undefined, 2);
697
- // fastly.toml
698
- let fastlyTomlLocalServer = '';
699
- let fastlyTomlSetup = '';
700
- if (storageMode === 'kv-store') {
701
- const localServerKvStorePath = dotRelative(computeJsDir, path.resolve(staticPublisherWorkingDir, 'kvstore.json'));
702
- fastlyTomlLocalServer = /* language=text */ `\
703
- [local_server]
704
-
705
- [local_server.kv_stores]
706
- ${kvStoreName} = { file = "${localServerKvStorePath}", format = "json" }
707
- `;
708
- fastlyTomlSetup = /* language=text */ `\
709
- [setup]
710
-
711
- [setup.kv_stores]
712
- [setup.kv_stores.${kvStoreName}]
713
- `;
714
- // kvstore.json
715
- resourceFiles[localServerKvStorePath] = '{}';
716
- }
717
- else if (storageMode === 's3') {
718
- fastlyTomlLocalServer = /* language=text */ `\
719
- [local_server]
720
-
721
- [local_server.secret_stores]
722
- [[local_server.secret_stores.S3_CREDENTIALS]]
723
- key = "S3_ACCESS_KEY_ID"
724
- env = "S3_ACCESS_KEY_ID"
725
- [[local_server.secret_stores.S3_CREDENTIALS]]
726
- key = "S3_SECRET_ACCESS_KEY"
727
- env = "S3_SECRET_ACCESS_KEY"
728
-
729
- [local_server.backends]
730
- [local_server.backends.s3_storage]
731
- url = "${String(s3EndpointUrl)}"
732
- override_host = "${s3EndpointUrl.hostname}"
733
- `;
734
- fastlyTomlSetup = /* language=text */ `\
735
- [setup]
736
-
737
- [setup.backends]
738
- [setup.backends.s3_storage]
739
- address = "${s3EndpointUrl.hostname}"
740
- description = "S3 API endpoint"
741
- port = 443
742
- [setup.secret_stores]
743
- [setup.secret_stores.S3_CREDENTIALS]
744
- description = "Credentials for S3 storage"
745
- [setup.secret_stores.S3_CREDENTIALS.entries]
746
- [setup.secret_stores.S3_CREDENTIALS.entries.S3_ACCESS_KEY_ID]
747
- description = "Access Key ID"
748
- [setup.secret_stores.S3_CREDENTIALS.entries.S3_SECRET_ACCESS_KEY]
749
- description = "Secret Access Key"
750
- `;
751
- }
752
- resourceFiles['fastly.toml'] = /* language=text */ `\
753
- # This file describes a Fastly Compute package. To learn more visit:
754
- # https://developer.fastly.com/reference/fastly-toml/
755
-
756
- authors = [ "${author}" ]
757
- description = "${description}"
758
- language = "javascript"
759
- manifest_version = 3
760
- name = "${name}"
761
- ${fastlyServiceId != null ? `service_id = "${fastlyServiceId}"\n` : ''}
762
- [scripts]
763
- build = "npm run build"
764
-
765
- ${fastlyTomlLocalServer}
766
- ${fastlyTomlSetup}
767
- `;
768
- // static-publish.rc.js
769
- let staticPublishStorage = '';
770
- if (storageMode === 'kv-store') {
771
- staticPublishStorage = `\
772
- storageMode: "kv-store",
773
- kvStore: {
774
- kvStoreName: ${JSON.stringify(kvStoreName)},
775
- },\
776
- `;
766
+ collectionSelection,
767
+ };
768
+ if (managed) {
769
+ writeManagedProject(appConfig, projectDir);
770
+ // The app is not installed yet, so template init uses the versions of the
771
+ // template's lockfile.
772
+ if (templateHasInit(options.template)) {
773
+ await runTemplateInit({ templateName: options.template, rc: {}, baseDir: projectDir, appNodeModulesDir: undefined });
774
+ }
775
+ return;
777
776
  }
778
- else if (storageMode === 's3') {
779
- staticPublishStorage = `\
780
- storageMode: "s3",
781
- s3: {
782
- region: ${JSON.stringify(s3Region)},
783
- bucket: ${JSON.stringify(s3Bucket)},\
784
- ` + (!s3EndpointGenerated ? `
785
- endpoint: ${JSON.stringify(String(s3EndpointUrl))},\
786
- ` : '') + `
787
- },\
788
- `;
789
- }
790
- resourceFiles['static-publish.rc.js'] = `\
791
- /*
792
- * Generated by @fastly/compute-js-static-publish.
793
- */
794
-
795
- /** @type {import('@fastly/compute-js-static-publish').StaticPublishRc} */
796
- const rc = {
797
- ${staticPublishStorage}
798
- publishId: ${JSON.stringify(publishId)},
799
- defaultCollectionName: ${JSON.stringify(defaultCollectionName)},
800
- staticPublisherWorkingDir: ${JSON.stringify(dotRelative(computeJsDir, staticPublisherWorkingDir))},
801
- };
802
-
803
- export default rc;
804
- `;
805
- // publish-content.config.js
806
- // publicDirPrefix -- if public dir is deeper than the root dir, then
807
- // public dir is used as a prefix to drill into asset names.
808
- // e.g.,
809
- // root dir : /path/to/root
810
- // public dir : /path/to/root/public
811
- // then publicDirPrefix = /public
812
- // We've already established publicDir.startsWith(rootDir)
813
- let publicDirPrefix = '';
814
- if (rootDir !== publicDir) {
815
- publicDirPrefix = publicDir.slice(rootDir.length);
816
- }
817
- // staticItems - specified as prefixes, relative to publicDir
818
- const staticItems = [];
819
- for (const staticDir of staticDirs) {
820
- // We've already established staticDir.startsWith(publicDir)
821
- let staticItem = staticDir.slice(publicDir.length);
822
- if (!staticItem.endsWith('/')) {
823
- // Ending with a slash denotes that this is a directory.
824
- staticItem = staticItem + '/';
825
- }
826
- staticItems.push(staticItem);
827
- }
828
- // spaFile - asset key of spa file
829
- let spaFile = false;
830
- if (spaFilename != null) {
831
- // We've already established spaFilename.startsWith(rootDir)
832
- // and that it exists
833
- spaFile = spaFilename.slice(rootDir.length);
834
- }
835
- let notFoundPageFile = false;
836
- if (notFoundPageFilename != null) {
837
- // We've already established notFoundPageFilename.startsWith(rootDir)
838
- // and that it exists
839
- notFoundPageFile = notFoundPageFilename.slice(rootDir.length);
840
- }
841
- resourceFiles['publish-content.config.js'] = `\
842
- /*
843
- * Generated by @fastly/compute-js-static-publish.
844
- */
845
-
846
- // Commented items are defaults, feel free to modify and experiment!
847
- // See README for a detailed explanation of the configuration options.
848
-
849
- /** @type {import('@fastly/compute-js-static-publish').PublishContentConfig} */
850
- const config = {
851
- rootDir: ${JSON.stringify(dotRelative(computeJsDir, rootDir))},
852
- // excludeDirs: [ './node_modules' ],
853
- // excludeDotFiles: true,
854
- // includeWellKnown: true,
855
- // assetInclusionTest: (assetKey) => true,
856
- // contentCompression: [ 'br', 'gzip' ],
857
- // brotliQuality: 11,
858
- // contentTypes: [
859
- // { test: /.custom$/, contentType: 'application/x-custom', text: false },
860
- // ],
861
-
862
- // Server settings are saved to storage per collection
863
- server: {${publicDirPrefix !== '' ? `
864
- publicDirPrefix: ${JSON.stringify(publicDirPrefix)},` : ''}
865
- staticItems: ${JSON.stringify(staticItems)},
866
- allowedEncodings: [ 'br', 'gzip' ],
867
- spaFile: ${JSON.stringify(spaFile)},
868
- notFoundPageFile: ${JSON.stringify(notFoundPageFile)},
869
- autoExt: ${JSON.stringify(autoExt)},
870
- autoIndex: ${JSON.stringify(autoIndex)},
871
- },
872
- };
873
-
874
- export default config;
875
- `;
876
- // src/index.js
877
- resourceFiles['./src/index.js'] = /* language=text */ `\
878
- /// <reference types="@fastly/js-compute" />
879
- import { env } from 'fastly:env';
880
- import { PublisherServer } from '@fastly/compute-js-static-publish';
881
- import rc from '../static-publish.rc.js';
882
- const publisherServer = PublisherServer.fromStaticPublishRc(rc);
883
-
884
- // eslint-disable-next-line no-restricted-globals
885
- addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
886
- async function handleRequest(event) {
887
-
888
- console.log('FASTLY_SERVICE_VERSION', env('FASTLY_SERVICE_VERSION'));
889
-
890
- const request = event.request;
891
-
892
- const response = await publisherServer.serveRequest(request);
893
- if (response != null) {
894
- return response;
895
- }
896
-
897
- // Do custom things here!
898
- // Handle API requests, serve non-static responses, etc.
899
-
900
- return new Response('Not found', { status: 404 });
901
- }
902
- `;
777
+ console.log("Initializing Compute Application in " + computeJsDir + "...");
778
+ fs.mkdirSync(computeJsDir);
779
+ fs.mkdirSync(path.resolve(computeJsDir, './src'));
780
+ const resourceFiles = generateApp(appConfig);
903
781
  // Write out the files
904
782
  for (const [filename, content] of Object.entries(resourceFiles)) {
905
783
  const filePath = path.resolve(computeJsDir, filename);
@@ -911,6 +789,16 @@ async function handleRequest(event) {
911
789
  console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
912
790
  child_process.spawnSync('npm', ['--prefix', COMPUTE_JS_DIR, 'install'], { stdio: 'inherit' });
913
791
  console.log('');
792
+ // The folder of the template (for the hono template: hono-extensions/, next
793
+ // to the app). It is in the directory where scaffold runs.
794
+ if (templateHasInit(options.template)) {
795
+ await runTemplateInit({
796
+ templateName: options.template,
797
+ rc: {},
798
+ baseDir: path.resolve(),
799
+ appNodeModulesDir: path.resolve(computeJsDir, 'node_modules'),
800
+ });
801
+ }
914
802
  if (storageMode === 'kv-store') {
915
803
  console.log(`
916
804
  To run your Compute application locally:
@@ -923,7 +811,11 @@ To build and deploy to your Compute service:
923
811
 
924
812
  cd ${COMPUTE_JS_DIR}
925
813
  npm run fastly:deploy
926
- npm run fastly:publish
814
+ FASTLY_API_TOKEN=xxxx npm run fastly:publish
815
+
816
+ fastly:publish reads the API token only from FASTLY_API_TOKEN or --fastly-api-token,
817
+ not from your Fastly CLI profile. To use the token of the Fastly CLI, type:
818
+ FASTLY_API_TOKEN=$(npx fastly auth token) npm run fastly:publish
927
819
 
928
820
  `);
929
821
  }
@@ -969,8 +861,55 @@ To build and deploy to your Compute service:
969
861
  If a Secret Store named 'S3_CREDENTIALS' already exists, the Fastly CLI asks for a
970
862
  different name. If you leave it empty, it uses the existing Secret Store. If you give
971
863
  a different name, the Fastly CLI uses it for the resource link too. Then call
972
- setSecretStoreForS3Credentials() with that name in src/index.js, and deploy again.
864
+ setSecretStoreForS3Credentials() with that name in ${appConfig.template.entry}, and deploy again.
865
+
866
+ After the deploy, fastly.toml has the service ID, so s3:publish also purges the
867
+ service's cache. For this purge, s3:publish needs FASTLY_API_TOKEN too.
973
868
 
974
869
  `);
975
870
  }
976
871
  }
872
+ // The lines that scaffold --managed adds to the .gitignore of the project dir.
873
+ const GITIGNORE_COMMENT = '# @fastly/compute-js-static-publish';
874
+ export function addGitignoreLines(existing, lines) {
875
+ const present = new Set((existing ?? '').split(/\r?\n/).map(x => x.trim()));
876
+ const added = lines.filter(line => !present.has(line));
877
+ if (added.length === 0) {
878
+ return { content: existing ?? '', added };
879
+ }
880
+ let content = existing ?? '';
881
+ if (content !== '' && !content.endsWith('\n')) {
882
+ content += '\n';
883
+ }
884
+ if (content !== '') {
885
+ content += '\n';
886
+ }
887
+ content += [GITIGNORE_COMMENT, ...added].join('\n') + '\n';
888
+ return { content, added };
889
+ }
890
+ function writeManagedProject(appConfig, projectDir) {
891
+ const projectFilePath = path.resolve(projectDir, PROJECT_FILE_NAME);
892
+ fs.writeFileSync(projectFilePath, renderProjectFile(appConfig, projectDir, getOwnVersion()), 'utf-8');
893
+ console.log(`🚀 Managed project created: ${rootRelative(projectFilePath)}`);
894
+ // Ignore the generated app and the working dir. Never change the customer's lines.
895
+ const gitignorePath = path.resolve(projectDir, '.gitignore');
896
+ const existing = fs.existsSync(gitignorePath) ? fs.readFileSync(gitignorePath, 'utf-8') : null;
897
+ const workingDir = path.relative(projectDir, appConfig.staticPublisherWorkingDir).split(path.sep).join('/');
898
+ const lines = ['/.static-publish/'];
899
+ if (!workingDir.startsWith('..')) {
900
+ lines.push(`/${workingDir}/`);
901
+ }
902
+ const { content, added } = addGitignoreLines(existing, lines);
903
+ if (added.length > 0) {
904
+ fs.writeFileSync(gitignorePath, content, 'utf-8');
905
+ console.log(`✔️ Added to ${existing == null ? 'a new ' : ''}.gitignore: ${added.join(', ')}`);
906
+ }
907
+ console.log(`
908
+ The CLI generates the Compute app from ${PROJECT_FILE_NAME}.
909
+ Commit ${PROJECT_FILE_NAME}. Do not commit .static-publish/.
910
+
911
+ To publish your content from this directory:
912
+
913
+ npx @fastly/compute-js-static-publish publish-content --local
914
+ `);
915
+ }