@fastly/compute-js-static-publish 2.2.1 → 2.3.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 (58) hide show
  1. package/README.md +5 -5
  2. package/build/assets.d.ts +8 -0
  3. package/build/assets.d.ts.map +1 -0
  4. package/build/assets.js +24 -0
  5. package/build/build-static.d.ts +3 -0
  6. package/build/build-static.d.ts.map +1 -0
  7. package/build/build-static.js +0 -3
  8. package/build/cli.d.ts +3 -0
  9. package/build/cli.d.ts.map +1 -0
  10. package/build/cli.js +77 -0
  11. package/build/index.d.ts +3 -0
  12. package/build/index.d.ts.map +1 -0
  13. package/build/index.js +2 -77
  14. package/build/init-app.d.ts +3 -0
  15. package/build/init-app.d.ts.map +1 -0
  16. package/build/init-app.js +8 -8
  17. package/build/presets/implementations/create-react-app.d.ts +16 -0
  18. package/build/presets/implementations/create-react-app.d.ts.map +1 -0
  19. package/build/presets/implementations/docusaurus.d.ts +11 -0
  20. package/build/presets/implementations/docusaurus.d.ts.map +1 -0
  21. package/build/presets/implementations/gatsby.d.ts +11 -0
  22. package/build/presets/implementations/gatsby.d.ts.map +1 -0
  23. package/build/presets/implementations/next.d.ts +11 -0
  24. package/build/presets/implementations/next.d.ts.map +1 -0
  25. package/build/presets/implementations/sveltekit.d.ts +11 -0
  26. package/build/presets/implementations/sveltekit.d.ts.map +1 -0
  27. package/build/presets/implementations/vite.d.ts +11 -0
  28. package/build/presets/implementations/vite.d.ts.map +1 -0
  29. package/build/presets/index.d.ts +3 -0
  30. package/build/presets/index.d.ts.map +1 -0
  31. package/build/presets/preset-base.d.ts +18 -0
  32. package/build/presets/preset-base.d.ts.map +1 -0
  33. package/build/static-assets.d.ts +8 -0
  34. package/build/static-assets.d.ts.map +1 -0
  35. package/build/static-assets.js +24 -0
  36. package/build/types.d.ts +26 -0
  37. package/build/types.d.ts.map +1 -0
  38. package/build/types.js +1 -0
  39. package/package.json +13 -4
  40. package/.idea/compute-js-static-publish.iml +0 -12
  41. package/.idea/inspectionProfiles/Project_Default.xml +0 -6
  42. package/.idea/jsLibraryMappings.xml +0 -6
  43. package/.idea/misc.xml +0 -6
  44. package/.idea/modules.xml +0 -8
  45. package/.idea/vcs.xml +0 -6
  46. package/src/build-static.ts +0 -245
  47. package/src/content-types.ts +0 -7
  48. package/src/index.ts +0 -89
  49. package/src/init-app.ts +0 -331
  50. package/src/presets/implementations/create-react-app.ts +0 -34
  51. package/src/presets/implementations/docusaurus.ts +0 -13
  52. package/src/presets/implementations/gatsby.ts +0 -13
  53. package/src/presets/implementations/next.ts +0 -13
  54. package/src/presets/implementations/sveltekit.ts +0 -13
  55. package/src/presets/implementations/vite.ts +0 -13
  56. package/src/presets/index.ts +0 -18
  57. package/src/presets/preset-base.ts +0 -18
  58. package/tsconfig.json +0 -19
@@ -1,245 +0,0 @@
1
- // This program builds static resources out of the files in the
2
- // public folder to be served. It reads the name of the public
3
- // folder from the static-publish.rc.js file.
4
-
5
- // With create-react-app, this would be the ./build directory.
6
-
7
- // This also reexports the "spa" value in the static-publish.rc.js
8
- // file so that the C@E handler knows what file to serve up if
9
- // the resource doesn't map to a file.
10
-
11
- import * as fs from "fs";
12
- import * as path from "path";
13
- import * as url from "url";
14
- import { ContentTypeDef } from "./content-types.js";
15
- import commandLineArgs from "command-line-args";
16
-
17
- function getFiles(results: string[], dir: string) {
18
- const entries = fs.readdirSync(dir, { withFileTypes: true });
19
- for (const entry of entries) {
20
- const name = path.resolve(dir, entry.name);
21
- if (entry.isDirectory()) {
22
- getFiles(results, name);
23
- } else {
24
- results.push(name);
25
- }
26
- }
27
- }
28
-
29
- export async function buildStaticLoader(commandLineValues: commandLineArgs.CommandLineOptions) {
30
-
31
- const { 'suppress-framework-warnings': suppressFrameworkWarnings } = commandLineValues;
32
- const displayFrameworkWarnings = !suppressFrameworkWarnings;
33
-
34
- console.log("🚀 Building loader...");
35
-
36
- let config: any;
37
- try {
38
- const staticPublishRcPath = path.resolve('./static-publish.rc.js');
39
- config = (await import(staticPublishRcPath)).default;
40
- } catch(ex) {
41
- console.error("❌ Can't load static-publish.rc.js");
42
- console.error("Run this from a compute-js-static-publish compute-js directory.");
43
- console.error("Error: ", String(ex));
44
- process.exitCode = 1;
45
- return;
46
- }
47
-
48
- const results: string[] = [];
49
- getFiles(results, config.publicDir);
50
-
51
- const outputDir = path.resolve();
52
-
53
- const publicDirRoot = path.resolve(config.publicDir);
54
-
55
- console.log(`✔️ Public directory '${publicDirRoot}'.`);
56
-
57
- const staticDirs: string[] = config.staticDirs ?? [];
58
- if (staticDirs.length > 0) {
59
- console.log(`✔️ Using static directories: ${staticDirs.join(', ')}`);
60
- } else {
61
- if (displayFrameworkWarnings) {
62
- console.log(`✔️ No static directories defined.`);
63
- }
64
- }
65
- const staticRoots = staticDirs.map(
66
- dir => path.resolve(config.publicDir, dir)
67
- );
68
-
69
- const DEFAULT_EXCLUDE_DIRS = [
70
- './node_modules'
71
- ];
72
-
73
- const excludeDirs: string[] = config.excludeDirs ?? DEFAULT_EXCLUDE_DIRS;
74
- if (excludeDirs.length > 0) {
75
- console.log(`✔️ Using exclude directories: ${excludeDirs.join(', ')}`);
76
- } else {
77
- if (displayFrameworkWarnings) {
78
- console.log(`✔️ No exclude directories defined.`);
79
- }
80
- }
81
- const excludeRoots = excludeDirs.map(
82
- dir => path.resolve(config.publicDir, dir)
83
- );
84
-
85
- // Load defaultContentTypes module
86
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
87
- const defaultContentTypesJsSrcPath = path.resolve(__dirname, '../resources/default-content-types.cjs');
88
- const defaultContentTypes = await import(defaultContentTypesJsSrcPath);
89
-
90
- // Load content types
91
- const finalContentTypes: ContentTypeDef[] = defaultContentTypes.mergeContentTypes(config.contentTypes ?? []);
92
-
93
- // Update the target file too, so webpack can see it.
94
- const defaultContentTypesJsPath = path.resolve('./default-content-types.cjs');
95
- fs.copyFileSync(defaultContentTypesJsSrcPath, defaultContentTypesJsPath);
96
-
97
- const DEFAULT_INCLUDE_DIRS = [
98
- './.well-known'
99
- ];
100
-
101
- const includeDirs: string[] = config.includeDirs ?? DEFAULT_INCLUDE_DIRS;
102
- if (includeDirs.length > 0) {
103
- console.log(`✔️ Using include directories: ${includeDirs.join(', ')}`);
104
- } else {
105
- if (displayFrameworkWarnings) {
106
- console.log(`✔️ No include directories defined.`);
107
- }
108
- }
109
- const includeRoots = includeDirs.map(
110
- dir => path.resolve(config.publicDir, dir)
111
- );
112
-
113
- const excludeTest: ((path: string) => boolean) | undefined = config.excludeTest;
114
-
115
- const files = results
116
- .filter(file => {
117
- // Exclude files that come from C@E app dir
118
- if(file.startsWith(outputDir)) {
119
- return false;
120
- }
121
- // Include files that come from "included roots" dir
122
- if(includeRoots.some(root => file.startsWith(root))) {
123
- return true;
124
- }
125
- // Exclude files that are in directories that start with "."
126
- if(file.indexOf('/.') !== -1) {
127
- return false;
128
- }
129
- // Exclude files that come from "excluded roots" dir
130
- if(excludeRoots.some(root => file.startsWith(root))) {
131
- return false;
132
- }
133
- return true;
134
- })
135
- .filter(file => {
136
- return excludeTest == null || !excludeTest(file);
137
- });
138
-
139
- const moduleTest: ((path: string) => boolean) | undefined = config.moduleTest;
140
-
141
- const knownAssets: Record<string, {contentType: string, isStatic: boolean, loadModule: boolean}> = {};
142
-
143
- let fileContents = 'import { Buffer } from "buffer";\n';
144
-
145
- for (const [index, file] of files.entries()) {
146
- const relativeFilePath = path.relative('./src', file);
147
- const contentDef = defaultContentTypes.testFileContentType(finalContentTypes, file);
148
- const filePath = file.slice(publicDirRoot.length);
149
- const type = contentDef?.type;
150
- const isStatic = staticRoots.some(root => file.startsWith(root));
151
-
152
- let query;
153
- if (contentDef == null || contentDef.binary) {
154
- query = '?staticBinary';
155
- } else {
156
- query = '?staticText';
157
- }
158
- fileContents += `import file${index} from "${relativeFilePath}${query}";\n`;
159
- let loadModule = false;
160
- if (moduleTest != null && moduleTest(filePath)) {
161
- loadModule = true;
162
- fileContents += `import * as fileModule${index} from "${relativeFilePath}";\n`;
163
- }
164
- knownAssets[filePath] = { contentType: type, isStatic, loadModule, };
165
- }
166
-
167
- fileContents += `\nexport const assets = {\n`;
168
-
169
- for (const [index, file] of files.entries()) {
170
- const contentDef = defaultContentTypes.testFileContentType(finalContentTypes, file);
171
- const filePath = file.slice(publicDirRoot.length);
172
- const { contentType: type, isStatic, loadModule } = knownAssets[filePath];
173
-
174
- if (contentDef != null) {
175
- console.log('✔️ ' + filePath + ': ' + JSON.stringify(type) + (isStatic ? ' [STATIC]' : ''));
176
- } else {
177
- if (displayFrameworkWarnings) {
178
- console.log('⚠️ Notice: Unknown file type ' + filePath + '. Treating as binary file.');
179
- }
180
- }
181
-
182
- let content;
183
- if (contentDef == null || contentDef.binary) {
184
- content = 'Buffer.from(file' + index + ', "base64")';
185
- } else {
186
- content = 'file' + index;
187
- }
188
-
189
- let module;
190
- if (loadModule) {
191
- module = 'fileModule' + index;
192
- } else {
193
- module = 'null';
194
- }
195
-
196
- fileContents += ` ${JSON.stringify(filePath)}: { contentType: ${JSON.stringify(type)}, content: ${content}, module: ${module}, isStatic: ${JSON.stringify(isStatic)} },\n`;
197
- }
198
-
199
- fileContents += '};\n';
200
-
201
- let spaFile: string | false = config.spa ?? false;
202
- if(spaFile) {
203
- console.log(`✔️ Application SPA file '${spaFile}'.`);
204
- if(!knownAssets[spaFile] || knownAssets[spaFile].contentType !== 'text/html') {
205
- if (displayFrameworkWarnings) {
206
- console.log(`⚠️ Notice: '${spaFile}' does not exist or is not of type 'text/html'. Ignoring.`);
207
- }
208
- spaFile = false;
209
- }
210
- } else {
211
- if (displayFrameworkWarnings) {
212
- console.log(`✔️ Application is not a SPA.`);
213
- }
214
- }
215
-
216
- fileContents += `\nexport const spaFile = ${JSON.stringify(spaFile)};\n`;
217
-
218
- let notFoundPageFile: string | false = config.notFoundPage ?? false;
219
- if(notFoundPageFile) {
220
- console.log(`✔️ Application 'not found (404)' file '${notFoundPageFile}'.`);
221
- if(!knownAssets[notFoundPageFile] || knownAssets[notFoundPageFile].contentType !== 'text/html') {
222
- if (displayFrameworkWarnings) {
223
- console.log(`⚠️ Notice: '${notFoundPageFile}' does not exist or is not of type 'text/html'. Ignoring.`);
224
- }
225
- notFoundPageFile = false;
226
- }
227
- } else {
228
- if (displayFrameworkWarnings) {
229
- console.log(`✔️ Application specifies no 'not found (404)' page.`);
230
- }
231
- }
232
-
233
- fileContents += `\nexport const notFoundPageFile = ${JSON.stringify(notFoundPageFile)};\n`;
234
-
235
- let autoIndex: string | false = config.autoIndex ?? null;
236
- fileContents += `\nexport const autoIndex = ${JSON.stringify(autoIndex)};\n`;
237
-
238
- let autoExt: string | false = config.autoExt ?? null;
239
- fileContents += `\nexport const autoExt = ${JSON.stringify(autoExt)};\n`;
240
-
241
- fs.writeFileSync('./src/statics.js', fileContents);
242
-
243
- console.log("✅ Wrote static file loader for " + files.length + " file(s).");
244
-
245
- }
@@ -1,7 +0,0 @@
1
- type TestFn = (name: string) => boolean;
2
-
3
- export type ContentTypeDef = {
4
- test: RegExp | TestFn,
5
- type: string,
6
- binary?: boolean,
7
- };
package/src/index.ts DELETED
@@ -1,89 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import commandLineArgs, { OptionDefinition } from "command-line-args";
4
-
5
- import { initApp } from "./init-app.js";
6
- import { buildStaticLoader } from "./build-static.js";
7
-
8
- const optionDefinitions: OptionDefinition[] = [
9
- // (optional) Should be one of:
10
- // - cra (or create-react-app)
11
- // - vite
12
- // - sveltekit
13
- // - next
14
- // - gatsby
15
- // - docusaurus
16
- { name: 'preset', type: String, },
17
-
18
- { name: 'build-static', type: Boolean },
19
- { name: 'suppress-framework-warnings', type: Boolean },
20
- { name: 'output', alias: 'o', type: String, defaultValue: './compute-js', },
21
- { name: 'public-dir', type: String, },
22
- { name: 'static-dir', type: String, },
23
-
24
- // List of files to automatically use as index, for example, index.html,index.htm
25
- // If a request comes in but the route does not exist, we check the route
26
- // plus a slash plus the items in this array.
27
- {
28
- name: 'auto-index',
29
- type: (val: string | null) => {
30
- if(val == null) {
31
- return null;
32
- }
33
- const values = val
34
- .split(',')
35
- .map(x => x.trim())
36
- .filter(x => x !== '');
37
- return values.length > 0 ? values : null;
38
- },
39
- },
40
-
41
- // List of extensions to apply to a path name, for example, if
42
- // http://example.com/about is requested, we can respond with http://example.com/about.html
43
- {
44
- name: 'auto-ext',
45
- type: (val: string | null) => {
46
- if(val == null) {
47
- return null;
48
- }
49
- const values = val
50
- .split(',')
51
- .map(x => x.trim())
52
- .map(x => {
53
- while(x.startsWith('.')) {
54
- x = x.slice(1);
55
- }
56
- return '.' + x;
57
- })
58
- .filter(x => x !== '');
59
- return values.length > 0 ? values : null;
60
- },
61
- },
62
-
63
- { name: 'spa', type: String, },
64
- { name: 'not-found-page', type: String, },
65
- { name: 'name', type: String, },
66
- { name: 'author', type: String, },
67
- { name: 'description', type: String, },
68
-
69
- // Fastly Service ID to be added to the fastly.toml that is generated.
70
- { name: 'service-id', type: String },
71
- ];
72
-
73
- const commandLineValues = commandLineArgs(optionDefinitions);
74
-
75
- console.log("Fastly Compute@Edge JavaScript Static Publisher");
76
-
77
- let mode: 'init-app' | 'build-static' = 'init-app';
78
- if(commandLineValues['build-static']) {
79
- mode = 'build-static';
80
- }
81
-
82
- switch(mode) {
83
- case 'build-static':
84
- await buildStaticLoader(commandLineValues);
85
- break;
86
- case 'init-app':
87
- initApp(commandLineValues);
88
- break;
89
- }
package/src/init-app.ts DELETED
@@ -1,331 +0,0 @@
1
- import { CommandLineOptions } from "command-line-args";
2
-
3
- // This program creates a Compute@Edge JavaScript application
4
- // in a subfolder named compute-js.
5
- // This project can be served using fastly compute serve
6
- // or deployed to a Compute@Edge service using fastly compute publish.
7
-
8
- import * as child_process from "child_process";
9
- import * as path from "path";
10
- import * as fs from "fs";
11
- import * as url from 'url';
12
-
13
- import { AppOptions, IPresetBase } from './presets/preset-base.js';
14
- import { presets } from './presets/index.js';
15
-
16
- const defaultOptions: AppOptions = {
17
- 'public-dir': undefined,
18
- 'static-dir': undefined,
19
- spa: undefined,
20
- 'not-found-page': '[public-dir]/404.html',
21
- 'auto-index': [ 'index.html', 'index.htm' ],
22
- 'auto-ext': [ '.html', '.htm' ],
23
- author: 'you@example.com',
24
- name: 'compute-js-static-site',
25
- description: 'Compute@Edge static site',
26
- 'service-id': undefined,
27
- };
28
-
29
- function pickKeys(keys: string[], object: Record<string, any>): Record<string, any> {
30
-
31
- const result: Record<string, any> = {};
32
-
33
- for (const key of keys) {
34
- if(object[key] !== undefined) {
35
- result[key] = object[key];
36
- }
37
- }
38
-
39
- return result;
40
-
41
- }
42
-
43
- function applyPublicDir(optionValue: string | null | undefined, publicDir: string) {
44
- if(optionValue == null) {
45
- return optionValue;
46
- }
47
- return optionValue.replace('[public-dir]', publicDir);
48
- }
49
-
50
- export function initApp(commandLineValues: CommandLineOptions) {
51
-
52
- let options: AppOptions = defaultOptions;
53
- let preset: IPresetBase | null = null;
54
-
55
- const presetName = (commandLineValues['preset'] as string | null) ?? 'none';
56
- if(presetName !== 'none') {
57
- const presetClass = presets[presetName];
58
- if(presetClass == null) {
59
- console.error('Unknown preset name.');
60
- console.error("--preset must be one of: none, " + (Object.keys(presets).join(', ')));
61
- process.exitCode = 1;
62
- return;
63
- }
64
- preset = new presetClass();
65
- }
66
-
67
- let packageJson;
68
- try {
69
- const packageJsonText = fs.readFileSync("./package.json", "utf-8");
70
- packageJson = JSON.parse(packageJsonText);
71
- } catch {
72
- console.log("Can't read/parse package.json in current directory, making no assumptions!");
73
- packageJson = null;
74
- }
75
-
76
- options = {
77
- ...options,
78
- ...(preset != null ? preset.defaultOptions : {}),
79
- ...pickKeys(['author', 'name', 'description'], packageJson ?? {}),
80
- ...pickKeys(['public-dir', 'static-dir', 'spa', 'not-found-page', 'auto-index', 'auto-ext', 'author', 'name', 'description', 'service-id'], commandLineValues)
81
- };
82
-
83
- if(preset != null) {
84
- if(!preset.check(packageJson, options)) {
85
- console.log("Failed preset check.");
86
- process.exitCode = 1;
87
- return;
88
- }
89
- }
90
-
91
- const COMPUTE_JS_DIR = commandLineValues.output as string;
92
- const computeJsDir = path.resolve(COMPUTE_JS_DIR);
93
-
94
- const PUBLIC_DIR = options['public-dir'];
95
- if(PUBLIC_DIR == null) {
96
- console.error("❌ required parameter --public-dir not provided.");
97
- process.exitCode = 1;
98
- return;
99
- }
100
- const publicDir = path.resolve(PUBLIC_DIR);
101
-
102
- const BUILD_STATIC_DIR = applyPublicDir(options['static-dir'], PUBLIC_DIR);
103
- const buildStaticDir = BUILD_STATIC_DIR != null ? path.resolve(BUILD_STATIC_DIR) : null;
104
-
105
- const spa = applyPublicDir(options['spa'], PUBLIC_DIR);
106
- const notFoundPage = applyPublicDir(options['not-found-page'], PUBLIC_DIR);
107
-
108
- const autoIndex = options['auto-index'];
109
- const autoExt = options['auto-ext'];
110
-
111
- let spaFilename = spa;
112
-
113
- // Specifically check for null instead of undefined
114
- if(spa === null) {
115
- spaFilename = path.resolve(publicDir, './index.html');
116
- let rel = path.relative(path.resolve(), spaFilename);
117
- if(!rel.startsWith('..')) {
118
- rel = './' + rel;
119
- }
120
- console.log('--spa provided with no value, assuming ' + rel);
121
- }
122
-
123
- if(spaFilename != null) {
124
- spaFilename = path.resolve(spaFilename);
125
- if(!spaFilename.startsWith(publicDir)) {
126
- console.error(`❌ SPA file '${spaFilename}' not inside public directory!`);
127
- process.exitCode = 1;
128
- return;
129
- }
130
- }
131
-
132
- let notFoundPageFilename = notFoundPage;
133
-
134
- // Specifically check for null instead of undefined
135
- if(notFoundPage === null) {
136
- notFoundPageFilename = path.resolve(publicDir, './404.html');
137
- let rel = path.relative(path.resolve(), notFoundPageFilename);
138
- if(!rel.startsWith('..')) {
139
- rel = './' + rel;
140
- }
141
- console.log('--not-found-page provided with no value, assuming ' + rel);
142
- }
143
-
144
- if(notFoundPageFilename != null) {
145
- notFoundPageFilename = path.resolve(notFoundPageFilename);
146
- if(!notFoundPageFilename.startsWith(publicDir)) {
147
- console.error(`❌ --not-found-page file '${notFoundPageFilename}' not inside public directory!`);
148
- process.exitCode = 1;
149
- return;
150
- }
151
- }
152
-
153
- const exists = fs.existsSync(computeJsDir);
154
- if(exists) {
155
- console.error(`❌ '${COMPUTE_JS_DIR}' directory already exists!`);
156
- process.exitCode = 1;
157
- return;
158
- }
159
-
160
- const author = options['author'];
161
- const name = options['name'];
162
- const description = options['description'];
163
- const fastlyServiceId = options['service-id'];
164
-
165
- let spaRel: string | null = spaFilename != null ? path.relative(path.resolve(), spaFilename) : null;
166
- if(spaRel != null && !spaRel.startsWith('..')) {
167
- spaRel = './' + spaRel;
168
- }
169
-
170
- let notFoundRel: string | null = notFoundPageFilename != null ? path.relative(path.resolve(), notFoundPageFilename) : null;
171
- if(notFoundRel != null && !notFoundRel.startsWith('..')) {
172
- notFoundRel = './' + notFoundRel;
173
- }
174
-
175
- console.log('');
176
- console.log('Public Dir :', PUBLIC_DIR);
177
- console.log('Static Dir :', BUILD_STATIC_DIR ?? '(None)');
178
- console.log('SPA :', spaRel != null ? spaRel : '(None)');
179
- console.log('404 Page :', notFoundRel != null ? notFoundRel : '(None)');
180
- console.log('Auto-Index :', autoIndex != null ? autoIndex : '(None)')
181
- console.log('Auto-Ext :', autoExt != null ? autoExt : '(None)')
182
- console.log('name :', name);
183
- console.log('author :', author);
184
- console.log('description :', description);
185
- console.log('Service ID :', fastlyServiceId);
186
- console.log('');
187
-
188
- console.log("Initializing Compute@Edge Application in " + computeJsDir + "...");
189
- fs.mkdirSync(computeJsDir);
190
- fs.mkdirSync(path.resolve(computeJsDir, './src'));
191
-
192
- // .gitignore
193
- const gitIgnoreContent = `\
194
- /node_modules
195
- /bin
196
- /pkg
197
- /src/statics.js
198
- `;
199
- const gitIgnorePath = path.resolve(computeJsDir, '.gitignore');
200
- fs.writeFileSync(gitIgnorePath, gitIgnoreContent, "utf-8");
201
-
202
- // package.json
203
-
204
- // language=JSON
205
- const packageJsonContent = `\
206
- {
207
- "name": ${JSON.stringify(name)},
208
- "description": ${JSON.stringify(description)},
209
- "author": ${JSON.stringify(author)},
210
- "devDependencies": {
211
- "@fastly/expressly": "^1.0.0-alpha.7",
212
- "@fastly/js-compute": "^0.5.3",
213
- "buffer": "^6.0.3",
214
- "core-js": "^3.19.1",
215
- "webpack": "^5.64.0",
216
- "webpack-cli": "^4.9.1"
217
- },
218
- "engines": {
219
- "node": ">=16.0.0"
220
- },
221
- "license": "MIT",
222
- "private": true,
223
- "main": "src/index.js",
224
- "scripts": {
225
- "deploy": "fastly compute deploy"
226
- },
227
- "version": "0.2.1"
228
- }
229
- `;
230
-
231
- const packageJsonPath = path.resolve(computeJsDir, 'package.json');
232
- fs.writeFileSync(packageJsonPath, packageJsonContent, "utf-8");
233
-
234
- // fastly.toml
235
-
236
- // language=toml
237
- const fastlyTomlContent = `\
238
- # This file describes a Fastly Compute@Edge package. To learn more visit:
239
- # https://developer.fastly.com/reference/fastly-toml/
240
-
241
- authors = [ "${author}" ]
242
- description = "${description}"
243
- language = "javascript"
244
- manifest_version = 2
245
- name = "${name}"
246
- service_id = "${fastlyServiceId}"
247
-
248
- [scripts]
249
- build = "npx @fastly/compute-js-static-publish --build-static && $(npm bin)/webpack && $(npm bin)/js-compute-runtime ./bin/index.js ./bin/main.wasm"
250
- `;
251
-
252
- const fastlyTomlPath = path.resolve(computeJsDir, 'fastly.toml');
253
- fs.writeFileSync(fastlyTomlPath, fastlyTomlContent, "utf-8");
254
-
255
- // static-publish.rc.js
256
- const publicDirRel = path.relative(computeJsDir, publicDir);
257
-
258
- const staticDirs = [];
259
- if (buildStaticDir != null) {
260
- staticDirs.push(buildStaticDir);
261
- }
262
-
263
- const staticDirsRel = [];
264
- for (const staticDir of staticDirs) {
265
- const rel = path.relative(publicDir, staticDir);
266
- if(rel.startsWith('../')) {
267
- // we can't have a path outside the public dir, so we ignore it
268
- console.warn(`Specified static dir '${staticDir}' is not inside public directory, ignoring...`);
269
- continue;
270
- }
271
- staticDirsRel.push('./' + rel);
272
- }
273
-
274
- let spaFileRel: string | false = false;
275
- if(spaFilename != null) {
276
- spaFileRel = '/' + path.relative(publicDir, spaFilename);
277
- }
278
-
279
- let notFoundFileRel: string | false = false;
280
- if(notFoundPageFilename != null) {
281
- notFoundFileRel = '/' + path.relative(publicDir, notFoundPageFilename);
282
- }
283
-
284
- const staticPublishJsContent = `\
285
- module.exports = {
286
- publicDir: ${JSON.stringify(publicDirRel)},
287
- excludeDirs: [ './node_modules' ],
288
- includeDirs: [ './.well-known' ],
289
- staticDirs: ${JSON.stringify(staticDirsRel)},
290
- spa: ${JSON.stringify(spaFileRel)},
291
- notFoundPage: ${JSON.stringify(notFoundFileRel)},
292
- autoIndex: ${JSON.stringify(autoIndex)},
293
- autoExt: ${JSON.stringify(autoExt)},
294
- };`;
295
-
296
- const staticPublishJsonPath = path.resolve(computeJsDir, 'static-publish.rc.js');
297
- fs.writeFileSync(staticPublishJsonPath, staticPublishJsContent, "utf-8");
298
-
299
- // Copy resource files
300
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
301
-
302
- // webpack.config.js
303
- const webpackConfigJsSrcPath = path.resolve(__dirname, '../resources/webpack.config.js');
304
- const webpackConfigJsPath = path.resolve(computeJsDir, 'webpack.config.js');
305
- fs.copyFileSync(webpackConfigJsSrcPath, webpackConfigJsPath);
306
-
307
- // src/index.js
308
- const indexJsSrcPath = path.resolve(__dirname, '../resources/index.js');
309
- const indexJsPath = path.resolve(computeJsDir, './src/index.js');
310
- fs.copyFileSync(indexJsSrcPath, indexJsPath);
311
-
312
- console.log("🚀 Compute@Edge application created!");
313
-
314
- console.log('Installing dependencies...');
315
- console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
316
- child_process.spawnSync('npm', [ '--prefix', COMPUTE_JS_DIR, 'install' ], { stdio: 'inherit' });
317
- console.log('');
318
-
319
- console.log('');
320
- console.log('To run your Compute@Edge application locally:');
321
- console.log('');
322
- console.log(' cd ' + COMPUTE_JS_DIR);
323
- console.log(' fastly compute serve');
324
- console.log('');
325
- console.log('To build and deploy to your Compute@Edge service:');
326
- console.log('');
327
- console.log(' cd ' + COMPUTE_JS_DIR);
328
- console.log(' fastly compute publish');
329
- console.log('');
330
-
331
- }