@fastly/compute-js-static-publish 6.3.0 → 7.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +31 -586
  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 +299 -266
  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 +11 -6
  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 +418 -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 -41
  238. /package/build/server/{serve-preconditions → publisher-server/serve-preconditions}/if-none-match.d.ts +0 -0
@@ -0,0 +1,2 @@
1
+ export declare function action(argv: string[]): Promise<void>;
2
+ //# sourceMappingURL=publish-content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publish-content.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/publish-content.ts"],"names":[],"mappings":"AAiCA,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,iBAuiB1C"}
@@ -0,0 +1,472 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import * as fs from 'node:fs';
6
+ import * as path from 'node:path';
7
+ import commandLineArgs from 'command-line-args';
8
+ import { isKVAssetVariantMetadata } from '../../models/assets/kvstore-assets.js';
9
+ import { FetchError, loadApiToken } from '../fastly-api/api-token.js';
10
+ import { getKvStoreEntryInfo } from '../fastly-api/kv-store.js';
11
+ import { mergeContentTypes, testFileContentType } from '../util/content-types.js';
12
+ import { LoadConfigError, loadPublishContentConfigFile, loadStaticPublisherRcFile } from '../util/config.js';
13
+ import { applyDefaults } from '../util/data.js';
14
+ import { calculateFileSizeAndHash, enumerateFiles, getFileSize, rootRelative } from '../util/files.js';
15
+ import { applyKVStoreEntriesChunks, uploadFilesToKVStore } from '../util/kv-store-items.js';
16
+ import { writeKVStoreEntriesForLocal } from '../util/kv-store-local-server.js';
17
+ import { attemptWithRetries } from '../util/retryable.js';
18
+ import { ensureVariantFileExists } from '../util/variants.js';
19
+ // KV Store key format:
20
+ // <publishId>_index_<preview_id>.json
21
+ // <publishId>_settings_<preview_id>.json
22
+ // <publishId>_files_sha256_<hash>_<variant>
23
+ // split large files into 20MiB chunks
24
+ const KV_STORE_CHUNK_SIZE = 1024 * 1024 * 20;
25
+ export async function action(argv) {
26
+ const optionDefinitions = [
27
+ { name: 'verbose', type: Boolean, },
28
+ // Fastly API Token to use for this publishing.
29
+ { name: 'fastly-api-token', type: String, },
30
+ // Collection name to be used for this publishing.
31
+ { name: 'collection-name', type: String, },
32
+ // The 'root' directory for the publishing.
33
+ // All assets are expected to exist under this root. Required.
34
+ // For backwards compatibility, if this value is not provided,
35
+ // then the value of 'public-dir' is used.
36
+ { name: 'root-dir', type: String, },
37
+ { name: 'force-upload', type: Boolean },
38
+ { name: 'no-local', type: Boolean },
39
+ { name: 'local-only', type: Boolean },
40
+ { name: 'config', type: String },
41
+ ];
42
+ const commandLineValues = commandLineArgs(optionDefinitions, { argv });
43
+ const { verbose, ['fastly-api-token']: fastlyApiToken, ['collection-name']: collectionNameValue, ['root-dir']: rootDir, ['force-upload']: forceUpload, ['no-local']: noLocalMode, ['local-only']: localOnlyMode, ['config']: configFilePathValue, } = commandLineValues;
44
+ // no-local and local-only are mutually exclusive
45
+ if (noLocalMode && localOnlyMode) {
46
+ console.error("❌ '--no-local' and '--local-only' are mutually exclusive.");
47
+ process.exitCode = 1;
48
+ return;
49
+ }
50
+ // Create local files unless 'no-local' is set
51
+ const createLocalFiles = !noLocalMode;
52
+ // Use the KV Store unless 'local-only' is set
53
+ const useKvStore = !localOnlyMode;
54
+ const segments = [];
55
+ if (createLocalFiles) {
56
+ segments.push('for local simluated KV Store');
57
+ }
58
+ if (useKvStore) {
59
+ segments.push('to the Fastly KV Store');
60
+ }
61
+ console.log(`🚀 Publishing content ${segments.join(' and ')}...`);
62
+ let fastlyApiContext = undefined;
63
+ if (useKvStore) {
64
+ const apiTokenResult = loadApiToken({ commandLine: fastlyApiToken });
65
+ if (apiTokenResult == null) {
66
+ console.error("❌ Fastly API Token not provided.");
67
+ console.error("Set the FASTLY_API_TOKEN environment variable to an API token that has write access to the KV Store.");
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ fastlyApiContext = { apiToken: apiTokenResult.apiToken };
72
+ console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
73
+ }
74
+ // compute-js-static-publisher cli is always run from the Compute application directory
75
+ // in other words, the directory that contains `fastly.toml`.
76
+ const computeAppDir = path.resolve();
77
+ // #### load config
78
+ let staticPublisherRc;
79
+ try {
80
+ staticPublisherRc = await loadStaticPublisherRcFile();
81
+ }
82
+ catch (err) {
83
+ console.error("❌ Can't load static-publish.rc.js");
84
+ console.error("Run this from a compute-js-static-publish compute-js directory.");
85
+ if (err instanceof LoadConfigError) {
86
+ for (const error of err.errors) {
87
+ console.error(error);
88
+ }
89
+ }
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+ const configFilePath = configFilePathValue ?? './publish-content.config.js';
94
+ let publishContentConfig;
95
+ try {
96
+ publishContentConfig = await loadPublishContentConfigFile(configFilePath);
97
+ }
98
+ catch (err) {
99
+ console.error(`❌ Can't load ${configFilePath}`);
100
+ if (err instanceof LoadConfigError) {
101
+ for (const error of err.errors) {
102
+ console.error(error);
103
+ }
104
+ }
105
+ process.exitCode = 1;
106
+ return;
107
+ }
108
+ const publicDirRoot = path.resolve(rootDir != null ? rootDir : publishContentConfig.rootDir);
109
+ if ((computeAppDir + '/').startsWith(publicDirRoot + '/')) {
110
+ if (verbose) {
111
+ console.log(`‼️ Public directory '${rootRelative(publicDirRoot)}' includes the Compute app directory.`);
112
+ console.log(`This may be caused by an incorrect configuration, as this could cause Compute application source`);
113
+ console.log(`files to be included in your published output.`);
114
+ }
115
+ }
116
+ console.log(`✔️ Public directory '${rootRelative(publicDirRoot)}'.`);
117
+ const publishId = staticPublisherRc.publishId;
118
+ console.log(`✔️ Publish ID: ${publishId}`);
119
+ const kvStoreName = staticPublisherRc.kvStoreName;
120
+ console.log(`✔️ Using KV Store: ${kvStoreName}`);
121
+ const defaultCollectionName = staticPublisherRc.defaultCollectionName;
122
+ console.log(`✔️ Default Collection Name: ${defaultCollectionName}`);
123
+ // The Static Content Root Dir, which will hold loaders and content generated by this publishing.
124
+ const staticPublisherWorkingDir = publishContentConfig.staticPublisherWorkingDir;
125
+ // Load content types
126
+ const contentTypes = mergeContentTypes(publishContentConfig.contentTypes);
127
+ // #### Collect all file paths
128
+ console.log(`🔍 Scanning root directory ${rootRelative(publicDirRoot)}...`);
129
+ const excludeDirs = publishContentConfig.excludeDirs;
130
+ if (excludeDirs.length > 0) {
131
+ console.log(`✔️ Using exclude directories: ${excludeDirs.join(', ')}`);
132
+ }
133
+ else {
134
+ if (verbose) {
135
+ console.log(`✔️ No exclude directories defined.`);
136
+ }
137
+ }
138
+ const excludeDotFiles = publishContentConfig.excludeDotFiles;
139
+ if (excludeDotFiles) {
140
+ console.log(`✔️ Files/Directories starting with . are excluded.`);
141
+ }
142
+ const includeWellKnown = publishContentConfig.includeWellKnown;
143
+ if (includeWellKnown) {
144
+ console.log(`✔️ (.well-known is exempt from exclusion.)`);
145
+ }
146
+ // files to be included in the build/publish
147
+ const files = enumerateFiles({
148
+ publicDirRoot,
149
+ excludeDirs,
150
+ excludeDotFiles,
151
+ includeWellKnown,
152
+ });
153
+ // ### Collection name that we're currently publishing
154
+ // for example, live, staging
155
+ const collectionName = collectionNameValue ?? process.env.PUBLISHER_COLLECTION_NAME ?? defaultCollectionName;
156
+ const stats = {
157
+ kvStore: 0,
158
+ };
159
+ // Create "KV Store content" sub dir if it doesn't exist already.
160
+ // This will be used to hold a copy of files to prepare for upload to the KV Store
161
+ // and for serving using the local development server.
162
+ const staticPublisherKvStoreContent = `${staticPublisherWorkingDir}/kv-store-content`;
163
+ fs.mkdirSync(staticPublisherKvStoreContent, { recursive: true });
164
+ // A list of items in the KV Store at the end of the publishing.
165
+ // Includes items that already exist as well. 'write' signifies
166
+ // that the item is to be written
167
+ const kvStoreItemDescriptions = [];
168
+ // Assets included in the publishing, keyed by asset key
169
+ const kvAssetsIndex = {};
170
+ const baseHashToVariantMetadatasMap = new Map();
171
+ // #### Iterate files
172
+ for (const file of files) {
173
+ // #### asset key
174
+ const assetKey = file.slice(publicDirRoot.length)
175
+ // in Windows, assetKey will otherwise end up as \path\file.html
176
+ .replace(/\\/g, '/');
177
+ // #### decide what the Content Type will be
178
+ let contentTypeTestResult = testFileContentType(contentTypes, assetKey);
179
+ if (contentTypeTestResult == null) {
180
+ contentTypeTestResult = {
181
+ text: false,
182
+ contentType: 'application/octet-stream',
183
+ precompressAsset: false,
184
+ };
185
+ if (verbose) {
186
+ console.log('⚠️ Notice: Unknown file type ' + assetKey + '. Treating as binary file.');
187
+ }
188
+ }
189
+ const contentType = contentTypeTestResult.contentType;
190
+ const contentCompression = contentTypeTestResult.precompressAsset ? publishContentConfig.contentCompression : [];
191
+ // #### Are we going to include this file?
192
+ let includeAsset;
193
+ if (publishContentConfig.kvStoreAssetInclusionTest != null) {
194
+ includeAsset = publishContentConfig.kvStoreAssetInclusionTest(assetKey, contentType);
195
+ }
196
+ else {
197
+ // If no test is set, then default to inclusion
198
+ includeAsset = true;
199
+ }
200
+ if (!includeAsset) {
201
+ continue;
202
+ }
203
+ // #### Base file size, hash, last modified time
204
+ const { size: baseSize, hash: baseHash } = await calculateFileSizeAndHash(file);
205
+ console.log(`📄 File '${rootRelative(file)}' - ${baseSize} bytes, sha256: ${baseHash}`);
206
+ const stats = fs.statSync(file);
207
+ const lastModifiedTime = Math.floor((stats.mtime).getTime() / 1000);
208
+ // #### Metadata per variant
209
+ let variantMetadatas = baseHashToVariantMetadatasMap.get(baseHash);
210
+ if (variantMetadatas == null) {
211
+ variantMetadatas = new Map();
212
+ baseHashToVariantMetadatasMap.set(baseHash, variantMetadatas);
213
+ }
214
+ const variantsToKeep = [];
215
+ const variants = [
216
+ 'original',
217
+ ...contentCompression,
218
+ ];
219
+ for (const variant of variants) {
220
+ let variantKey = `${publishId}_files_sha256_${baseHash}`;
221
+ let variantFilename = `${baseHash}`;
222
+ if (variant !== 'original') {
223
+ variantKey = `${variantKey}_${variant}`;
224
+ variantFilename = `${variantFilename}_${variant}`;
225
+ }
226
+ const variantFilePath = path.resolve(staticPublisherKvStoreContent, variantFilename);
227
+ let variantMetadata = variantMetadatas.get(variant);
228
+ if (variantMetadata != null) {
229
+ console.log(` 🏃‍♂️ Asset "${variantKey}" is identical to an item we already know about, reusing existing copy.`);
230
+ }
231
+ else {
232
+ let kvStoreItemMetadata = null;
233
+ if (useKvStore && !forceUpload) {
234
+ await attemptWithRetries(async () => {
235
+ // fastlyApiContext is non-null if useKvStore is true
236
+ const kvStoreEntryInfo = await getKvStoreEntryInfo(fastlyApiContext, kvStoreName, variantKey);
237
+ if (!kvStoreEntryInfo) {
238
+ return;
239
+ }
240
+ let itemMetadata;
241
+ if (kvStoreEntryInfo.metadata != null) {
242
+ try {
243
+ itemMetadata = JSON.parse(kvStoreEntryInfo.metadata);
244
+ }
245
+ catch {
246
+ // if the metadata does not parse successfully as JSON,
247
+ // treat it as though it didn't exist.
248
+ }
249
+ }
250
+ if (isKVAssetVariantMetadata(itemMetadata)) {
251
+ let exists = false;
252
+ if (itemMetadata.size <= KV_STORE_CHUNK_SIZE) {
253
+ // For an item equal to or smaller than the chunk size, if it exists
254
+ // and its metadata asserts no chunk count, then we assume it exists.
255
+ if (itemMetadata.numChunks === undefined) {
256
+ exists = true;
257
+ }
258
+ }
259
+ else {
260
+ // For chunked objects, if the first chunk exists, and its metadata asserts
261
+ // the same number of chunks based on size, then we assume it exists (for now).
262
+ // In the future we might actually check for the existence and sizes of
263
+ // every chunk in the KV Store.
264
+ const expectedNumChunks = Math.ceil(itemMetadata.size / KV_STORE_CHUNK_SIZE);
265
+ if (itemMetadata.numChunks === expectedNumChunks) {
266
+ exists = true;
267
+ }
268
+ }
269
+ if (exists) {
270
+ kvStoreItemMetadata = {
271
+ contentEncoding: itemMetadata.contentEncoding,
272
+ size: itemMetadata.size,
273
+ hash: itemMetadata.hash,
274
+ numChunks: itemMetadata.numChunks,
275
+ };
276
+ }
277
+ }
278
+ }, {
279
+ onAttempt(attempt) {
280
+ if (attempt > 0) {
281
+ console.log(`Attempt ${attempt + 1} for: ${variantKey}`);
282
+ }
283
+ },
284
+ onRetry(attempt, err, delay) {
285
+ let statusMessage = 'unknown';
286
+ if (err instanceof FetchError) {
287
+ statusMessage = `HTTP ${err.status}`;
288
+ }
289
+ else if (err instanceof TypeError) {
290
+ statusMessage = 'transport';
291
+ }
292
+ console.log(`Attempt ${attempt + 1} for ${variantKey} gave retryable error (${statusMessage}), delaying ${delay} ms`);
293
+ },
294
+ });
295
+ }
296
+ if (kvStoreItemMetadata != null) {
297
+ console.log(` ・ Asset found in KV Store with key "${variantKey}".`);
298
+ // And we already know its hash and size.
299
+ variantMetadata = {
300
+ contentEncoding: kvStoreItemMetadata.contentEncoding,
301
+ size: kvStoreItemMetadata.size,
302
+ hash: kvStoreItemMetadata.hash,
303
+ numChunks: kvStoreItemMetadata.numChunks,
304
+ existsInKvStore: true,
305
+ };
306
+ }
307
+ else {
308
+ await ensureVariantFileExists(variantFilePath, variant, file);
309
+ if (useKvStore) {
310
+ console.log(` ・ Flagging asset for upload to KV Store with key "${variantKey}".`);
311
+ }
312
+ let contentEncoding, hash, size;
313
+ if (variant === 'original') {
314
+ contentEncoding = undefined;
315
+ hash = baseHash;
316
+ size = baseSize;
317
+ }
318
+ else {
319
+ contentEncoding = variant;
320
+ ({ hash, size } = await calculateFileSizeAndHash(variantFilePath));
321
+ }
322
+ const numChunks = Math.ceil(size / KV_STORE_CHUNK_SIZE);
323
+ variantMetadata = {
324
+ contentEncoding,
325
+ size,
326
+ hash,
327
+ numChunks: numChunks > 1 ? numChunks : undefined,
328
+ existsInKvStore: false,
329
+ };
330
+ }
331
+ variantMetadatas.set(variant, variantMetadata);
332
+ kvStoreItemDescriptions.push({
333
+ write: !variantMetadata.existsInKvStore,
334
+ size: variantMetadata.size,
335
+ key: variantKey,
336
+ filePath: variantFilePath,
337
+ metadataJson: {
338
+ contentEncoding: variantMetadata.contentEncoding,
339
+ size: variantMetadata.size,
340
+ hash: variantMetadata.hash,
341
+ numChunks: variantMetadata.numChunks,
342
+ },
343
+ });
344
+ if (createLocalFiles) {
345
+ // Although we already know the size and hash of the file, the local server
346
+ // needs a copy of the file so we create it if it doesn't exist.
347
+ // This may happen for example if files were uploaded to the KV Store in a previous
348
+ // publishing, but local static content files have been removed since.
349
+ await ensureVariantFileExists(variantFilePath, variant, file);
350
+ console.log(` ・ Prepping asset for local KV Store with key "${variantKey}".`);
351
+ }
352
+ }
353
+ // Only keep variants whose file size actually ends up smaller than
354
+ // what we started with.
355
+ if (variant !== 'original' && variantMetadata.size < baseSize) {
356
+ variantsToKeep.push(variant);
357
+ }
358
+ }
359
+ kvAssetsIndex[assetKey] = {
360
+ key: `sha256:${baseHash}`,
361
+ size: baseSize,
362
+ contentType: contentTypeTestResult.contentType,
363
+ lastModifiedTime,
364
+ variants: variantsToKeep,
365
+ };
366
+ }
367
+ console.log(`✅ Scan complete.`);
368
+ // #### INDEX FILE
369
+ console.log(`🗂️ Creating Index...`);
370
+ const indexFileName = `index_${collectionName}.json`;
371
+ const indexFileKey = `${publishId}_index_${collectionName}`;
372
+ // Metadata can have build time, expiration date, build name
373
+ // const indexMetadata = {};
374
+ const indexFilePath = path.resolve(staticPublisherKvStoreContent, indexFileName);
375
+ fs.writeFileSync(indexFilePath, JSON.stringify(kvAssetsIndex));
376
+ const indexFileSize = getFileSize(indexFilePath);
377
+ kvStoreItemDescriptions.push({
378
+ write: true,
379
+ size: indexFileSize,
380
+ key: indexFileKey,
381
+ filePath: indexFilePath,
382
+ // metadata: indexMetadata,
383
+ });
384
+ console.log(`✅ Index has been saved.`);
385
+ // #### SERVER SETTINGS
386
+ // These are saved to KV Store
387
+ console.log(`⚙️ Saving server settings...`);
388
+ const server = applyDefaults(publishContentConfig.server, {
389
+ publicDirPrefix: '',
390
+ staticItems: [],
391
+ allowedEncodings: ['br', 'gzip'],
392
+ spaFile: null,
393
+ notFoundPageFile: null,
394
+ autoExt: [],
395
+ autoIndex: [],
396
+ });
397
+ let publicDirPrefix = server.publicDirPrefix;
398
+ console.log(` ✔️ Server public dir prefix '${publicDirPrefix}'.`);
399
+ let staticItems = server.staticItems;
400
+ let allowedEncodings = server.allowedEncodings;
401
+ let spaFile = server.spaFile;
402
+ if (spaFile != null) {
403
+ console.log(` ✔️ Application SPA file '${spaFile}'.`);
404
+ const spaAsset = kvAssetsIndex[spaFile];
405
+ if (spaAsset == null || spaAsset.contentType !== 'text/html') {
406
+ if (verbose) {
407
+ console.log(` ⚠️ Notice: '${spaFile}' does not exist or is not of type 'text/html'. Ignoring.`);
408
+ }
409
+ spaFile = null;
410
+ }
411
+ }
412
+ else {
413
+ if (verbose) {
414
+ console.log(` ✔️ Application is not a SPA.`);
415
+ }
416
+ }
417
+ let notFoundPageFile = server.notFoundPageFile;
418
+ if (notFoundPageFile != null) {
419
+ console.log(` ✔️ Application 'not found (404)' file '${notFoundPageFile}'.`);
420
+ const notFoundPageAsset = kvAssetsIndex[notFoundPageFile];
421
+ if (notFoundPageAsset == null || notFoundPageAsset.contentType !== 'text/html') {
422
+ if (verbose) {
423
+ console.log(` ⚠️ Notice: '${notFoundPageFile}' does not exist or is not of type 'text/html'. Ignoring.`);
424
+ }
425
+ notFoundPageFile = null;
426
+ }
427
+ }
428
+ else {
429
+ if (verbose) {
430
+ console.log(` ✔️ Application specifies no 'not found (404)' page.`);
431
+ }
432
+ }
433
+ let autoIndex = server.autoIndex;
434
+ let autoExt = server.autoExt;
435
+ const serverSettings = {
436
+ publicDirPrefix,
437
+ staticItems,
438
+ allowedEncodings,
439
+ spaFile,
440
+ notFoundPageFile,
441
+ autoExt,
442
+ autoIndex,
443
+ };
444
+ const settingsFileName = `settings_${collectionName}.json`;
445
+ const settingsFileKey = `${publishId}_settings_${collectionName}`;
446
+ const settingsFilePath = path.resolve(staticPublisherKvStoreContent, settingsFileName);
447
+ fs.writeFileSync(settingsFilePath, JSON.stringify(serverSettings));
448
+ const settingsFileSize = getFileSize(settingsFilePath);
449
+ kvStoreItemDescriptions.push({
450
+ write: true,
451
+ size: settingsFileSize,
452
+ key: settingsFileKey,
453
+ filePath: settingsFilePath,
454
+ });
455
+ console.log(`✅ Settings have been saved.`);
456
+ console.log(`🍪 Chunking large files...`);
457
+ await applyKVStoreEntriesChunks(kvStoreItemDescriptions, KV_STORE_CHUNK_SIZE);
458
+ console.log(`✅ Large files have been chunked.`);
459
+ if (useKvStore) {
460
+ console.log(`📤 Uploading entries to KV Store.`);
461
+ // fastlyApiContext is non-null if useKvStore is true
462
+ await uploadFilesToKVStore(fastlyApiContext, kvStoreName, kvStoreItemDescriptions);
463
+ console.log(`✅ Uploaded entries to KV Store.`);
464
+ }
465
+ if (createLocalFiles) {
466
+ console.log(`📝 Writing local server KV Store entries.`);
467
+ const storeFile = path.resolve(staticPublisherWorkingDir, `./kvstore.json`);
468
+ writeKVStoreEntriesForLocal(storeFile, computeAppDir, kvStoreItemDescriptions);
469
+ console.log(`✅ Wrote KV Store entries for local server.`);
470
+ }
471
+ console.log(`🎉 Completed.`);
472
+ }
@@ -1,3 +1,3 @@
1
1
  export declare const key = "br";
2
- export declare function compressTo(src: string, dest: string, isText: boolean): Promise<boolean>;
2
+ export declare function compressTo(src: string, dest: string): Promise<void>;
3
3
  //# sourceMappingURL=brotli.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"brotli.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/brotli.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,GAAG,OAAO,CAAC;AAExB,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAa7F"}
1
+ {"version":3,"file":"brotli.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/brotli.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,GAAG,OAAO,CAAC;AAExB,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMzE"}
@@ -1,15 +1,12 @@
1
- import fs from 'fs';
2
- import zlib from 'zlib';
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import fs from 'node:fs';
6
+ import zlib from 'node:zlib';
3
7
  export const key = 'br';
4
- export async function compressTo(src, dest, isText) {
8
+ export async function compressTo(src, dest) {
5
9
  const buffer = fs.readFileSync(src);
6
10
  const resultBuffer = zlib.brotliCompressSync(buffer);
7
- // Don't actually create the file if it would be bigger
8
- if (resultBuffer.length < buffer.length) {
9
- fs.writeFileSync(dest, resultBuffer);
10
- return true;
11
- }
12
- else {
13
- return false;
14
- }
11
+ fs.writeFileSync(dest, resultBuffer);
15
12
  }
@@ -1,3 +1,3 @@
1
1
  export declare const key = "gzip";
2
- export declare function compressTo(src: string, dest: string, isText: boolean): Promise<boolean>;
2
+ export declare function compressTo(src: string, dest: string): Promise<void>;
3
3
  //# sourceMappingURL=gzip.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gzip.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/gzip.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,GAAG,SAAS,CAAC;AAE1B,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAa7F"}
1
+ {"version":3,"file":"gzip.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/gzip.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,GAAG,SAAS,CAAC;AAE1B,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMzE"}
@@ -1,15 +1,12 @@
1
- import fs from 'fs';
2
- import zlib from 'zlib';
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ import fs from 'node:fs';
6
+ import zlib from 'node:zlib';
3
7
  export const key = 'gzip';
4
- export async function compressTo(src, dest, isText) {
8
+ export async function compressTo(src, dest) {
5
9
  const buffer = fs.readFileSync(src);
6
10
  const resultBuffer = zlib.gzipSync(buffer);
7
- // Don't actually create the file if it would be bigger
8
- if (resultBuffer.length < buffer.length) {
9
- fs.writeFileSync(dest, resultBuffer);
10
- return true;
11
- }
12
- else {
13
- return false;
14
- }
11
+ fs.writeFileSync(dest, resultBuffer);
15
12
  }
@@ -1,8 +1,5 @@
1
- export type CompressAlg = (src: string, dest: string, text: boolean) => Promise<boolean>;
2
- export type AlgLib = {
3
- key: string;
4
- compressTo: CompressAlg;
5
- };
6
- declare const algs: Partial<Record<"br" | "gzip", CompressAlg>>;
1
+ import { type ContentCompressionTypes } from '../../models/compression/index.js';
2
+ export type CompressAlg = (src: string, dest: string) => Promise<void>;
3
+ declare const algs: Record<ContentCompressionTypes, CompressAlg>;
7
4
  export { algs };
8
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/index.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAEzF,MAAM,MAAM,MAAM,GAAG;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,WAAW,CAAC;CACzB,CAAC;AAIF,QAAA,MAAM,IAAI,6CAMJ,CAAC;AAEP,OAAO,EAAE,IAAI,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/cli/compression/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAEjF,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEvE,QAAA,MAAM,IAAI,EAAE,MAAM,CAAC,uBAAuB,EAAE,WAAW,CAGtD,CAAC;AAEF,OAAO,EAAE,IAAI,EAAE,CAAC"}
@@ -1,12 +1,11 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
1
5
  import * as brotli from './brotli.js';
2
6
  import * as gzip from './gzip.js';
3
- import { compressionTypes } from "../../constants/compression.js";
4
- const libs = [brotli, gzip];
5
- const algs = compressionTypes.reduce((obj, alg) => {
6
- const lib = libs.find((lib) => lib.key === alg);
7
- if (lib != null) {
8
- obj[alg] = lib.compressTo;
9
- }
10
- return obj;
11
- }, {});
7
+ const algs = {
8
+ br: brotli.compressTo,
9
+ gzip: gzip.compressTo,
10
+ };
12
11
  export { algs };
@@ -0,0 +1,17 @@
1
+ export interface FastlyApiContext {
2
+ apiToken: string;
3
+ }
4
+ export type LoadApiTokenResult = {
5
+ apiToken: string;
6
+ source: string;
7
+ };
8
+ export type LoadApiParams = {
9
+ commandLine: any;
10
+ };
11
+ export declare function loadApiToken(params: LoadApiParams): LoadApiTokenResult | null;
12
+ export declare class FetchError extends Error {
13
+ constructor(message: string, status: number);
14
+ status: number;
15
+ }
16
+ export declare function callFastlyApi(fastlyApiContext: FastlyApiContext, endpoint: string, operationName: string, queryParams?: URLSearchParams | null, requestInit?: RequestInit): Promise<Response>;
17
+ //# sourceMappingURL=api-token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-token.d.ts","sourceRoot":"","sources":["../../../src/cli/fastly-api/api-token.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,WAAW,EAAE,GAAG,CAAC;CAClB,CAAC;AAEF,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,kBAAkB,GAAG,IAAI,CAwC7E;AAaD,qBAAa,UAAW,SAAQ,KAAK;gBACvB,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAK3C,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,aAAa,CACjC,gBAAgB,EAAE,gBAAgB,EAClC,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,eAAe,GAAG,IAAI,EACpC,WAAW,CAAC,EAAE,WAAW,GACxB,OAAO,CAAC,QAAQ,CAAC,CAmCnB"}