@serwist/range-requests 8.4.4 → 9.0.0-preview.1

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.
@@ -17,3 +17,4 @@ declare class RangeRequestsPlugin implements SerwistPlugin {
17
17
  cachedResponseWillBeUsed: SerwistPlugin["cachedResponseWillBeUsed"];
18
18
  }
19
19
  export { RangeRequestsPlugin };
20
+ //# sourceMappingURL=RangeRequestsPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RangeRequestsPlugin.d.ts","sourceRoot":"","sources":["../src/RangeRequestsPlugin.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAInD;;;;;;GAMG;AACH,cAAM,mBAAoB,YAAW,aAAa;IAChD;;;;;;OAMG;IACH,wBAAwB,EAAE,aAAa,CAAC,0BAA0B,CAAC,CAUjE;CACH;AAED,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -16,3 +16,4 @@
16
16
  */
17
17
  declare function createPartialResponse(request: Request, originalResponse: Response): Promise<Response>;
18
18
  export { createPartialResponse };
19
+ //# sourceMappingURL=createPartialResponse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createPartialResponse.d.ts","sourceRoot":"","sources":["../src/createPartialResponse.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;GAeG;AACH,iBAAe,qBAAqB,CAAC,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8DpG;AAED,OAAO,EAAE,qBAAqB,EAAE,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { RangeRequestsPlugin } from "./RangeRequestsPlugin.js";
2
2
  import { createPartialResponse } from "./createPartialResponse.js";
3
3
  export { createPartialResponse, RangeRequestsPlugin };
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -1,14 +1,6 @@
1
1
  import { assert, SerwistError, logger } from '@serwist/core/internal';
2
2
 
3
- /**
4
- * @param blob A source blob.
5
- * @param start The offset to use as the start of the
6
- * slice.
7
- * @param end The offset to use as the end of the slice.
8
- * @returns An object with `start` and `end` properties, reflecting
9
- * the effective boundaries to use given the size of the blob.
10
- * @private
11
- */ function calculateEffectiveBoundaries(blob, start, end) {
3
+ function calculateEffectiveBoundaries(blob, start, end) {
12
4
  if (process.env.NODE_ENV !== "production") {
13
5
  assert.isInstance(blob, Blob, {
14
6
  moduleName: "@serwist/range-requests",
@@ -28,7 +20,6 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
28
20
  let effectiveEnd;
29
21
  if (start !== undefined && end !== undefined) {
30
22
  effectiveStart = start;
31
- // Range values are inclusive, so add 1 to the value.
32
23
  effectiveEnd = end + 1;
33
24
  } else if (start !== undefined && end === undefined) {
34
25
  effectiveStart = start;
@@ -43,13 +34,7 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
43
34
  };
44
35
  }
45
36
 
46
- /**
47
- * @param rangeHeader A Range: header value.
48
- * @returns An object with `start` and `end` properties, reflecting
49
- * the parsed value of the Range: header. If either the `start` or `end` are
50
- * omitted, then `null` will be returned.
51
- * @private
52
- */ function parseRangeHeader(rangeHeader) {
37
+ function parseRangeHeader(rangeHeader) {
53
38
  if (process.env.NODE_ENV !== "production") {
54
39
  assert.isType(rangeHeader, "string", {
55
40
  moduleName: "@serwist/range-requests",
@@ -63,16 +48,12 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
63
48
  normalizedRangeHeader
64
49
  });
65
50
  }
66
- // Specifying multiple ranges separate by commas is valid syntax, but this
67
- // library only attempts to handle a single, contiguous sequence of bytes.
68
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax
69
51
  if (normalizedRangeHeader.includes(",")) {
70
52
  throw new SerwistError("single-range-only", {
71
53
  normalizedRangeHeader
72
54
  });
73
55
  }
74
56
  const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader);
75
- // We need either at least one of the start or end values.
76
57
  if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {
77
58
  throw new SerwistError("invalid-range-values", {
78
59
  normalizedRangeHeader
@@ -84,22 +65,7 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
84
65
  };
85
66
  }
86
67
 
87
- /**
88
- * Given a `Request` and `Response` objects as input, this will return a
89
- * promise for a new `Response`.
90
- *
91
- * If the original `Response` already contains partial content (i.e. it has
92
- * a status of 206), then this assumes it already fulfills the `Range:`
93
- * requirements, and will return it as-is.
94
- *
95
- * @param request A request, which should contain a Range:
96
- * header.
97
- * @param originalResponse A response.
98
- * @returns Either a `206 Partial Content` response, with
99
- * the response body set to the slice of content specified by the request's
100
- * `Range:` header, or a `416 Range Not Satisfiable` response if the
101
- * conditions of the `Range:` header can't be met.
102
- */ async function createPartialResponse(request, originalResponse) {
68
+ async function createPartialResponse(request, originalResponse) {
103
69
  try {
104
70
  if (process.env.NODE_ENV !== "production") {
105
71
  assert.isInstance(request, Request, {
@@ -114,8 +80,6 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
114
80
  });
115
81
  }
116
82
  if (originalResponse.status === 206) {
117
- // If we already have a 206, then just pass it through as-is;
118
- // see https://github.com/GoogleChrome/workbox/issues/1720
119
83
  return originalResponse;
120
84
  }
121
85
  const rangeHeader = request.headers.get("range");
@@ -128,8 +92,6 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
128
92
  const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);
129
93
  const slicedBlobSize = slicedBlob.size;
130
94
  const slicedResponse = new Response(slicedBlob, {
131
- // Status code 206 is for a Partial Content response.
132
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206
133
95
  status: 206,
134
96
  statusText: "Partial Content",
135
97
  headers: originalResponse.headers
@@ -153,27 +115,11 @@ import { assert, SerwistError, logger } from '@serwist/core/internal';
153
115
  }
154
116
  }
155
117
 
156
- /**
157
- * The range request plugin makes it easy for a request with a 'Range' header to
158
- * be fulfilled by a cached response.
159
- *
160
- * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
161
- * and returning the appropriate subset of the cached response body.
162
- */ class RangeRequestsPlugin {
163
- /**
164
- * @param options
165
- * @returns If request contains a 'Range' header, then a
166
- * new response with status 206 whose body is a subset of `cachedResponse` is
167
- * returned. Otherwise, `cachedResponse` is returned as-is.
168
- * @private
169
- */ cachedResponseWillBeUsed = async ({ request, cachedResponse })=>{
170
- // Only return a sliced response if there's something valid in the cache,
171
- // and there's a Range: header in the request.
118
+ class RangeRequestsPlugin {
119
+ cachedResponseWillBeUsed = async ({ request, cachedResponse })=>{
172
120
  if (cachedResponse && request.headers.has("range")) {
173
121
  return await createPartialResponse(request, cachedResponse);
174
122
  }
175
- // If there was no Range: header, or if cachedResponse wasn't valid, just
176
- // pass it through as-is.
177
123
  return cachedResponse;
178
124
  };
179
125
  }
@@ -12,3 +12,4 @@ declare function calculateEffectiveBoundaries(blob: Blob, start?: number, end?:
12
12
  end: number;
13
13
  };
14
14
  export { calculateEffectiveBoundaries };
15
+ //# sourceMappingURL=calculateEffectiveBoundaries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calculateEffectiveBoundaries.d.ts","sourceRoot":"","sources":["../../src/utils/calculateEffectiveBoundaries.ts"],"names":[],"mappings":"AAUA;;;;;;;;GAQG;AACH,iBAAS,4BAA4B,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAsC9G;AAED,OAAO,EAAE,4BAA4B,EAAE,CAAC"}
@@ -10,3 +10,4 @@ declare function parseRangeHeader(rangeHeader: string): {
10
10
  end?: number;
11
11
  };
12
12
  export { parseRangeHeader };
13
+ //# sourceMappingURL=parseRangeHeader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseRangeHeader.d.ts","sourceRoot":"","sources":["../../src/utils/parseRangeHeader.ts"],"names":[],"mappings":"AAUA;;;;;;GAMG;AACH,iBAAS,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CA+BA;AAED,OAAO,EAAE,gBAAgB,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@serwist/range-requests",
3
- "version": "8.4.4",
3
+ "version": "9.0.0-preview.1",
4
4
  "type": "module",
5
5
  "description": "This library creates a new Response, given a source Response and a Range header value.",
6
6
  "files": [
7
- "dist",
8
- "!dist/**/dts"
7
+ "src",
8
+ "dist"
9
9
  ],
10
10
  "keywords": [
11
11
  "serwist",
@@ -23,28 +23,30 @@
23
23
  "repository": "serwist/serwist",
24
24
  "bugs": "https://github.com/serwist/serwist/issues",
25
25
  "homepage": "https://serwist.pages.dev",
26
- "module": "./dist/index.js",
27
- "main": "./dist/index.cjs",
26
+ "main": "./dist/index.js",
28
27
  "types": "./dist/index.d.ts",
29
28
  "exports": {
30
29
  ".": {
31
- "import": {
32
- "types": "./dist/index.d.ts",
33
- "default": "./dist/index.js"
34
- },
35
- "require": {
36
- "types": "./dist/index.d.cts",
37
- "default": "./dist/index.cjs"
38
- }
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
39
32
  },
40
33
  "./package.json": "./package.json"
41
34
  },
42
35
  "dependencies": {
43
- "@serwist/core": "8.4.4"
36
+ "@serwist/core": "9.0.0-preview.1"
44
37
  },
45
38
  "devDependencies": {
46
- "rollup": "4.9.1",
47
- "@serwist/constants": "8.4.4"
39
+ "rollup": "4.9.6",
40
+ "typescript": "5.4.0-dev.20240203",
41
+ "@serwist/constants": "9.0.0-preview.1"
42
+ },
43
+ "peerDependencies": {
44
+ "typescript": ">=5.0.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "typescript": {
48
+ "optional": true
49
+ }
48
50
  },
49
51
  "scripts": {
50
52
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
@@ -0,0 +1,41 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { SerwistPlugin } from "@serwist/core";
10
+
11
+ import { createPartialResponse } from "./createPartialResponse.js";
12
+
13
+ /**
14
+ * The range request plugin makes it easy for a request with a 'Range' header to
15
+ * be fulfilled by a cached response.
16
+ *
17
+ * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
18
+ * and returning the appropriate subset of the cached response body.
19
+ */
20
+ class RangeRequestsPlugin implements SerwistPlugin {
21
+ /**
22
+ * @param options
23
+ * @returns If request contains a 'Range' header, then a
24
+ * new response with status 206 whose body is a subset of `cachedResponse` is
25
+ * returned. Otherwise, `cachedResponse` is returned as-is.
26
+ * @private
27
+ */
28
+ cachedResponseWillBeUsed: SerwistPlugin["cachedResponseWillBeUsed"] = async ({ request, cachedResponse }) => {
29
+ // Only return a sliced response if there's something valid in the cache,
30
+ // and there's a Range: header in the request.
31
+ if (cachedResponse && request.headers.has("range")) {
32
+ return await createPartialResponse(request, cachedResponse);
33
+ }
34
+
35
+ // If there was no Range: header, or if cachedResponse wasn't valid, just
36
+ // pass it through as-is.
37
+ return cachedResponse;
38
+ };
39
+ }
40
+
41
+ export { RangeRequestsPlugin };
@@ -0,0 +1,94 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { assert, SerwistError, logger } from "@serwist/core/internal";
10
+
11
+ import { calculateEffectiveBoundaries } from "./utils/calculateEffectiveBoundaries.js";
12
+ import { parseRangeHeader } from "./utils/parseRangeHeader.js";
13
+
14
+ /**
15
+ * Given a `Request` and `Response` objects as input, this will return a
16
+ * promise for a new `Response`.
17
+ *
18
+ * If the original `Response` already contains partial content (i.e. it has
19
+ * a status of 206), then this assumes it already fulfills the `Range:`
20
+ * requirements, and will return it as-is.
21
+ *
22
+ * @param request A request, which should contain a Range:
23
+ * header.
24
+ * @param originalResponse A response.
25
+ * @returns Either a `206 Partial Content` response, with
26
+ * the response body set to the slice of content specified by the request's
27
+ * `Range:` header, or a `416 Range Not Satisfiable` response if the
28
+ * conditions of the `Range:` header can't be met.
29
+ */
30
+ async function createPartialResponse(request: Request, originalResponse: Response): Promise<Response> {
31
+ try {
32
+ if (process.env.NODE_ENV !== "production") {
33
+ assert!.isInstance(request, Request, {
34
+ moduleName: "@serwist/range-requests",
35
+ funcName: "createPartialResponse",
36
+ paramName: "request",
37
+ });
38
+
39
+ assert!.isInstance(originalResponse, Response, {
40
+ moduleName: "@serwist/range-requests",
41
+ funcName: "createPartialResponse",
42
+ paramName: "originalResponse",
43
+ });
44
+ }
45
+
46
+ if (originalResponse.status === 206) {
47
+ // If we already have a 206, then just pass it through as-is;
48
+ // see https://github.com/GoogleChrome/workbox/issues/1720
49
+ return originalResponse;
50
+ }
51
+
52
+ const rangeHeader = request.headers.get("range");
53
+ if (!rangeHeader) {
54
+ throw new SerwistError("no-range-header");
55
+ }
56
+
57
+ const boundaries = parseRangeHeader(rangeHeader);
58
+ const originalBlob = await originalResponse.blob();
59
+
60
+ const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);
61
+
62
+ const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);
63
+ const slicedBlobSize = slicedBlob.size;
64
+
65
+ const slicedResponse = new Response(slicedBlob, {
66
+ // Status code 206 is for a Partial Content response.
67
+ // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206
68
+ status: 206,
69
+ statusText: "Partial Content",
70
+ headers: originalResponse.headers,
71
+ });
72
+
73
+ slicedResponse.headers.set("Content-Length", String(slicedBlobSize));
74
+ slicedResponse.headers.set("Content-Range", `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + `${originalBlob.size}`);
75
+
76
+ return slicedResponse;
77
+ } catch (error) {
78
+ if (process.env.NODE_ENV !== "production") {
79
+ logger.warn("Unable to construct a partial response; returning a " + "416 Range Not Satisfiable response instead.");
80
+ logger.groupCollapsed("View details here.");
81
+ logger.log(error);
82
+ logger.log(request);
83
+ logger.log(originalResponse);
84
+ logger.groupEnd();
85
+ }
86
+
87
+ return new Response("", {
88
+ status: 416,
89
+ statusText: "Range Not Satisfiable",
90
+ });
91
+ }
92
+ }
93
+
94
+ export { createPartialResponse };
@@ -1,3 +1,12 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
1
9
  import { RangeRequestsPlugin } from "./RangeRequestsPlugin.js";
2
10
  import { createPartialResponse } from "./createPartialResponse.js";
11
+
3
12
  export { createPartialResponse, RangeRequestsPlugin };
@@ -0,0 +1,60 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { assert, SerwistError } from "@serwist/core/internal";
10
+
11
+ /**
12
+ * @param blob A source blob.
13
+ * @param start The offset to use as the start of the
14
+ * slice.
15
+ * @param end The offset to use as the end of the slice.
16
+ * @returns An object with `start` and `end` properties, reflecting
17
+ * the effective boundaries to use given the size of the blob.
18
+ * @private
19
+ */
20
+ function calculateEffectiveBoundaries(blob: Blob, start?: number, end?: number): { start: number; end: number } {
21
+ if (process.env.NODE_ENV !== "production") {
22
+ assert!.isInstance(blob, Blob, {
23
+ moduleName: "@serwist/range-requests",
24
+ funcName: "calculateEffectiveBoundaries",
25
+ paramName: "blob",
26
+ });
27
+ }
28
+
29
+ const blobSize = blob.size;
30
+
31
+ if ((end && end > blobSize) || (start && start < 0)) {
32
+ throw new SerwistError("range-not-satisfiable", {
33
+ size: blobSize,
34
+ end,
35
+ start,
36
+ });
37
+ }
38
+
39
+ let effectiveStart: number;
40
+ let effectiveEnd: number;
41
+
42
+ if (start !== undefined && end !== undefined) {
43
+ effectiveStart = start;
44
+ // Range values are inclusive, so add 1 to the value.
45
+ effectiveEnd = end + 1;
46
+ } else if (start !== undefined && end === undefined) {
47
+ effectiveStart = start;
48
+ effectiveEnd = blobSize;
49
+ } else if (end !== undefined && start === undefined) {
50
+ effectiveStart = blobSize - end;
51
+ effectiveEnd = blobSize;
52
+ }
53
+
54
+ return {
55
+ start: effectiveStart!,
56
+ end: effectiveEnd!,
57
+ };
58
+ }
59
+
60
+ export { calculateEffectiveBoundaries };
@@ -0,0 +1,54 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { assert, SerwistError } from "@serwist/core/internal";
10
+
11
+ /**
12
+ * @param rangeHeader A Range: header value.
13
+ * @returns An object with `start` and `end` properties, reflecting
14
+ * the parsed value of the Range: header. If either the `start` or `end` are
15
+ * omitted, then `null` will be returned.
16
+ * @private
17
+ */
18
+ function parseRangeHeader(rangeHeader: string): {
19
+ start?: number;
20
+ end?: number;
21
+ } {
22
+ if (process.env.NODE_ENV !== "production") {
23
+ assert!.isType(rangeHeader, "string", {
24
+ moduleName: "@serwist/range-requests",
25
+ funcName: "parseRangeHeader",
26
+ paramName: "rangeHeader",
27
+ });
28
+ }
29
+
30
+ const normalizedRangeHeader = rangeHeader.trim().toLowerCase();
31
+ if (!normalizedRangeHeader.startsWith("bytes=")) {
32
+ throw new SerwistError("unit-must-be-bytes", { normalizedRangeHeader });
33
+ }
34
+
35
+ // Specifying multiple ranges separate by commas is valid syntax, but this
36
+ // library only attempts to handle a single, contiguous sequence of bytes.
37
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax
38
+ if (normalizedRangeHeader.includes(",")) {
39
+ throw new SerwistError("single-range-only", { normalizedRangeHeader });
40
+ }
41
+
42
+ const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader);
43
+ // We need either at least one of the start or end values.
44
+ if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {
45
+ throw new SerwistError("invalid-range-values", { normalizedRangeHeader });
46
+ }
47
+
48
+ return {
49
+ start: rangeParts[1] === "" ? undefined : Number(rangeParts[1]),
50
+ end: rangeParts[2] === "" ? undefined : Number(rangeParts[2]),
51
+ };
52
+ }
53
+
54
+ export { parseRangeHeader };
package/dist/index.cjs DELETED
@@ -1,184 +0,0 @@
1
- 'use strict';
2
-
3
- var internal = require('@serwist/core/internal');
4
-
5
- /**
6
- * @param blob A source blob.
7
- * @param start The offset to use as the start of the
8
- * slice.
9
- * @param end The offset to use as the end of the slice.
10
- * @returns An object with `start` and `end` properties, reflecting
11
- * the effective boundaries to use given the size of the blob.
12
- * @private
13
- */ function calculateEffectiveBoundaries(blob, start, end) {
14
- if (process.env.NODE_ENV !== "production") {
15
- internal.assert.isInstance(blob, Blob, {
16
- moduleName: "@serwist/range-requests",
17
- funcName: "calculateEffectiveBoundaries",
18
- paramName: "blob"
19
- });
20
- }
21
- const blobSize = blob.size;
22
- if (end && end > blobSize || start && start < 0) {
23
- throw new internal.SerwistError("range-not-satisfiable", {
24
- size: blobSize,
25
- end,
26
- start
27
- });
28
- }
29
- let effectiveStart;
30
- let effectiveEnd;
31
- if (start !== undefined && end !== undefined) {
32
- effectiveStart = start;
33
- // Range values are inclusive, so add 1 to the value.
34
- effectiveEnd = end + 1;
35
- } else if (start !== undefined && end === undefined) {
36
- effectiveStart = start;
37
- effectiveEnd = blobSize;
38
- } else if (end !== undefined && start === undefined) {
39
- effectiveStart = blobSize - end;
40
- effectiveEnd = blobSize;
41
- }
42
- return {
43
- start: effectiveStart,
44
- end: effectiveEnd
45
- };
46
- }
47
-
48
- /**
49
- * @param rangeHeader A Range: header value.
50
- * @returns An object with `start` and `end` properties, reflecting
51
- * the parsed value of the Range: header. If either the `start` or `end` are
52
- * omitted, then `null` will be returned.
53
- * @private
54
- */ function parseRangeHeader(rangeHeader) {
55
- if (process.env.NODE_ENV !== "production") {
56
- internal.assert.isType(rangeHeader, "string", {
57
- moduleName: "@serwist/range-requests",
58
- funcName: "parseRangeHeader",
59
- paramName: "rangeHeader"
60
- });
61
- }
62
- const normalizedRangeHeader = rangeHeader.trim().toLowerCase();
63
- if (!normalizedRangeHeader.startsWith("bytes=")) {
64
- throw new internal.SerwistError("unit-must-be-bytes", {
65
- normalizedRangeHeader
66
- });
67
- }
68
- // Specifying multiple ranges separate by commas is valid syntax, but this
69
- // library only attempts to handle a single, contiguous sequence of bytes.
70
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#Syntax
71
- if (normalizedRangeHeader.includes(",")) {
72
- throw new internal.SerwistError("single-range-only", {
73
- normalizedRangeHeader
74
- });
75
- }
76
- const rangeParts = /(\d*)-(\d*)/.exec(normalizedRangeHeader);
77
- // We need either at least one of the start or end values.
78
- if (!rangeParts || !(rangeParts[1] || rangeParts[2])) {
79
- throw new internal.SerwistError("invalid-range-values", {
80
- normalizedRangeHeader
81
- });
82
- }
83
- return {
84
- start: rangeParts[1] === "" ? undefined : Number(rangeParts[1]),
85
- end: rangeParts[2] === "" ? undefined : Number(rangeParts[2])
86
- };
87
- }
88
-
89
- /**
90
- * Given a `Request` and `Response` objects as input, this will return a
91
- * promise for a new `Response`.
92
- *
93
- * If the original `Response` already contains partial content (i.e. it has
94
- * a status of 206), then this assumes it already fulfills the `Range:`
95
- * requirements, and will return it as-is.
96
- *
97
- * @param request A request, which should contain a Range:
98
- * header.
99
- * @param originalResponse A response.
100
- * @returns Either a `206 Partial Content` response, with
101
- * the response body set to the slice of content specified by the request's
102
- * `Range:` header, or a `416 Range Not Satisfiable` response if the
103
- * conditions of the `Range:` header can't be met.
104
- */ async function createPartialResponse(request, originalResponse) {
105
- try {
106
- if (process.env.NODE_ENV !== "production") {
107
- internal.assert.isInstance(request, Request, {
108
- moduleName: "@serwist/range-requests",
109
- funcName: "createPartialResponse",
110
- paramName: "request"
111
- });
112
- internal.assert.isInstance(originalResponse, Response, {
113
- moduleName: "@serwist/range-requests",
114
- funcName: "createPartialResponse",
115
- paramName: "originalResponse"
116
- });
117
- }
118
- if (originalResponse.status === 206) {
119
- // If we already have a 206, then just pass it through as-is;
120
- // see https://github.com/GoogleChrome/workbox/issues/1720
121
- return originalResponse;
122
- }
123
- const rangeHeader = request.headers.get("range");
124
- if (!rangeHeader) {
125
- throw new internal.SerwistError("no-range-header");
126
- }
127
- const boundaries = parseRangeHeader(rangeHeader);
128
- const originalBlob = await originalResponse.blob();
129
- const effectiveBoundaries = calculateEffectiveBoundaries(originalBlob, boundaries.start, boundaries.end);
130
- const slicedBlob = originalBlob.slice(effectiveBoundaries.start, effectiveBoundaries.end);
131
- const slicedBlobSize = slicedBlob.size;
132
- const slicedResponse = new Response(slicedBlob, {
133
- // Status code 206 is for a Partial Content response.
134
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206
135
- status: 206,
136
- statusText: "Partial Content",
137
- headers: originalResponse.headers
138
- });
139
- slicedResponse.headers.set("Content-Length", String(slicedBlobSize));
140
- slicedResponse.headers.set("Content-Range", `bytes ${effectiveBoundaries.start}-${effectiveBoundaries.end - 1}/` + `${originalBlob.size}`);
141
- return slicedResponse;
142
- } catch (error) {
143
- if (process.env.NODE_ENV !== "production") {
144
- internal.logger.warn("Unable to construct a partial response; returning a " + "416 Range Not Satisfiable response instead.");
145
- internal.logger.groupCollapsed("View details here.");
146
- internal.logger.log(error);
147
- internal.logger.log(request);
148
- internal.logger.log(originalResponse);
149
- internal.logger.groupEnd();
150
- }
151
- return new Response("", {
152
- status: 416,
153
- statusText: "Range Not Satisfiable"
154
- });
155
- }
156
- }
157
-
158
- /**
159
- * The range request plugin makes it easy for a request with a 'Range' header to
160
- * be fulfilled by a cached response.
161
- *
162
- * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback
163
- * and returning the appropriate subset of the cached response body.
164
- */ class RangeRequestsPlugin {
165
- /**
166
- * @param options
167
- * @returns If request contains a 'Range' header, then a
168
- * new response with status 206 whose body is a subset of `cachedResponse` is
169
- * returned. Otherwise, `cachedResponse` is returned as-is.
170
- * @private
171
- */ cachedResponseWillBeUsed = async ({ request, cachedResponse })=>{
172
- // Only return a sliced response if there's something valid in the cache,
173
- // and there's a Range: header in the request.
174
- if (cachedResponse && request.headers.has("range")) {
175
- return await createPartialResponse(request, cachedResponse);
176
- }
177
- // If there was no Range: header, or if cachedResponse wasn't valid, just
178
- // pass it through as-is.
179
- return cachedResponse;
180
- };
181
- }
182
-
183
- exports.RangeRequestsPlugin = RangeRequestsPlugin;
184
- exports.createPartialResponse = createPartialResponse;