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

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 (68) hide show
  1. package/build/cli/commands/manage/clean.d.ts +2 -0
  2. package/build/cli/commands/manage/clean.d.ts.map +1 -0
  3. package/build/cli/commands/manage/clean.js +201 -0
  4. package/build/cli/commands/manage/collections/delete.d.ts +2 -0
  5. package/build/cli/commands/manage/collections/delete.d.ts.map +1 -0
  6. package/build/cli/commands/{collections → manage/collections}/delete.js +56 -25
  7. package/build/cli/commands/manage/collections/index.d.ts.map +1 -0
  8. package/build/cli/commands/{collections → manage/collections}/index.js +27 -22
  9. package/build/cli/commands/manage/collections/list.d.ts +2 -0
  10. package/build/cli/commands/manage/collections/list.d.ts.map +1 -0
  11. package/build/cli/commands/manage/collections/list.js +133 -0
  12. package/build/cli/commands/manage/collections/promote.d.ts +2 -0
  13. package/build/cli/commands/manage/collections/promote.d.ts.map +1 -0
  14. package/build/cli/commands/manage/collections/promote.js +153 -0
  15. package/build/cli/commands/manage/collections/update-expiration.d.ts +2 -0
  16. package/build/cli/commands/manage/collections/update-expiration.d.ts.map +1 -0
  17. package/build/cli/commands/manage/collections/update-expiration.js +129 -0
  18. package/build/cli/commands/manage/index.d.ts.map +1 -0
  19. package/build/cli/commands/{index.js → manage/index.js} +26 -29
  20. package/build/cli/commands/manage/publish-content.d.ts +2 -0
  21. package/build/cli/commands/manage/publish-content.d.ts.map +1 -0
  22. package/build/cli/commands/{publish-content.js → manage/publish-content.js} +142 -56
  23. package/build/cli/commands/{init-app.d.ts → scaffold/index.d.ts} +2 -2
  24. package/build/cli/commands/scaffold/index.d.ts.map +1 -0
  25. package/build/cli/commands/{init-app.js → scaffold/index.js} +70 -22
  26. package/build/cli/fastly-api/api-token.d.ts.map +1 -1
  27. package/build/cli/fastly-api/api-token.js +7 -1
  28. package/build/cli/fastly-api/kv-store.d.ts +2 -2
  29. package/build/cli/fastly-api/kv-store.d.ts.map +1 -1
  30. package/build/cli/fastly-api/kv-store.js +2 -2
  31. package/build/cli/index.js +11 -3
  32. package/build/cli/util/args.d.ts +16 -2
  33. package/build/cli/util/args.d.ts.map +1 -1
  34. package/build/cli/util/args.js +32 -6
  35. package/build/cli/util/fastly-toml.d.ts +2 -0
  36. package/build/cli/util/fastly-toml.d.ts.map +1 -0
  37. package/build/cli/util/fastly-toml.js +15 -0
  38. package/build/cli/util/kv-store-items.d.ts +3 -2
  39. package/build/cli/util/kv-store-items.d.ts.map +1 -1
  40. package/build/cli/util/kv-store-items.js +6 -12
  41. package/build/cli/util/node.d.ts +2 -0
  42. package/build/cli/util/node.d.ts.map +1 -0
  43. package/build/cli/util/node.js +10 -0
  44. package/build/models/server/index.d.ts +5 -0
  45. package/build/models/server/index.d.ts.map +1 -0
  46. package/build/models/server/index.js +1 -0
  47. package/build/models/time/index.d.ts +7 -0
  48. package/build/models/time/index.d.ts.map +1 -0
  49. package/build/models/time/index.js +51 -0
  50. package/build/server/publisher-server/index.d.ts +2 -0
  51. package/build/server/publisher-server/index.d.ts.map +1 -1
  52. package/build/server/publisher-server/index.js +34 -3
  53. package/package.json +3 -2
  54. package/build/cli/commands/clean.d.ts +0 -2
  55. package/build/cli/commands/clean.d.ts.map +0 -1
  56. package/build/cli/commands/clean.js +0 -121
  57. package/build/cli/commands/collections/delete.d.ts +0 -2
  58. package/build/cli/commands/collections/delete.d.ts.map +0 -1
  59. package/build/cli/commands/collections/index.d.ts.map +0 -1
  60. package/build/cli/commands/collections/list.d.ts +0 -2
  61. package/build/cli/commands/collections/list.d.ts.map +0 -1
  62. package/build/cli/commands/collections/list.js +0 -62
  63. package/build/cli/commands/index.d.ts.map +0 -1
  64. package/build/cli/commands/init-app.d.ts.map +0 -1
  65. package/build/cli/commands/publish-content.d.ts +0 -2
  66. package/build/cli/commands/publish-content.d.ts.map +0 -1
  67. /package/build/cli/commands/{collections → manage/collections}/index.d.ts +0 -0
  68. /package/build/cli/commands/{index.d.ts → manage/index.d.ts} +0 -0
@@ -4,56 +4,132 @@
4
4
  */
5
5
  import * as fs from 'node:fs';
6
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';
7
+ import { isKVAssetVariantMetadata } from '../../../models/assets/kvstore-assets.js';
8
+ import { calcExpirationTime } from '../../../models/time/index.js';
9
+ import { loadApiToken } from '../../fastly-api/api-token.js';
10
+ import { getKvStoreEntryInfo, kvStoreSubmitEntry } from '../../fastly-api/kv-store.js';
11
+ import { parseCommandLine } from '../../util/args.js';
12
+ import { mergeContentTypes, testFileContentType } from '../../util/content-types.js';
13
+ import { LoadConfigError, loadPublishContentConfigFile, loadStaticPublisherRcFile } from '../../util/config.js';
14
+ import { applyDefaults } from '../../util/data.js';
15
+ import { readServiceId } from '../../util/fastly-toml.js';
16
+ import { calculateFileSizeAndHash, enumerateFiles, getFileSize, rootRelative } from '../../util/files.js';
17
+ import { applyKVStoreEntriesChunks, doKvStoreItemsOperation, } from '../../util/kv-store-items.js';
18
+ import { writeKVStoreEntriesForLocal } from '../../util/kv-store-local-server.js';
19
+ import { isNodeError } from '../../util/node.js';
20
+ import { ensureVariantFileExists } from '../../util/variants.js';
19
21
  // KV Store key format:
20
22
  // <publishId>_index_<preview_id>.json
21
23
  // <publishId>_settings_<preview_id>.json
22
24
  // <publishId>_files_sha256_<hash>_<variant>
23
25
  // split large files into 20MiB chunks
24
26
  const KV_STORE_CHUNK_SIZE = 1024 * 1024 * 20;
25
- export async function action(argv) {
27
+ function help() {
28
+ console.log(`\
29
+
30
+ Usage:
31
+ npx @fastly/compute-js-static-publish publish-content [options]
32
+
33
+ Description:
34
+ Publishes static files from your root directory into the configured Fastly KV Store,
35
+ under a named collection (e.g., "live", "staging", "preview-123").
36
+ Automatically skips uploading content that already exists in KV Store.
37
+
38
+ Options:
39
+ --config <config-file> Path to a publish-content.config.js file
40
+ (default: publish-content.config.js in the current directory)
41
+ --root-dir <dir> Override the root directory to publish from
42
+ --collection-name <name> Publish under a specific collection name (defaults to value in static-publish.rc.js).
43
+ --expires-in <duration> Set expiration for the collection relative to now (e.g., 3d, 6h, 1w).
44
+ --expires-at <timestamp> Set expiration using an absolute ISO 8601 timestamp.
45
+ --local-only Write content to local KV Store for testing only. No remote uploads.
46
+ --no-local Skip local KV Store writes and upload only to the Fastly KV Store.
47
+ --kv-overwrite When Fastly KV Store is used, always overwrite existing items in the store.
48
+
49
+ --fastly-api-token <token> Fastly API token used for KV Store access. If not provided,
50
+ the tool will try:
51
+ 1. FASTLY_API_TOKEN environment variable
52
+ 2. fastly profile token (via CLI)
53
+ -h, --help Show help for this command.
54
+ `);
55
+ }
56
+ export async function action(actionArgs) {
26
57
  const optionDefinitions = [
27
58
  { 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, },
59
+ { name: 'config', type: String },
32
60
  // The 'root' directory for the publishing.
33
61
  // All assets are expected to exist under this root. Required.
34
62
  // For backwards compatibility, if this value is not provided,
35
63
  // then the value of 'public-dir' is used.
36
64
  { name: 'root-dir', type: String, },
37
- { name: 'force-upload', type: Boolean },
38
- { name: 'no-local', type: Boolean },
65
+ // Collection name to be used for this publishing.
66
+ { name: 'collection-name', type: String, },
67
+ { name: 'expires-in', type: String },
68
+ { name: 'expires-at', type: String },
39
69
  { name: 'local-only', type: Boolean },
40
- { name: 'config', type: String },
70
+ { name: 'no-local', type: Boolean },
71
+ { name: 'kv-overwrite', type: Boolean },
72
+ // Fastly API Token to use for this publishing.
73
+ { name: 'fastly-api-token', type: String, },
41
74
  ];
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;
75
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
76
+ if (parsed.needHelp) {
77
+ if (parsed.error != null) {
78
+ console.error(String(parsed.error));
79
+ console.error();
80
+ process.exitCode = 1;
81
+ }
82
+ help();
83
+ return;
84
+ }
85
+ const { verbose, ['config']: configFilePathValue, ['root-dir']: rootDir, ['collection-name']: collectionNameValue, ['expires-in']: expiresIn, ['expires-at']: expiresAt, ['local-only']: localOnlyMode, ['no-local']: noLocalMode, ['kv-overwrite']: overwriteKvStoreItems, ['fastly-api-token']: fastlyApiToken, } = parsed.commandLineOptions;
44
86
  // no-local and local-only are mutually exclusive
45
87
  if (noLocalMode && localOnlyMode) {
46
88
  console.error("❌ '--no-local' and '--local-only' are mutually exclusive.");
47
89
  process.exitCode = 1;
48
90
  return;
49
91
  }
92
+ // compute-js-static-publisher cli is always run from the Compute application directory
93
+ // in other words, the directory that contains `fastly.toml`.
94
+ const computeAppDir = path.resolve();
95
+ // Check to see if we have a service ID listed in `fastly.toml`.
96
+ // If we do NOT, then we do not use the KV Store.
97
+ let serviceId;
98
+ try {
99
+ serviceId = readServiceId(path.resolve(computeAppDir, './fastly.toml'));
100
+ }
101
+ catch (err) {
102
+ if (isNodeError(err) && err.code === 'ENOENT') {
103
+ console.warn(`❌ ERROR: can't find 'fastly.toml'.`);
104
+ process.exitCode = 1;
105
+ return;
106
+ }
107
+ console.warn(`❌ ERROR: can't read or parse 'fastly.toml'.`);
108
+ process.exitCode = 1;
109
+ return;
110
+ }
50
111
  // Create local files unless 'no-local' is set
51
- const createLocalFiles = !noLocalMode;
112
+ let createLocalFiles = false;
113
+ if (noLocalMode) {
114
+ console.log(`ℹ️ 'No local mode' - skipping creation of files for local simulated KV Store`);
115
+ }
116
+ else {
117
+ createLocalFiles = true;
118
+ }
52
119
  // Use the KV Store unless 'local-only' is set
53
- const useKvStore = !localOnlyMode;
120
+ let useKvStore = false;
121
+ if (serviceId == null) {
122
+ console.log(`ℹ️ 'service_id' not set in 'fastly.toml' - skipping creation of files for Fastly KV Store`);
123
+ }
124
+ else if (localOnlyMode) {
125
+ console.log(`ℹ️ 'Local only mode' - skipping creation of files for Fastly KV Store`);
126
+ }
127
+ else {
128
+ useKvStore = true;
129
+ }
54
130
  const segments = [];
55
131
  if (createLocalFiles) {
56
- segments.push('for local simluated KV Store');
132
+ segments.push('for local simulated KV Store');
57
133
  }
58
134
  if (useKvStore) {
59
135
  segments.push('to the Fastly KV Store');
@@ -71,9 +147,6 @@ export async function action(argv) {
71
147
  fastlyApiContext = { apiToken: apiTokenResult.apiToken };
72
148
  console.log(`✔️ Fastly API Token: ${fastlyApiContext.apiToken.slice(0, 4)}${'*'.repeat(fastlyApiContext.apiToken.length - 4)} from '${apiTokenResult.source}'`);
73
149
  }
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
150
  // #### load config
78
151
  let staticPublisherRc;
79
152
  try {
@@ -113,13 +186,23 @@ export async function action(argv) {
113
186
  console.log(`files to be included in your published output.`);
114
187
  }
115
188
  }
189
+ let expirationTime;
190
+ try {
191
+ expirationTime = calcExpirationTime({ expiresIn, expiresAt });
192
+ }
193
+ catch (err) {
194
+ console.error(`❌ Cannot process expiration time`);
195
+ console.error(String(err));
196
+ process.exitCode = 1;
197
+ return;
198
+ }
116
199
  console.log(`✔️ Public directory '${rootRelative(publicDirRoot)}'.`);
117
200
  const publishId = staticPublisherRc.publishId;
118
- console.log(`✔️ Publish ID: ${publishId}`);
201
+ console.log(` | Publish ID: ${publishId}`);
119
202
  const kvStoreName = staticPublisherRc.kvStoreName;
120
- console.log(`✔️ Using KV Store: ${kvStoreName}`);
203
+ console.log(` | Using KV Store: ${kvStoreName}`);
121
204
  const defaultCollectionName = staticPublisherRc.defaultCollectionName;
122
- console.log(`✔️ Default Collection Name: ${defaultCollectionName}`);
205
+ console.log(` | Default Collection Name: ${defaultCollectionName}`);
123
206
  // The Static Content Root Dir, which will hold loaders and content generated by this publishing.
124
207
  const staticPublisherWorkingDir = publishContentConfig.staticPublisherWorkingDir;
125
208
  // Load content types
@@ -143,6 +226,19 @@ export async function action(argv) {
143
226
  if (includeWellKnown) {
144
227
  console.log(`✔️ (.well-known is exempt from exclusion.)`);
145
228
  }
229
+ // ### Collection name that we're currently publishing
230
+ // for example, live, staging
231
+ const collectionName = collectionNameValue ?? process.env.PUBLISHER_COLLECTION_NAME ?? defaultCollectionName;
232
+ console.log(`✔️ Collection Name: ${collectionName}`);
233
+ if (expirationTime != null) {
234
+ console.log(`✔️ Publishing with expiration timestamp: ${new Date(expirationTime * 1000).toISOString()}`);
235
+ }
236
+ else {
237
+ console.log(`✔️ Publishing with no expiration timestamp.`);
238
+ }
239
+ if (collectionName === defaultCollectionName && expirationTime != null) {
240
+ console.log(` ⚠️ NOTE: Expiration time not enforced for default collection.`);
241
+ }
146
242
  // files to be included in the build/publish
147
243
  const files = enumerateFiles({
148
244
  publicDirRoot,
@@ -150,9 +246,6 @@ export async function action(argv) {
150
246
  excludeDotFiles,
151
247
  includeWellKnown,
152
248
  });
153
- // ### Collection name that we're currently publishing
154
- // for example, live, staging
155
- const collectionName = collectionNameValue ?? process.env.PUBLISHER_COLLECTION_NAME ?? defaultCollectionName;
156
249
  const stats = {
157
250
  kvStore: 0,
158
251
  };
@@ -230,8 +323,11 @@ export async function action(argv) {
230
323
  }
231
324
  else {
232
325
  let kvStoreItemMetadata = null;
233
- if (useKvStore && !forceUpload) {
234
- await attemptWithRetries(async () => {
326
+ if (useKvStore && !overwriteKvStoreItems) {
327
+ const items = [{
328
+ key: variantKey,
329
+ }];
330
+ await doKvStoreItemsOperation(items, async (_, variantKey) => {
235
331
  // fastlyApiContext is non-null if useKvStore is true
236
332
  const kvStoreEntryInfo = await getKvStoreEntryInfo(fastlyApiContext, kvStoreName, variantKey);
237
333
  if (!kvStoreEntryInfo) {
@@ -275,22 +371,6 @@ export async function action(argv) {
275
371
  };
276
372
  }
277
373
  }
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
374
  });
295
375
  }
296
376
  if (kvStoreItemMetadata != null) {
@@ -369,17 +449,19 @@ export async function action(argv) {
369
449
  console.log(`🗂️ Creating Index...`);
370
450
  const indexFileName = `index_${collectionName}.json`;
371
451
  const indexFileKey = `${publishId}_index_${collectionName}`;
372
- // Metadata can have build time, expiration date, build name
373
- // const indexMetadata = {};
374
452
  const indexFilePath = path.resolve(staticPublisherKvStoreContent, indexFileName);
375
453
  fs.writeFileSync(indexFilePath, JSON.stringify(kvAssetsIndex));
376
454
  const indexFileSize = getFileSize(indexFilePath);
455
+ const indexMetadata = {
456
+ publishedTime: Math.floor(Date.now() / 1000),
457
+ expirationTime,
458
+ };
377
459
  kvStoreItemDescriptions.push({
378
460
  write: true,
379
461
  size: indexFileSize,
380
462
  key: indexFileKey,
381
463
  filePath: indexFilePath,
382
- // metadata: indexMetadata,
464
+ metadataJson: indexMetadata,
383
465
  });
384
466
  console.log(`✅ Index has been saved.`);
385
467
  // #### SERVER SETTINGS
@@ -459,7 +541,11 @@ export async function action(argv) {
459
541
  if (useKvStore) {
460
542
  console.log(`📤 Uploading entries to KV Store.`);
461
543
  // fastlyApiContext is non-null if useKvStore is true
462
- await uploadFilesToKVStore(fastlyApiContext, kvStoreName, kvStoreItemDescriptions);
544
+ await doKvStoreItemsOperation(kvStoreItemDescriptions.filter(x => x.write), async ({ filePath, metadataJson }, key) => {
545
+ const fileBytes = fs.readFileSync(filePath);
546
+ await kvStoreSubmitEntry(fastlyApiContext, kvStoreName, key, fileBytes, metadataJson != null ? JSON.stringify(metadataJson) : undefined);
547
+ console.log(` 🌐 Submitted asset "${rootRelative(filePath)}" to KV Store with key "${key}".`);
548
+ });
463
549
  console.log(`✅ Uploaded entries to KV Store.`);
464
550
  }
465
551
  if (createLocalFiles) {
@@ -15,5 +15,5 @@ export type InitAppOptions = {
15
15
  publishId: string | undefined;
16
16
  kvStoreName: string | undefined;
17
17
  };
18
- export declare function action(argv: string[]): Promise<void>;
19
- //# sourceMappingURL=init-app.d.ts.map
18
+ export declare function action(actionArgs: string[]): Promise<void>;
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/cli/commands/scaffold/index.ts"],"names":[],"mappings":"AA2DA,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9C,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;CACjC,CAAC;AA0QF,wBAAsB,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,iBAuehD"}
@@ -9,9 +9,48 @@
9
9
  import * as child_process from 'node:child_process';
10
10
  import * as path from 'node:path';
11
11
  import * as fs from 'node:fs';
12
- import commandLineArgs from 'command-line-args';
13
- import { dotRelative, rootRelative } from '../util/files.js';
14
- import { findComputeJsStaticPublisherVersion } from '../util/package.js';
12
+ import { dotRelative, rootRelative } from '../../util/files.js';
13
+ import { findComputeJsStaticPublisherVersion } from '../../util/package.js';
14
+ import { parseCommandLine } from "../../util/args.js";
15
+ function help() {
16
+ console.log(`\
17
+
18
+ Usage:
19
+ npx @fastly/compute-js-static-publish [options]
20
+
21
+ Description:
22
+ Scaffold a new Compute app configured for static publishing.
23
+
24
+ Note: If run inside a scaffolded project, this tool will automatically enter project
25
+ management mode.
26
+
27
+ Options:
28
+ --kv-store-name <name> (required) KV Store name for content storage
29
+ --root-dir <path> (required) Path to static content (e.g., ./public)
30
+ -o, --output <dir> Output directory for Compute app (default: ./compute-js)
31
+ --publish-id <id> Advanced. Prefix for KV keys (default: "default")
32
+ --static-publisher-working-dir <dir> Working directory for build artifacts
33
+ (default: ./compute-js/static-publisher)
34
+
35
+ Compute Service Metadata:
36
+ --name <name> App name (for fastly.toml)
37
+ --description <text> App description (for fastly.toml)
38
+ --author <name/email> App author (for fastly.toml)
39
+ --service-id <id> (optional) Fastly service ID
40
+
41
+ Server Config:
42
+ --public-dir <path> Base dir for content (default: root-dir)
43
+ --static-dir <path>,<path...> Directory served with long TTL (can repeat)
44
+ --spa <file> SPA fallback file (e.g., /index.html)
45
+ --not-found-page <file> 404 fallback file (e.g., /404.html)
46
+ --auto-index <name>,<name...> Index filename (e.g., index.html,index.htm)
47
+ --auto-ext <ext>,<ext...> Automatic extensions (e.g., .html,.htm)
48
+
49
+ Other:
50
+ --verbose Enable verbose output
51
+ -h, --help Show help
52
+ `);
53
+ }
15
54
  const defaultOptions = {
16
55
  outputDir: undefined,
17
56
  rootDir: undefined,
@@ -29,7 +68,7 @@ const defaultOptions = {
29
68
  publishId: undefined,
30
69
  kvStoreName: undefined,
31
70
  };
32
- function buildOptions(packageJson, commandLineValues) {
71
+ function buildOptions(packageJson, commandLineOptions) {
33
72
  // Applied in this order for proper overriding
34
73
  // 1. defaults
35
74
  // 2. package.json
@@ -46,7 +85,7 @@ function buildOptions(packageJson, commandLineValues) {
46
85
  }
47
86
  {
48
87
  let outputDir;
49
- const outputDirValue = commandLineValues['output'];
88
+ const outputDirValue = commandLineOptions['output'];
50
89
  if (outputDirValue == null || typeof outputDirValue === 'string') {
51
90
  outputDir = outputDirValue;
52
91
  }
@@ -56,7 +95,7 @@ function buildOptions(packageJson, commandLineValues) {
56
95
  }
57
96
  {
58
97
  let rootDir;
59
- const rootDirValue = commandLineValues['root-dir'];
98
+ const rootDirValue = commandLineOptions['root-dir'];
60
99
  if (rootDirValue == null || typeof rootDirValue === 'string') {
61
100
  rootDir = rootDirValue;
62
101
  }
@@ -66,7 +105,7 @@ function buildOptions(packageJson, commandLineValues) {
66
105
  }
67
106
  {
68
107
  let publicDir;
69
- const publicDirValue = commandLineValues['public-dir'];
108
+ const publicDirValue = commandLineOptions['public-dir'];
70
109
  if (publicDirValue == null || typeof publicDirValue === 'string') {
71
110
  publicDir = publicDirValue;
72
111
  }
@@ -76,7 +115,7 @@ function buildOptions(packageJson, commandLineValues) {
76
115
  }
77
116
  {
78
117
  let staticDirs;
79
- const staticDirsValue = commandLineValues['static-dir'];
118
+ const staticDirsValue = commandLineOptions['static-dir'];
80
119
  const asArray = Array.isArray(staticDirsValue) ? staticDirsValue : [staticDirsValue];
81
120
  if (asArray.every((x) => typeof x === 'string')) {
82
121
  staticDirs = asArray;
@@ -87,7 +126,7 @@ function buildOptions(packageJson, commandLineValues) {
87
126
  }
88
127
  {
89
128
  let staticPublisherWorkingDir;
90
- const staticPublisherWorkingDirValue = commandLineValues['static-publisher-working-dir'];
129
+ const staticPublisherWorkingDirValue = commandLineOptions['static-publisher-working-dir'];
91
130
  if (staticPublisherWorkingDirValue == null || typeof staticPublisherWorkingDirValue === 'string') {
92
131
  staticPublisherWorkingDir = staticPublisherWorkingDirValue;
93
132
  }
@@ -97,7 +136,7 @@ function buildOptions(packageJson, commandLineValues) {
97
136
  }
98
137
  {
99
138
  let spa;
100
- const spaValue = commandLineValues['spa'];
139
+ const spaValue = commandLineOptions['spa'];
101
140
  if (spaValue === null) {
102
141
  // If 'spa' is provided with a null value, then the flag was provided
103
142
  // with no value. Assumed to be './index.html' relative to the public directory.
@@ -113,7 +152,7 @@ function buildOptions(packageJson, commandLineValues) {
113
152
  }
114
153
  {
115
154
  let notFoundPage;
116
- const notFoundPageValue = commandLineValues['not-found-page'];
155
+ const notFoundPageValue = commandLineOptions['not-found-page'];
117
156
  if (notFoundPageValue === null) {
118
157
  // If 'spa' is provided with a null value, then the flag was provided
119
158
  // with no value. Assumed to be './404.html' relative to the public directory.
@@ -129,7 +168,7 @@ function buildOptions(packageJson, commandLineValues) {
129
168
  }
130
169
  {
131
170
  let autoIndex;
132
- const autoIndexValue = commandLineValues['auto-index'];
171
+ const autoIndexValue = commandLineOptions['auto-index'];
133
172
  const asArray = Array.isArray(autoIndexValue) ? autoIndexValue : [autoIndexValue];
134
173
  if (asArray.every((x) => typeof x === 'string')) {
135
174
  autoIndex = asArray.reduce((acc, entry) => {
@@ -149,7 +188,7 @@ function buildOptions(packageJson, commandLineValues) {
149
188
  }
150
189
  {
151
190
  let autoExt = [];
152
- const autoExtValue = commandLineValues['auto-ext'];
191
+ const autoExtValue = commandLineOptions['auto-ext'];
153
192
  const asArray = Array.isArray(autoExtValue) ? autoExtValue : [autoExtValue];
154
193
  if (asArray.every((x) => typeof x === 'string')) {
155
194
  autoExt = asArray.reduce((acc, entry) => {
@@ -170,7 +209,7 @@ function buildOptions(packageJson, commandLineValues) {
170
209
  }
171
210
  {
172
211
  let name;
173
- const nameValue = commandLineValues['name'];
212
+ const nameValue = commandLineOptions['name'];
174
213
  if (nameValue == null || typeof nameValue === 'string') {
175
214
  name = nameValue;
176
215
  }
@@ -180,7 +219,7 @@ function buildOptions(packageJson, commandLineValues) {
180
219
  }
181
220
  {
182
221
  let author;
183
- const authorValue = commandLineValues['author'];
222
+ const authorValue = commandLineOptions['author'];
184
223
  if (authorValue == null || typeof authorValue === 'string') {
185
224
  author = authorValue;
186
225
  }
@@ -190,7 +229,7 @@ function buildOptions(packageJson, commandLineValues) {
190
229
  }
191
230
  {
192
231
  let description;
193
- const descriptionValue = commandLineValues['description'];
232
+ const descriptionValue = commandLineOptions['description'];
194
233
  if (descriptionValue == null || typeof descriptionValue === 'string') {
195
234
  description = descriptionValue;
196
235
  }
@@ -200,7 +239,7 @@ function buildOptions(packageJson, commandLineValues) {
200
239
  }
201
240
  {
202
241
  let serviceId;
203
- const serviceIdValue = commandLineValues['service-id'];
242
+ const serviceIdValue = commandLineOptions['service-id'];
204
243
  if (serviceIdValue == null || typeof serviceIdValue === 'string') {
205
244
  serviceId = serviceIdValue;
206
245
  }
@@ -210,7 +249,7 @@ function buildOptions(packageJson, commandLineValues) {
210
249
  }
211
250
  {
212
251
  let publishId;
213
- const publishIdValue = commandLineValues['publish-id'];
252
+ const publishIdValue = commandLineOptions['publish-id'];
214
253
  if (publishIdValue == null || typeof publishIdValue === 'string') {
215
254
  publishId = publishIdValue;
216
255
  }
@@ -220,7 +259,7 @@ function buildOptions(packageJson, commandLineValues) {
220
259
  }
221
260
  {
222
261
  let kvStoreName;
223
- const kvStoreNameValue = commandLineValues['kv-store-name'];
262
+ const kvStoreNameValue = commandLineOptions['kv-store-name'];
224
263
  if (kvStoreNameValue == null || typeof kvStoreNameValue === 'string') {
225
264
  kvStoreName = kvStoreNameValue;
226
265
  }
@@ -238,7 +277,7 @@ function processPublicDirToken(filepath, publicDir) {
238
277
  const processedPath = '.' + filepath.slice(PUBLIC_DIR_TOKEN.length);
239
278
  return path.resolve(publicDir, processedPath);
240
279
  }
241
- export async function action(argv) {
280
+ export async function action(actionArgs) {
242
281
  const optionDefinitions = [
243
282
  { name: 'verbose', type: Boolean },
244
283
  // Required. The name of a Fastly KV Store to hold the content assets.
@@ -295,7 +334,16 @@ export async function action(argv) {
295
334
  // http://example.com/about is requested, we can respond with http://example.com/about.html
296
335
  { name: 'auto-ext', type: String, multiple: true, },
297
336
  ];
298
- const commandLineValues = commandLineArgs(optionDefinitions, { argv });
337
+ const parsed = parseCommandLine(actionArgs, optionDefinitions);
338
+ if (parsed.needHelp) {
339
+ if (parsed.error != null) {
340
+ console.error(String(parsed.error));
341
+ console.error();
342
+ process.exitCode = 1;
343
+ }
344
+ help();
345
+ return;
346
+ }
299
347
  let packageJson;
300
348
  try {
301
349
  const packageJsonText = fs.readFileSync("./package.json", "utf-8");
@@ -305,7 +353,7 @@ export async function action(argv) {
305
353
  console.log("Can't read/parse package.json in current directory, making no assumptions!");
306
354
  packageJson = null;
307
355
  }
308
- const options = buildOptions(packageJson, commandLineValues);
356
+ const options = buildOptions(packageJson, parsed.commandLineOptions);
309
357
  const COMPUTE_JS_DIR = options.outputDir;
310
358
  if (COMPUTE_JS_DIR == null) {
311
359
  console.error("❌ required parameter --output not provided.");
@@ -1 +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"}
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;AAWD,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,CAqCnB"}
@@ -5,7 +5,6 @@
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import cli from '@fastly/cli';
7
7
  import { makeRetryable } from '../util/retryable.js';
8
- ;
9
8
  export function loadApiToken(params) {
10
9
  let apiToken = null;
11
10
  let source = '';
@@ -58,6 +57,12 @@ export class FetchError extends Error {
58
57
  this.status = status;
59
58
  }
60
59
  }
60
+ function isReadableStream(data) {
61
+ return (typeof data === 'object' &&
62
+ data !== null &&
63
+ typeof data.getReader === 'function' &&
64
+ typeof data.tee === 'function');
65
+ }
61
66
  export async function callFastlyApi(fastlyApiContext, endpoint, operationName, queryParams, requestInit) {
62
67
  const url = new URL(endpoint, 'https://api.fastly.com/');
63
68
  if (queryParams != null) {
@@ -71,6 +76,7 @@ export async function callFastlyApi(fastlyApiContext, endpoint, operationName, q
71
76
  ...requestInit,
72
77
  headers,
73
78
  redirect: 'error',
79
+ ...(isReadableStream(requestInit?.body) ? { duplex: 'half' } : null),
74
80
  });
75
81
  let response;
76
82
  try {
@@ -18,7 +18,7 @@ export declare function getKvStoreEntry(fastlyApiContext: FastlyApiContext, kvSt
18
18
  generation: string | null;
19
19
  response: Response;
20
20
  }>;
21
- export declare function kvStoreSubmitFile(fastlyApiContext: FastlyApiContext, kvStoreName: string, key: string, data: Uint8Array | string, metadata: string | undefined): Promise<void>;
22
- export declare function kvStoreDeleteFile(fastlyApiContext: FastlyApiContext, kvStoreName: string, key: string): Promise<void>;
21
+ export declare function kvStoreSubmitEntry(fastlyApiContext: FastlyApiContext, kvStoreName: string, key: string, data: ReadableStream<Uint8Array> | Uint8Array | string, metadata: string | undefined): Promise<void>;
22
+ export declare function kvStoreDeleteEntry(fastlyApiContext: FastlyApiContext, kvStoreName: string, key: string): Promise<void>;
23
23
  export {};
24
24
  //# sourceMappingURL=kv-store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"kv-store.d.ts","sourceRoot":"","sources":["../../../src/cli/fastly-api/kv-store.ts"],"names":[],"mappings":"AAKA,OAAO,EAAiB,KAAK,gBAAgB,EAAc,MAAM,gBAAgB,CAAC;AAElF,KAAK,WAAW,GAAG;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAmBF,wBAAsB,sBAAsB,CAAC,gBAAgB,EAAE,gBAAgB,mCAkB9E;AAED,wBAAsB,mBAAmB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAKhG;AAqCD,wBAAsB,eAAe,CAAC,gBAAgB,EAAE,gBAAgB,0BAcvE;AAED,eAAO,MAAM,eAAe,qBAjDgB,gBAAgB,iBAAiB,MAAM,sEAyDlF,CAAC;AAEF,wBAAsB,cAAc,CAClC,gBAAgB,EAAE,gBAAgB,EAClC,WAAW,EAAE,MAAM,EACnB,MAAM,CAAC,EAAE,MAAM,4BAchB;AAED,wBAAsB,mBAAmB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM;;;;GAI7G;AAED,wBAAsB,eAAe,CACnC,gBAAgB,EAAE,gBAAgB,EAClC,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,EACX,YAAY,CAAC,EAAE,OAAO;;;;GA8BvB;AAGD,wBAAsB,iBAAiB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,iBAmBpK;AAED,wBAAsB,iBAAiB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,iBAa3G"}
1
+ {"version":3,"file":"kv-store.d.ts","sourceRoot":"","sources":["../../../src/cli/fastly-api/kv-store.ts"],"names":[],"mappings":"AAKA,OAAO,EAAiB,KAAK,gBAAgB,EAAc,MAAM,gBAAgB,CAAC;AAElF,KAAK,WAAW,GAAG;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAmBF,wBAAsB,sBAAsB,CAAC,gBAAgB,EAAE,gBAAgB,mCAkB9E;AAED,wBAAsB,mBAAmB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAKhG;AAqCD,wBAAsB,eAAe,CAAC,gBAAgB,EAAE,gBAAgB,0BAcvE;AAED,eAAO,MAAM,eAAe,qBAjDgB,gBAAgB,iBAAiB,MAAM,sEAyDlF,CAAC;AAEF,wBAAsB,cAAc,CAClC,gBAAgB,EAAE,gBAAgB,EAClC,WAAW,EAAE,MAAM,EACnB,MAAM,CAAC,EAAE,MAAM,4BAchB;AAED,wBAAsB,mBAAmB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM;;;;GAI7G;AAED,wBAAsB,eAAe,CACnC,gBAAgB,EAAE,gBAAgB,EAClC,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,MAAM,EACX,YAAY,CAAC,EAAE,OAAO;;;;GA8BvB;AAGD,wBAAsB,kBAAkB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,UAAU,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,iBAmBlM;AAED,wBAAsB,kBAAkB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,iBAa5G"}
@@ -100,7 +100,7 @@ export async function getKvStoreEntry(fastlyApiContext, kvStoreName, key, metada
100
100
  };
101
101
  }
102
102
  const encoder = new TextEncoder();
103
- export async function kvStoreSubmitFile(fastlyApiContext, kvStoreName, key, data, metadata) {
103
+ export async function kvStoreSubmitEntry(fastlyApiContext, kvStoreName, key, data, metadata) {
104
104
  const kvStoreId = await getKVStoreIdForName(fastlyApiContext, kvStoreName);
105
105
  if (kvStoreId == null) {
106
106
  throw new Error('KV Store not found');
@@ -116,7 +116,7 @@ export async function kvStoreSubmitFile(fastlyApiContext, kvStoreName, key, data
116
116
  body,
117
117
  });
118
118
  }
119
- export async function kvStoreDeleteFile(fastlyApiContext, kvStoreName, key) {
119
+ export async function kvStoreDeleteEntry(fastlyApiContext, kvStoreName, key) {
120
120
  const kvStoreId = await getKVStoreIdForName(fastlyApiContext, kvStoreName);
121
121
  if (kvStoreId == null) {
122
122
  throw new Error('KV Store not found');
@@ -3,6 +3,14 @@
3
3
  * Copyright Fastly, Inc.
4
4
  * Licensed under the MIT license. See LICENSE file for details.
5
5
  */
6
- import { action } from './commands/index.js';
7
- console.log("🧑‍💻 Fastly Compute JavaScript Static Publisher");
8
- await action(process.argv);
6
+ import fs from 'node:fs';
7
+ import * as scaffoldCommand from './commands/scaffold/index.js';
8
+ import * as manageCommands from './commands/manage/index.js';
9
+ if (!fs.existsSync('./static-publish.rc.js')) {
10
+ console.log("🧑‍💻Fastly Compute JavaScript Static Publisher (Scaffolding mode)");
11
+ await scaffoldCommand.action(process.argv);
12
+ }
13
+ else {
14
+ console.log("🧑‍💻Fastly Compute JavaScript Static Publisher (Management mode)");
15
+ await manageCommands.action(process.argv);
16
+ }