@fastly/compute-js-static-publish 1.0.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 (39) hide show
  1. package/.idea/compute-js-static-publish.iml +12 -0
  2. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  3. package/.idea/jsLibraryMappings.xml +6 -0
  4. package/.idea/misc.xml +6 -0
  5. package/.idea/modules.xml +8 -0
  6. package/.idea/vcs.xml +6 -0
  7. package/LICENSE +21 -0
  8. package/README.md +106 -0
  9. package/SECURITY.md +13 -0
  10. package/build/build-static.js +160 -0
  11. package/build/content-types.js +1 -0
  12. package/build/index.js +69 -0
  13. package/build/init-app.js +276 -0
  14. package/build/presets/implementations/create-react-app.js +35 -0
  15. package/build/presets/implementations/docusaurus.js +13 -0
  16. package/build/presets/implementations/gatsby.js +13 -0
  17. package/build/presets/implementations/next.js +13 -0
  18. package/build/presets/implementations/sveltekit.js +13 -0
  19. package/build/presets/implementations/vite.js +13 -0
  20. package/build/presets/index.js +16 -0
  21. package/build/presets/preset-base.js +1 -0
  22. package/package.json +43 -0
  23. package/resources/README.md +3 -0
  24. package/resources/default-content-types.cjs +105 -0
  25. package/resources/index.js +120 -0
  26. package/resources/webpack.config.js +111 -0
  27. package/src/build-static.ts +195 -0
  28. package/src/content-types.ts +7 -0
  29. package/src/index.ts +81 -0
  30. package/src/init-app.ts +330 -0
  31. package/src/presets/implementations/create-react-app.ts +34 -0
  32. package/src/presets/implementations/docusaurus.ts +13 -0
  33. package/src/presets/implementations/gatsby.ts +13 -0
  34. package/src/presets/implementations/next.ts +13 -0
  35. package/src/presets/implementations/sveltekit.ts +13 -0
  36. package/src/presets/implementations/vite.ts +13 -0
  37. package/src/presets/index.ts +18 -0
  38. package/src/presets/preset-base.ts +18 -0
  39. package/tsconfig.json +19 -0
@@ -0,0 +1,330 @@
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.exit(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.exit(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.exit(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.exit(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.exit(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.exit(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.3.0",
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"
220
+ },
221
+ "license": "MIT",
222
+ "private": true,
223
+ "main": "src/index.js",
224
+ "scripts": {
225
+ "build": "js-compute-runtime bin/index.js bin/main.wasm",
226
+ "deploy": "npm run build && fastly compute deploy",
227
+ "prebuild": "npx @fastly/compute-js-static-publish --build-static && webpack"
228
+ },
229
+ "version": "0.2.1"
230
+ }
231
+ `;
232
+
233
+ const packageJsonPath = path.resolve(computeJsDir, 'package.json');
234
+ fs.writeFileSync(packageJsonPath, packageJsonContent, "utf-8");
235
+
236
+ // fastly.toml
237
+
238
+ // language=toml
239
+ const fastlyTomlContent = `\
240
+ # This file describes a Fastly Compute@Edge package. To learn more visit:
241
+ # https://developer.fastly.com/reference/fastly-toml/
242
+
243
+ authors = [ "${author}" ]
244
+ description = "${description}"
245
+ language = "javascript"
246
+ manifest_version = 2
247
+ name = "${name}"
248
+ service_id = "${fastlyServiceId}"
249
+ `;
250
+
251
+ const fastlyTomlPath = path.resolve(computeJsDir, 'fastly.toml');
252
+ fs.writeFileSync(fastlyTomlPath, fastlyTomlContent, "utf-8");
253
+
254
+ // static-publish.rc.js
255
+ const publicDirRel = path.relative(computeJsDir, publicDir);
256
+
257
+ const staticDirs = [];
258
+ if (buildStaticDir != null) {
259
+ staticDirs.push(buildStaticDir);
260
+ }
261
+
262
+ const staticDirsRel = [];
263
+ for (const staticDir of staticDirs) {
264
+ const rel = path.relative(publicDir, staticDir);
265
+ if(rel.startsWith('../')) {
266
+ // we can't have a path outside the public dir, so we ignore it
267
+ console.warn(`Specified static dir '${staticDir}' is not inside public directory, ignoring...`);
268
+ continue;
269
+ }
270
+ staticDirsRel.push('./' + rel);
271
+ }
272
+
273
+ let spaFileRel: string | false = false;
274
+ if(spaFilename != null) {
275
+ spaFileRel = '/' + path.relative(publicDir, spaFilename);
276
+ }
277
+
278
+ let notFoundFileRel: string | false = false;
279
+ if(notFoundPageFilename != null) {
280
+ notFoundFileRel = '/' + path.relative(publicDir, notFoundPageFilename);
281
+ }
282
+
283
+ const staticPublishJsContent = `\
284
+ module.exports = {
285
+ publicDir: ${JSON.stringify(publicDirRel)},
286
+ excludeDirs: [ './node_modules' ],
287
+ includeDirs: [ './.well-known' ],
288
+ staticDirs: ${JSON.stringify(staticDirsRel)},
289
+ spa: ${JSON.stringify(spaFileRel)},
290
+ notFoundPage: ${JSON.stringify(notFoundFileRel)},
291
+ autoIndex: ${JSON.stringify(autoIndex)},
292
+ autoExt: ${JSON.stringify(autoExt)},
293
+ };`;
294
+
295
+ const staticPublishJsonPath = path.resolve(computeJsDir, 'static-publish.rc.js');
296
+ fs.writeFileSync(staticPublishJsonPath, staticPublishJsContent, "utf-8");
297
+
298
+ // Copy resource files
299
+ const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
300
+
301
+ // webpack.config.js
302
+ const webpackConfigJsSrcPath = path.resolve(__dirname, '../resources/webpack.config.js');
303
+ const webpackConfigJsPath = path.resolve(computeJsDir, 'webpack.config.js');
304
+ fs.copyFileSync(webpackConfigJsSrcPath, webpackConfigJsPath);
305
+
306
+ // src/index.js
307
+ const indexJsSrcPath = path.resolve(__dirname, '../resources/index.js');
308
+ const indexJsPath = path.resolve(computeJsDir, './src/index.js');
309
+ fs.copyFileSync(indexJsSrcPath, indexJsPath);
310
+
311
+ console.log("🚀 Compute@Edge application created!");
312
+
313
+ console.log('Installing dependencies...');
314
+ console.log(`npm --prefix ${COMPUTE_JS_DIR} install`);
315
+ child_process.spawnSync('npm', [ '--prefix', COMPUTE_JS_DIR, 'install' ], { stdio: 'inherit' });
316
+ console.log('');
317
+
318
+ console.log('');
319
+ console.log('To run your Compute@Edge application locally:');
320
+ console.log('');
321
+ console.log(' cd ' + COMPUTE_JS_DIR);
322
+ console.log(' fastly compute serve');
323
+ console.log('');
324
+ console.log('To build and deploy to your Compute@Edge service:');
325
+ console.log('');
326
+ console.log(' cd ' + COMPUTE_JS_DIR);
327
+ console.log(' fastly compute publish');
328
+ console.log('');
329
+
330
+ }
@@ -0,0 +1,34 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class CreateReactAppPreset implements IPresetBase {
4
+ name = 'Create React App';
5
+ defaultOptions = {
6
+ 'public-dir': './build',
7
+ 'static-dir': '[public-dir]/static',
8
+ name: 'my-create-react-app',
9
+ description: 'Compute@Edge static site from create-react-app',
10
+ };
11
+
12
+ check(packageJson: any): boolean {
13
+ if(packageJson == null) {
14
+ console.error("❌ Can't read/parse package.json");
15
+ console.error("Run this from a create-react-app project directory.");
16
+ return false;
17
+ }
18
+ if(packageJson?.dependencies?.['react-scripts'] == null) {
19
+ console.error("❌ Can't find react-scripts in dependencies");
20
+ console.error("Run this from a create-react-app project directory.");
21
+ console.log("If this is a project created with create-react-app and has since been ejected, specify preset cra-eject to skip this check.")
22
+ return false;
23
+ }
24
+ return true;
25
+ }
26
+
27
+ }
28
+
29
+ export class CreateReactAppEjectedPreset extends CreateReactAppPreset {
30
+ name = 'Create React App (Ejected)';
31
+ check() {
32
+ return true;
33
+ }
34
+ }
@@ -0,0 +1,13 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class DocusaurusPreset implements IPresetBase {
4
+ name = 'Docusaurus';
5
+ defaultOptions = {
6
+ 'public-dir': './build',
7
+ name: 'my-docusaurus-app',
8
+ description: 'Compute@Edge static site from docusaurus',
9
+ };
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class GatsbyPreset implements IPresetBase {
4
+ name = 'Gatsby';
5
+ defaultOptions = {
6
+ 'public-dir': './public',
7
+ name: 'my-gatsby-app',
8
+ description: 'Compute@Edge static site from Gatsby',
9
+ };
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class NextJsPreset implements IPresetBase {
4
+ name = 'Next.js';
5
+ defaultOptions = {
6
+ 'public-dir': './out',
7
+ name: 'my-next-app',
8
+ description: 'Compute@Edge static site from Next.js',
9
+ };
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class SvelteKitPreset implements IPresetBase {
4
+ name = 'SvelteKit';
5
+ defaultOptions = {
6
+ 'public-dir': './dist',
7
+ name: 'my-sveltekit-app',
8
+ description: 'Compute@Edge static site from SvelteKit',
9
+ };
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,13 @@
1
+ import { IPresetBase } from '../preset-base.js';
2
+
3
+ export class VitePreset implements IPresetBase {
4
+ name = 'Vite';
5
+ defaultOptions = {
6
+ 'public-dir': './dist',
7
+ name: 'my-vite-app',
8
+ description: 'Compute@Edge static site from Vite',
9
+ };
10
+ check() {
11
+ return true;
12
+ }
13
+ }
@@ -0,0 +1,18 @@
1
+ import { IPresetBase } from './preset-base.js';
2
+ import { CreateReactAppPreset, CreateReactAppEjectedPreset } from './implementations/create-react-app.js';
3
+ import { VitePreset } from './implementations/vite.js';
4
+ import { SvelteKitPreset } from './implementations/sveltekit.js';
5
+ import { NextJsPreset } from './implementations/next.js';
6
+ import { GatsbyPreset } from './implementations/gatsby.js';
7
+ import { DocusaurusPreset } from './implementations/docusaurus.js';
8
+
9
+ export const presets: Record<string, new() => IPresetBase> = {
10
+ 'cra': CreateReactAppPreset,
11
+ 'create-react-app': CreateReactAppPreset,
12
+ 'cra-eject': CreateReactAppEjectedPreset,
13
+ 'vite': VitePreset,
14
+ 'sveltekit': SvelteKitPreset,
15
+ 'next': NextJsPreset,
16
+ 'gatsby': GatsbyPreset,
17
+ 'docusaurus': DocusaurusPreset,
18
+ };
@@ -0,0 +1,18 @@
1
+ export type AppOptions = {
2
+ 'public-dir': string | undefined,
3
+ 'static-dir': string | undefined,
4
+ spa: string | null | undefined,
5
+ 'not-found-page': string | null | undefined,
6
+ 'auto-index': string[] | null | undefined,
7
+ 'auto-ext': string[] | null | undefined,
8
+ name: string,
9
+ author: string,
10
+ description: string,
11
+ 'service-id': string | undefined,
12
+ };
13
+
14
+ export interface IPresetBase {
15
+ name: string;
16
+ defaultOptions: Partial<AppOptions>;
17
+ check(packageJson: any | null, options: AppOptions): boolean;
18
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "rootDir": "./src",
4
+ "outDir": "./build/",
5
+ "target": "es2018",
6
+ "module": "node16",
7
+ "resolveJsonModule": true,
8
+ "strict": true,
9
+ "skipLibCheck": true,
10
+ "moduleResolution": "node16"
11
+ },
12
+ "include": [
13
+ "src/**/*.ts",
14
+ "test/**/*.ts"
15
+ ],
16
+ "exclude": [
17
+ "node_modules",
18
+ ]
19
+ }