@fastly/compute-js-static-publish 6.2.0 → 7.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +31 -575
  3. package/README.short.md +53 -0
  4. package/build/cli/commands/clean.d.ts +2 -0
  5. package/build/cli/commands/clean.d.ts.map +1 -0
  6. package/build/cli/commands/clean.js +121 -0
  7. package/build/cli/commands/collections/delete.d.ts +2 -0
  8. package/build/cli/commands/collections/delete.d.ts.map +1 -0
  9. package/build/cli/commands/collections/delete.js +88 -0
  10. package/build/cli/commands/collections/index.d.ts +2 -0
  11. package/build/cli/commands/collections/index.d.ts.map +1 -0
  12. package/build/cli/commands/collections/index.js +52 -0
  13. package/build/cli/commands/collections/list.d.ts +2 -0
  14. package/build/cli/commands/collections/list.d.ts.map +1 -0
  15. package/build/cli/commands/collections/list.js +62 -0
  16. package/build/cli/commands/index.d.ts +2 -0
  17. package/build/cli/commands/index.d.ts.map +1 -0
  18. package/build/cli/commands/index.js +67 -0
  19. package/build/cli/commands/init-app.d.ts +18 -2
  20. package/build/cli/commands/init-app.d.ts.map +1 -1
  21. package/build/cli/commands/init-app.js +291 -264
  22. package/build/cli/commands/publish-content.d.ts +2 -0
  23. package/build/cli/commands/publish-content.d.ts.map +1 -0
  24. package/build/cli/commands/publish-content.js +472 -0
  25. package/build/cli/compression/brotli.d.ts +1 -1
  26. package/build/cli/compression/brotli.d.ts.map +1 -1
  27. package/build/cli/compression/brotli.js +8 -11
  28. package/build/cli/compression/gzip.d.ts +1 -1
  29. package/build/cli/compression/gzip.d.ts.map +1 -1
  30. package/build/cli/compression/gzip.js +8 -11
  31. package/build/cli/compression/index.d.ts +3 -6
  32. package/build/cli/compression/index.d.ts.map +1 -1
  33. package/build/cli/compression/index.js +8 -9
  34. package/build/cli/fastly-api/api-token.d.ts +17 -0
  35. package/build/cli/fastly-api/api-token.d.ts.map +1 -0
  36. package/build/cli/fastly-api/api-token.js +94 -0
  37. package/build/cli/fastly-api/kv-store.d.ts +24 -0
  38. package/build/cli/fastly-api/kv-store.d.ts.map +1 -0
  39. package/build/cli/{util → fastly-api}/kv-store.js +42 -22
  40. package/build/cli/index.js +7 -91
  41. package/build/cli/util/args.d.ts +16 -0
  42. package/build/cli/util/args.d.ts.map +1 -0
  43. package/build/cli/util/args.js +55 -0
  44. package/build/cli/util/config.d.ts +13 -0
  45. package/build/cli/util/config.d.ts.map +1 -0
  46. package/build/cli/{load-config.js → util/config.js} +234 -187
  47. package/build/{util → cli/util}/content-types.d.ts +1 -2
  48. package/build/cli/util/content-types.d.ts.map +1 -0
  49. package/build/{util → cli/util}/content-types.js +38 -32
  50. package/build/cli/util/data.d.ts +3 -3
  51. package/build/cli/util/data.d.ts.map +1 -1
  52. package/build/cli/util/data.js +6 -2
  53. package/build/cli/util/files.d.ts +10 -2
  54. package/build/cli/util/files.d.ts.map +1 -1
  55. package/build/cli/util/files.js +53 -6
  56. package/build/cli/util/kv-store-items.d.ts +12 -0
  57. package/build/cli/util/kv-store-items.d.ts.map +1 -0
  58. package/build/cli/util/kv-store-items.js +161 -0
  59. package/build/cli/util/kv-store-local-server.d.ts +3 -0
  60. package/build/cli/util/kv-store-local-server.d.ts.map +1 -0
  61. package/build/cli/util/kv-store-local-server.js +35 -0
  62. package/build/cli/util/package.d.ts +9 -0
  63. package/build/cli/util/package.d.ts.map +1 -0
  64. package/build/cli/util/package.js +44 -0
  65. package/build/cli/util/retryable.d.ts +12 -0
  66. package/build/cli/util/retryable.d.ts.map +1 -0
  67. package/build/cli/util/retryable.js +43 -0
  68. package/build/cli/util/variants.d.ts +4 -0
  69. package/build/cli/util/variants.d.ts.map +1 -0
  70. package/build/cli/util/variants.js +27 -0
  71. package/build/index.d.ts +5 -5
  72. package/build/index.d.ts.map +1 -1
  73. package/build/index.js +7 -6
  74. package/build/models/assets/kvstore-assets.d.ts +17 -0
  75. package/build/models/assets/kvstore-assets.d.ts.map +1 -0
  76. package/build/models/assets/kvstore-assets.js +28 -0
  77. package/build/{constants/compression.d.ts → models/compression/index.d.ts} +2 -1
  78. package/build/models/compression/index.d.ts.map +1 -0
  79. package/build/models/compression/index.js +11 -0
  80. package/build/models/config/publish-content-config.d.ts +41 -0
  81. package/build/models/config/publish-content-config.d.ts.map +1 -0
  82. package/build/models/config/publish-content-config.js +5 -0
  83. package/build/models/config/publisher-server-config.d.ts +20 -0
  84. package/build/models/config/publisher-server-config.d.ts.map +1 -0
  85. package/build/models/config/publisher-server-config.js +5 -0
  86. package/build/models/config/static-publish-rc.d.ts +6 -0
  87. package/build/models/config/static-publish-rc.d.ts.map +1 -0
  88. package/build/models/config/static-publish-rc.js +5 -0
  89. package/build/server/collection-selector/from-config-store.d.ts +2 -0
  90. package/build/server/collection-selector/from-config-store.d.ts.map +1 -0
  91. package/build/server/collection-selector/from-config-store.js +15 -0
  92. package/build/server/collection-selector/from-cookie.d.ts +23 -0
  93. package/build/server/collection-selector/from-cookie.d.ts.map +1 -0
  94. package/build/server/collection-selector/from-cookie.js +98 -0
  95. package/build/server/collection-selector/from-request.d.ts +13 -0
  96. package/build/server/collection-selector/from-request.d.ts.map +1 -0
  97. package/build/server/collection-selector/from-request.js +22 -0
  98. package/build/server/collection-selector/index.d.ts +5 -0
  99. package/build/server/collection-selector/index.d.ts.map +1 -0
  100. package/build/server/collection-selector/index.js +7 -0
  101. package/build/server/collection-selector/request-collection-selector.d.ts +5 -0
  102. package/build/server/collection-selector/request-collection-selector.d.ts.map +1 -0
  103. package/build/server/collection-selector/request-collection-selector.js +5 -0
  104. package/build/server/publisher-server/index.d.ts +38 -0
  105. package/build/server/publisher-server/index.d.ts.map +1 -0
  106. package/build/server/publisher-server/index.js +415 -0
  107. package/build/server/publisher-server/serve-preconditions/if-modified-since.d.ts +3 -0
  108. package/build/server/publisher-server/serve-preconditions/if-modified-since.d.ts.map +1 -0
  109. package/build/server/{serve-preconditions → publisher-server/serve-preconditions}/if-modified-since.js +6 -2
  110. package/build/server/publisher-server/serve-preconditions/if-none-match.d.ts.map +1 -0
  111. package/build/server/{serve-preconditions → publisher-server/serve-preconditions}/if-none-match.js +4 -0
  112. package/build/server/util/cookies.d.ts +2 -0
  113. package/build/server/util/cookies.d.ts.map +1 -0
  114. package/build/server/util/cookies.js +14 -0
  115. package/build/server/util/kv-store.d.ts +3 -0
  116. package/build/server/util/kv-store.d.ts.map +1 -0
  117. package/build/server/util/kv-store.js +95 -0
  118. package/package.json +18 -10
  119. package/build/cli/commands/build-static.d.ts +0 -3
  120. package/build/cli/commands/build-static.d.ts.map +0 -1
  121. package/build/cli/commands/build-static.js +0 -541
  122. package/build/cli/commands/clean-kv-store.d.ts +0 -3
  123. package/build/cli/commands/clean-kv-store.d.ts.map +0 -1
  124. package/build/cli/commands/clean-kv-store.js +0 -55
  125. package/build/cli/load-config.d.ts +0 -6
  126. package/build/cli/load-config.d.ts.map +0 -1
  127. package/build/cli/presets/implementations/astro.d.ts +0 -7
  128. package/build/cli/presets/implementations/astro.d.ts.map +0 -1
  129. package/build/cli/presets/implementations/astro.js +0 -23
  130. package/build/cli/presets/implementations/create-react-app.d.ts +0 -11
  131. package/build/cli/presets/implementations/create-react-app.d.ts.map +0 -1
  132. package/build/cli/presets/implementations/create-react-app.js +0 -34
  133. package/build/cli/presets/implementations/docusaurus.d.ts +0 -7
  134. package/build/cli/presets/implementations/docusaurus.d.ts.map +0 -1
  135. package/build/cli/presets/implementations/docusaurus.js +0 -13
  136. package/build/cli/presets/implementations/gatsby.d.ts +0 -7
  137. package/build/cli/presets/implementations/gatsby.d.ts.map +0 -1
  138. package/build/cli/presets/implementations/gatsby.js +0 -13
  139. package/build/cli/presets/implementations/next.d.ts +0 -7
  140. package/build/cli/presets/implementations/next.d.ts.map +0 -1
  141. package/build/cli/presets/implementations/next.js +0 -13
  142. package/build/cli/presets/implementations/sveltekit.d.ts +0 -7
  143. package/build/cli/presets/implementations/sveltekit.d.ts.map +0 -1
  144. package/build/cli/presets/implementations/sveltekit.js +0 -13
  145. package/build/cli/presets/implementations/vite.d.ts +0 -7
  146. package/build/cli/presets/implementations/vite.d.ts.map +0 -1
  147. package/build/cli/presets/implementations/vite.js +0 -13
  148. package/build/cli/presets/implementations/vue.d.ts +0 -7
  149. package/build/cli/presets/implementations/vue.d.ts.map +0 -1
  150. package/build/cli/presets/implementations/vue.js +0 -24
  151. package/build/cli/presets/index.d.ts +0 -3
  152. package/build/cli/presets/index.d.ts.map +0 -1
  153. package/build/cli/presets/index.js +0 -20
  154. package/build/cli/presets/preset-base.d.ts +0 -21
  155. package/build/cli/presets/preset-base.d.ts.map +0 -1
  156. package/build/cli/presets/preset-base.js +0 -1
  157. package/build/cli/util/fastly-api.d.ts +0 -10
  158. package/build/cli/util/fastly-api.d.ts.map +0 -1
  159. package/build/cli/util/fastly-api.js +0 -47
  160. package/build/cli/util/hash.d.ts +0 -5
  161. package/build/cli/util/hash.d.ts.map +0 -1
  162. package/build/cli/util/hash.js +0 -9
  163. package/build/cli/util/id.d.ts +0 -3
  164. package/build/cli/util/id.d.ts.map +0 -1
  165. package/build/cli/util/id.js +0 -17
  166. package/build/cli/util/kv-store.d.ts +0 -16
  167. package/build/cli/util/kv-store.d.ts.map +0 -1
  168. package/build/cli/util/publish-id.d.ts +0 -5
  169. package/build/cli/util/publish-id.d.ts.map +0 -1
  170. package/build/cli/util/publish-id.js +0 -26
  171. package/build/compute-js.d.ts +0 -3
  172. package/build/compute-js.d.ts.map +0 -1
  173. package/build/compute-js.js +0 -2
  174. package/build/constants/compression.d.ts.map +0 -1
  175. package/build/constants/compression.js +0 -4
  176. package/build/server/assets/asset-manager.d.ts +0 -8
  177. package/build/server/assets/asset-manager.d.ts.map +0 -1
  178. package/build/server/assets/asset-manager.js +0 -14
  179. package/build/server/assets/content-asset-kv-store.d.ts +0 -19
  180. package/build/server/assets/content-asset-kv-store.d.ts.map +0 -1
  181. package/build/server/assets/content-asset-kv-store.js +0 -70
  182. package/build/server/assets/content-asset-wasm-inline.d.ts +0 -18
  183. package/build/server/assets/content-asset-wasm-inline.d.ts.map +0 -1
  184. package/build/server/assets/content-asset-wasm-inline.js +0 -52
  185. package/build/server/assets/content-assets.d.ts +0 -46
  186. package/build/server/assets/content-assets.d.ts.map +0 -1
  187. package/build/server/assets/content-assets.js +0 -100
  188. package/build/server/assets/module-assets.d.ts +0 -23
  189. package/build/server/assets/module-assets.d.ts.map +0 -1
  190. package/build/server/assets/module-assets.js +0 -45
  191. package/build/server/kv-store/inline-store-entry.d.ts +0 -25
  192. package/build/server/kv-store/inline-store-entry.d.ts.map +0 -1
  193. package/build/server/kv-store/inline-store-entry.js +0 -100
  194. package/build/server/publisher-server.d.ts +0 -23
  195. package/build/server/publisher-server.d.ts.map +0 -1
  196. package/build/server/publisher-server.js +0 -257
  197. package/build/server/serve-preconditions/if-modified-since.d.ts +0 -4
  198. package/build/server/serve-preconditions/if-modified-since.d.ts.map +0 -1
  199. package/build/server/serve-preconditions/if-none-match.d.ts.map +0 -1
  200. package/build/server/util/http.d.ts +0 -2
  201. package/build/server/util/http.d.ts.map +0 -1
  202. package/build/server/util/http.js +0 -9
  203. package/build/types/compute.d.ts +0 -11
  204. package/build/types/compute.d.ts.map +0 -1
  205. package/build/types/compute.js +0 -1
  206. package/build/types/config-normalized.d.ts +0 -34
  207. package/build/types/config-normalized.d.ts.map +0 -1
  208. package/build/types/config-normalized.js +0 -1
  209. package/build/types/config.d.ts +0 -37
  210. package/build/types/config.d.ts.map +0 -1
  211. package/build/types/config.js +0 -1
  212. package/build/types/content-assets.d.ts +0 -55
  213. package/build/types/content-assets.d.ts.map +0 -1
  214. package/build/types/content-assets.js +0 -1
  215. package/build/types/content-types.d.ts +0 -11
  216. package/build/types/content-types.d.ts.map +0 -1
  217. package/build/types/content-types.js +0 -1
  218. package/build/types/index.d.ts +0 -7
  219. package/build/types/index.d.ts.map +0 -1
  220. package/build/types/index.js +0 -1
  221. package/build/types/module-assets.d.ts +0 -15
  222. package/build/types/module-assets.d.ts.map +0 -1
  223. package/build/types/module-assets.js +0 -1
  224. package/build/types/util.d.ts +0 -7
  225. package/build/types/util.d.ts.map +0 -1
  226. package/build/types/util.js +0 -1
  227. package/build/util/content-types.d.ts.map +0 -1
  228. package/build/util/index.d.ts +0 -3
  229. package/build/util/index.d.ts.map +0 -1
  230. package/build/util/index.js +0 -2
  231. package/build/util/metadata.d.ts +0 -3
  232. package/build/util/metadata.d.ts.map +0 -1
  233. package/build/util/metadata.js +0 -12
  234. package/resources/README.md +0 -3
  235. package/resources/statics-metadata.d.ts +0 -10
  236. package/resources/statics.d.ts +0 -19
  237. package/resources/webpack.config.js +0 -33
  238. /package/build/server/{serve-preconditions → publisher-server/serve-preconditions}/if-none-match.d.ts +0 -0
@@ -0,0 +1,415 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ /// <reference types="@fastly/js-compute" />
6
+ import { KVStore } from 'fastly:kv-store';
7
+ import { isKVAssetVariantMetadata, } from '../../models/assets/kvstore-assets.js';
8
+ import { getKVStoreEntry } from '../util/kv-store.js';
9
+ import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-preconditions/if-modified-since.js';
10
+ import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
11
+ export function buildHeadersSubset(responseHeaders, keys) {
12
+ const resultHeaders = new Headers();
13
+ for (const value of keys) {
14
+ if (value in responseHeaders) {
15
+ const responseHeaderValue = responseHeaders.get(value);
16
+ if (responseHeaderValue != null) {
17
+ resultHeaders.set(value, responseHeaderValue);
18
+ }
19
+ }
20
+ }
21
+ return resultHeaders;
22
+ }
23
+ // https://httpwg.org/specs/rfc9110.html#rfc.section.15.4.5
24
+ // The server generating a 304 response MUST generate any of the following header fields that would have been sent in
25
+ // a 200 (OK) response to the same request:
26
+ // * Content-Location, Date, ETag, and Vary
27
+ // * Cache-Control and Expires
28
+ const headersToPreserveForUnmodified = ['Content-Location', 'ETag', 'Vary', 'Cache-Control', 'Expires'];
29
+ function requestAcceptsTextHtml(req) {
30
+ const accept = (req.headers.get('Accept') ?? '')
31
+ .split(',')
32
+ .map(x => x.split(';')[0]);
33
+ if (!accept.includes('text/html') && !accept.includes('*/*') && accept.includes('*')) {
34
+ return false;
35
+ }
36
+ return true;
37
+ }
38
+ export class PublisherServer {
39
+ constructor(publishId, kvStoreName, defaultCollectionName) {
40
+ this.publishId = publishId;
41
+ this.kvStoreName = kvStoreName;
42
+ this.defaultCollectionName = defaultCollectionName;
43
+ this.activeCollectionName = this.defaultCollectionName;
44
+ this.collectionNameHeader = 'X-Publisher-Server-Collection';
45
+ }
46
+ static fromStaticPublishRc(config) {
47
+ return new PublisherServer(config.publishId, config.kvStoreName, config.defaultCollectionName);
48
+ }
49
+ setActiveCollectionName(collectionName) {
50
+ this.activeCollectionName = collectionName;
51
+ }
52
+ setCollectionNameHeader(collectionHeader) {
53
+ this.collectionNameHeader = collectionHeader;
54
+ }
55
+ // Server config is obtained from the KV Store, and cached for the duration of this object.
56
+ // TODO get from simple cache
57
+ async getServerConfig() {
58
+ const settingsFileKey = `${this.publishId}_settings_${this.activeCollectionName}`;
59
+ const kvStore = new KVStore(this.kvStoreName);
60
+ const settingsFile = await getKVStoreEntry(kvStore, settingsFileKey);
61
+ if (settingsFile == null) {
62
+ console.error(`Settings File not found at ${settingsFileKey}.`);
63
+ console.error(`You may need to publish your application.`);
64
+ return null;
65
+ }
66
+ return (await settingsFile.json());
67
+ }
68
+ async getStaticItems() {
69
+ const serverConfig = await this.getServerConfig();
70
+ if (serverConfig == null) {
71
+ return [];
72
+ }
73
+ return serverConfig.staticItems
74
+ .map((x, i) => {
75
+ if (x.startsWith('re:')) {
76
+ const fragments = x.slice(3).match(/\/(.*?)\/([a-z]*)?$/i);
77
+ if (fragments == null) {
78
+ console.warn(`Cannot parse staticItems item index ${i}: '${x}', skipping...`);
79
+ return '';
80
+ }
81
+ return new RegExp(fragments[1], fragments[2] || '');
82
+ }
83
+ return x;
84
+ })
85
+ .filter(x => Boolean(x));
86
+ }
87
+ async getKvAssetsIndex() {
88
+ const indexFileKey = `${this.publishId}_index_${this.activeCollectionName}`;
89
+ const kvStore = new KVStore(this.kvStoreName);
90
+ const indexFile = await getKVStoreEntry(kvStore, indexFileKey);
91
+ if (indexFile == null) {
92
+ console.error(`Index File not found at ${indexFileKey}.`);
93
+ console.error(`You may need to publish your application.`);
94
+ return null;
95
+ }
96
+ return (await indexFile.json());
97
+ }
98
+ async getMatchingAsset(assetKey, applyAuto = false) {
99
+ const serverConfig = await this.getServerConfig();
100
+ if (serverConfig == null) {
101
+ return null;
102
+ }
103
+ const kvAssetsIndex = await this.getKvAssetsIndex();
104
+ if (kvAssetsIndex == null) {
105
+ return null;
106
+ }
107
+ if (!assetKey.endsWith('/')) {
108
+ // A path that does not end in a slash can match an asset directly
109
+ const asset = kvAssetsIndex[assetKey];
110
+ if (asset != null) {
111
+ return asset;
112
+ }
113
+ if (applyAuto) {
114
+ // ... or, we can try auto-ext:
115
+ // looks for an asset that has the specified suffix (usually extension, such as .html)
116
+ for (const extEntry of serverConfig.autoExt) {
117
+ let assetKeyWithExt = assetKey + extEntry;
118
+ const asset = kvAssetsIndex[assetKeyWithExt];
119
+ if (asset != null) {
120
+ return asset;
121
+ }
122
+ }
123
+ }
124
+ }
125
+ if (applyAuto) {
126
+ if (serverConfig.autoIndex.length > 0) {
127
+ // try auto-index:
128
+ // treats the path as a directory, and looks for an asset with the specified
129
+ // suffix (usually an index file, such as index.html)
130
+ let assetNameAsDir = assetKey;
131
+ // remove all slashes from end, and add one trailing slash
132
+ while (assetNameAsDir.endsWith('/')) {
133
+ assetNameAsDir = assetNameAsDir.slice(0, -1);
134
+ }
135
+ assetNameAsDir = assetNameAsDir + '/';
136
+ for (const indexEntry of serverConfig.autoIndex) {
137
+ let assetKeyIndex = assetNameAsDir + indexEntry;
138
+ const asset = kvAssetsIndex[assetKeyIndex];
139
+ if (asset != null) {
140
+ return asset;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+ // A pedantic function that returns all content types that are requested for in the accept-encoding header that are
148
+ // accepted by the server config, grouped by descending order of q values.
149
+ // For example, if accept-encoding had br;q=1,gzip;q=0.5, and the server accepts both br and gzip,
150
+ // the result would be [['br'], ['gzip']]
151
+ async findAcceptEncodingsGroups(request) {
152
+ const serverConfig = await this.getServerConfig();
153
+ if (serverConfig == null || serverConfig.allowedEncodings.length === 0) {
154
+ return [];
155
+ }
156
+ const acceptEncodingHeader = request.headers.get('accept-encoding')?.trim() ?? '';
157
+ if (acceptEncodingHeader == '') {
158
+ return [];
159
+ }
160
+ const priorityMap = new Map;
161
+ for (const headerValue of acceptEncodingHeader.trim().split(',')) {
162
+ let [encodingValue, qValueStr] = headerValue.trim().split(';');
163
+ encodingValue = encodingValue.trim();
164
+ if (!serverConfig.allowedEncodings.includes(encodingValue)) {
165
+ continue;
166
+ }
167
+ let qValue; // q value multiplied by 1000
168
+ if (qValueStr == null || !qValueStr.startsWith('q=')) {
169
+ // use default of 1.0
170
+ qValue = 1000;
171
+ }
172
+ else {
173
+ qValueStr = qValueStr.slice(2); // remove the q=
174
+ qValue = parseFloat(qValueStr);
175
+ if (Number.isNaN(qValue) || qValue > 1) {
176
+ qValue = 1;
177
+ }
178
+ if (qValue < 0) {
179
+ qValue = 0;
180
+ }
181
+ // q values can have up to 3 decimal digits
182
+ qValue = Math.floor(qValue * 1000);
183
+ }
184
+ let typesForQValue = priorityMap.get(qValue);
185
+ if (typesForQValue == null) {
186
+ typesForQValue = [];
187
+ priorityMap.set(qValue, typesForQValue);
188
+ }
189
+ typesForQValue.push(encodingValue);
190
+ }
191
+ // Sort keys, larger numbers to come first
192
+ const keysSorted = [...priorityMap.keys()]
193
+ .sort((qValueA, qValueB) => qValueB - qValueA);
194
+ return keysSorted
195
+ .map(qValue => priorityMap.get(qValue));
196
+ }
197
+ async testExtendedCache(pathname) {
198
+ const staticItems = await this.getStaticItems();
199
+ return staticItems
200
+ .some(x => {
201
+ if (x instanceof RegExp) {
202
+ return x.test(pathname);
203
+ }
204
+ if (x.endsWith('/')) {
205
+ return pathname.startsWith(x);
206
+ }
207
+ return x === pathname;
208
+ });
209
+ }
210
+ handlePreconditions(request, asset, responseHeaders) {
211
+ // Handle preconditions according to https://httpwg.org/specs/rfc9110.html#rfc.section.13.2.2
212
+ // A recipient cache or origin server MUST evaluate the request preconditions defined by this specification in the following order:
213
+ // 1. When recipient is the origin server and If-Match is present, evaluate the If-Match precondition:
214
+ // - if true, continue to step 3
215
+ // - if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see Section 13.1.1)
216
+ // 2. When recipient is the origin server, If-Match is not present, and If-Unmodified-Since is present, evaluate the If-Unmodified-Since precondition:
217
+ // - if true, continue to step 3
218
+ // - if false, respond 412 (Precondition Failed) unless it can be determined that the state-changing request has already succeeded (see Section 13.1.4)
219
+ // 3. When If-None-Match is present, evaluate the If-None-Match precondition:
220
+ // - if true, continue to step 5
221
+ // - if false for GET/HEAD, respond 304 (Not Modified)
222
+ // - if false for other methods, respond 412 (Precondition Failed)
223
+ let skipIfNoneMatch = false;
224
+ {
225
+ const headerValue = getIfNoneMatchHeader(request);
226
+ if (headerValue.length > 0) {
227
+ const result = checkIfNoneMatch(responseHeaders.get('ETag'), headerValue);
228
+ if (result) {
229
+ skipIfNoneMatch = true;
230
+ }
231
+ else {
232
+ return new Response(null, {
233
+ status: 304,
234
+ headers: buildHeadersSubset(responseHeaders, headersToPreserveForUnmodified),
235
+ });
236
+ }
237
+ }
238
+ }
239
+ // 4. When the method is GET or HEAD, If-None-Match is not present, and If-Modified-Since is present, evaluate the
240
+ // If-Modified-Since precondition:
241
+ // - if true, continue to step 5
242
+ // - if false, respond 304 (Not Modified)
243
+ if (!skipIfNoneMatch) {
244
+ // For us, method is always GET or HEAD here.
245
+ const headerValue = getIfModifiedSinceHeader(request);
246
+ if (headerValue != null) {
247
+ const result = checkIfModifiedSince(asset.lastModifiedTime, headerValue);
248
+ if (!result) {
249
+ return new Response(null, {
250
+ status: 304,
251
+ headers: buildHeadersSubset(responseHeaders, headersToPreserveForUnmodified),
252
+ });
253
+ }
254
+ }
255
+ }
256
+ // 5. When the method is GET and both Range and If-Range are present, evaluate the If-Range precondition:
257
+ // - if true and the Range is applicable to the selected representation, respond 206 (Partial Content)
258
+ // - otherwise, ignore the Range header field and respond 200 (OK)
259
+ // 6. Otherwise,
260
+ // - perform the requested method and respond according to its success or failure.
261
+ return null;
262
+ }
263
+ async loadKvAssetVariant(entry, variant) {
264
+ const kvStore = new KVStore(this.kvStoreName);
265
+ const baseHash = entry.key.slice(7);
266
+ const baseKey = `${this.publishId}_files_sha256_${baseHash}`;
267
+ const variantKey = variant != null ? `${baseKey}_${variant}` : baseKey;
268
+ const kvStoreEntry = await getKVStoreEntry(kvStore, variantKey);
269
+ if (kvStoreEntry == null) {
270
+ return null;
271
+ }
272
+ const metadataText = kvStoreEntry.metadataText() ?? '';
273
+ if (metadataText === '') {
274
+ return null;
275
+ }
276
+ let metadata;
277
+ try {
278
+ metadata = JSON.parse(metadataText);
279
+ }
280
+ catch {
281
+ return null;
282
+ }
283
+ if (!isKVAssetVariantMetadata(metadata)) {
284
+ return null;
285
+ }
286
+ if (metadata.size == null) {
287
+ return null;
288
+ }
289
+ return {
290
+ kvStoreEntry,
291
+ ...metadata,
292
+ };
293
+ }
294
+ async findKVAssetVariantForAcceptEncodingsGroups(entry, acceptEncodingsGroups = []) {
295
+ if (!entry.key.startsWith('sha256:')) {
296
+ throw new TypeError(`Key must start with 'sha256:': ${entry.key}`);
297
+ }
298
+ // Each encodingGroup is an array of Accept-Encodings that have the same q value,
299
+ // with the highest first
300
+ for (const encodingGroup of acceptEncodingsGroups) {
301
+ let smallestSize = undefined;
302
+ let smallestEntry = undefined;
303
+ for (const encoding of encodingGroup) {
304
+ if (!entry.variants.includes(encoding)) {
305
+ continue;
306
+ }
307
+ const variantKvStoreEntry = await this.loadKvAssetVariant(entry, encoding);
308
+ if (variantKvStoreEntry == null) {
309
+ continue;
310
+ }
311
+ if (smallestSize == null || variantKvStoreEntry.size < smallestSize) {
312
+ smallestSize = variantKvStoreEntry.size;
313
+ smallestEntry = variantKvStoreEntry;
314
+ }
315
+ }
316
+ if (smallestEntry != null) {
317
+ return smallestEntry;
318
+ }
319
+ }
320
+ const baseKvStoreEntry = await this.loadKvAssetVariant(entry, null);
321
+ if (baseKvStoreEntry == null) {
322
+ throw new TypeError('Key not found: ' + entry.key);
323
+ }
324
+ return baseKvStoreEntry;
325
+ }
326
+ async serveAsset(request, asset, init) {
327
+ const headers = new Headers(init?.headers);
328
+ headers.set('Content-Type', asset.contentType);
329
+ if (this.collectionNameHeader) {
330
+ headers.set(this.collectionNameHeader, this.activeCollectionName);
331
+ headers.append('Vary', this.collectionNameHeader);
332
+ }
333
+ if (init?.cache != null) {
334
+ let cacheControlValue;
335
+ switch (init.cache) {
336
+ case 'extended':
337
+ cacheControlValue = 'max-age=31536000';
338
+ break;
339
+ case 'never':
340
+ cacheControlValue = 'no-store';
341
+ break;
342
+ }
343
+ headers.append('Cache-Control', cacheControlValue);
344
+ }
345
+ const acceptEncodings = await this.findAcceptEncodingsGroups(request);
346
+ const kvAssetVariant = await this.findKVAssetVariantForAcceptEncodingsGroups(asset, acceptEncodings);
347
+ if (kvAssetVariant.contentEncoding != null) {
348
+ headers.append('Content-Encoding', kvAssetVariant.contentEncoding);
349
+ }
350
+ headers.set('ETag', `"${kvAssetVariant.hash}"`);
351
+ if (asset.lastModifiedTime !== 0) {
352
+ headers.set('Last-Modified', (new Date(asset.lastModifiedTime * 1000)).toUTCString());
353
+ }
354
+ const preconditionResponse = this.handlePreconditions(request, asset, headers);
355
+ if (preconditionResponse != null) {
356
+ return preconditionResponse;
357
+ }
358
+ const kvStoreEntry = kvAssetVariant.kvStoreEntry;
359
+ return new Response(kvStoreEntry.body, {
360
+ status: init?.status ?? 200,
361
+ headers,
362
+ });
363
+ }
364
+ async serveRequest(request) {
365
+ // Only handle GET and HEAD
366
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
367
+ return null;
368
+ }
369
+ const url = new URL(request.url);
370
+ const pathname = decodeURI(url.pathname);
371
+ const serverConfig = await this.getServerConfig();
372
+ if (serverConfig == null) {
373
+ return new Response(`Settings not found. You may need to publish your application.`, {
374
+ status: 500,
375
+ headers: {
376
+ 'content-type': 'text/plain',
377
+ },
378
+ });
379
+ }
380
+ const asset = await this.getMatchingAsset(serverConfig.publicDirPrefix + pathname, true);
381
+ if (asset != null) {
382
+ return this.serveAsset(request, asset, {
383
+ cache: await this.testExtendedCache(pathname) ? 'extended' : null,
384
+ });
385
+ }
386
+ // fallback HTML responses, like SPA and "not found" pages
387
+ if (requestAcceptsTextHtml(request)) {
388
+ const kvAssetsIndex = await this.getKvAssetsIndex();
389
+ if (kvAssetsIndex == null) {
390
+ return null;
391
+ }
392
+ // These are raw asset paths, not relative to public path
393
+ const { spaFile } = serverConfig;
394
+ if (spaFile != null) {
395
+ const asset = kvAssetsIndex[spaFile];
396
+ if (asset != null) {
397
+ return this.serveAsset(request, asset, {
398
+ cache: 'never',
399
+ });
400
+ }
401
+ }
402
+ const { notFoundPageFile } = serverConfig;
403
+ if (notFoundPageFile != null) {
404
+ const asset = kvAssetsIndex[notFoundPageFile];
405
+ if (asset != null) {
406
+ return this.serveAsset(request, asset, {
407
+ status: 404,
408
+ cache: 'never',
409
+ });
410
+ }
411
+ }
412
+ }
413
+ return null;
414
+ }
415
+ }
@@ -0,0 +1,3 @@
1
+ export declare function getIfModifiedSinceHeader(request: Request): number | null;
2
+ export declare function checkIfModifiedSince(lastModifiedTime: number, ifModifiedSince: number): boolean;
3
+ //# sourceMappingURL=if-modified-since.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"if-modified-since.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/serve-preconditions/if-modified-since.ts"],"names":[],"mappings":"AAOA,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAgBxE;AAED,wBAAgB,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAW/F"}
@@ -1,3 +1,7 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
1
5
  // https://httpwg.org/specs/rfc9110.html#field.if-modified-since
2
6
  export function getIfModifiedSinceHeader(request) {
3
7
  // A recipient MUST ignore the If-Modified-Since header field if the received
@@ -15,10 +19,10 @@ export function getIfModifiedSinceHeader(request) {
15
19
  // We want to return this as a number of seconds;
16
20
  return Math.floor(dateValueMs / 1000);
17
21
  }
18
- export function checkIfModifiedSince(asset, ifModifiedSince) {
22
+ export function checkIfModifiedSince(lastModifiedTime, ifModifiedSince) {
19
23
  // 1. If the selected representation's last modification date is earlier or equal to the
20
24
  // date provided in the field value, the condition is false.
21
- if (asset.getMetadata().lastModifiedTime <= ifModifiedSince) {
25
+ if (lastModifiedTime <= ifModifiedSince) {
22
26
  return false;
23
27
  }
24
28
  // 2. Otherwise, the condition is true.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"if-none-match.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/serve-preconditions/if-none-match.ts"],"names":[],"mappings":"AAOA,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,EAAE,CAO/D;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,OAAO,CAmB7E"}
@@ -1,3 +1,7 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
1
5
  // https://httpwg.org/specs/rfc9110.html#field.if-none-match
2
6
  export function getIfNoneMatchHeader(request) {
3
7
  return (request.headers.get('If-None-Match') ?? '')
@@ -0,0 +1,2 @@
1
+ export declare function getCookieValue(request: Request, name: string): string | null;
2
+ //# sourceMappingURL=cookies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../../../src/server/util/cookies.ts"],"names":[],"mappings":"AAKA,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,iBAU5D"}
@@ -0,0 +1,14 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ export function getCookieValue(request, name) {
6
+ const cookieHeader = request.headers.get('Cookie');
7
+ if (!cookieHeader) {
8
+ return null;
9
+ }
10
+ return cookieHeader
11
+ .split(';')
12
+ .map(v => v.trim().split('='))
13
+ .find(([key]) => key === name)?.[1] ?? null;
14
+ }
@@ -0,0 +1,3 @@
1
+ import { KVStore, type KVStoreEntry } from 'fastly:kv-store';
2
+ export declare function getKVStoreEntry(kvStore: KVStore, key: string): Promise<KVStoreEntry | null>;
3
+ //# sourceMappingURL=kv-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv-store.d.ts","sourceRoot":"","sources":["../../../src/server/util/kv-store.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAwB7D,wBAAsB,eAAe,CACnC,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CA2C9B"}
@@ -0,0 +1,95 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ // This is a custom KVStoreEntry implementation that is built by using a body and
6
+ // metadataText passed in through the constructor. We piggyback off Response
7
+ // for the utility functions such as json() and text().
8
+ class CustomKVStoreEntry extends Response {
9
+ constructor(body, metadataText) {
10
+ super(body);
11
+ this.metadataTextValue = metadataText;
12
+ }
13
+ get body() {
14
+ return super.body;
15
+ }
16
+ metadata() {
17
+ return new TextEncoder().encode(this.metadataTextValue);
18
+ }
19
+ metadataText() {
20
+ return this.metadataTextValue;
21
+ }
22
+ }
23
+ export async function getKVStoreEntry(kvStore, key) {
24
+ const entry = await kvStore.get(key);
25
+ if (entry == null) {
26
+ return null;
27
+ }
28
+ const metadataText = entry.metadataText() ?? '';
29
+ if (metadataText === '') {
30
+ return entry;
31
+ }
32
+ let metadata;
33
+ try {
34
+ metadata = JSON.parse(metadataText);
35
+ }
36
+ catch {
37
+ return entry;
38
+ }
39
+ if (!('numChunks' in metadata) || typeof metadata.numChunks !== 'number') {
40
+ return entry;
41
+ }
42
+ if (metadata.numChunks < 2) {
43
+ return entry;
44
+ }
45
+ const streams = [
46
+ entry.body,
47
+ ];
48
+ for (let chunkIndex = 1; chunkIndex < metadata.numChunks; chunkIndex++) {
49
+ const chunkKey = `${key}_${chunkIndex}`;
50
+ const chunkEntry = await kvStore.get(chunkKey);
51
+ if (chunkEntry == null) {
52
+ throw new Error(`Missing chunk ${chunkKey}`);
53
+ }
54
+ streams.push(chunkEntry?.body);
55
+ }
56
+ const combinedStream = concatReadableStreams(streams);
57
+ return new CustomKVStoreEntry(combinedStream, metadataText);
58
+ }
59
+ function concatReadableStreams(streams) {
60
+ let currentStreamIndex = 0;
61
+ let currentReader = null;
62
+ return new ReadableStream({
63
+ async pull(controller) {
64
+ while (true) {
65
+ // If no current reader, get one from the next stream
66
+ if (!currentReader) {
67
+ if (currentStreamIndex >= streams.length) {
68
+ controller.close();
69
+ return;
70
+ }
71
+ currentReader = streams[currentStreamIndex].getReader();
72
+ }
73
+ const { value, done } = await currentReader.read();
74
+ if (done) {
75
+ currentReader.releaseLock();
76
+ currentReader = null;
77
+ currentStreamIndex++;
78
+ continue; // Go to next stream
79
+ }
80
+ controller.enqueue(value);
81
+ return; // Let pull() be called again
82
+ }
83
+ },
84
+ async cancel(reason) {
85
+ if (currentReader) {
86
+ try {
87
+ await currentReader.cancel(reason);
88
+ }
89
+ catch {
90
+ // swallow
91
+ }
92
+ }
93
+ }
94
+ });
95
+ }
package/package.json CHANGED
@@ -1,15 +1,22 @@
1
1
  {
2
2
  "name": "@fastly/compute-js-static-publish",
3
3
  "type": "module",
4
- "version": "6.2.0",
4
+ "version": "7.0.0-beta.0",
5
5
  "description": "Static Publisher for Fastly Compute JavaScript",
6
- "main": "./build/index.js",
7
- "types": "./build/index.d.ts",
6
+ "main": "build/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./build/index.d.ts",
10
+ "default": "./build/index.js"
11
+ }
12
+ },
8
13
  "scripts": {
9
14
  "clean": "rimraf build",
10
15
  "prepack": "npm run build",
11
- "build": "tsc",
12
- "test": "echo \"Error: no test specified\" && exit 1"
16
+ "build": "npm run clean && npm run compile",
17
+ "compile": "tsc",
18
+ "test": "echo \"Error: no test specified\" && exit 1",
19
+ "prepublishOnly": "cp README.short.md README.md"
13
20
  },
14
21
  "bin": {
15
22
  "compute-js-static-publish": "./build/cli/index.js"
@@ -31,22 +38,23 @@
31
38
  },
32
39
  "homepage": "https://github.com/fastly/compute-js-static-publish#readme",
33
40
  "dependencies": {
41
+ "@fastly/cli": "^11.2.0",
34
42
  "command-line-args": "^5.2.1",
35
43
  "glob-to-regexp": "^0.4.1"
36
44
  },
37
45
  "peerDependencies": {
38
- "@fastly/js-compute": "^2.0.0 || ^3.0.0"
46
+ "@fastly/js-compute": "^3.33.2"
39
47
  },
40
48
  "devDependencies": {
41
- "@fastly/js-compute": "^3.0.0",
49
+ "@fastly/js-compute": "^3.33.2",
42
50
  "@types/command-line-args": "^5.2.0",
43
51
  "@types/glob-to-regexp": "^0.4.1",
44
- "@types/node": "^18.0.0",
52
+ "@types/node": "^20.11.0",
45
53
  "rimraf": "^4.3.0",
46
- "typescript": "^5.0.2"
54
+ "typescript": "^5.8.0"
47
55
  },
48
56
  "engines": {
49
- "node": ">=18"
57
+ "node": ">=20.11.0"
50
58
  },
51
59
  "files": [
52
60
  "build",
@@ -1,3 +0,0 @@
1
- import commandLineArgs from "command-line-args";
2
- export declare function buildStaticLoader(commandLineValues: commandLineArgs.CommandLineOptions): Promise<void>;
3
- //# sourceMappingURL=build-static.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-static.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/build-static.ts"],"names":[],"mappings":"AA+DA,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAgJhD,wBAAsB,iBAAiB,CAAC,iBAAiB,EAAE,eAAe,CAAC,kBAAkB,iBA2e5F"}