@fastly/compute-js-static-publish 8.0.1 → 8.1.0-beta.2

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 (247) hide show
  1. package/DOCUMENTATION.md +792 -35
  2. package/README.md +13 -3
  3. package/README.short.md +13 -3
  4. package/build/cli/cli/commands/manage/clean.d.ts.map +1 -1
  5. package/build/cli/cli/commands/manage/clean.js +14 -8
  6. package/build/cli/cli/commands/manage/collections/delete.d.ts.map +1 -1
  7. package/build/cli/cli/commands/manage/collections/delete.js +32 -15
  8. package/build/cli/cli/commands/manage/collections/index.d.ts.map +1 -1
  9. package/build/cli/cli/commands/manage/collections/index.js +10 -4
  10. package/build/cli/cli/commands/manage/collections/list.d.ts.map +1 -1
  11. package/build/cli/cli/commands/manage/collections/list.js +49 -8
  12. package/build/cli/cli/commands/manage/collections/promote.d.ts.map +1 -1
  13. package/build/cli/cli/commands/manage/collections/promote.js +69 -21
  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 +12 -12
  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 +78 -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 +42 -5
  27. package/build/cli/cli/commands/manage/publish-content.d.ts.map +1 -1
  28. package/build/cli/cli/commands/manage/publish-content.js +83 -37
  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 +43 -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 +208 -290
  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 +298 -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 +1 -0
  100. package/build/cli/cli/storage/kv-store-provider.d.ts.map +1 -1
  101. package/build/cli/cli/storage/kv-store-provider.js +9 -1
  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 +4 -0
  105. package/build/cli/cli/storage/storage-provider.d.ts +3 -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.map +1 -1
  109. package/build/cli/cli/util/collection-name.d.ts +3 -0
  110. package/build/cli/cli/util/collection-name.d.ts.map +1 -0
  111. package/build/cli/cli/util/collection-name.js +24 -0
  112. package/build/cli/cli/util/collection-selection-flags.d.ts +13 -0
  113. package/build/cli/cli/util/collection-selection-flags.d.ts.map +1 -0
  114. package/build/cli/cli/util/collection-selection-flags.js +131 -0
  115. package/build/cli/cli/util/config.d.ts +13 -0
  116. package/build/cli/cli/util/config.d.ts.map +1 -1
  117. package/build/cli/cli/util/config.js +172 -38
  118. package/build/cli/cli/util/data.d.ts.map +1 -1
  119. package/build/cli/cli/util/global-options.d.ts +13 -0
  120. package/build/cli/cli/util/global-options.d.ts.map +1 -0
  121. package/build/cli/cli/util/global-options.js +53 -0
  122. package/build/cli/cli/util/kv-store-items.d.ts +1 -0
  123. package/build/cli/cli/util/kv-store-items.d.ts.map +1 -1
  124. package/build/cli/cli/util/kv-store-items.js +16 -40
  125. package/build/cli/cli/util/kv-store-local-server.d.ts +1 -1
  126. package/build/cli/cli/util/kv-store-local-server.d.ts.map +1 -1
  127. package/build/cli/cli/util/kv-store-local-server.js +4 -2
  128. package/build/cli/cli/util/output.d.ts +31 -0
  129. package/build/cli/cli/util/output.d.ts.map +1 -0
  130. package/build/cli/cli/util/output.js +139 -0
  131. package/build/cli/cli/util/package.d.ts +6 -0
  132. package/build/cli/cli/util/package.d.ts.map +1 -1
  133. package/build/cli/cli/util/package.js +23 -0
  134. package/build/cli/cli/util/progress.d.ts.map +1 -1
  135. package/build/cli/cli/util/purge.d.ts +6 -2
  136. package/build/cli/cli/util/purge.d.ts.map +1 -1
  137. package/build/cli/cli/util/purge.js +7 -2
  138. package/build/cli/cli/util/resources.d.ts +2 -0
  139. package/build/cli/cli/util/resources.d.ts.map +1 -0
  140. package/build/cli/cli/util/resources.js +8 -0
  141. package/build/cli/cli/util/service-id.d.ts +1 -0
  142. package/build/cli/cli/util/service-id.d.ts.map +1 -1
  143. package/build/cli/cli/util/service-id.js +5 -1
  144. package/build/cli/cli/util/variants.d.ts.map +1 -1
  145. package/build/cli/models/assets/index.d.ts +6 -0
  146. package/build/cli/models/assets/index.d.ts.map +1 -1
  147. package/build/cli/models/assets/index.js +24 -0
  148. package/build/cli/models/collections/index.d.ts +3 -0
  149. package/build/cli/models/collections/index.d.ts.map +1 -0
  150. package/build/cli/models/collections/index.js +15 -0
  151. package/build/cli/models/compression/index.d.ts +1 -1
  152. package/build/cli/models/compression/index.d.ts.map +1 -1
  153. package/build/cli/models/config/collection-selection.d.ts +55 -0
  154. package/build/cli/models/config/collection-selection.d.ts.map +1 -0
  155. package/build/cli/models/config/collection-selection.js +238 -0
  156. package/build/cli/models/config/item-patterns.d.ts +4 -0
  157. package/build/cli/models/config/item-patterns.d.ts.map +1 -0
  158. package/build/cli/models/config/item-patterns.js +43 -0
  159. package/build/cli/models/config/publish-content-config.d.ts +6 -1
  160. package/build/cli/models/config/publish-content-config.d.ts.map +1 -1
  161. package/build/cli/models/config/static-publish-project.d.ts +23 -0
  162. package/build/cli/models/config/static-publish-project.d.ts.map +1 -0
  163. package/build/cli/models/config/static-publish-project.js +11 -0
  164. package/build/cli/models/config/static-publish-rc.d.ts +25 -0
  165. package/build/cli/models/config/static-publish-rc.d.ts.map +1 -1
  166. package/build/cli/models/config/static-publish-rc.js +31 -0
  167. package/build/cli/models/config/template-settings.d.ts +10 -0
  168. package/build/cli/models/config/template-settings.d.ts.map +1 -0
  169. package/build/cli/models/config/template-settings.js +72 -0
  170. package/build/cli/models/server/index.d.ts.map +1 -1
  171. package/build/cli/models/server/index.js +6 -2
  172. package/build/server/hono/extensions.d.ts +48 -0
  173. package/build/server/hono/extensions.d.ts.map +1 -0
  174. package/build/server/hono/extensions.js +65 -0
  175. package/build/server/hono/index.d.ts +30 -0
  176. package/build/server/hono/index.d.ts.map +1 -0
  177. package/build/server/hono/index.js +72 -0
  178. package/build/server/hono/path.d.ts +7 -0
  179. package/build/server/hono/path.d.ts.map +1 -0
  180. package/build/server/hono/path.js +32 -0
  181. package/build/server/models/assets/index.d.ts +6 -0
  182. package/build/server/models/assets/index.d.ts.map +1 -1
  183. package/build/server/models/assets/index.js +24 -0
  184. package/build/server/models/collections/index.d.ts +3 -0
  185. package/build/server/models/collections/index.d.ts.map +1 -0
  186. package/build/server/models/collections/index.js +15 -0
  187. package/build/server/models/compression/index.d.ts +1 -1
  188. package/build/server/models/compression/index.d.ts.map +1 -1
  189. package/build/server/models/config/collection-selection.d.ts +55 -0
  190. package/build/server/models/config/collection-selection.d.ts.map +1 -0
  191. package/build/server/models/config/collection-selection.js +238 -0
  192. package/build/server/models/config/item-patterns.d.ts +4 -0
  193. package/build/server/models/config/item-patterns.d.ts.map +1 -0
  194. package/build/server/models/config/item-patterns.js +43 -0
  195. package/build/server/models/config/publish-content-config.d.ts +6 -1
  196. package/build/server/models/config/publish-content-config.d.ts.map +1 -1
  197. package/build/server/models/config/static-publish-project.d.ts +23 -0
  198. package/build/server/models/config/static-publish-project.d.ts.map +1 -0
  199. package/build/server/models/config/static-publish-project.js +11 -0
  200. package/build/server/models/config/static-publish-rc.d.ts +25 -0
  201. package/build/server/models/config/static-publish-rc.d.ts.map +1 -1
  202. package/build/server/models/config/static-publish-rc.js +31 -0
  203. package/build/server/models/server/index.d.ts.map +1 -1
  204. package/build/server/models/server/index.js +6 -2
  205. package/build/server/server/collection-selection/index.d.ts +11 -0
  206. package/build/server/server/collection-selection/index.d.ts.map +1 -0
  207. package/build/server/server/collection-selection/index.js +192 -0
  208. package/build/server/server/collection-selector/from-cookie.d.ts.map +1 -1
  209. package/build/server/server/collection-selector/from-cookie.js +6 -8
  210. package/build/server/server/collection-selector/from-request.d.ts.map +1 -1
  211. package/build/server/server/index.d.ts +4 -1
  212. package/build/server/server/index.d.ts.map +1 -1
  213. package/build/server/server/index.js +3 -1
  214. package/build/server/server/publisher-server/accept-html.d.ts +2 -0
  215. package/build/server/server/publisher-server/accept-html.d.ts.map +1 -0
  216. package/build/server/server/publisher-server/accept-html.js +50 -0
  217. package/build/server/server/publisher-server/index.d.ts +59 -7
  218. package/build/server/server/publisher-server/index.d.ts.map +1 -1
  219. package/build/server/server/publisher-server/index.js +362 -145
  220. package/build/server/server/publisher-server/response-cache.d.ts +3 -0
  221. package/build/server/server/publisher-server/response-cache.d.ts.map +1 -1
  222. package/build/server/server/publisher-server/response-cache.js +24 -1
  223. package/build/server/server/storage/kv-store-provider.d.ts.map +1 -1
  224. package/build/server/server/storage/s3-storage-provider.d.ts.map +1 -1
  225. package/build/server/server/storage/storage-provider.d.ts.map +1 -1
  226. package/build/server/server/util/body-length.d.ts.map +1 -1
  227. package/build/server/server/util/server-timing.d.ts.map +1 -1
  228. package/package.json +21 -3
  229. package/resources/app/fastly.toml.njk +58 -0
  230. package/resources/app/gitignore.njk +9 -0
  231. package/resources/app/publish-content.config.from-project.js.njk +9 -0
  232. package/resources/app/publish-content.config.js.njk +35 -0
  233. package/resources/app/static-publish.project.js.njk +83 -0
  234. package/resources/app/static-publish.rc.js.njk +43 -0
  235. package/resources/template-init/hono/_example.ts +22 -0
  236. package/resources/template-init/hono/tsconfig.json +17 -0
  237. package/resources/templates/hono/package-lock.json +4123 -0
  238. package/resources/templates/hono/package.json +15 -0
  239. package/resources/templates/hono/scripts/template_postinstall.js +10 -0
  240. package/resources/templates/hono/scripts/template_prebuild.js +8 -0
  241. package/resources/templates/hono/scripts/template_watch.js +15 -0
  242. package/resources/templates/hono/src/hono-extensions.generated.d.ts +5 -0
  243. package/resources/templates/hono/src/index.ts +53 -0
  244. package/resources/templates/hono/tsconfig.json +17 -0
  245. package/resources/templates/plain/package-lock.json +4088 -0
  246. package/resources/templates/plain/package.json +10 -0
  247. 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,39 +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) {
45
- // When true, serveCached() does not store the response of the current request.
46
- this.doNotStoreResponse = false;
53
+ // See setCollectionSelection().
54
+ this.collectionSelection = null;
47
55
  this.publishId = publishId;
48
56
  this.storageProvider = storageProvider;
49
57
  this.defaultCollectionName = defaultCollectionName;
50
58
  this.activeCollectionName = this.defaultCollectionName;
51
59
  this.collectionNameHeader = 'X-Publisher-Server-Collection';
52
60
  this.serverTimingRequestHeader = null;
53
- this.serverTiming = null;
54
61
  this.responseCache = null;
62
+ this.currentScope = this.newScope(this.activeCollectionName, null);
63
+ this.requestScopes = new WeakMap();
55
64
  }
56
65
  static fromStaticPublishRc(config) {
57
66
  const storeProvider = loadStorageProviderFromStaticPublishRc(config);
58
- 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;
59
93
  }
60
94
  // null selects the default collection. A sandbox can be reused for more than
61
95
  // one request, so call this for each request, also when no collection is
62
96
  // selected. Otherwise, the collection of the previous request stays active.
63
97
  setActiveCollectionName(collectionName) {
64
98
  this.activeCollectionName = collectionName ?? this.defaultCollectionName;
65
- this.settingsCached = undefined;
66
- this.assetEntryMapCache = undefined;
99
+ this.currentScope = this.newScope(this.activeCollectionName, this.currentScope.serverTiming);
67
100
  }
68
101
  setCollectionNameHeader(collectionHeader) {
69
102
  this.collectionNameHeader = collectionHeader;
@@ -81,30 +114,84 @@ export class PublisherServer {
81
114
  setResponseCache(options) {
82
115
  this.responseCache = options;
83
116
  }
84
- // 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
85
143
  // getMatchingAsset() and serveAsset() directly, call this first.
86
- // A sandbox can be reused for more than one request, so this also clears the
87
- // settings and the index that a previous request read. Without this, a reused
88
- // 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.
89
148
  beginRequest(request) {
90
- this.settingsCached = undefined;
91
- this.assetEntryMapCache = undefined;
92
- this.doNotStoreResponse = false;
149
+ this.beginRequestFor(request, undefined);
150
+ }
151
+ newServerTiming(request) {
93
152
  const header = this.serverTimingRequestHeader;
94
- this.serverTiming = header != null && request.headers.has(header) ? new ServerTiming() : null;
153
+ return header != null && request.headers.has(header) ? new ServerTiming() : null;
95
154
  }
96
- timed(name, fn) {
97
- return this.serverTiming != null ? this.serverTiming.measure(name, fn) : fn();
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;
179
+ }
180
+ timed(scope, name, fn) {
181
+ return scope.serverTiming != null ? scope.serverTiming.measure(name, fn) : fn();
98
182
  }
99
183
  // Server config is obtained from storage, and cached until the next beginRequest()
100
184
  // or setActiveCollectionName().
101
185
  async getServerConfig() {
102
- if (this.settingsCached !== undefined) {
103
- return this.settingsCached;
186
+ return this.getServerConfigFor(this.currentScope);
187
+ }
188
+ async getServerConfigFor(scope) {
189
+ if (scope.settings !== undefined) {
190
+ return scope.settings;
104
191
  }
105
- const settingsFileKey = `${this.publishId}_settings_${this.activeCollectionName}`;
106
- this.settingsCached = await this.timed('settings', async () => {
107
- 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']);
108
195
  if (settingsFile == null) {
109
196
  console.error(`Settings File not found at ${settingsFileKey}.`);
110
197
  console.error(`You may need to publish your application.`);
@@ -112,37 +199,33 @@ export class PublisherServer {
112
199
  }
113
200
  return (await settingsFile.json());
114
201
  });
115
- return this.settingsCached;
202
+ return scope.settings;
116
203
  }
117
204
  async getStaticItems() {
118
- const serverConfig = await this.getServerConfig();
205
+ return this.getStaticItemsFor(this.currentScope);
206
+ }
207
+ async getStaticItemsFor(scope) {
208
+ const serverConfig = await this.getServerConfigFor(scope);
119
209
  if (serverConfig == null) {
120
210
  return [];
121
211
  }
122
- return serverConfig.staticItems
123
- .map((x, i) => {
124
- if (x.startsWith('re:')) {
125
- const fragments = x.slice(3).match(/\/(.*?)\/([a-z]*)?$/i);
126
- if (fragments == null) {
127
- console.warn(`Cannot parse staticItems item index ${i}: '${x}', skipping...`);
128
- return '';
129
- }
130
- return new RegExp(fragments[1], fragments[2] || '');
131
- }
132
- return x;
133
- })
134
- .filter(x => Boolean(x));
212
+ return parseItemPatterns(serverConfig.staticItems, (i, x) => {
213
+ console.warn(`Cannot parse staticItems item index ${i}: '${x}', skipping...`);
214
+ });
135
215
  }
136
216
  async getAssetEntryMap() {
137
- if (this.assetEntryMapCache !== undefined) {
138
- return this.assetEntryMapCache;
217
+ return this.getAssetEntryMapFor(this.currentScope);
218
+ }
219
+ async getAssetEntryMapFor(scope) {
220
+ if (scope.assetEntryMap !== undefined) {
221
+ return scope.assetEntryMap;
139
222
  }
140
- const indexFileKey = `${this.publishId}_index_${this.activeCollectionName}`;
141
- 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']));
142
225
  if (indexFile == null) {
143
226
  console.error(`Index File not found at ${indexFileKey}.`);
144
227
  console.error(`You may need to publish your application.`);
145
- this.assetEntryMapCache = null;
228
+ scope.assetEntryMap = null;
146
229
  return null;
147
230
  }
148
231
  let metadata;
@@ -161,35 +244,48 @@ export class PublisherServer {
161
244
  if (unsupportedFeatures.length > 0) {
162
245
  console.error(`Collection at ${indexFileKey} requires features that this version of the server does not support: ${unsupportedFeatures.join(', ')}.`);
163
246
  console.error(`Build and deploy the application with a newer version of @fastly/compute-js-static-publish.`);
164
- this.assetEntryMapCache = null;
247
+ scope.assetEntryMap = null;
165
248
  return null;
166
249
  }
167
250
  let collectionIsExpired = false;
168
- if (this.activeCollectionName !== this.defaultCollectionName && metadata != null) {
251
+ if (scope.collectionName !== this.defaultCollectionName && metadata != null) {
169
252
  collectionIsExpired = metadata.expirationTime != null && isExpired(metadata.expirationTime);
170
253
  }
171
254
  if (collectionIsExpired) {
172
255
  console.error(`Requested collection expired at ${indexFileKey}.`);
173
- this.assetEntryMapCache = null;
256
+ scope.assetEntryMap = null;
174
257
  return null;
175
258
  }
176
259
  // Read and parse in two steps, so that Server-Timing can report each one.
177
- const indexText = await this.timed('index-body', () => indexFile.text());
178
- this.assetEntryMapCache = await this.timed('index-parse', async () => JSON.parse(indexText));
179
- 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;
263
+ }
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);
180
269
  }
181
- async getMatchingAsset(assetKey, applyAuto = false) {
182
- const serverConfig = await this.getServerConfig();
270
+ async getMatchingAssetFor(scope, assetKey, applyAuto, includeHidden) {
271
+ const serverConfig = await this.getServerConfigFor(scope);
183
272
  if (serverConfig == null) {
184
273
  return null;
185
274
  }
186
- const assetEntryMap = await this.getAssetEntryMap();
275
+ const assetEntryMap = await this.getAssetEntryMapFor(scope);
187
276
  if (assetEntryMap == null) {
188
277
  return null;
189
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);
190
286
  if (!assetKey.endsWith('/')) {
191
287
  // A path that does not end in a slash can match an asset directly
192
- const asset = assetEntryMap[assetKey];
288
+ const asset = lookup(assetKey);
193
289
  if (asset != null) {
194
290
  return asset;
195
291
  }
@@ -198,7 +294,7 @@ export class PublisherServer {
198
294
  // looks for an asset that has the specified suffix (usually extension, such as .html)
199
295
  for (const extEntry of serverConfig.autoExt) {
200
296
  let assetKeyWithExt = assetKey + extEntry;
201
- const asset = assetEntryMap[assetKeyWithExt];
297
+ const asset = lookup(assetKeyWithExt);
202
298
  if (asset != null) {
203
299
  return asset;
204
300
  }
@@ -218,7 +314,7 @@ export class PublisherServer {
218
314
  assetNameAsDir = assetNameAsDir + '/';
219
315
  for (const indexEntry of serverConfig.autoIndex) {
220
316
  let assetKeyIndex = assetNameAsDir + indexEntry;
221
- const asset = assetEntryMap[assetKeyIndex];
317
+ const asset = lookup(assetKeyIndex);
222
318
  if (asset != null) {
223
319
  return asset;
224
320
  }
@@ -232,24 +328,21 @@ export class PublisherServer {
232
328
  // For example, if accept-encoding had br;q=1,gzip;q=0.5, and the server accepts both br and gzip,
233
329
  // the result would be [['br'], ['gzip']]
234
330
  async findAcceptEncodingsGroups(request) {
235
- 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);
236
335
  if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
237
336
  return [];
238
337
  }
239
338
  return parseAcceptEncodingGroups(request.headers.get('accept-encoding') ?? '', serverConfig.allowedEncodings);
240
339
  }
241
340
  async testExtendedCache(pathname) {
242
- const staticItems = await this.getStaticItems();
243
- return staticItems
244
- .some(x => {
245
- if (x instanceof RegExp) {
246
- return x.test(pathname);
247
- }
248
- if (x.endsWith('/')) {
249
- return pathname.startsWith(x);
250
- }
251
- return x === pathname;
252
- });
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);
253
346
  }
254
347
  handlePreconditions(request, asset, responseHeaders) {
255
348
  return this.handlePreconditionsForLastModified(request, asset.lastModifiedTime, responseHeaders);
@@ -310,10 +403,13 @@ export class PublisherServer {
310
403
  return null;
311
404
  }
312
405
  async loadAssetVariant(entry, variant) {
406
+ return this.loadAssetVariantFor(this.currentScope, entry, variant);
407
+ }
408
+ async loadAssetVariantFor(scope, entry, variant) {
313
409
  const baseHash = entry.key.slice(7);
314
410
  const baseKey = `${this.publishId}_files_sha256_${baseHash}`;
315
411
  const variantKey = variant != null ? `${baseKey}_${variant}` : baseKey;
316
- const storageEntry = await this.timed('asset', () => this.storageProvider.getEntry(variantKey));
412
+ const storageEntry = await this.timed(scope, 'asset', () => this.storageProvider.getEntry(variantKey));
317
413
  if (storageEntry == null) {
318
414
  return null;
319
415
  }
@@ -337,7 +433,7 @@ export class PublisherServer {
337
433
  ...metadata,
338
434
  };
339
435
  }
340
- async findAssetVariantForAcceptEncodingsGroups(entry, acceptEncodingsGroups = []) {
436
+ async findAssetVariantForAcceptEncodingsGroups(scope, entry, acceptEncodingsGroups = []) {
341
437
  if (!entry.key.startsWith('sha256:')) {
342
438
  throw new TypeError(`Key must start with 'sha256:': ${entry.key}`);
343
439
  }
@@ -350,7 +446,7 @@ export class PublisherServer {
350
446
  if (!entry.variants.includes(encoding)) {
351
447
  continue;
352
448
  }
353
- const assetVariant = await this.loadAssetVariant(entry, encoding);
449
+ const assetVariant = await this.loadAssetVariantFor(scope, entry, encoding);
354
450
  if (assetVariant == null) {
355
451
  continue;
356
452
  }
@@ -363,17 +459,20 @@ export class PublisherServer {
363
459
  return smallestVariant;
364
460
  }
365
461
  }
366
- const baseAssetVariant = await this.loadAssetVariant(entry, null);
462
+ const baseAssetVariant = await this.loadAssetVariantFor(scope, entry, null);
367
463
  if (baseAssetVariant == null) {
368
464
  throw new TypeError('Key not found: ' + entry.key);
369
465
  }
370
466
  return baseAssetVariant;
371
467
  }
372
468
  async serveAsset(request, asset, init) {
469
+ return this.serveAssetFor(this.currentScope, request, asset, init);
470
+ }
471
+ async serveAssetFor(scope, request, asset, init) {
373
472
  const headers = new Headers(init?.headers);
374
473
  headers.set('Content-Type', asset.contentType);
375
474
  if (this.collectionNameHeader) {
376
- headers.set(this.collectionNameHeader, this.activeCollectionName);
475
+ headers.set(this.collectionNameHeader, scope.collectionName);
377
476
  headers.append('Vary', this.collectionNameHeader);
378
477
  }
379
478
  if (init?.cache != null) {
@@ -388,8 +487,8 @@ export class PublisherServer {
388
487
  }
389
488
  headers.append('Cache-Control', cacheControlValue);
390
489
  }
391
- const acceptEncodings = await this.findAcceptEncodingsGroups(request);
392
- const assetVariant = await this.findAssetVariantForAcceptEncodingsGroups(asset, acceptEncodings);
490
+ const acceptEncodings = await this.findAcceptEncodingsGroupsFor(scope, request);
491
+ const assetVariant = await this.findAssetVariantForAcceptEncodingsGroups(scope, asset, acceptEncodings);
393
492
  if (assetVariant.contentEncoding != null) {
394
493
  headers.append('Content-Encoding', assetVariant.contentEncoding);
395
494
  }
@@ -397,8 +496,8 @@ export class PublisherServer {
397
496
  if (asset.lastModifiedTime !== 0) {
398
497
  headers.set('Last-Modified', (new Date(asset.lastModifiedTime * 1000)).toUTCString());
399
498
  }
400
- if (this.serverTiming != null) {
401
- headers.append('Server-Timing', this.serverTiming.toHeaderValue());
499
+ if (scope.serverTiming != null) {
500
+ headers.append('Server-Timing', scope.serverTiming.toHeaderValue());
402
501
  }
403
502
  const preconditionResponse = this.handlePreconditions(request, asset, headers);
404
503
  if (preconditionResponse != null) {
@@ -421,30 +520,33 @@ export class PublisherServer {
421
520
  // null (not found). Conditional requests and HEAD are then answered from the
422
521
  // cached response. If the cache is off, produce() gets the original request.
423
522
  async serveCached(request, keyPath, produce) {
523
+ return this.serveCachedFor(this.currentScope, request, keyPath, produce);
524
+ }
525
+ async serveCachedFor(scope, request, keyPath, produce) {
424
526
  if (this.responseCache == null) {
425
527
  return produce(request);
426
528
  }
427
- const key = buildResponseCacheKey(this.publishId, this.activeCollectionName, keyPath, request);
529
+ const key = buildResponseCacheKey(this.publishId, scope.collectionName, keyPath, request);
428
530
  const lookupStart = performance.now();
429
531
  const entry = CoreCache.transactionLookup(key);
430
532
  const state = entry.state();
431
533
  if (!state.mustInsertOrUpdate()) {
432
534
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
433
535
  if (metadata?.tooLarge) {
434
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
536
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
435
537
  return produce(request);
436
538
  }
437
539
  if (metadata != null) {
438
540
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
439
- this.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
440
- 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());
441
543
  }
442
544
  // Not usable, and another request is not filling it for us: serve without the cache.
443
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
545
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
444
546
  return produce(request);
445
547
  }
446
548
  // This request must fill the entry (a miss, or a stale entry after a soft purge).
447
- this.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
549
+ scope.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
448
550
  let response;
449
551
  try {
450
552
  response = await produce(buildCacheFillRequest(request));
@@ -453,14 +555,14 @@ export class PublisherServer {
453
555
  entry.cancel();
454
556
  throw err;
455
557
  }
456
- if (this.doNotStoreResponse) {
558
+ if (scope.doNotStoreResponse) {
457
559
  entry.cancel();
458
560
  return response;
459
561
  }
460
562
  const insertOptions = {
461
563
  // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
462
564
  maxAge: this.responseCache.maxAge * 1000,
463
- surrogateKeys: [`${this.publishId}-${this.activeCollectionName}`],
565
+ surrogateKeys: [`${this.publishId}-${scope.collectionName}`],
464
566
  };
465
567
  if (response == null) {
466
568
  const metadata = { notFound: true };
@@ -503,24 +605,28 @@ export class PublisherServer {
503
605
  length: 0,
504
606
  });
505
607
  writer.close();
506
- return this.responseFromCache(request, metadata, readResult.body);
608
+ return this.responseFromCache(scope, request, metadata, readResult.body);
507
609
  }
508
610
  const writer = entry.insert({
509
611
  ...insertOptions,
510
612
  userMetadata: encodeCachedResponseMetadata(metadata),
511
613
  length: readResult.bytes.byteLength,
512
614
  });
513
- 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
+ }
514
620
  writer.close();
515
- return this.responseFromCache(request, metadata, readResult.bytes);
621
+ return this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes));
516
622
  }
517
- responseFromCache(request, metadata, body) {
623
+ responseFromCache(scope, request, metadata, body) {
518
624
  if (metadata.notFound) {
519
625
  return null;
520
626
  }
521
627
  const headers = new Headers(metadata.headers);
522
- if (this.serverTiming != null) {
523
- headers.append('Server-Timing', this.serverTiming.toHeaderValue());
628
+ if (scope.serverTiming != null) {
629
+ headers.append('Server-Timing', scope.serverTiming.toHeaderValue());
524
630
  }
525
631
  const lastModified = headers.get('Last-Modified');
526
632
  const lastModifiedMs = lastModified != null ? Date.parse(lastModified) : NaN;
@@ -534,25 +640,138 @@ export class PublisherServer {
534
640
  headers,
535
641
  });
536
642
  }
537
- async serveRequest(request) {
538
- 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);
539
648
  // Only handle GET and HEAD
540
649
  if (request.method !== 'GET' && request.method !== 'HEAD') {
541
650
  return null;
542
651
  }
543
- const url = new URL(request.url);
544
- 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
+ }
545
662
  // Custom health check route
546
- if (pathname === '/healthz') {
663
+ if (options.healthCheck !== false && pathname === '/healthz') {
547
664
  return new Response("OK", { status: 200 });
548
665
  }
666
+ const selected = await this.checkSelectedCollection(request, scope);
667
+ if (selected instanceof Response) {
668
+ return selected;
669
+ }
670
+ scope = selected.scope;
549
671
  // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
550
- const keyPath = requestAcceptsTextHtml(request) ? pathname : `${pathname}|no-html`;
551
- 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;
677
+ }
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;
552
771
  }
553
- async serveRequestFromStorage(request, pathname) {
554
- const serverConfig = await this.getServerConfig();
555
- if (serverConfig == null && this.activeCollectionName === this.defaultCollectionName) {
772
+ async serveRequestFromStorage(scope, request, pathname, fallback) {
773
+ const serverConfig = await this.getServerConfigFor(scope);
774
+ if (serverConfig == null && scope.collectionName === this.defaultCollectionName) {
556
775
  return new Response(`Settings not found. You may need to publish your application.`, {
557
776
  status: 500,
558
777
  headers: {
@@ -564,48 +783,46 @@ export class PublisherServer {
564
783
  // that expired, gets a 404. It can be published at any time, so the
565
784
  // response cache does not store this response.
566
785
  if (serverConfig == null ||
567
- (this.activeCollectionName !== this.defaultCollectionName && await this.getAssetEntryMap() == null)) {
568
- this.doNotStoreResponse = true;
569
- return new Response(`Collection '${this.activeCollectionName}' is not available. It is not published, or it expired.`, {
570
- status: 404,
571
- headers: {
572
- 'content-type': 'text/plain',
573
- 'x-content-type-options': 'nosniff',
574
- 'cache-control': 'no-store',
575
- },
576
- });
786
+ (scope.collectionName !== this.defaultCollectionName && await this.getAssetEntryMapFor(scope) == null)) {
787
+ scope.doNotStoreResponse = true;
788
+ return collectionNotAvailableResponse(scope.collectionName);
577
789
  }
578
- const asset = await this.getMatchingAsset(serverConfig.publicDirPrefix + pathname, true);
790
+ const asset = await this.getMatchingAssetFor(scope, serverConfig.publicDirPrefix + pathname, true, false);
579
791
  if (asset != null) {
580
- return this.serveAsset(request, asset, {
581
- cache: await this.testExtendedCache(pathname) ? 'extended' : null,
792
+ return this.serveAssetFor(scope, request, asset, {
793
+ cache: await this.testExtendedCacheFor(scope, pathname) ? 'extended' : null,
582
794
  });
583
795
  }
584
- // fallback HTML responses, like SPA and "not found" pages
585
- if (requestAcceptsTextHtml(request)) {
586
- const assetEntryMap = await this.getAssetEntryMap();
587
- if (assetEntryMap == null) {
588
- return null;
589
- }
590
- // These are raw asset paths, not relative to public path
591
- const { spaFile } = serverConfig;
592
- if (spaFile != null) {
593
- const asset = assetEntryMap[spaFile];
594
- if (asset != null) {
595
- return this.serveAsset(request, asset, {
596
- cache: 'never',
597
- });
598
- }
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
+ });
599
816
  }
600
- const { notFoundPageFile } = serverConfig;
601
- if (notFoundPageFile != null) {
602
- const asset = assetEntryMap[notFoundPageFile];
603
- if (asset != null) {
604
- return this.serveAsset(request, asset, {
605
- status: 404,
606
- cache: 'never',
607
- });
608
- }
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
+ });
609
826
  }
610
827
  }
611
828
  return null;