@fastly/compute-js-static-publish 3.6.0 → 4.0.0-alpha.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 (197) hide show
  1. package/README.md +440 -103
  2. package/build/assets/asset-manager.d.ts +7 -0
  3. package/build/assets/asset-manager.d.ts.map +1 -0
  4. package/build/assets/asset-manager.js +11 -0
  5. package/build/assets/content-assets.d.ts +29 -0
  6. package/build/assets/content-assets.d.ts.map +1 -0
  7. package/build/assets/content-assets.js +88 -0
  8. package/build/assets/module-assets.d.ts +23 -0
  9. package/build/assets/module-assets.d.ts.map +1 -0
  10. package/build/assets/module-assets.js +45 -0
  11. package/build/cli/build-static.d.ts.map +1 -0
  12. package/build/cli/build-static.js +524 -0
  13. package/build/cli/clean-object-store.d.ts +2 -0
  14. package/build/cli/clean-object-store.d.ts.map +1 -0
  15. package/build/cli/cli.d.ts.map +1 -0
  16. package/build/{cli.js → cli/cli.js} +0 -0
  17. package/build/cli/commands/build-static.d.ts +3 -0
  18. package/build/cli/commands/build-static.d.ts.map +1 -0
  19. package/build/cli/commands/build-static.js +501 -0
  20. package/build/cli/commands/clean-object-store.d.ts +3 -0
  21. package/build/cli/commands/clean-object-store.d.ts.map +1 -0
  22. package/build/cli/commands/clean-object-store.js +54 -0
  23. package/build/cli/commands/init-app.d.ts.map +1 -0
  24. package/build/cli/commands/init-app.js +559 -0
  25. package/build/cli/compression/brotli.d.ts +3 -0
  26. package/build/cli/compression/brotli.d.ts.map +1 -0
  27. package/build/cli/compression/brotli.js +15 -0
  28. package/build/cli/compression/gzip.d.ts +3 -0
  29. package/build/cli/compression/gzip.d.ts.map +1 -0
  30. package/build/cli/compression/gzip.js +15 -0
  31. package/build/cli/compression/index.d.ts +8 -0
  32. package/build/cli/compression/index.d.ts.map +1 -0
  33. package/build/cli/compression/index.js +12 -0
  34. package/build/cli/index.d.ts +3 -0
  35. package/build/cli/index.d.ts.map +1 -0
  36. package/build/cli/index.js +86 -0
  37. package/build/cli/init-app.d.ts +3 -0
  38. package/build/cli/init-app.d.ts.map +1 -0
  39. package/build/{init-app.js → cli/init-app.js} +16 -16
  40. package/build/cli/load-config.d.ts +3 -0
  41. package/build/cli/load-config.d.ts.map +1 -0
  42. package/build/cli/load-config.js +357 -0
  43. package/build/cli/presets/implementations/create-react-app.d.ts +11 -0
  44. package/build/cli/presets/implementations/create-react-app.d.ts.map +1 -0
  45. package/build/cli/presets/implementations/create-react-app.js +34 -0
  46. package/build/cli/presets/implementations/docusaurus.d.ts +7 -0
  47. package/build/cli/presets/implementations/docusaurus.d.ts.map +1 -0
  48. package/build/cli/presets/implementations/docusaurus.js +13 -0
  49. package/build/cli/presets/implementations/gatsby.d.ts +7 -0
  50. package/build/cli/presets/implementations/gatsby.d.ts.map +1 -0
  51. package/build/cli/presets/implementations/gatsby.js +13 -0
  52. package/build/cli/presets/implementations/next.d.ts +7 -0
  53. package/build/cli/presets/implementations/next.d.ts.map +1 -0
  54. package/build/cli/presets/implementations/next.js +13 -0
  55. package/build/cli/presets/implementations/sveltekit.d.ts +7 -0
  56. package/build/cli/presets/implementations/sveltekit.d.ts.map +1 -0
  57. package/build/cli/presets/implementations/sveltekit.js +13 -0
  58. package/build/cli/presets/implementations/vite.d.ts +7 -0
  59. package/build/cli/presets/implementations/vite.d.ts.map +1 -0
  60. package/build/cli/presets/implementations/vite.js +13 -0
  61. package/build/cli/presets/index.d.ts +3 -0
  62. package/build/cli/presets/index.d.ts.map +1 -0
  63. package/build/cli/presets/index.js +16 -0
  64. package/build/cli/presets/preset-base.d.ts +19 -0
  65. package/build/cli/presets/preset-base.d.ts.map +1 -0
  66. package/build/cli/util/data.d.ts +7 -0
  67. package/build/cli/util/data.d.ts.map +1 -0
  68. package/build/cli/util/data.js +58 -0
  69. package/build/cli/util/fastly-api.d.ts +10 -0
  70. package/build/cli/util/fastly-api.d.ts.map +1 -0
  71. package/build/cli/util/fastly-api.js +47 -0
  72. package/build/cli/util/files.d.ts +11 -0
  73. package/build/cli/util/files.d.ts.map +1 -0
  74. package/build/cli/util/files.js +33 -0
  75. package/build/cli/util/hash.d.ts +2 -0
  76. package/build/cli/util/hash.d.ts.map +1 -0
  77. package/build/cli/util/hash.js +8 -0
  78. package/build/cli/util/id.d.ts +3 -0
  79. package/build/cli/util/id.d.ts.map +1 -0
  80. package/build/cli/util/id.js +17 -0
  81. package/build/cli/util/object-store.d.ts +16 -0
  82. package/build/cli/util/object-store.d.ts.map +1 -0
  83. package/build/cli/util/object-store.js +108 -0
  84. package/build/cli/util/publish-id.d.ts +5 -0
  85. package/build/cli/util/publish-id.d.ts.map +1 -0
  86. package/build/cli/util/publish-id.js +26 -0
  87. package/build/constants/compression.d.ts +3 -0
  88. package/build/constants/compression.d.ts.map +1 -0
  89. package/build/constants/compression.js +4 -0
  90. package/build/index.d.ts +5 -2
  91. package/build/index.d.ts.map +1 -1
  92. package/build/index.js +5 -1
  93. package/build/presets/implementations/create-react-app.js +1 -2
  94. package/build/presets/preset-base.d.ts +1 -1
  95. package/build/presets/preset-base.d.ts.map +1 -1
  96. package/build/server/assets/asset-manager.d.ts +7 -0
  97. package/build/server/assets/asset-manager.d.ts.map +1 -0
  98. package/build/server/assets/asset-manager.js +11 -0
  99. package/build/server/assets/content-assets.d.ts +33 -0
  100. package/build/server/assets/content-assets.d.ts.map +1 -0
  101. package/build/server/assets/content-assets.js +135 -0
  102. package/build/server/assets/module-assets.d.ts +23 -0
  103. package/build/server/assets/module-assets.d.ts.map +1 -0
  104. package/build/server/assets/module-assets.js +45 -0
  105. package/build/server/object-store/include-bytes-store-entry.d.ts +19 -0
  106. package/build/server/object-store/include-bytes-store-entry.d.ts.map +1 -0
  107. package/build/server/object-store/include-bytes-store-entry.js +87 -0
  108. package/build/server/object-store/inline-store-entry.d.ts +23 -0
  109. package/build/server/object-store/inline-store-entry.d.ts.map +1 -0
  110. package/build/server/object-store/inline-store-entry.js +95 -0
  111. package/build/server/publisher-server.d.ts +23 -0
  112. package/build/server/publisher-server.d.ts.map +1 -0
  113. package/build/server/publisher-server.js +224 -0
  114. package/build/server/serve-preconditions/if-modified-since.d.ts +4 -0
  115. package/build/server/serve-preconditions/if-modified-since.d.ts.map +1 -0
  116. package/build/server/serve-preconditions/if-modified-since.js +26 -0
  117. package/build/server/serve-preconditions/if-none-match.d.ts +3 -0
  118. package/build/server/serve-preconditions/if-none-match.d.ts.map +1 -0
  119. package/build/server/serve-preconditions/if-none-match.js +24 -0
  120. package/build/server/util/http.d.ts +2 -0
  121. package/build/server/util/http.d.ts.map +1 -0
  122. package/build/server/util/http.js +9 -0
  123. package/build/types/compute.d.ts +10 -0
  124. package/build/types/compute.d.ts.map +1 -0
  125. package/build/types/compute.js +1 -0
  126. package/build/types/config-normalized.d.ts +33 -0
  127. package/build/types/config-normalized.d.ts.map +1 -0
  128. package/build/types/config-normalized.js +1 -0
  129. package/build/types/config.d.ts +36 -0
  130. package/build/types/config.d.ts.map +1 -0
  131. package/build/types/config.js +1 -0
  132. package/build/types/content-assets.d.ts +37 -0
  133. package/build/types/content-assets.d.ts.map +1 -0
  134. package/build/types/content-assets.js +1 -0
  135. package/build/types/content-types.d.ts +11 -0
  136. package/build/types/content-types.d.ts.map +1 -0
  137. package/build/types/content-types.js +1 -0
  138. package/build/types/index.d.ts +7 -0
  139. package/build/types/index.d.ts.map +1 -0
  140. package/build/types/index.js +1 -0
  141. package/build/types/module-assets.d.ts +15 -0
  142. package/build/types/module-assets.d.ts.map +1 -0
  143. package/build/types/module-assets.js +1 -0
  144. package/build/types/util.d.ts +7 -0
  145. package/build/types/util.d.ts.map +1 -0
  146. package/build/types/util.js +1 -0
  147. package/build/util/content-types.d.ts +5 -0
  148. package/build/util/content-types.d.ts.map +1 -0
  149. package/build/util/content-types.js +92 -0
  150. package/build/util/data.d.ts +7 -0
  151. package/build/util/data.d.ts.map +1 -0
  152. package/build/util/data.js +58 -0
  153. package/build/util/fastly-api.d.ts +10 -0
  154. package/build/util/fastly-api.d.ts.map +1 -0
  155. package/build/util/fastly-api.js +47 -0
  156. package/build/util/files.d.ts +10 -0
  157. package/build/util/files.d.ts.map +1 -0
  158. package/build/util/files.js +32 -0
  159. package/build/util/hash.d.ts +2 -0
  160. package/build/util/hash.d.ts.map +1 -0
  161. package/build/util/hash.js +8 -0
  162. package/build/util/id.d.ts +3 -0
  163. package/build/util/id.d.ts.map +1 -0
  164. package/build/util/id.js +17 -0
  165. package/build/util/index.d.ts +3 -0
  166. package/build/util/index.d.ts.map +1 -0
  167. package/build/util/index.js +2 -0
  168. package/build/util/metadata.d.ts +3 -0
  169. package/build/util/metadata.d.ts.map +1 -0
  170. package/build/util/metadata.js +12 -0
  171. package/build/util/object-store.d.ts +12 -0
  172. package/build/util/object-store.d.ts.map +1 -0
  173. package/build/util/object-store.js +80 -0
  174. package/package.json +10 -5
  175. package/resources/index.js +9 -114
  176. package/resources/statics-metadata.d.ts +10 -0
  177. package/resources/statics.d.ts +15 -7
  178. package/resources/webpack.config.js +4 -10
  179. package/build/assets.d.ts +0 -8
  180. package/build/assets.d.ts.map +0 -1
  181. package/build/assets.js +0 -24
  182. package/build/build-static.d.ts.map +0 -1
  183. package/build/build-static.js +0 -249
  184. package/build/cli.d.ts.map +0 -1
  185. package/build/init-app.d.ts.map +0 -1
  186. package/build/static-assets.d.ts +0 -11
  187. package/build/static-assets.d.ts.map +0 -1
  188. package/build/static-assets.js +0 -33
  189. package/build/types.d.ts +0 -50
  190. package/build/types.d.ts.map +0 -1
  191. package/resources/default-content-types.cjs +0 -106
  192. package/resources/default-content-types.d.ts +0 -15
  193. /package/build/{build-static.d.ts → cli/build-static.d.ts} +0 -0
  194. /package/build/{content-types.js → cli/clean-object-store.js} +0 -0
  195. /package/build/{cli.d.ts → cli/cli.d.ts} +0 -0
  196. /package/build/{init-app.d.ts → cli/commands/init-app.d.ts} +0 -0
  197. /package/build/{types.js → cli/presets/preset-base.js} +0 -0
@@ -0,0 +1,559 @@
1
+ // This program creates a Compute@Edge JavaScript application
2
+ // in a subfolder named compute-js.
3
+ // This project can be served using fastly compute serve
4
+ // or deployed to a Compute@Edge service using fastly compute publish.
5
+ import * as child_process from "child_process";
6
+ import * as path from "path";
7
+ import * as fs from "fs";
8
+ import * as url from 'url';
9
+ import { presets } from '../presets/index.js';
10
+ const defaultOptions = {
11
+ rootDir: undefined,
12
+ publicDir: undefined,
13
+ staticDirs: [],
14
+ spa: undefined,
15
+ notFoundPage: '[public-dir]/404.html',
16
+ autoIndex: ['index.html', 'index.htm'],
17
+ autoExt: ['.html', '.htm'],
18
+ author: 'you@example.com',
19
+ name: 'compute-js-static-site',
20
+ description: 'Compute@Edge static site',
21
+ serviceId: undefined,
22
+ };
23
+ // Current directory of this program that's running.
24
+ const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
25
+ function processCommandLineArgs(commandLineValues) {
26
+ // All paths are relative to CWD.
27
+ let preset;
28
+ {
29
+ const presetValue = commandLineValues['preset'];
30
+ if (presetValue == null || typeof presetValue === 'string') {
31
+ preset = presetValue;
32
+ }
33
+ }
34
+ let rootDir;
35
+ let publicDir;
36
+ {
37
+ const rootDirValue = commandLineValues['root-dir'];
38
+ if (rootDirValue == null || typeof rootDirValue === 'string') {
39
+ rootDir = rootDirValue;
40
+ }
41
+ if (rootDir != null) {
42
+ rootDir = path.resolve(rootDir);
43
+ }
44
+ const publicDirValue = commandLineValues['public-dir'];
45
+ if (publicDirValue == null || typeof publicDirValue === 'string') {
46
+ publicDir = publicDirValue;
47
+ }
48
+ if (publicDir != null) {
49
+ publicDir = path.resolve(publicDir);
50
+ }
51
+ // If we don't have a preset, then for backwards compatibility
52
+ // we check if we have public-dir but no root-dir. If that is
53
+ // the case then we use the value public-dir as root-dir.
54
+ if (preset == null && rootDir == null && publicDir != null) {
55
+ rootDir = publicDir;
56
+ publicDir = undefined;
57
+ }
58
+ }
59
+ // Filepaths provided on the command line are always given relative to CWD,
60
+ // so we need to resolve them.
61
+ let staticDirs;
62
+ {
63
+ const staticDirsValue = commandLineValues['static-dir'];
64
+ const asArray = Array.isArray(staticDirsValue) ? staticDirsValue : [staticDirsValue];
65
+ if (asArray.every((x) => typeof x === 'string')) {
66
+ staticDirs = asArray.map(x => path.resolve(x));
67
+ }
68
+ }
69
+ let spa;
70
+ {
71
+ const spaValue = commandLineValues['spa'];
72
+ if (spaValue === null) {
73
+ // If 'spa' is provided with a null value, then the flag was provided
74
+ // with no value. Assumed to be './index.html' relative to the public directory.
75
+ spa = '[public-dir]/index.html';
76
+ console.log('--spa provided, but no value specified. Assuming ' + spa);
77
+ }
78
+ else if (spaValue == null || typeof spaValue === 'string') {
79
+ spa = spaValue;
80
+ }
81
+ }
82
+ let notFoundPage;
83
+ {
84
+ const notFoundPageValue = commandLineValues['not-found-page'];
85
+ if (notFoundPageValue === null) {
86
+ // If 'spa' is provided with a null value, then the flag was provided
87
+ // with no value. Assumed to be './404.html' relative to the public directory.
88
+ notFoundPage = '[public-dir]/404.html';
89
+ console.log('--not-found-page provided, but no value specified. Assuming ' + notFoundPage);
90
+ }
91
+ else if (notFoundPageValue == null || typeof notFoundPageValue === 'string') {
92
+ notFoundPage = notFoundPageValue;
93
+ }
94
+ }
95
+ let autoIndex;
96
+ {
97
+ const autoIndexValue = commandLineValues['auto-index'];
98
+ const asArray = Array.isArray(autoIndexValue) ? autoIndexValue : [autoIndexValue];
99
+ if (asArray.every((x) => typeof x === 'string')) {
100
+ autoIndex = asArray.reduce((acc, entry) => {
101
+ const segments = entry
102
+ .split(',')
103
+ .map(x => x.trim())
104
+ .filter(x => Boolean(x));
105
+ for (const segment of segments) {
106
+ acc.push(segment);
107
+ }
108
+ return acc;
109
+ }, []);
110
+ }
111
+ }
112
+ let autoExt = [];
113
+ {
114
+ const autoExtValue = commandLineValues['auto-ext'];
115
+ const asArray = Array.isArray(autoExtValue) ? autoExtValue : [autoExtValue];
116
+ if (asArray.every((x) => typeof x === 'string')) {
117
+ autoExt = asArray.reduce((acc, entry) => {
118
+ const segments = entry
119
+ .split(',')
120
+ .map(x => x.trim())
121
+ .filter(x => Boolean(x))
122
+ .map(x => !x.startsWith('.') ? '.' + x : x);
123
+ for (const segment of segments) {
124
+ acc.push(segment);
125
+ }
126
+ return acc;
127
+ }, []);
128
+ }
129
+ }
130
+ let name;
131
+ {
132
+ const nameValue = commandLineValues['name'];
133
+ if (nameValue == null || typeof nameValue === 'string') {
134
+ name = nameValue;
135
+ }
136
+ }
137
+ let author;
138
+ {
139
+ const authorValue = commandLineValues['author'];
140
+ if (authorValue == null || typeof authorValue === 'string') {
141
+ author = authorValue;
142
+ }
143
+ }
144
+ let description;
145
+ {
146
+ const descriptionValue = commandLineValues['description'];
147
+ if (descriptionValue == null || typeof descriptionValue === 'string') {
148
+ description = descriptionValue;
149
+ }
150
+ }
151
+ let serviceId;
152
+ {
153
+ const serviceIdValue = commandLineValues['service-id'];
154
+ if (serviceIdValue == null || typeof serviceIdValue === 'string') {
155
+ serviceId = serviceIdValue;
156
+ }
157
+ }
158
+ return {
159
+ rootDir,
160
+ publicDir,
161
+ staticDirs,
162
+ spa,
163
+ notFoundPage,
164
+ autoIndex,
165
+ autoExt,
166
+ name,
167
+ author,
168
+ description,
169
+ serviceId,
170
+ };
171
+ }
172
+ function pickKeys(keys, object) {
173
+ const result = {};
174
+ for (const key of keys) {
175
+ if (object[key] !== undefined) {
176
+ result[key] = object[key];
177
+ }
178
+ }
179
+ return result;
180
+ }
181
+ const PUBLIC_DIR_TOKEN = '[public-dir]';
182
+ function processPublicDirToken(filepath, publicDir) {
183
+ if (!filepath.startsWith(PUBLIC_DIR_TOKEN)) {
184
+ return filepath;
185
+ }
186
+ const processedPath = '.' + filepath.slice(PUBLIC_DIR_TOKEN.length);
187
+ const resolvedPath = path.resolve(publicDir, processedPath);
188
+ return path.relative(path.resolve(), resolvedPath);
189
+ }
190
+ export function initApp(commandLineValues) {
191
+ let options = defaultOptions;
192
+ let preset = null;
193
+ const presetName = commandLineValues['preset'] ?? 'none';
194
+ if (presetName !== 'none') {
195
+ const presetClass = presets[presetName];
196
+ if (presetClass == null) {
197
+ console.error('Unknown preset name.');
198
+ console.error("--preset must be one of: none, " + (Object.keys(presets).join(', ')));
199
+ process.exitCode = 1;
200
+ return;
201
+ }
202
+ preset = new presetClass();
203
+ }
204
+ let packageJson;
205
+ try {
206
+ const packageJsonText = fs.readFileSync("./package.json", "utf-8");
207
+ packageJson = JSON.parse(packageJsonText);
208
+ }
209
+ catch {
210
+ console.log("Can't read/parse package.json in current directory, making no assumptions!");
211
+ packageJson = null;
212
+ }
213
+ // Get the current compute js static publisher version.
214
+ let computeJsStaticPublisherVersion = null;
215
+ if (packageJson != null) {
216
+ // First try current project's package.json
217
+ computeJsStaticPublisherVersion =
218
+ packageJson.dependencies["@fastly/compute-js-static-publish"] ??
219
+ packageJson.devDependencies["@fastly/compute-js-static-publish"];
220
+ // This may be a file url if during development
221
+ if (computeJsStaticPublisherVersion != null) {
222
+ if (computeJsStaticPublisherVersion.startsWith('file:')) {
223
+ // this is a relative path from the current directory.
224
+ // we replace it with an absolute path
225
+ const relPath = computeJsStaticPublisherVersion.slice('file:'.length);
226
+ const absPath = path.resolve(relPath);
227
+ computeJsStaticPublisherVersion = 'file:' + absPath;
228
+ }
229
+ }
230
+ }
231
+ if (computeJsStaticPublisherVersion == null) {
232
+ // Also try package.json of the package that contains the currently running program
233
+ // This is used when the program doesn't actually install the package (running via npx).
234
+ const computeJsStaticPublishPackageJsonPath = path.resolve(__dirname, '../../../package.json');
235
+ const computeJsStaticPublishPackageJsonText = fs.readFileSync(computeJsStaticPublishPackageJsonPath, 'utf-8');
236
+ const computeJsStaticPublishPackageJson = JSON.parse(computeJsStaticPublishPackageJsonText);
237
+ computeJsStaticPublisherVersion = computeJsStaticPublishPackageJson?.version;
238
+ }
239
+ if (computeJsStaticPublisherVersion == null) {
240
+ // Unexpected, but if it's still null then we go to a literal
241
+ computeJsStaticPublisherVersion = '^4.0.0';
242
+ }
243
+ const commandLineAppOptions = processCommandLineArgs(commandLineValues);
244
+ options = {
245
+ ...options,
246
+ ...(preset != null ? preset.defaultOptions : {}),
247
+ ...pickKeys(['author', 'name', 'description'], (packageJson ?? {})),
248
+ ...pickKeys(['rootDir', 'publicDir', 'staticDirs', 'spa', 'notFoundPage', 'autoIndex', 'autoExt', 'author', 'name', 'description', 'serviceId'], commandLineAppOptions),
249
+ };
250
+ if (preset != null) {
251
+ if (!preset.check(packageJson, options)) {
252
+ console.log("Failed preset check.");
253
+ process.exitCode = 1;
254
+ return;
255
+ }
256
+ }
257
+ // Webpack now optional as of v4
258
+ const useWebpack = commandLineValues['webpack'];
259
+ const COMPUTE_JS_DIR = commandLineValues.output;
260
+ const computeJsDir = path.resolve(COMPUTE_JS_DIR);
261
+ // Resolve the root dir, relative to current directory, and make sure it exists.
262
+ const ROOT_DIR = options.rootDir;
263
+ if (ROOT_DIR == null) {
264
+ console.error("❌ required parameter --root-dir not provided.");
265
+ process.exitCode = 1;
266
+ return;
267
+ }
268
+ const rootDir = path.resolve(ROOT_DIR);
269
+ if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
270
+ console.error(`❌ Specified root directory '${ROOT_DIR}' does not exist.`);
271
+ console.error(` * ${rootDir} must exist and be a directory.`);
272
+ process.exitCode = 1;
273
+ return;
274
+ }
275
+ // Resolve the public dir as well. If it's not specified, we use the root directory.
276
+ const PUBLIC_DIR = options.publicDir ?? ROOT_DIR;
277
+ const publicDir = path.resolve(PUBLIC_DIR);
278
+ if (!fs.existsSync(publicDir) || !fs.statSync(publicDir).isDirectory()) {
279
+ console.error(`❌ Specified public directory '${PUBLIC_DIR}' does not exist.`);
280
+ console.error(` * ${publicDir} must exist and be a directory.`);
281
+ process.exitCode = 1;
282
+ return;
283
+ }
284
+ // Public dir must be inside the root dir.
285
+ if (!publicDir.startsWith(rootDir)) {
286
+ console.error(`❌ Specified public directory '${PUBLIC_DIR}' is not under the asset root directory.`);
287
+ console.error(` * ${publicDir} must be under ${rootDir}`);
288
+ process.exitCode = 1;
289
+ return;
290
+ }
291
+ // Static dirs must be inside the public dir.
292
+ const STATIC_DIRS = options.staticDirs;
293
+ const staticDirs = [];
294
+ for (const STATIC_DIR of STATIC_DIRS) {
295
+ // For backwards compatibility, these values can start with [public-dir]
296
+ const staticDir = path.resolve(processPublicDirToken(STATIC_DIR, publicDir));
297
+ if (!staticDir.startsWith(publicDir)) {
298
+ console.log(`⚠️ Ignoring static directory '${STATIC_DIR}'`);
299
+ console.log(` * ${staticDir} is not under ${publicDir}`);
300
+ continue;
301
+ }
302
+ if (!fs.existsSync(staticDir) || !fs.statSync(staticDir).isDirectory()) {
303
+ console.log(`⚠️ Ignoring static directory '${STATIC_DIR}'`);
304
+ console.log(` * ${staticDir} does not exist or is not a directory.`);
305
+ continue;
306
+ }
307
+ staticDirs.push(staticDir);
308
+ }
309
+ // SPA and Not Found are relative to the asset root dir.
310
+ const SPA = options.spa;
311
+ let spaFilename;
312
+ if (SPA != null) {
313
+ // If it starts with [public-dir], then resolve it relative to public directory.
314
+ spaFilename = path.resolve(processPublicDirToken(SPA, publicDir));
315
+ // At any rate it must exist under the root directory
316
+ if (!spaFilename.startsWith(rootDir)) {
317
+ console.log(`⚠️ Ignoring specified SPA file '${SPA}' as is not under the asset root directory.`);
318
+ console.log(` * ${spaFilename} is not under ${rootDir}`);
319
+ spaFilename = undefined;
320
+ }
321
+ else if (!fs.existsSync(spaFilename)) {
322
+ console.log(`⚠️ Ignoring specified SPA file '${SPA}' as it does not exist.`);
323
+ console.log(` * ${spaFilename} does not exist.`);
324
+ spaFilename = undefined;
325
+ }
326
+ }
327
+ const NOT_FOUND_PAGE = options.notFoundPage;
328
+ let notFoundPageFilename;
329
+ if (NOT_FOUND_PAGE != null) {
330
+ // If it starts with [public-dir], then resolve it relative to public directory.
331
+ notFoundPageFilename = path.resolve(processPublicDirToken(NOT_FOUND_PAGE, publicDir));
332
+ // At any rate it must exist under the root directory
333
+ if (!notFoundPageFilename.startsWith(rootDir)) {
334
+ console.log(`⚠️ Ignoring specified Not Found file '${NOT_FOUND_PAGE}' as is not under the asset root directory.`);
335
+ console.log(` * ${notFoundPageFilename} is not under ${rootDir}`);
336
+ notFoundPageFilename = undefined;
337
+ }
338
+ else if (!fs.existsSync(notFoundPageFilename)) {
339
+ console.log(`⚠️ Ignoring specified Not Found file '${NOT_FOUND_PAGE}' as it does not exist.`);
340
+ console.log(` * ${notFoundPageFilename} does not exist.`);
341
+ notFoundPageFilename = undefined;
342
+ }
343
+ }
344
+ const autoIndex = options.autoIndex;
345
+ const autoExt = options.autoExt;
346
+ const exists = fs.existsSync(computeJsDir);
347
+ if (exists) {
348
+ console.error(`❌ '${COMPUTE_JS_DIR}' directory already exists!`);
349
+ console.error(` You should not run this command if this directory exists.`);
350
+ console.error(` If you need to re-scaffold the static publisher, delete the following directory and then try again:`);
351
+ console.error(` ${computeJsDir}`);
352
+ process.exitCode = 1;
353
+ return;
354
+ }
355
+ const author = options.author;
356
+ const name = options.name;
357
+ const description = options.description;
358
+ const fastlyServiceId = options.serviceId;
359
+ function rootRelative(itemPath) {
360
+ if (itemPath == null) {
361
+ return null;
362
+ }
363
+ const v = path.relative(path.resolve(), itemPath);
364
+ return v.startsWith('..') ? v : './' + v;
365
+ }
366
+ console.log('');
367
+ console.log('Asset Root Dir :', rootRelative(rootDir));
368
+ console.log('Public Dir :', rootRelative(publicDir));
369
+ console.log('Static Dir :', staticDirs.length > 0 ? staticDirs.map(rootRelative) : '(None)');
370
+ console.log('SPA :', rootRelative(spaFilename) ?? '(None)');
371
+ console.log('404 Page :', rootRelative(notFoundPageFilename) ?? '(None)');
372
+ console.log('Auto-Index :', autoIndex.length > 0 ? autoIndex.map(rootRelative) : '(None)');
373
+ console.log('Auto-Ext :', autoExt.length > 0 ? autoExt.map(rootRelative) : '(None)');
374
+ console.log('name :', name);
375
+ console.log('author :', author);
376
+ console.log('description :', description);
377
+ console.log('Service ID :', fastlyServiceId ?? '(None)');
378
+ console.log('');
379
+ if (useWebpack) {
380
+ console.log('Creating project with Webpack.');
381
+ console.log('');
382
+ }
383
+ console.log("Initializing Compute@Edge Application in " + computeJsDir + "...");
384
+ fs.mkdirSync(computeJsDir);
385
+ fs.mkdirSync(path.resolve(computeJsDir, './src'));
386
+ // .gitignore
387
+ const gitIgnoreContent = `\
388
+ /node_modules
389
+ /bin
390
+ /pkg
391
+ /src/statics.js
392
+ /src/statics.d.ts
393
+ /src/statics-metadata.js
394
+ /src/statics-metadata.d.ts
395
+ /src/static-content
396
+ `;
397
+ const gitIgnorePath = path.resolve(computeJsDir, '.gitignore');
398
+ fs.writeFileSync(gitIgnorePath, gitIgnoreContent, "utf-8");
399
+ // package.json
400
+ const packageJsonContent = {
401
+ name,
402
+ version: '0.1.0',
403
+ description,
404
+ author,
405
+ type: 'module',
406
+ devDependencies: {
407
+ '@fastly/compute-js-static-publish': computeJsStaticPublisherVersion,
408
+ },
409
+ dependencies: {
410
+ '@fastly/js-compute': '^1.4.0',
411
+ },
412
+ engines: {
413
+ node: '>=18.0.0',
414
+ },
415
+ license: 'UNLICENSED',
416
+ private: true,
417
+ scripts: {
418
+ deploy: 'fastly compute deploy',
419
+ prebuild: 'npx @fastly/compute-js-static-publish --build-static',
420
+ build: 'js-compute-runtime ./src/index.js ./bin/main.wasm'
421
+ },
422
+ };
423
+ if (useWebpack) {
424
+ delete packageJsonContent.type;
425
+ packageJsonContent.devDependencies = {
426
+ ...packageJsonContent.devDependencies,
427
+ 'webpack': '^5.75.0',
428
+ 'webpack-cli': '^5.0.0',
429
+ };
430
+ packageJsonContent.scripts = {
431
+ ...packageJsonContent.scripts,
432
+ prebuild: 'npx @fastly/compute-js-static-publish --build-static && webpack',
433
+ build: 'js-compute-runtime ./bin/index.js ./bin/main.wasm'
434
+ };
435
+ }
436
+ const packageJsonContentJson = JSON.stringify(packageJsonContent, undefined, 2);
437
+ const packageJsonPath = path.resolve(computeJsDir, 'package.json');
438
+ fs.writeFileSync(packageJsonPath, packageJsonContentJson, "utf-8");
439
+ // fastly.toml
440
+ // language=toml
441
+ const fastlyTomlContent = `\
442
+ # This file describes a Fastly Compute@Edge package. To learn more visit:
443
+ # https://developer.fastly.com/reference/fastly-toml/
444
+
445
+ authors = [ "${author}" ]
446
+ description = "${description}"
447
+ language = "javascript"
448
+ manifest_version = 2
449
+ name = "${name}"
450
+ ${fastlyServiceId != null ? `service_id = "${fastlyServiceId}"
451
+ ` : ''}
452
+ [scripts]
453
+ build = "npm run build"
454
+ `;
455
+ const fastlyTomlPath = path.resolve(computeJsDir, 'fastly.toml');
456
+ fs.writeFileSync(fastlyTomlPath, fastlyTomlContent, "utf-8");
457
+ // static-publish.rc.js
458
+ const rootDirRel = path.relative(computeJsDir, rootDir);
459
+ const publicDirRel = path.relative(computeJsDir, publicDir);
460
+ // publicDirPrefix -- if public dir is deeper than the root dir, then
461
+ // public dir is used as a prefix to drill into asset names.
462
+ // e.g.,
463
+ // root dir : /path/to/root
464
+ // public dir : /path/to/root/public
465
+ // then publicDirPrefix = /public
466
+ // We've already established publicDir.startsWith(rootDir)
467
+ let publicDirPrefix = '';
468
+ if (rootDir !== publicDir) {
469
+ publicDirPrefix = rootDir.slice(rootDir.length);
470
+ }
471
+ // staticItems - specified as prefixes, relative to publicDir
472
+ const staticItems = [];
473
+ for (const staticDir of staticDirs) {
474
+ // We've already established staticDir.startsWith(publicDir)
475
+ let staticItem = staticDir.slice(publicDir.length);
476
+ if (!staticItem.endsWith('/')) {
477
+ // Ending with a slash denotes that this is a directory.
478
+ staticItem = staticItem + '/';
479
+ }
480
+ staticItems.push(staticItem);
481
+ }
482
+ // spaFile - asset key of spa file
483
+ let spaFile = false;
484
+ if (spaFilename != null) {
485
+ // We've already established spaFilename.startsWith(rootDir)
486
+ // and that it exists
487
+ spaFile = spaFilename.slice(rootDir.length);
488
+ }
489
+ let notFoundPageFile = false;
490
+ if (notFoundPageFilename != null) {
491
+ // We've already established notFoundPageFilename.startsWith(rootDir)
492
+ // and that it exists
493
+ notFoundPageFile = notFoundPageFilename.slice(rootDir.length);
494
+ }
495
+ const staticPublishJsContent = `\
496
+ /*
497
+ * Copyright Fastly, Inc.
498
+ * Licensed under the MIT license. See LICENSE file for details.
499
+ */
500
+
501
+ // Commented items are defaults, feel free to modify and experiment!
502
+ // See README for a detailed explanation of the configuration options.
503
+
504
+ /** @type {import('@fastly/compute-js-static-publish').StaticPublisherConfig} */
505
+ const config = {
506
+ rootDir: ${JSON.stringify(rootDirRel)},
507
+ // objectStore: false,
508
+ // excludeDirs: [ './node_modules' ],
509
+ // excludeDotFiles: true,
510
+ // includeWellKnown: true,
511
+ // contentAssetInclusionTest: (filename) => true,
512
+ // contentCompression: [ 'br', 'gzip' ],
513
+ // moduleAssetInclusionTest: (filename) => false,
514
+ // contentTypes: [
515
+ // { test: /.custom$/, contentType: 'application/x-custom', text: false },
516
+ // ],
517
+ server: {
518
+ publicDirPrefix: ${JSON.stringify(publicDirPrefix)},
519
+ staticItems: ${JSON.stringify(staticItems)},
520
+ // compression: [ 'br', 'gzip' ],
521
+ spaFile: ${JSON.stringify(spaFile)},
522
+ notFoundPageFile: ${JSON.stringify(notFoundPageFile)},
523
+ autoExt: ${JSON.stringify(autoExt)},
524
+ autoIndex: ${JSON.stringify(autoIndex)},
525
+ },
526
+ };
527
+
528
+ ${useWebpack ? 'module.exports =' : 'export default'} config;
529
+ `;
530
+ const staticPublishJsonPath = path.resolve(computeJsDir, 'static-publish.rc.js');
531
+ fs.writeFileSync(staticPublishJsonPath, staticPublishJsContent, "utf-8");
532
+ // Copy resource files
533
+ if (useWebpack) {
534
+ // webpack.config.js
535
+ const webpackConfigJsSrcPath = path.resolve(__dirname, '../../../resources/webpack.config.js');
536
+ const webpackConfigJsPath = path.resolve(computeJsDir, 'webpack.config.js');
537
+ fs.copyFileSync(webpackConfigJsSrcPath, webpackConfigJsPath);
538
+ }
539
+ // src/index.js
540
+ const indexJsSrcPath = path.resolve(__dirname, '../../../resources/index.js');
541
+ const indexJsPath = path.resolve(computeJsDir, './src/index.js');
542
+ fs.copyFileSync(indexJsSrcPath, indexJsPath);
543
+ console.log("🚀 Compute@Edge application created!");
544
+ console.log('Installing dependencies...');
545
+ console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
546
+ child_process.spawnSync('npm', ['--prefix', COMPUTE_JS_DIR, 'install'], { stdio: 'inherit' });
547
+ console.log('');
548
+ console.log('');
549
+ console.log('To run your Compute@Edge application locally:');
550
+ console.log('');
551
+ console.log(' cd ' + COMPUTE_JS_DIR);
552
+ console.log(' fastly compute serve');
553
+ console.log('');
554
+ console.log('To build and deploy to your Compute@Edge service:');
555
+ console.log('');
556
+ console.log(' cd ' + COMPUTE_JS_DIR);
557
+ console.log(' fastly compute publish');
558
+ console.log('');
559
+ }
@@ -0,0 +1,3 @@
1
+ export declare const key = "br";
2
+ export declare function compressTo(src: string, dest: string, isText: boolean): Promise<boolean>;
3
+ //# sourceMappingURL=brotli.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,15 @@
1
+ import fs from 'fs';
2
+ import brotliCompress from 'brotli-compress';
3
+ export const key = 'br';
4
+ export async function compressTo(src, dest, isText) {
5
+ const buffer = fs.readFileSync(src);
6
+ const resultBuffer = await brotliCompress.compress(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
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ export declare const key = "gzip";
2
+ export declare function compressTo(src: string, dest: string, isText: boolean): Promise<boolean>;
3
+ //# sourceMappingURL=gzip.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,15 @@
1
+ import fs from 'fs';
2
+ import zlib from 'zlib';
3
+ export const key = 'gzip';
4
+ export async function compressTo(src, dest, isText) {
5
+ const buffer = fs.readFileSync(src);
6
+ 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
+ }
15
+ }
@@ -0,0 +1,8 @@
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>>;
7
+ export { algs };
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,12 @@
1
+ import * as brotli from './brotli.js';
2
+ 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
+ }, {});
12
+ export { algs };
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":""}