@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
@@ -4,14 +4,18 @@
4
4
  */
5
5
  /// <reference types="@fastly/js-compute" />
6
6
  import { CoreCache } from 'fastly:cache';
7
- import { decodeAssetVariantMetadata, } from '../../models/assets/index.js';
7
+ import { decodeAssetVariantMetadata, findAssetEntry, isHiddenIndexKey, } from '../../models/assets/index.js';
8
+ import { parseItemPatterns, testItemPatterns } from '../../models/config/item-patterns.js';
9
+ import { validateCollectionSelection, } from '../../models/config/collection-selection.js';
10
+ import { isSelectedByUrl, resolveCollection } from '../collection-selection/index.js';
8
11
  import { decodeIndexMetadata, getUnsupportedIndexFeatures } from '../../models/server/index.js';
9
12
  import { isExpired } from '../../models/time/index.js';
10
13
  import { loadStorageProviderFromStaticPublishRc, } from '../storage/storage-provider.js';
11
14
  import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
12
15
  import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
13
16
  import { ServerTiming } from '../util/server-timing.js';
14
- import { CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, readBodyUpTo, } from './response-cache.js';
17
+ import { requestAcceptsTextHtml } from './accept-html.js';
18
+ import { CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, bytesInPieces, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, readBodyUpTo, streamBytesInPieces, } from './response-cache.js';
15
19
  import { checkBodyLength } from '../util/body-length.js';
16
20
  export function buildHeadersSubset(responseHeaders, keys) {
17
21
  const resultHeaders = new Headers();
@@ -31,37 +35,68 @@ export function buildHeadersSubset(responseHeaders, keys) {
31
35
  // * Content-Location, Date, ETag, and Vary
32
36
  // * Cache-Control and Expires
33
37
  const headersToPreserveForUnmodified = ['Content-Location', 'ETag', 'Vary', 'Cache-Control', 'Expires'];
34
- function requestAcceptsTextHtml(req) {
35
- const accept = (req.headers.get('Accept') ?? '')
36
- .split(',')
37
- .map(x => x.split(';')[0]);
38
- if (!accept.includes('text/html') && !accept.includes('*/*') && accept.includes('*')) {
39
- return false;
40
- }
41
- return true;
38
+ // The response for a collection other than the default collection that is not
39
+ // published, or that expired. It can be published at any time, so no cache
40
+ // stores this response.
41
+ function collectionNotAvailableResponse(collectionName) {
42
+ return new Response(`Collection '${collectionName}' is not available. It is not published, or it expired.`, {
43
+ status: 404,
44
+ headers: {
45
+ 'content-type': 'text/plain',
46
+ 'x-content-type-options': 'nosniff',
47
+ 'cache-control': 'no-store',
48
+ },
49
+ });
42
50
  }
43
51
  export class PublisherServer {
44
52
  constructor(publishId, storageProvider, defaultCollectionName) {
53
+ // See setCollectionSelection().
54
+ this.collectionSelection = null;
45
55
  this.publishId = publishId;
46
56
  this.storageProvider = storageProvider;
47
57
  this.defaultCollectionName = defaultCollectionName;
48
58
  this.activeCollectionName = this.defaultCollectionName;
49
59
  this.collectionNameHeader = 'X-Publisher-Server-Collection';
50
60
  this.serverTimingRequestHeader = null;
51
- this.serverTiming = null;
52
61
  this.responseCache = null;
62
+ this.currentScope = this.newScope(this.activeCollectionName, null);
63
+ this.requestScopes = new WeakMap();
53
64
  }
54
65
  static fromStaticPublishRc(config) {
55
66
  const storeProvider = loadStorageProviderFromStaticPublishRc(config);
56
- return new PublisherServer(config.publishId, storeProvider, config.defaultCollectionName);
67
+ const server = new PublisherServer(config.publishId, storeProvider, config.defaultCollectionName);
68
+ server.setCollectionSelection(config.collectionSelection ?? null);
69
+ return server;
70
+ }
71
+ /**
72
+ * @deprecated Read-only. This returns the Server-Timing of the current request.
73
+ * It will be removed in v9.
74
+ */
75
+ get serverTiming() {
76
+ return this.currentScope.serverTiming;
77
+ }
78
+ /**
79
+ * @deprecated Read-only. This returns the settings that the current request
80
+ * read. Use getServerConfig().
81
+ * It will be removed in v9.
82
+ */
83
+ get settingsCached() {
84
+ return this.currentScope.settings;
85
+ }
86
+ /**
87
+ * @deprecated Read-only. This returns the index that the current request read.
88
+ * Use getAssetEntryMap().
89
+ * It will be removed in v9.
90
+ */
91
+ get assetEntryMapCache() {
92
+ return this.currentScope.assetEntryMap;
57
93
  }
58
94
  // null selects the default collection. A sandbox can be reused for more than
59
95
  // one request, so call this for each request, also when no collection is
60
96
  // selected. Otherwise, the collection of the previous request stays active.
61
97
  setActiveCollectionName(collectionName) {
62
98
  this.activeCollectionName = collectionName ?? this.defaultCollectionName;
63
- this.settingsCached = undefined;
64
- this.assetEntryMapCache = undefined;
99
+ this.currentScope = this.newScope(this.activeCollectionName, this.currentScope.serverTiming);
65
100
  }
66
101
  setCollectionNameHeader(collectionHeader) {
67
102
  this.collectionNameHeader = collectionHeader;
@@ -79,29 +114,84 @@ export class PublisherServer {
79
114
  setResponseCache(options) {
80
115
  this.responseCache = options;
81
116
  }
82
- // Start handling a new request. serveRequest() calls this. If you call
117
+ // The collectionSelection of static-publish.rc.js. fromStaticPublishRc() sets
118
+ // it. null (the default) turns collection selection off. Throws a TypeError if
119
+ // the config is not valid.
120
+ // With a config, a collection that is not the default collection, selected
121
+ // with the collectionName option of serveRequest() or serveFallback(), gets:
122
+ // - if it does not exist or has expired: onMissing ('not-found': a 404
123
+ // response; 'default': the default collection).
124
+ // - X-Robots-Tag: noindex (unless noindex is false).
125
+ // - Cache-Control: private, unless the collection comes from the URL (a host,
126
+ // path, or query source). See markPreviewResponse().
127
+ setCollectionSelection(config) {
128
+ if (config != null) {
129
+ const errors = validateCollectionSelection(config);
130
+ if (errors.length > 0) {
131
+ throw new TypeError(`Invalid collectionSelection:\n${errors.join('\n')}`);
132
+ }
133
+ }
134
+ this.collectionSelection = config;
135
+ }
136
+ // Choose the collection for a request with the collectionSelection config.
137
+ // If the result has a response, return it. Otherwise, pass its collectionName
138
+ // and pathname to serveRequest().
139
+ resolveCollection(request) {
140
+ return resolveCollection(request, this.collectionSelection);
141
+ }
142
+ // Start handling a new request. serveRequest() and serveFallback() call this. If you call
83
143
  // getMatchingAsset() and serveAsset() directly, call this first.
84
- // A sandbox can be reused for more than one request, so this also clears the
85
- // settings and the index that a previous request read. Without this, a reused
86
- // sandbox serves an old index after a publish, and serves an expired collection.
144
+ // A sandbox can be reused for more than one request, so this starts a new
145
+ // scope: the settings and the index that a previous request read are not used.
146
+ // Without this, a reused sandbox serves an old index after a publish, and
147
+ // serves an expired collection.
87
148
  beginRequest(request) {
88
- this.settingsCached = undefined;
89
- this.assetEntryMapCache = undefined;
149
+ this.beginRequestFor(request, undefined);
150
+ }
151
+ newServerTiming(request) {
90
152
  const header = this.serverTimingRequestHeader;
91
- this.serverTiming = header != null && request.headers.has(header) ? new ServerTiming() : null;
153
+ return header != null && request.headers.has(header) ? new ServerTiming() : null;
154
+ }
155
+ newScope(collectionName, serverTiming) {
156
+ return {
157
+ collectionName,
158
+ serverTiming,
159
+ settings: undefined,
160
+ assetEntryMap: undefined,
161
+ doNotStoreResponse: false,
162
+ };
163
+ }
164
+ // The scope of a request for a collection. A new request gets a new scope.
165
+ scopeForRequest(request, name) {
166
+ let scopes = this.requestScopes.get(request);
167
+ if (scopes == null) {
168
+ scopes = new Map();
169
+ this.requestScopes.set(request, scopes);
170
+ }
171
+ let scope = scopes.get(name);
172
+ if (scope == null) {
173
+ // All the collections of one request share one Server-Timing.
174
+ const otherScope = scopes.values().next().value;
175
+ scope = this.newScope(name, otherScope != null ? otherScope.serverTiming : this.newServerTiming(request));
176
+ scopes.set(name, scope);
177
+ }
178
+ return scope;
92
179
  }
93
- timed(name, fn) {
94
- return this.serverTiming != null ? this.serverTiming.measure(name, fn) : fn();
180
+ timed(scope, name, fn) {
181
+ return scope.serverTiming != null ? scope.serverTiming.measure(name, fn) : fn();
95
182
  }
96
183
  // Server config is obtained from storage, and cached until the next beginRequest()
97
184
  // or setActiveCollectionName().
98
185
  async getServerConfig() {
99
- if (this.settingsCached !== undefined) {
100
- return this.settingsCached;
186
+ return this.getServerConfigFor(this.currentScope);
187
+ }
188
+ async getServerConfigFor(scope) {
189
+ if (scope.settings !== undefined) {
190
+ return scope.settings;
101
191
  }
102
- const settingsFileKey = `${this.publishId}_settings_${this.activeCollectionName}`;
103
- this.settingsCached = await this.timed('settings', async () => {
104
- const settingsFile = await this.storageProvider.getEntry(settingsFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'settings']);
192
+ const settingsFileKey = `${this.publishId}_settings_${scope.collectionName}`;
193
+ scope.settings = await this.timed(scope, 'settings', async () => {
194
+ const settingsFile = await this.storageProvider.getEntry(settingsFileKey, [`${this.publishId}-${scope.collectionName}`, 'settings']);
105
195
  if (settingsFile == null) {
106
196
  console.error(`Settings File not found at ${settingsFileKey}.`);
107
197
  console.error(`You may need to publish your application.`);
@@ -109,37 +199,33 @@ export class PublisherServer {
109
199
  }
110
200
  return (await settingsFile.json());
111
201
  });
112
- return this.settingsCached;
202
+ return scope.settings;
113
203
  }
114
204
  async getStaticItems() {
115
- const serverConfig = await this.getServerConfig();
205
+ return this.getStaticItemsFor(this.currentScope);
206
+ }
207
+ async getStaticItemsFor(scope) {
208
+ const serverConfig = await this.getServerConfigFor(scope);
116
209
  if (serverConfig == null) {
117
210
  return [];
118
211
  }
119
- return serverConfig.staticItems
120
- .map((x, i) => {
121
- if (x.startsWith('re:')) {
122
- const fragments = x.slice(3).match(/\/(.*?)\/([a-z]*)?$/i);
123
- if (fragments == null) {
124
- console.warn(`Cannot parse staticItems item index ${i}: '${x}', skipping...`);
125
- return '';
126
- }
127
- return new RegExp(fragments[1], fragments[2] || '');
128
- }
129
- return x;
130
- })
131
- .filter(x => Boolean(x));
212
+ return parseItemPatterns(serverConfig.staticItems, (i, x) => {
213
+ console.warn(`Cannot parse staticItems item index ${i}: '${x}', skipping...`);
214
+ });
132
215
  }
133
216
  async getAssetEntryMap() {
134
- if (this.assetEntryMapCache !== undefined) {
135
- return this.assetEntryMapCache;
217
+ return this.getAssetEntryMapFor(this.currentScope);
218
+ }
219
+ async getAssetEntryMapFor(scope) {
220
+ if (scope.assetEntryMap !== undefined) {
221
+ return scope.assetEntryMap;
136
222
  }
137
- const indexFileKey = `${this.publishId}_index_${this.activeCollectionName}`;
138
- const indexFile = await this.timed('index', () => this.storageProvider.getEntry(indexFileKey, [`${this.publishId}-${this.activeCollectionName}`, 'index']));
223
+ const indexFileKey = `${this.publishId}_index_${scope.collectionName}`;
224
+ const indexFile = await this.timed(scope, 'index', () => this.storageProvider.getEntry(indexFileKey, [`${this.publishId}-${scope.collectionName}`, 'index']));
139
225
  if (indexFile == null) {
140
226
  console.error(`Index File not found at ${indexFileKey}.`);
141
227
  console.error(`You may need to publish your application.`);
142
- this.assetEntryMapCache = null;
228
+ scope.assetEntryMap = null;
143
229
  return null;
144
230
  }
145
231
  let metadata;
@@ -158,35 +244,48 @@ export class PublisherServer {
158
244
  if (unsupportedFeatures.length > 0) {
159
245
  console.error(`Collection at ${indexFileKey} requires features that this version of the server does not support: ${unsupportedFeatures.join(', ')}.`);
160
246
  console.error(`Build and deploy the application with a newer version of @fastly/compute-js-static-publish.`);
161
- this.assetEntryMapCache = null;
247
+ scope.assetEntryMap = null;
162
248
  return null;
163
249
  }
164
250
  let collectionIsExpired = false;
165
- if (this.activeCollectionName !== this.defaultCollectionName && metadata != null) {
251
+ if (scope.collectionName !== this.defaultCollectionName && metadata != null) {
166
252
  collectionIsExpired = metadata.expirationTime != null && isExpired(metadata.expirationTime);
167
253
  }
168
254
  if (collectionIsExpired) {
169
255
  console.error(`Requested collection expired at ${indexFileKey}.`);
170
- this.assetEntryMapCache = null;
256
+ scope.assetEntryMap = null;
171
257
  return null;
172
258
  }
173
259
  // Read and parse in two steps, so that Server-Timing can report each one.
174
- const indexText = await this.timed('index-body', () => indexFile.text());
175
- this.assetEntryMapCache = await this.timed('index-parse', async () => JSON.parse(indexText));
176
- return this.assetEntryMapCache;
260
+ const indexText = await this.timed(scope, 'index-body', () => indexFile.text());
261
+ scope.assetEntryMap = await this.timed(scope, 'index-parse', async () => JSON.parse(indexText));
262
+ return scope.assetEntryMap;
177
263
  }
178
- async getMatchingAsset(assetKey, applyAuto = false) {
179
- const serverConfig = await this.getServerConfig();
264
+ // Find the file for an asset key. The second argument can also be a boolean,
265
+ // the value of applyAuto.
266
+ async getMatchingAsset(assetKey, options = false) {
267
+ const { applyAuto = false, includeHidden = false } = typeof options === 'boolean' ? { applyAuto: options } : options;
268
+ return this.getMatchingAssetFor(this.currentScope, assetKey, applyAuto, includeHidden);
269
+ }
270
+ async getMatchingAssetFor(scope, assetKey, applyAuto, includeHidden) {
271
+ const serverConfig = await this.getServerConfigFor(scope);
180
272
  if (serverConfig == null) {
181
273
  return null;
182
274
  }
183
- const assetEntryMap = await this.getAssetEntryMap();
275
+ const assetEntryMap = await this.getAssetEntryMapFor(scope);
184
276
  if (assetEntryMap == null) {
185
277
  return null;
186
278
  }
279
+ // A key that starts with 'hidden:' is never looked up, so that a request path
280
+ // cannot name a hidden file. (A real asset key always starts with a slash.)
281
+ // With includeHidden, a normal key also finds the hidden file of that key.
282
+ if (isHiddenIndexKey(assetKey)) {
283
+ return null;
284
+ }
285
+ const lookup = (key) => findAssetEntry(assetEntryMap, key, includeHidden);
187
286
  if (!assetKey.endsWith('/')) {
188
287
  // A path that does not end in a slash can match an asset directly
189
- const asset = assetEntryMap[assetKey];
288
+ const asset = lookup(assetKey);
190
289
  if (asset != null) {
191
290
  return asset;
192
291
  }
@@ -195,7 +294,7 @@ export class PublisherServer {
195
294
  // looks for an asset that has the specified suffix (usually extension, such as .html)
196
295
  for (const extEntry of serverConfig.autoExt) {
197
296
  let assetKeyWithExt = assetKey + extEntry;
198
- const asset = assetEntryMap[assetKeyWithExt];
297
+ const asset = lookup(assetKeyWithExt);
199
298
  if (asset != null) {
200
299
  return asset;
201
300
  }
@@ -215,7 +314,7 @@ export class PublisherServer {
215
314
  assetNameAsDir = assetNameAsDir + '/';
216
315
  for (const indexEntry of serverConfig.autoIndex) {
217
316
  let assetKeyIndex = assetNameAsDir + indexEntry;
218
- const asset = assetEntryMap[assetKeyIndex];
317
+ const asset = lookup(assetKeyIndex);
219
318
  if (asset != null) {
220
319
  return asset;
221
320
  }
@@ -229,24 +328,21 @@ export class PublisherServer {
229
328
  // For example, if accept-encoding had br;q=1,gzip;q=0.5, and the server accepts both br and gzip,
230
329
  // the result would be [['br'], ['gzip']]
231
330
  async findAcceptEncodingsGroups(request) {
232
- const serverConfig = await this.getServerConfig();
331
+ return this.findAcceptEncodingsGroupsFor(this.currentScope, request);
332
+ }
333
+ async findAcceptEncodingsGroupsFor(scope, request) {
334
+ const serverConfig = await this.getServerConfigFor(scope);
233
335
  if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
234
336
  return [];
235
337
  }
236
338
  return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
237
339
  }
238
340
  async testExtendedCache(pathname) {
239
- const staticItems = await this.getStaticItems();
240
- return staticItems
241
- .some(x => {
242
- if (x instanceof RegExp) {
243
- return x.test(pathname);
244
- }
245
- if (x.endsWith('/')) {
246
- return pathname.startsWith(x);
247
- }
248
- return x === pathname;
249
- });
341
+ return this.testExtendedCacheFor(this.currentScope, pathname);
342
+ }
343
+ async testExtendedCacheFor(scope, pathname) {
344
+ const staticItems = await this.getStaticItemsFor(scope);
345
+ return testItemPatterns(staticItems, pathname);
250
346
  }
251
347
  handlePreconditions(request, asset, responseHeaders) {
252
348
  return this.handlePreconditionsForLastModified(request, asset.lastModifiedTime, responseHeaders);
@@ -307,10 +403,13 @@ export class PublisherServer {
307
403
  return null;
308
404
  }
309
405
  async loadAssetVariant(entry, variant) {
406
+ return this.loadAssetVariantFor(this.currentScope, entry, variant);
407
+ }
408
+ async loadAssetVariantFor(scope, entry, variant) {
310
409
  const baseHash = entry.key.slice(7);
311
410
  const baseKey = `${this.publishId}_files_sha256_${baseHash}`;
312
411
  const variantKey = variant != null ? `${baseKey}_${variant}` : baseKey;
313
- const storageEntry = await this.timed('asset', () => this.storageProvider.getEntry(variantKey));
412
+ const storageEntry = await this.timed(scope, 'asset', () => this.storageProvider.getEntry(variantKey));
314
413
  if (storageEntry == null) {
315
414
  return null;
316
415
  }
@@ -334,7 +433,7 @@ export class PublisherServer {
334
433
  ...metadata,
335
434
  };
336
435
  }
337
- async findAssetVariantForAcceptEncodingsGroups(entry, acceptEncodingsGroups = []) {
436
+ async findAssetVariantForAcceptEncodingsGroups(scope, entry, acceptEncodingsGroups = []) {
338
437
  if (!entry.key.startsWith('sha256:')) {
339
438
  throw new TypeError(`Key must start with 'sha256:': ${entry.key}`);
340
439
  }
@@ -347,7 +446,7 @@ export class PublisherServer {
347
446
  if (!entry.variants.includes(encoding)) {
348
447
  continue;
349
448
  }
350
- const assetVariant = await this.loadAssetVariant(entry, encoding);
449
+ const assetVariant = await this.loadAssetVariantFor(scope, entry, encoding);
351
450
  if (assetVariant == null) {
352
451
  continue;
353
452
  }
@@ -360,17 +459,20 @@ export class PublisherServer {
360
459
  return smallestVariant;
361
460
  }
362
461
  }
363
- const baseAssetVariant = await this.loadAssetVariant(entry, null);
462
+ const baseAssetVariant = await this.loadAssetVariantFor(scope, entry, null);
364
463
  if (baseAssetVariant == null) {
365
464
  throw new TypeError('Key not found: ' + entry.key);
366
465
  }
367
466
  return baseAssetVariant;
368
467
  }
369
468
  async serveAsset(request, asset, init) {
469
+ return this.serveAssetFor(this.currentScope, request, asset, init);
470
+ }
471
+ async serveAssetFor(scope, request, asset, init) {
370
472
  const headers = new Headers(init?.headers);
371
473
  headers.set('Content-Type', asset.contentType);
372
474
  if (this.collectionNameHeader) {
373
- headers.set(this.collectionNameHeader, this.activeCollectionName);
475
+ headers.set(this.collectionNameHeader, scope.collectionName);
374
476
  headers.append('Vary', this.collectionNameHeader);
375
477
  }
376
478
  if (init?.cache != null) {
@@ -385,8 +487,8 @@ export class PublisherServer {
385
487
  }
386
488
  headers.append('Cache-Control', cacheControlValue);
387
489
  }
388
- const acceptEncodings = await this.findAcceptEncodingsGroups(request);
389
- const assetVariant = await this.findAssetVariantForAcceptEncodingsGroups(asset, acceptEncodings);
490
+ const acceptEncodings = await this.findAcceptEncodingsGroupsFor(scope, request);
491
+ const assetVariant = await this.findAssetVariantForAcceptEncodingsGroups(scope, asset, acceptEncodings);
390
492
  if (assetVariant.contentEncoding != null) {
391
493
  headers.append('Content-Encoding', assetVariant.contentEncoding);
392
494
  }
@@ -394,8 +496,8 @@ export class PublisherServer {
394
496
  if (asset.lastModifiedTime !== 0) {
395
497
  headers.set('Last-Modified', (new Date(asset.lastModifiedTime * 1000)).toUTCString());
396
498
  }
397
- if (this.serverTiming != null) {
398
- headers.append('Server-Timing', this.serverTiming.toHeaderValue());
499
+ if (scope.serverTiming != null) {
500
+ headers.append('Server-Timing', scope.serverTiming.toHeaderValue());
399
501
  }
400
502
  const preconditionResponse = this.handlePreconditions(request, asset, headers);
401
503
  if (preconditionResponse != null) {
@@ -418,30 +520,33 @@ export class PublisherServer {
418
520
  // null (not found). Conditional requests and HEAD are then answered from the
419
521
  // cached response. If the cache is off, produce() gets the original request.
420
522
  async serveCached(request, keyPath, produce) {
523
+ return this.serveCachedFor(this.currentScope, request, keyPath, produce);
524
+ }
525
+ async serveCachedFor(scope, request, keyPath, produce) {
421
526
  if (this.responseCache == null) {
422
527
  return produce(request);
423
528
  }
424
- const key = buildResponseCacheKey(this.publishId, this.activeCollectionName, keyPath, request);
529
+ const key = buildResponseCacheKey(this.publishId, scope.collectionName, keyPath, request);
425
530
  const lookupStart = performance.now();
426
531
  const entry = CoreCache.transactionLookup(key);
427
532
  const state = entry.state();
428
533
  if (!state.mustInsertOrUpdate()) {
429
534
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
430
535
  if (metadata?.tooLarge) {
431
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
536
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
432
537
  return produce(request);
433
538
  }
434
539
  if (metadata != null) {
435
540
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
436
- this.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
437
- return this.responseFromCache(request, metadata, entry.body());
541
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
542
+ return this.responseFromCache(scope, request, metadata, entry.body());
438
543
  }
439
544
  // Not usable, and another request is not filling it for us: serve without the cache.
440
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
545
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
441
546
  return produce(request);
442
547
  }
443
548
  // This request must fill the entry (a miss, or a stale entry after a soft purge).
444
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
549
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
445
550
  let response;
446
551
  try {
447
552
  response = await produce(buildCacheFillRequest(request));
@@ -450,10 +555,14 @@ export class PublisherServer {
450
555
  entry.cancel();
451
556
  throw err;
452
557
  }
558
+ if (scope.doNotStoreResponse) {
559
+ entry.cancel();
560
+ return response;
561
+ }
453
562
  const insertOptions = {
454
563
  // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
455
564
  maxAge: this.responseCache.maxAge * 1000,
456
- surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
565
+ surrogateKeys: [`${this.publishId}-${scope.collectionName}`],
457
566
  };
458
567
  if (response == null) {
459
568
  const metadata = { notFound: true };
@@ -496,24 +605,28 @@ export class PublisherServer {
496
605
  length: 0,
497
606
  });
498
607
  writer.close();
499
- return this.responseFromCache(request, metadata, readResult.body);
608
+ return this.responseFromCache(scope, request, metadata, readResult.body);
500
609
  }
501
610
  const writer = entry.insert({
502
611
  ...insertOptions,
503
612
  userMetadata: encodeCachedResponseMetadata(metadata),
504
613
  length: readResult.bytes.byteLength,
505
614
  });
506
- writer.append(readResult.bytes);
615
+ // The body goes to the entry and to the response in pieces. A call with the
616
+ // whole body makes a full copy of it, which needs memory for one more body.
617
+ for (const piece of bytesInPieces(readResult.bytes)) {
618
+ writer.append(piece);
619
+ }
507
620
  writer.close();
508
- return this.responseFromCache(request, metadata, readResult.bytes);
621
+ return this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes));
509
622
  }
510
- responseFromCache(request, metadata, body) {
623
+ responseFromCache(scope, request, metadata, body) {
511
624
  if (metadata.notFound) {
512
625
  return null;
513
626
  }
514
627
  const headers = new Headers(metadata.headers);
515
- if (this.serverTiming != null) {
516
- headers.append('Server-Timing', this.serverTiming.toHeaderValue());
628
+ if (scope.serverTiming != null) {
629
+ headers.append('Server-Timing', scope.serverTiming.toHeaderValue());
517
630
  }
518
631
  const lastModified = headers.get('Last-Modified');
519
632
  const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
@@ -527,25 +640,138 @@ export class PublisherServer {
527
640
  headers,
528
641
  });
529
642
  }
530
- async serveRequest(request) {
531
- this.beginRequest(request);
643
+ // Serve the file that matches the request. If no file matches, serve the SPA
644
+ // file or the 404 page (see options.fallback). Returns null if there is no
645
+ // response for the request, for example for a method other than GET and HEAD.
646
+ async serveRequest(request, options = {}) {
647
+ let scope = this.beginRequestFor(request, options.collectionName);
532
648
  // Only handle GET and HEAD
533
649
  if (request.method !== 'GET' && request.method !== 'HEAD') {
534
650
  return null;
535
651
  }
536
- const url = new URL(request.url);
537
- const pathname = decodeURI(url.pathname);
652
+ let pathname;
653
+ if (options.pathname != null) {
654
+ if (!options.pathname.startsWith('/')) {
655
+ throw new TypeError(`pathname must start with '/': ${options.pathname}`);
656
+ }
657
+ pathname = options.pathname;
658
+ }
659
+ else {
660
+ pathname = decodeURI(new URL(request.url).pathname);
661
+ }
538
662
  // Custom health check route
539
- if (pathname === '/healthz') {
663
+ if (options.healthCheck !== false && pathname === '/healthz') {
540
664
  return new Response("OK", { status: 200 });
541
665
  }
666
+ const selected = await this.checkSelectedCollection(request, scope);
667
+ if (selected instanceof Response) {
668
+ return selected;
669
+ }
670
+ scope = selected.scope;
542
671
  // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
543
- const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
544
- return this.serveCached(request, keyPath, (fillRequest) => this.serveRequestFromStorage(fillRequest, pathname));
672
+ // With fallback: false, the response does not depend on HTML, so it has its own cache key.
673
+ const fallback = options.fallback !== false && requestAcceptsTextHtml(request);
674
+ const keyPath = fallback ? pathname : `${pathname}|no-html`;
675
+ const response = await this.serveCachedFor(scope, request, keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback));
676
+ return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
545
677
  }
546
- async serveRequestFromStorage(request, pathname) {
547
- const serverConfig = await this.getServerConfig();
548
- if (serverConfig == null) {
678
+ // Serve the SPA file or the 404 page, as serveRequest() does when no file
679
+ // matches. Use it after serveRequest() with fallback: false. Returns null for
680
+ // a method other than GET and HEAD, if the client does not accept HTML, or if
681
+ // the collection has no fallback page.
682
+ async serveFallback(request, options = {}) {
683
+ let scope = this.beginRequestFor(request, options.collectionName);
684
+ // Only handle GET and HEAD
685
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
686
+ return null;
687
+ }
688
+ if (!requestAcceptsTextHtml(request)) {
689
+ return null;
690
+ }
691
+ const selected = await this.checkSelectedCollection(request, scope);
692
+ if (selected instanceof Response) {
693
+ return selected;
694
+ }
695
+ scope = selected.scope;
696
+ // The fallback response is the same for all paths, so it has one cache key.
697
+ // A path always starts with a slash, so this key is not the key of a path.
698
+ const response = await this.serveCachedFor(scope, request, '|fallback', async (fillRequest) => {
699
+ const serverConfig = await this.getServerConfigFor(scope);
700
+ if (serverConfig == null) {
701
+ return null;
702
+ }
703
+ return this.serveFallbackFromStorage(scope, fillRequest, serverConfig);
704
+ });
705
+ return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
706
+ }
707
+ // Returns true if the collection is published, has not expired, and can
708
+ // be served by this version. It reads the settings and the index into the scope.
709
+ async isCollectionAvailable(request, collectionName) {
710
+ return this.isCollectionAvailableFor(this.scopeForRequest(request, collectionName ?? this.defaultCollectionName));
711
+ }
712
+ async isCollectionAvailableFor(scope) {
713
+ return (await this.getServerConfigFor(scope)) != null && (await this.getAssetEntryMapFor(scope)) != null;
714
+ }
715
+ // With collection selection, check a collection that is not the default
716
+ // collection (see setCollectionSelection()). Returns the scope to serve, and
717
+ // whether to mark the response as a preview, or a 404 response for onMissing:
718
+ // 'not-found'. The check reads the index, also when the response cache has the
719
+ // response.
720
+ async checkSelectedCollection(request, scope) {
721
+ const config = this.collectionSelection;
722
+ if (config == null || scope.collectionName === this.defaultCollectionName) {
723
+ return { scope, preview: false };
724
+ }
725
+ if (await this.isCollectionAvailableFor(scope)) {
726
+ return { scope, preview: true };
727
+ }
728
+ if (config.onMissing === 'default') {
729
+ this.currentScope = this.scopeForRequest(request, this.defaultCollectionName);
730
+ return { scope: this.currentScope, preview: false };
731
+ }
732
+ const response = collectionNotAvailableResponse(scope.collectionName);
733
+ if (config.noindex !== false) {
734
+ response.headers.set('X-Robots-Tag', 'noindex');
735
+ }
736
+ return response;
737
+ }
738
+ // A response from a collection that is not the default collection. If a host,
739
+ // path, or query source of the request selects this collection, the URL
740
+ // names the collection, so a shared cache can store the response. Otherwise
741
+ // (a cookie or header source, or a collectionName that the app chose) the same
742
+ // URL can serve another collection, so the response gets Cache-Control:
743
+ // private, and shared caches do not store it.
744
+ markPreviewResponse(request, scope, response) {
745
+ if (response == null || this.collectionSelection == null) {
746
+ return response;
747
+ }
748
+ const headers = new Headers(response.headers);
749
+ if (!isSelectedByUrl(resolveCollection(request, this.collectionSelection), scope.collectionName)) {
750
+ const cacheControl = headers.get('Cache-Control');
751
+ if (cacheControl == null || cacheControl === '') {
752
+ headers.set('Cache-Control', 'private');
753
+ }
754
+ else if (!/\b(private|no-store)\b/i.test(cacheControl)) {
755
+ headers.set('Cache-Control', `private, ${cacheControl}`);
756
+ }
757
+ }
758
+ if (this.collectionSelection.noindex !== false) {
759
+ headers.set('X-Robots-Tag', 'noindex');
760
+ }
761
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
762
+ }
763
+ // Make the scope of the request for the collection the current scope.
764
+ // collectionName is as in ServeRequestOptions.
765
+ beginRequestFor(request, collectionName) {
766
+ const name = collectionName === undefined ?
767
+ this.activeCollectionName :
768
+ collectionName ?? this.defaultCollectionName;
769
+ this.currentScope = this.scopeForRequest(request, name);
770
+ return this.currentScope;
771
+ }
772
+ async serveRequestFromStorage(scope, request, pathname, fallback) {
773
+ const serverConfig = await this.getServerConfigFor(scope);
774
+ if (serverConfig == null && scope.collectionName === this.defaultCollectionName) {
549
775
  return new Response(`Settings not found. You may need to publish your application.`, {
550
776
  status: 500,
551
777
  headers: {
@@ -553,37 +779,50 @@ export class PublisherServer {
553
779
  },
554
780
  });
555
781
  }
556
- const asset = await this.getMatchingAsset(serverConfig.publicDirPrefix + pathname, true);
782
+ // A collection other than the default collection that is not published, or
783
+ // that expired, gets a 404. It can be published at any time, so the
784
+ // response cache does not store this response.
785
+ if (serverConfig == null ||
786
+ (scope.collectionName !== this.defaultCollectionName && await this.getAssetEntryMapFor(scope) == null)) {
787
+ scope.doNotStoreResponse = true;
788
+ return collectionNotAvailableResponse(scope.collectionName);
789
+ }
790
+ const asset = await this.getMatchingAssetFor(scope, serverConfig.publicDirPrefix + pathname, true, false);
557
791
  if (asset != null) {
558
- return this.serveAsset(request, asset, {
559
- cache: await this.testExtendedCache(pathname) ? 'extended' : null,
792
+ return this.serveAssetFor(scope, request, asset, {
793
+ cache: await this.testExtendedCacheFor(scope, pathname) ? 'extended' : null,
560
794
  });
561
795
  }
562
- // fallback HTML responses, like SPA and "not found" pages
563
- if (requestAcceptsTextHtml(request)) {
564
- const assetEntryMap = await this.getAssetEntryMap();
565
- if (assetEntryMap == null) {
566
- return null;
567
- }
568
- // These are raw asset paths, not relative to public path
569
- const { spaFile } = serverConfig;
570
- if (spaFile != null) {
571
- const asset = assetEntryMap[spaFile];
572
- if (asset != null) {
573
- return this.serveAsset(request, asset, {
574
- cache: 'never',
575
- });
576
- }
796
+ if (fallback) {
797
+ return this.serveFallbackFromStorage(scope, request, serverConfig);
798
+ }
799
+ return null;
800
+ }
801
+ // fallback HTML responses, like SPA and "not found" pages
802
+ async serveFallbackFromStorage(scope, request, serverConfig) {
803
+ const assetEntryMap = await this.getAssetEntryMapFor(scope);
804
+ if (assetEntryMap == null) {
805
+ return null;
806
+ }
807
+ // These are raw asset paths, not relative to public path. The SPA file and
808
+ // the 404 page can be hidden files.
809
+ const { spaFile } = serverConfig;
810
+ if (spaFile != null) {
811
+ const asset = findAssetEntry(assetEntryMap, spaFile, true);
812
+ if (asset != null) {
813
+ return this.serveAssetFor(scope, request, asset, {
814
+ cache: 'never',
815
+ });
577
816
  }
578
- const { notFoundPageFile } = serverConfig;
579
- if (notFoundPageFile != null) {
580
- const asset = assetEntryMap[notFoundPageFile];
581
- if (asset != null) {
582
- return this.serveAsset(request, asset, {
583
- status: 404,
584
- cache: 'never',
585
- });
586
- }
817
+ }
818
+ const { notFoundPageFile } = serverConfig;
819
+ if (notFoundPageFile != null) {
820
+ const asset = findAssetEntry(assetEntryMap, notFoundPageFile, true);
821
+ if (asset != null) {
822
+ return this.serveAssetFor(scope, request, asset, {
823
+ status: 404,
824
+ cache: 'never',
825
+ });
587
826
  }
588
827
  }
589
828
  return null;