@fastly/compute-js-static-publish 8.1.0-beta.6 → 8.1.0-beta.7

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.
package/CHANGELOG.md CHANGED
@@ -50,15 +50,14 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
50
50
  - Error codes: with `--json`, an error gives `{ "schemaVersion": 1, "error": { "code", "message" } }`. The README lists the codes, for example `collection-name-invalid` and `credentials-missing`.
51
51
  - README: "Using the CLI in CI", with the exit codes, the JSON output, and the error codes.
52
52
  - `PublisherServer`: the options `status` and `headers` of `serveRequest()` and `serveFallback()` change the status and the headers of the response of a file, for one call. For a status other than `2xx`, the server does not evaluate the preconditions of the request.
53
+ - `PublisherServer`: `serveRequestStreaming()`, `serveFallbackStreaming()`, and `serveCachedStreaming()` return `{ response, fillPromise }`. On a Fastly service with `@fastly/js-compute` 4.2 or later (not in `fastly compute serve`), a response cache fill for a body with a known length streams the body to the visitor and into the cache at the same time. Pass `fillPromise` to `event.waitUntil()`. A body that does not have its declared length is not cached, and the next fill reads the whole body first. The `plain` template and the Hono helpers use them.
54
+ - `PublisherServer`: the function of `serveCached()` can return `{ response, length }`. With `length: null`, the response is not cached.
53
55
 
54
56
  ### Changed
55
57
 
56
- - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
57
58
  - A command for a managed project or an app (for example `status` or `deploy`) in a directory that has no `static-publish.project.js` or `static-publish.rc.js` now stops with an error that names the directories nearby that have one. Before, the CLI started scaffolding, and showed an unclear error for the command.
58
59
  - Scaffolding: the `src/index.js` of the `plain` app calls `serveRequest()` with `fallback: false`, then has the place for your own code, and then calls `serveFallback()` for the SPA file or the 404 page. Thus your code runs for each request that no published file matches, also when the collection has a fallback page. Code that must run before the published files goes before `serveRequest()`.
59
60
  - Scaffolding: the app has `@fastly/compute-js-static-publish` in `dependencies`. It was in `devDependencies`. The code of the app imports it, and the `postinstall` script of the app runs it, so `npm ci --omit=dev` needs it.
60
- - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
61
- - Scaffolder: in the generated `src/index.js`, the place for your own code is before `serveRequest()`. It was after `serveRequest()`, where it did not run for a path that has no file when a 404 page or an SPA file is set.
62
61
  - The help and the hints of the CLI show the npx command with the dist-tag of a prerelease, for example `npx @fastly/compute-js-static-publish@beta dev` in 8.1.0-beta.2. Without the dist-tag, npx runs the latest stable version, which does not have the new commands. When the copy that runs is installed in the project or the app (so that a plain `npx` runs it), the command has no dist-tag, because with a dist-tag npx gets the version of that tag from npm. A stable version shows the command as before.
63
62
  - `collectionSelector.fromCookie()`: the activate and reset paths now redirect with `308`. Before, they used `302`.
64
63
  - Collection names have a rule: a DNS label (lowercase `a-z`, `0-9`, and `-`, from 1 to 63 characters, with no `-` at the start or the end). Thus a name is safe in storage keys, in the surrogate key of the purge, in a cookie, and in a hostname.
@@ -79,7 +78,19 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
79
78
  ### Fixed
80
79
 
81
80
  - `PublisherServer`: a request for the 404 page with an `If-None-Match` that matched its `ETag` (or an `If-Modified-Since` after its time) got a `304` with no body. Now the server evaluates the preconditions only for a `2xx` response, as RFC 9110 says, so the response is always the `404` with the page.
82
- - `collections promote` now purges the target collection, as `publish-content` and `collections delete` do. Before, after a promote (for example to `live`), the service could serve the old content of the target from the cache until it expired. The new options `--fastly-service-id` and `--purge-environment` work as in `publish-content`. If a Service ID is found, the command needs an API token, also in S3 mode, and stops before it writes anything if the token is missing.
81
+ - `scaffold` now escapes the values that it writes into `fastly.toml`. Before, a `"` or a `\` in `--name`, `--description`, or `--author`, or a KV Store name with a character such as `.`, gave a `fastly.toml` that was not valid.
82
+
83
+ ## [8.0.2] - 2026-11-16
84
+
85
+ ### Changed
86
+
87
+ - The npm package includes `CHANGELOG.md` and `MIGRATING.md`.
88
+ - `PublisherServer.setResponseCache()`: the default of `maxBodySize` is now 16 MiB. It was 8 MiB.
89
+ - Scaffolder: in the generated `src/index.js`, the place for your own code is before `serveRequest()`. It was after `serveRequest()`, where it did not run for a path that has no file when a 404 page or an SPA file is set.
90
+
91
+ ### Fixed
92
+
93
+ - `collections promote` now purges the target collection, as `publish-content` and `collections delete` do. Before, after a promote (for example to `live`), the service could serve the old content of the target from the cache until it expired. The new options `--fastly-service-id` and `--purge-environment` work as in `publish-content`. If a Service ID is found, the command needs an API token, also in S3 mode, and stops before it writes anything if the token is missing. Thus in S3 mode, if your pipeline has a Service ID, set `FASTLY_API_TOKEN` for `collections promote` too.
83
94
  - `collections promote --local`: the target collection got the index and settings files of the source collection. Thus a later `publish-content --local` to the source also changed the target, for example `live` after a promote from `staging`. Now the target has its own files. The KV Store and S3 modes were not affected.
84
95
  - `scaffold --storage-mode s3` without `--s3-endpoint` (a bucket on AWS): the command stopped with an uncaught `CredentialsProviderError` when the computer had no usable AWS credentials. Now it computes the host name of the bucket (`<bucket>.s3.<region>.amazonaws.com`, the same host name that the server uses), with no credentials and no network. A bucket name with a dot needs `--s3-endpoint`, and the command says so.
85
96
  - `PublisherServer` response cache: the request that caches a response now uses memory of about two times the body. Before, it used about four times the body. On a Fastly service, with `maxBodySize` set larger than the default, a response of 32 MiB caused a `500` for that request. With a response of 48 MiB, other requests that waited for the same response also got a `200` with an empty body.
@@ -88,7 +99,6 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
88
99
  - `PublisherServer`: when no file matches a request, the server serves the SPA file or the 404 page only if the request accepts HTML. Now a request accepts HTML only if its `Accept` header is missing or empty, or has `text/html`, `text/*`, or `*/*` with a q-value that is not 0. The most specific of these media ranges gives the q-value. Before, almost all requests got the HTML page, for example a request with `Accept: application/json`, `Accept: image/*`, or `Accept: text/html;q=0`. Now `serveRequest()` returns `null` for such a request, and your app makes the response.
89
100
  - README: the Fastly Object Storage example uses the region `us-east-1` and the endpoint `https://us-east-1.object.fastlystorage.app`. The example used `us-east`, which is a legacy region: you cannot make a new bucket in it in the Fastly control panel. The README also links to the list of regions and endpoints.
90
101
  - README: the custom app example handles its route before `serveRequest()`, and the text says when `serveRequest()` returns `null`. Before, the example handled `/api/hello` after `serveRequest()`, so a request for it got the 404 page when a 404 page was set.
91
- - `scaffold` now escapes the values that it writes into `fastly.toml`. Before, a `"` or a `\` in `--name`, `--description`, or `--author`, or a KV Store name with a character such as `.`, gave a `fastly.toml` that was not valid.
92
102
 
93
103
  ## [8.0.1] - 2026-11-04
94
104
 
@@ -561,7 +571,8 @@ This file does not list v7 releases after 7.0.8, or v6 releases after 6.3.0. For
561
571
  - Updated generated app's webpack and webpack-cli versions
562
572
  - Use atob() and removed dependency on Buffer
563
573
 
564
- [unreleased]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.1...HEAD
574
+ [unreleased]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.2...HEAD
575
+ [8.0.2]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.1...v8.0.2
565
576
  [8.0.1]: https://github.com/fastly/compute-js-static-publish/compare/v8.0.0...v8.0.1
566
577
  [8.0.0]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.8...v8.0.0
567
578
  [7.0.8]: https://github.com/fastly/compute-js-static-publish/compare/v7.0.7...v7.0.8
package/DOCUMENTATION.md CHANGED
@@ -1161,9 +1161,31 @@ const response = await publisherServer.serveCached(request, pathname, async (fil
1161
1161
 
1162
1162
  The second argument identifies the response in the collection. If anything other than the path and `Accept-Encoding` changes your response, include it in this value.
1163
1163
 
1164
+ Your function can return a `Response`, `null` (not found), or `{ response, length }`. `length` is the number of bytes in the body. With `length: null`, the response is not cached. `serveCached()` reads the body, and stores it with its real length. If that is not `length`, it logs a warning. A `Response` from `serveAsset()` has a known length.
1165
+
1166
+ #### Streaming the response into the cache
1167
+
1168
+ `serveRequestStreaming()`, `serveFallbackStreaming()`, and `serveCachedStreaming()` take the same arguments as `serveRequest()`, `serveFallback()`, and `serveCached()`. When the response is not cached yet and the length of its body is known, the body goes to the visitor and into the cache at the same time. The visitor does not wait for the whole file, and the request does not keep the whole body in memory. They return `{ response, fillPromise }`. Pass `fillPromise` to `event.waitUntil()`:
1169
+
1170
+ ```js
1171
+ async function handleRequest(event) {
1172
+ const { response, fillPromise } = await publisherServer.serveRequestStreaming(event.request);
1173
+ event.waitUntil(fillPromise);
1174
+ return response ?? new Response('Not Found', { status: 404 });
1175
+ }
1176
+ ```
1177
+
1178
+ With `event.waitUntil()`, the fill continues after your handler returns, also if the visitor disconnects. Without it, the fill stops when your handler returns, and nothing is cached. `fillPromise` never rejects.
1179
+
1180
+ The scaffolded app of the `plain` template and the [Hono](#-using-hono) helpers use these methods.
1181
+
1182
+ The fill streams only on a Fastly service with `@fastly/js-compute` 4.2 or later. With an earlier version, in `fastly compute serve`, or for a body with a length that is not known, the fill reads the whole body first, as `serveCached()` does, and `fillPromise` is already resolved.
1183
+
1184
+ If a body does not have the number of bytes of `length`, nothing is cached, the requests for the response get an error, and an error is logged. The next fill for that response reads the whole body first.
1185
+
1164
1186
  Notes:
1165
1187
 
1166
- - A response is read completely before it is cached. The request that caches it uses memory of about two times the body, up to two times `maxBodySize`. A Compute instance has a limit on its memory, so do not set `maxBodySize` larger than 48 MiB (`48 * 1024 * 1024`). Other requests that wait for the same response get it when it is cached.
1188
+ - `serveRequest()`, `serveFallback()`, and `serveCached()`, and the streaming methods when the fill does not stream, read a response completely before it is cached. The request that caches it uses memory of about two times the body, up to two times `maxBodySize`. A Compute instance has a limit on its memory, so do not set `maxBodySize` larger than 48 MiB (`48 * 1024 * 1024`). Other requests that wait for the same response get it when it is cached. A streaming fill also caches only a body of `maxBodySize` or less.
1167
1189
  - A response is cached only if its body has the size in the file's metadata. If storage returns a different body, nothing is cached, the request gets an error, and the next request reads the file again.
1168
1190
  - With `--local`, `publish-content` cannot purge the local cache. Restart `fastly compute serve` to see newly published content, or leave the response cache off in local development.
1169
1191
  - On staging, a purge must include the `Fastly-Purge-Environment: staging` header to clear the staging cache. Without it, a purge clears only the production cache. Use `publish-content --purge-environment=production,staging` to purge both.
@@ -1320,7 +1342,7 @@ export default defineExtension((app, options, { isCollectionAvailable, staticRes
1320
1342
  - `isCollectionAvailable()`, `serveRequest()`, `serveFallback()`, and `resolveCollection()`.
1321
1343
  - The methods that read the collection of the request: `getServerConfig()`, `getStaticItems()`, `getAssetEntryMap()`, `getMatchingAsset()`, and `testExtendedCache()`. They use the collection of the last `serveRequest()` or `serveFallback()` in the request (also through `serveStatic()` and the other helpers), or of `beginRequest()`, which uses the active collection, not the selected one. If neither ran in the request, call `publisherServer.beginRequest(c.req.raw)` first.
1322
1344
 
1323
- Do not call the `set…()` methods (`setActiveCollectionName()`, `setCollectionSelection()`, `setResponseCache()`, and the others) in a handler: they change the server for all requests. In the phase function, which runs one time when the app starts, they change the configuration of the whole app. Do not call the lower-level methods (`serveAsset()`, `serveCached()`, `loadAssetVariant()`, `handlePreconditions()`, and `findAcceptEncodingsGroups()`). Use `staticResponse()` and `fallbackResponse()` in their place.
1345
+ Do not call the `set…()` methods (`setActiveCollectionName()`, `setCollectionSelection()`, `setResponseCache()`, and the others) in a handler: they change the server for all requests. In the phase function, which runs one time when the app starts, they change the configuration of the whole app. Do not call the lower-level methods (`serveAsset()`, `serveCached()`, `serveCachedStreaming()`, `loadAssetVariant()`, `handlePreconditions()`, and `findAcceptEncodingsGroups()`). Use `staticResponse()` and `fallbackResponse()` in their place.
1324
1346
 
1325
1347
  **Bindings** put Fastly resources on `c.env`, as `buildFire()` of `@fastly/hono-fastly-compute` does. A module declares the bindings that it uses in the first argument of `defineExtension()`, and `c.env` in its handlers has their types, for example `ConfigStore | undefined` for `'ConfigStore:site_config'` (`undefined` if the resource does not exist or is not linked to the service). `templateOptions.hono.bindings` adds bindings for the app. The same name with the same resource in two places is allowed. The same name with two different resources stops the build, and the message names both places. `c.var` is not typed in a module, so that a module can set its own variables.
1326
1348
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hono/index.ts"],"names":[],"mappings":"AAUA,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OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;IAIvF,aAAa,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,KAAK,eAAe,CAAC;IAKnE,gBAAgB,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,oBAAoB,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;IAK3F,qBAAqB,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,CAAC,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAK/F,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;CAC3C,CAAC;AAmDF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,eAAe,EAAE,QAAQ,GAAE,iCAAsC,GAAG,yBAAyB,CA0FxI;AAED,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,eAAe,EAAE,QAAQ,GAAE,iCAAsC,GAAG,yBAAyB,CAEpI"}
@@ -20,6 +20,30 @@ function resolveCollectionName(c, option, selection) {
20
20
  // undefined selects the active collection of the PublisherServer.
21
21
  return selection != null ? selection.collectionName : undefined;
22
22
  }
23
+ // The waitUntil() of the FetchEvent of the request, or null if Hono does not
24
+ // have it (for example, when app.request() runs the app in a test).
25
+ function getWaitUntil(c) {
26
+ try {
27
+ const executionCtx = c.executionCtx;
28
+ return typeof executionCtx?.waitUntil === 'function' ? (promise) => executionCtx.waitUntil(promise) : null;
29
+ }
30
+ catch {
31
+ // c.executionCtx throws if the app has no execution context.
32
+ return null;
33
+ }
34
+ }
35
+ // Serves with the streaming form of a PublisherServer method if the request
36
+ // has waitUntil(), so that the response cache fill continues after the handler
37
+ // returns. Otherwise, serves with the form that does not stream.
38
+ async function serveWithFill(c, streaming, buffered) {
39
+ const waitUntil = getWaitUntil(c);
40
+ if (waitUntil == null) {
41
+ return buffered();
42
+ }
43
+ const { response, fillPromise } = await streaming();
44
+ waitUntil(fillPromise);
45
+ return response;
46
+ }
23
47
  export function fromPublisherServer(server, defaults = {}) {
24
48
  const staticResponse = async (c, callOptions = {}) => {
25
49
  const options = { ...defaults, ...callOptions };
@@ -31,7 +55,7 @@ export function fromPublisherServer(server, defaults = {}) {
31
55
  if (pathname == null) {
32
56
  return null;
33
57
  }
34
- return server.serveRequest(c.req.raw, {
58
+ const serveOptions = {
35
59
  collectionName: resolveCollectionName(c, options.collectionName, selection),
36
60
  pathname,
37
61
  fallback: false,
@@ -39,7 +63,8 @@ export function fromPublisherServer(server, defaults = {}) {
39
63
  onMissing: options.onMissing,
40
64
  status: options.status,
41
65
  headers: options.headers,
42
- });
66
+ };
67
+ return serveWithFill(c, () => server.serveRequestStreaming(c.req.raw, serveOptions), () => server.serveRequest(c.req.raw, serveOptions));
43
68
  };
44
69
  const serveStatic = (callOptions = {}) => {
45
70
  return async (c, next) => {
@@ -53,12 +78,13 @@ export function fromPublisherServer(server, defaults = {}) {
53
78
  };
54
79
  const fallbackResponse = async (c, callOptions = {}) => {
55
80
  const options = { ...defaults, ...callOptions };
56
- return server.serveFallback(c.req.raw, {
81
+ const serveOptions = {
57
82
  collectionName: resolveCollectionName(c, options.collectionName, getSelection(c, server)),
58
83
  onMissing: options.onMissing,
59
84
  status: options.status,
60
85
  headers: options.headers,
61
- });
86
+ };
87
+ return serveWithFill(c, () => server.serveFallbackStreaming(c.req.raw, serveOptions), () => server.serveFallback(c.req.raw, serveOptions));
62
88
  };
63
89
  const serveFallback = (callOptions = {}) => {
64
90
  return async (c) => {
@@ -7,5 +7,5 @@ export { type CollectionSelection, type CollectionSelectionSource, previewUrl, v
7
7
  export { CookieCollectionSelector, type CookieCollectionSelectorOpts, } from './collection-selector/from-cookie.js';
8
8
  export { type StorageProvider, type StorageProviderBuilder, type StorageEntry, registerStorageProviderBuilder, } from './storage/storage-provider.js';
9
9
  export { setSecretStoreForS3Credentials, setSecretStoreKeyForS3AccessKeyId, setSecretStoreKeyForS3SecretAccessKey, setS3CredentialsBuilder, } from './storage/s3-storage-provider.js';
10
- export { type GetMatchingAssetOptions, type ResponseOverrides, type ServeFallbackOptions, type ServeRequestOptions, PublisherServer, } from './publisher-server/index.js';
10
+ export { type GetMatchingAssetOptions, type ProduceResult, type ResponseOverrides, type ServeFallbackOptions, type ServeRequestOptions, type StreamingServeResult, PublisherServer, } from './publisher-server/index.js';
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,kBAAkB,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,KAAK,uBAAuB,EAC5B,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,UAAU,EACV,2BAA2B,GAC5B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,KAAK,4BAA4B,GAClC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EACjB,8BAA8B,GAC/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,8BAA8B,EAC9B,iCAAiC,EACjC,qCAAqC,EACrC,uBAAuB,GACxB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,eAAe,GAChB,MAAM,6BAA6B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AACvF,OAAO,KAAK,kBAAkB,MAAM,gCAAgC,CAAC;AACrE,OAAO,EACL,KAAK,uBAAuB,EAC5B,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,UAAU,EACV,2BAA2B,GAC5B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,KAAK,4BAA4B,GAClC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EACjB,8BAA8B,GAC/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,8BAA8B,EAC9B,iCAAiC,EACjC,qCAAqC,EACrC,uBAAuB,GACxB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,eAAe,GAChB,MAAM,6BAA6B,CAAC"}
@@ -35,6 +35,14 @@ export type ResponseOverrides = {
35
35
  status?: number;
36
36
  headers?: HeadersInit;
37
37
  };
38
+ export type ProduceResult = Response | {
39
+ response: Response;
40
+ length?: number | null;
41
+ } | null;
42
+ export type StreamingServeResult = {
43
+ response: Response | null;
44
+ fillPromise: Promise<void>;
45
+ };
38
46
  export declare class PublisherServer {
39
47
  constructor(publishId: string, storageProvider: StorageProvider, defaultCollectionName: string);
40
48
  static fromStaticPublishRc(config: StaticPublishRc): PublisherServer;
@@ -95,11 +103,17 @@ export declare class PublisherServer {
95
103
  private findAssetVariantForAcceptEncodingsGroups;
96
104
  serveAsset(request: Request, asset: AssetEntry, init?: AssetInit): Promise<Response>;
97
105
  private serveAssetFor;
98
- serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<Response | null>): Promise<Response | null>;
106
+ serveCached(request: Request, keyPath: string, produce: (request: Request) => Promise<ProduceResult>): Promise<Response | null>;
107
+ serveCachedStreaming(request: Request, keyPath: string, produce: (request: Request) => Promise<ProduceResult>): Promise<StreamingServeResult>;
99
108
  private serveCachedFor;
109
+ private streamFill;
100
110
  private responseFromCache;
101
111
  serveRequest(request: Request, options?: ServeRequestOptions): Promise<Response | null>;
112
+ serveRequestStreaming(request: Request, options?: ServeRequestOptions): Promise<StreamingServeResult>;
113
+ private serveRequestWith;
102
114
  serveFallback(request: Request, options?: ServeFallbackOptions): Promise<Response | null>;
115
+ serveFallbackStreaming(request: Request, options?: ServeFallbackOptions): Promise<StreamingServeResult>;
116
+ private serveFallbackWith;
103
117
  isCollectionAvailable(request: Request, collectionName: string | null): Promise<boolean>;
104
118
  private isCollectionAvailableFor;
105
119
  private checkSelectedCollection;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/index.ts"],"names":[],"mappings":"AASA,OAAO,EACL,KAAK,eAAe,EACrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,KAAK,+BAA+B,EACrC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EACL,KAAK,uBAAuB,EAC7B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,oBAAoB,EAI1B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,KAAK,uBAAuB,EAAsC,MAAM,kCAAkC,CAAC;AAGpH,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,eAAe,EAErB,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,C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AE,OAAO,EAAE,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAE9G;YAEa,gBAAgB;IAoDxB,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAElG;IAIK,sBAAsB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAEhH;YAEa,iBAAiB;IA2CzB,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7F;YAEa,wBAAwB;YASxB,uBAAuB;IAyBrC,OAAO,CAAC,mBAAmB;IAqB3B,OAAO,CAAC,eAAe;YAQT,uBAAuB;YAwCvB,wBAAwB;CAiCvC"}
@@ -2,8 +2,8 @@
2
2
  * Copyright Fastly, Inc.
3
3
  * Licensed under the MIT license. See LICENSE file for details.
4
4
  */
5
- /// <reference types="@fastly/js-compute" />
6
5
  import { CoreCache } from 'fastly:cache';
6
+ import { env } from 'fastly:env';
7
7
  import { decodeAssetVariantMetadata, findAssetEntry, isHiddenIndexKey, } from '../../models/assets/index.js';
8
8
  import { parseItemPatterns, testItemPatterns } from '../../models/config/item-patterns.js';
9
9
  import { validateCollectionSelection, } from '../../models/config/collection-selection.js';
@@ -15,8 +15,9 @@ import { checkIfModifiedSince, getIfModifiedSinceHeader } from './serve-precondi
15
15
  import { checkIfNoneMatch, getIfNoneMatchHeader } from './serve-preconditions/if-none-match.js';
16
16
  import { ServerTiming } from '../util/server-timing.js';
17
17
  import { requestAcceptsTextHtml } from './accept-html.js';
18
- import { CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, bytesInPieces, decodeCachedResponseMetadata, encodeCachedResponseMetadata, parseAcceptEncodingGroups, readBodyUpTo, streamBytesInPieces, } from './response-cache.js';
18
+ import { BodyLengthMismatchError, CACHEABLE_STATUSES, DEFAULT_MAX_BODY_SIZE, buildCacheFillRequest, buildResponseCacheKey, bytesInPieces, decodeCachedResponseMetadata, encodeCachedResponseMetadata, lengthMismatchMarkerKey, parseAcceptEncodingGroups, pipeBodyWithLength, readBodyUpTo, streamBytesInPieces, } from './response-cache.js';
19
19
  import { checkBodyLength } from '../util/body-length.js';
20
+ import { isSdkVersionAtLeast } from '../util/sdk-version.js';
20
21
  export function buildHeadersSubset(responseHeaders, keys) {
21
22
  const resultHeaders = new Headers();
22
23
  for (const value of keys) {
@@ -72,6 +73,37 @@ function applyResponseOverrides(response, overrides) {
72
73
  headers,
73
74
  });
74
75
  }
76
+ const FILL_DONE = Promise.resolve();
77
+ // The length of the body of each full response that serveAsset() made.
78
+ const assetResponseLengths = new WeakMap();
79
+ function readProduceResult(result) {
80
+ if (result == null) {
81
+ return { response: null, length: undefined };
82
+ }
83
+ if (result instanceof Response) {
84
+ return { response: result, length: assetResponseLengths.get(result) };
85
+ }
86
+ const { response, length } = result;
87
+ if (length != null && !(Number.isSafeInteger(length) && length >= 0)) {
88
+ throw new TypeError(`length must be an integer of 0 or more, null, or undefined: ${length}`);
89
+ }
90
+ return { response, length };
91
+ }
92
+ // A streaming fill (insertAndStreamBack() with event.waitUntil()) is safe on a
93
+ // real service from js-compute 4.2. Earlier versions do not show the waiters an
94
+ // error when a fill fails. Viceroy (FASTLY_HOSTNAME is 'localhost') keeps an
95
+ // abandoned fill, and each later request for it gets an error. In these cases,
96
+ // serveCachedStreaming() reads the whole body first, as serveCached() does.
97
+ // The js-compute version is known when the module loads. The environment is
98
+ // read at the first request, and kept.
99
+ const SDK_SUPPORTS_STREAMING_FILL = isSdkVersionAtLeast(globalThis.fastly?.sdkVersion, 4, 2);
100
+ let streamingFillSupported;
101
+ function isStreamingFillSupported() {
102
+ if (streamingFillSupported === undefined) {
103
+ streamingFillSupported = SDK_SUPPORTS_STREAMING_FILL && env('FASTLY_HOSTNAME') !== 'localhost';
104
+ }
105
+ return streamingFillSupported;
106
+ }
75
107
  // The response for a collection other than the default collection that is not
76
108
  // published, or that expired. It can be published at any time, so no cache
77
109
  // stores this response.
@@ -195,7 +227,6 @@ export class PublisherServer {
195
227
  serverTiming,
196
228
  settings: undefined,
197
229
  assetEntryMap: undefined,
198
- doNotStoreResponse: false,
199
230
  };
200
231
  }
201
232
  // The scope of a request for a collection. A new request gets a new scope.
@@ -547,10 +578,12 @@ export class PublisherServer {
547
578
  // look complete. An empty body throws here, and any other mismatch causes an
548
579
  // error in the body stream, so that the client gets an incomplete response.
549
580
  const body = await checkBodyLength(assetVariant.storageEntry.body, assetVariant.size, `File ${asset.key} (${assetVariant.contentEncoding ?? 'identity'})`);
550
- return new Response(body, {
581
+ const response = new Response(body, {
551
582
  status,
552
583
  headers,
553
584
  });
585
+ assetResponseLengths.set(response, assetVariant.size);
586
+ return response;
554
587
  }
555
588
  // Serve a response through the response cache (see setResponseCache()).
556
589
  // keyPath identifies the response in the active collection. Include in it
@@ -559,12 +592,25 @@ export class PublisherServer {
559
592
  // range headers, and its result is cached if it is a 200 or 404 response, or
560
593
  // null (not found). Conditional requests and HEAD are then answered from the
561
594
  // cached response. If the cache is off, produce() gets the original request.
595
+ // produce() can also return { response, length } (see ProduceResult). The fill
596
+ // reads the whole body before it stores it.
562
597
  async serveCached(request, keyPath, produce) {
563
- return this.serveCachedFor(this.currentScope, request, keyPath, produce);
564
- }
565
- async serveCachedFor(scope, request, keyPath, produce) {
598
+ return (await this.serveCachedFor(this.currentScope, request, keyPath, produce, false)).response;
599
+ }
600
+ // As serveCached(), but a fill for a body with a known length (see
601
+ // ProduceResult) streams the body into the cache while the response sends it.
602
+ // Pass fillPromise to event.waitUntil(), or the fill stops when the handler
603
+ // returns. With js-compute earlier than 4.2, and in Viceroy, the fill reads
604
+ // the whole body first, and fillPromise is already resolved.
605
+ async serveCachedStreaming(request, keyPath, produce) {
606
+ return this.serveCachedFor(this.currentScope, request, keyPath, produce, true);
607
+ }
608
+ async serveCachedFor(scope, request, keyPath, produce, streaming) {
609
+ const produceResponse = async (request) => {
610
+ return { response: readProduceResult(await produce(request)).response, fillPromise: FILL_DONE };
611
+ };
566
612
  if (this.responseCache == null) {
567
- return produce(request);
613
+ return produceResponse(request);
568
614
  }
569
615
  const key = buildResponseCacheKey(this.publishId, scope.collectionName, keyPath, request);
570
616
  const lookupStart = performance.now();
@@ -574,30 +620,31 @@ export class PublisherServer {
574
620
  const metadata = state.found() && state.usable() ? decodeCachedResponseMetadata(entry.userMetadata()) : null;
575
621
  if (metadata?.tooLarge) {
576
622
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
577
- return produce(request);
623
+ return produceResponse(request);
578
624
  }
579
625
  if (metadata != null) {
580
626
  // age() is in milliseconds. A hit younger than the time since a purge proves the entry was refilled.
581
627
  scope.serverTiming?.add('cache', performance.now() - lookupStart, `hit age=${Math.round(entry.age() / 1000)}s`);
582
- return this.responseFromCache(scope, request, metadata, entry.body());
628
+ return { response: this.responseFromCache(scope, request, metadata, entry.body()), fillPromise: FILL_DONE };
583
629
  }
584
630
  // Not usable, and another request is not filling it for us: serve without the cache.
585
631
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'bypass');
586
- return produce(request);
632
+ return produceResponse(request);
587
633
  }
588
634
  // This request must fill the entry (a miss, or a stale entry after a soft purge).
589
635
  scope.serverTiming?.add('cache', performance.now() - lookupStart, 'miss');
590
636
  let response;
637
+ let length;
591
638
  try {
592
- response = await produce(buildCacheFillRequest(request));
639
+ ({ response, length } = readProduceResult(await produce(buildCacheFillRequest(request))));
593
640
  }
594
641
  catch (err) {
595
642
  entry.cancel();
596
643
  throw err;
597
644
  }
598
- if (scope.doNotStoreResponse) {
645
+ if (length === null) {
599
646
  entry.cancel();
600
- return response;
647
+ return { response, fillPromise: FILL_DONE };
601
648
  }
602
649
  const insertOptions = {
603
650
  // The Core Cache takes maxAge in milliseconds. ResponseCacheOptions.maxAge is in seconds.
@@ -612,16 +659,34 @@ export class PublisherServer {
612
659
  length: 0,
613
660
  });
614
661
  writer.close();
615
- return null;
662
+ return { response: null, fillPromise: FILL_DONE };
616
663
  }
617
664
  if (!CACHEABLE_STATUSES.includes(response.status)) {
618
665
  entry.cancel();
619
- return response;
666
+ return { response, fillPromise: FILL_DONE };
620
667
  }
621
668
  const headers = new Headers(response.headers);
622
669
  // Server-Timing describes one request, so it is not stored.
623
670
  headers.delete('Server-Timing');
624
671
  const metadata = { status: response.status, headers: [...headers] };
672
+ const maxBodySize = this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
673
+ if (streaming &&
674
+ length !== undefined &&
675
+ length <= maxBodySize &&
676
+ isStreamingFillSupported() &&
677
+ CoreCache.lookup(lengthMismatchMarkerKey(key)) == null) {
678
+ // The fill streams the body into the entry, and the response streams it
679
+ // back from the entry. A fill that fails, or that does not have length
680
+ // bytes, is abandoned and not stored, and the requests that read the
681
+ // entry get an error.
682
+ const [writer, streamBack] = entry.insertAndStreamBack({
683
+ ...insertOptions,
684
+ userMetadata: encodeCachedResponseMetadata(metadata),
685
+ length,
686
+ });
687
+ const fillPromise = this.streamFill(key, insertOptions, writer, response.body, length);
688
+ return { response: this.responseFromCache(scope, request, metadata, streamBack.body()), fillPromise };
689
+ }
625
690
  // Read the whole body before the insertion starts. After it starts, a body
626
691
  // that is not complete is not safe: the requests that read the entry get
627
692
  // a short body that ends as if it is complete. If the read fails (for example,
@@ -629,7 +694,7 @@ export class PublisherServer {
629
694
  // cancel() stores nothing, and the next request fills the entry again.
630
695
  let readResult;
631
696
  try {
632
- readResult = await readBodyUpTo(response.body, this.responseCache.maxBodySize ?? DEFAULT_MAX_BODY_SIZE);
697
+ readResult = await readBodyUpTo(response.body, maxBodySize);
633
698
  }
634
699
  catch (err) {
635
700
  entry.cancel();
@@ -645,7 +710,12 @@ export class PublisherServer {
645
710
  length: 0,
646
711
  });
647
712
  writer.close();
648
- return this.responseFromCache(scope, request, metadata, readResult.body);
713
+ return { response: this.responseFromCache(scope, request, metadata, readResult.body), fillPromise: FILL_DONE };
714
+ }
715
+ // The fill stores the body that it read. A declared length that is not
716
+ // the length of that body is a mistake in produce(), so it is logged.
717
+ if (length !== undefined && length !== readResult.bytes.byteLength) {
718
+ console.warn(`Response cache: the body of '${key}' has ${readResult.bytes.byteLength} bytes, not the declared length ${length}. The fill stores the body that it read.`);
649
719
  }
650
720
  const writer = entry.insert({
651
721
  ...insertOptions,
@@ -658,7 +728,33 @@ export class PublisherServer {
658
728
  writer.append(piece);
659
729
  }
660
730
  writer.close();
661
- return this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes));
731
+ return { response: this.responseFromCache(scope, request, metadata, streamBytesInPieces(readResult.bytes)), fillPromise: FILL_DONE };
732
+ }
733
+ // Writes body into the entry. Never rejects: a failure is logged. If body
734
+ // does not have length bytes, the fill is abandoned, and a marker tells the
735
+ // next fill for key to read the whole body first.
736
+ async streamFill(key, insertOptions, writer, body, length) {
737
+ try {
738
+ await pipeBodyWithLength(body, length, (chunk) => writer.append(chunk));
739
+ writer.close();
740
+ }
741
+ catch (err) {
742
+ try {
743
+ writer.abandon();
744
+ }
745
+ catch {
746
+ // The entry is already closed or abandoned.
747
+ }
748
+ console.error(`Response cache: the fill of '${key}' stopped:`, String(err));
749
+ if (err instanceof BodyLengthMismatchError) {
750
+ try {
751
+ CoreCache.insert(lengthMismatchMarkerKey(key), { ...insertOptions, length: 0 }).close();
752
+ }
753
+ catch (markerErr) {
754
+ console.error(`Response cache: cannot store the length mismatch marker of '${key}':`, String(markerErr));
755
+ }
756
+ }
757
+ }
662
758
  }
663
759
  responseFromCache(scope, request, metadata, body) {
664
760
  if (metadata.notFound) {
@@ -686,10 +782,18 @@ export class PublisherServer {
686
782
  // file or the 404 page (see options.fallback). Returns null if there is no
687
783
  // response for the request, for example for a method other than GET and HEAD.
688
784
  async serveRequest(request, options = {}) {
785
+ return (await this.serveRequestWith(request, options, false)).response;
786
+ }
787
+ // As serveRequest(), but the response cache fill streams (see
788
+ // serveCachedStreaming()). Pass fillPromise to event.waitUntil().
789
+ async serveRequestStreaming(request, options = {}) {
790
+ return this.serveRequestWith(request, options, true);
791
+ }
792
+ async serveRequestWith(request, options, streaming) {
689
793
  let scope = this.beginRequestFor(request, options.collectionName);
690
794
  // Only handle GET and HEAD
691
795
  if (request.method !== 'GET' && request.method !== 'HEAD') {
692
- return null;
796
+ return { response: null, fillPromise: FILL_DONE };
693
797
  }
694
798
  let pathname;
695
799
  if (options.pathname != null) {
@@ -703,48 +807,64 @@ export class PublisherServer {
703
807
  }
704
808
  // Custom health check route
705
809
  if (options.healthCheck !== false && pathname === '/healthz') {
706
- return new Response("OK", { status: 200 });
810
+ return { response: new Response("OK", { status: 200 }), fillPromise: FILL_DONE };
707
811
  }
708
812
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
709
813
  if (selected instanceof Response) {
710
- return selected;
814
+ return { response: selected, fillPromise: FILL_DONE };
711
815
  }
712
816
  scope = selected.scope;
713
817
  // The fallback pages (SPA, not found) depend on whether the client accepts HTML.
714
818
  // With fallback: false, the response does not depend on HTML, so it has its own cache key.
715
819
  const fallback = options.fallback !== false && requestAcceptsTextHtml(request);
716
820
  const keyPath = fallback ? pathname : `${pathname}|no-html`;
717
- const response = applyResponseOverrides(await this.serveCachedFor(scope, requestForStatus(request, options.status), keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback)), options);
718
- return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
821
+ const served = await this.serveCachedFor(scope, requestForStatus(request, options.status), keyPath, (fillRequest) => this.serveRequestFromStorage(scope, fillRequest, pathname, fallback), streaming);
822
+ const response = applyResponseOverrides(served.response, options);
823
+ return {
824
+ response: selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response,
825
+ fillPromise: served.fillPromise,
826
+ };
719
827
  }
720
828
  // Serve the SPA file or the 404 page, as serveRequest() does when no file
721
829
  // matches. Use it after serveRequest() with fallback: false. Returns null for
722
830
  // a method other than GET and HEAD, if the client does not accept HTML, or if
723
831
  // the collection has no fallback page.
724
832
  async serveFallback(request, options = {}) {
833
+ return (await this.serveFallbackWith(request, options, false)).response;
834
+ }
835
+ // As serveFallback(), but the response cache fill streams (see
836
+ // serveCachedStreaming()). Pass fillPromise to event.waitUntil().
837
+ async serveFallbackStreaming(request, options = {}) {
838
+ return this.serveFallbackWith(request, options, true);
839
+ }
840
+ async serveFallbackWith(request, options, streaming) {
725
841
  let scope = this.beginRequestFor(request, options.collectionName);
726
842
  // Only handle GET and HEAD
727
843
  if (request.method !== 'GET' && request.method !== 'HEAD') {
728
- return null;
844
+ return { response: null, fillPromise: FILL_DONE };
729
845
  }
730
846
  if (!requestAcceptsTextHtml(request)) {
731
- return null;
847
+ return { response: null, fillPromise: FILL_DONE };
732
848
  }
733
849
  const selected = await this.checkSelectedCollection(request, scope, options.onMissing);
734
850
  if (selected instanceof Response) {
735
- return selected;
851
+ return { response: selected, fillPromise: FILL_DONE };
736
852
  }
737
853
  scope = selected.scope;
738
854
  // The fallback response is the same for all paths, so it has one cache key.
739
855
  // A path always starts with a slash, so this key is not the key of a path.
740
- const response = applyResponseOverrides(await this.serveCachedFor(scope, requestForStatus(request, options.status), '|fallback', async (fillRequest) => {
856
+ const served = await this.serveCachedFor(scope, requestForStatus(request, options.status), '|fallback', async (fillRequest) => {
741
857
  const serverConfig = await this.getServerConfigFor(scope);
742
858
  if (serverConfig == null) {
743
859
  return null;
744
860
  }
745
861
  return this.serveFallbackFromStorage(scope, fillRequest, serverConfig);
746
- }), options);
747
- return selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response;
862
+ }, streaming);
863
+ const response = applyResponseOverrides(served.response, options);
864
+ return {
865
+ response: selected.preview ? this.markPreviewResponse(request, selected.scope, response) : response,
866
+ fillPromise: served.fillPromise,
867
+ };
748
868
  }
749
869
  // Returns true if the collection is published, has not expired, and can
750
870
  // be served by this version. It reads the settings and the index into the scope.
@@ -826,8 +946,7 @@ export class PublisherServer {
826
946
  // response cache does not store this response.
827
947
  if (serverConfig == null ||
828
948
  (scope.collectionName !== this.defaultCollectionName && await this.getAssetEntryMapFor(scope) == null)) {
829
- scope.doNotStoreResponse = true;
830
- return collectionNotAvailableResponse(scope.collectionName);
949
+ return { response: collectionNotAvailableResponse(scope.collectionName), length: null };
831
950
  }
832
951
  const asset = await this.getMatchingAssetFor(scope, serverConfig.publicDirPrefix + pathname, true, false);
833
952
  if (asset != null) {
@@ -27,6 +27,11 @@ export type ReadBodyResult = {
27
27
  body: ReadableStream<Uint8Array>;
28
28
  };
29
29
  export declare function readBodyUpTo(body: ReadableStream<Uint8Array> | null, maxLength: number): Promise<ReadBodyResult>;
30
+ export declare class BodyLengthMismatchError extends Error {
31
+ constructor(message: string);
32
+ }
33
+ export declare function pipeBodyWithLength(body: ReadableStream<Uint8Array> | null, length: number, append: (chunk: Uint8Array) => void): Promise<void>;
34
+ export declare function lengthMismatchMarkerKey(key: string): string;
30
35
  export declare const BODY_PIECE_SIZE: number;
31
36
  export declare function bytesInPieces(bytes: Uint8Array<ArrayBuffer>): Generator<Uint8Array<ArrayBuffer>>;
32
37
  export declare function streamBytesInPieces(bytes: Uint8Array<ArrayBuffer>): ReadableStream<Uint8Array>;
@@ -1 +1 @@
1
- {"version":3,"file":"response-cache.d.ts","sourceRoot":"","sources":["../../../../src/server/publisher-server/response-cache.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,KAAK,uBAAuB,EAE7B,MAAM,mCAAmC,CAAC;AAE3C,MAAM,MAAM,oBAAoB,GAAG;IAIjC,MAAM,EAAE,MAAM,CAAC;IAIf,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,qBAAqB,QAAmB,CAAC;AAKtD,MAAM,MAAM,sBAAsB,GAC9B;IAAE,QAAQ,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,EAAE,KAAK,CAAA;CAAE,GACpC;IAAE,QAAQ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OAAO,UAGjB;AAID,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAM/D;AAED,MAAM,MAAM,cAAc,GACtB;IAAE,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;CAAE,CAAC;AAMzC,wBAAsB,YAAY,CAChC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,CAAC,CA8CzB;AAGD,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACF;AAMD,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,IAAI,EACvC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAClC,OAAO,CAAC,IAAI,CAAC,CAoBf;AAID,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,eAAO,MAAM,eAAe,QAAc,CAAC;AAI3C,wBAAiB,aAAa,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,SAAS,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAIjG;AAGD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAY9F;AAED,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,sBAAsB,GAAG,MAAM,CAErF;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,WAAW,GAAG,sBAAsB,GAAG,IAAI,CAgB/F"}
@@ -137,6 +137,43 @@ export async function readBodyUpTo(body, maxLength) {
137
137
  }
138
138
  return { bytes };
139
139
  }
140
+ // The body of a response has a number of bytes that is not its declared length.
141
+ export class BodyLengthMismatchError extends Error {
142
+ constructor(message) {
143
+ super(message);
144
+ this.name = 'BodyLengthMismatchError';
145
+ }
146
+ }
147
+ // Reads body, and gives each chunk to append(). Rejects with
148
+ // BodyLengthMismatchError if body has more or fewer bytes than length. A chunk
149
+ // that goes past length does not go to append(), and the read of body stops.
150
+ // An error from body or from append() rejects the promise.
151
+ export async function pipeBodyWithLength(body, length, append) {
152
+ let written = 0;
153
+ if (body != null) {
154
+ const reader = body.getReader();
155
+ for (;;) {
156
+ const { done, value } = await reader.read();
157
+ if (done) {
158
+ break;
159
+ }
160
+ if (written + value.byteLength > length) {
161
+ await reader.cancel().catch(() => { });
162
+ throw new BodyLengthMismatchError(`The body has more than ${length} bytes.`);
163
+ }
164
+ append(value);
165
+ written += value.byteLength;
166
+ }
167
+ }
168
+ if (written !== length) {
169
+ throw new BodyLengthMismatchError(`The body has ${written} bytes, not ${length}.`);
170
+ }
171
+ }
172
+ // The key of the marker that tells a cache fill for key to read the whole body
173
+ // first. A streaming fill stores it when the body did not have its declared length.
174
+ export function lengthMismatchMarkerKey(key) {
175
+ return `${key}|length-mismatch`;
176
+ }
140
177
  export const BODY_PIECE_SIZE = 1024 * 1024;
141
178
  // Gives bytes in pieces of BODY_PIECE_SIZE bytes. The pieces are views of
142
179
  // bytes, not copies.
@@ -0,0 +1,2 @@
1
+ export declare function isSdkVersionAtLeast(version: string | null | undefined, major: number, minor: number): boolean;
2
+ //# sourceMappingURL=sdk-version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-version.d.ts","sourceRoot":"","sources":["../../../../src/server/util/sdk-version.ts"],"names":[],"mappings":"AAOA,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ7G"}
@@ -0,0 +1,15 @@
1
+ /*
2
+ * Copyright Fastly, Inc.
3
+ * Licensed under the MIT license. See LICENSE file for details.
4
+ */
5
+ // Returns true if version (for example, fastly.sdkVersion, '4.3.0') is
6
+ // major.minor or later. A version that is missing or cannot be read gives false.
7
+ export function isSdkVersionAtLeast(version, major, minor) {
8
+ const match = /^(\d+)\.(\d+)/.exec(version ?? '');
9
+ if (match == null) {
10
+ return false;
11
+ }
12
+ const versionMajor = Number(match[1]);
13
+ const versionMinor = Number(match[2]);
14
+ return versionMajor > major || (versionMajor === major && versionMinor >= minor);
15
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fastly/compute-js-static-publish",
3
3
  "type": "module",
4
- "version": "8.1.0-beta.6",
4
+ "version": "8.1.0-beta.7",
5
5
  "description": "Static Publisher for Fastly Compute JavaScript",
6
6
  "main": "build/server/server/index.js",
7
7
  "exports": {
@@ -23,11 +23,13 @@ async function handleRequest(event) {
23
23
 
24
24
  // Serve the published file for the request. With fallback: false, a path
25
25
  // that has no file does not get the SPA file or the 404 page here.
26
- const response = await publisherServer.serveRequest(request, {
26
+ // waitUntil() lets the response cache fill continue after the response.
27
+ const { response, fillPromise } = await publisherServer.serveRequestStreaming(request, {
27
28
  collectionName: selection.collectionName,
28
29
  pathname: selection.pathname,
29
30
  fallback: false,
30
31
  });
32
+ event.waitUntil(fillPromise);
31
33
  if (response != null) {
32
34
  return response;
33
35
  }
@@ -37,8 +39,9 @@ async function handleRequest(event) {
37
39
  // for the requests that no published file matches.
38
40
 
39
41
  // When nothing else matches, serve the SPA file or the 404 page.
40
- const fallback = await publisherServer.serveFallback(request, {
42
+ const fallback = await publisherServer.serveFallbackStreaming(request, {
41
43
  collectionName: selection.collectionName,
42
44
  });
43
- return fallback ?? new Response('Not found', { status: 404 });
45
+ event.waitUntil(fallback.fillPromise);
46
+ return fallback.response ?? new Response('Not found', { status: 404 });
44
47
  }