exifreader 4.47.0 → 4.48.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.
package/exif-reader.d.ts CHANGED
@@ -329,7 +329,7 @@ interface PhotoshopTags {
329
329
  }
330
330
 
331
331
  interface CanonTags {
332
- AutoRotate: {
332
+ AutoRotate?: {
333
333
  value: number;
334
334
  description: 'None' | 'Rotate 90 CW' | 'Rotate 180' | 'Rotate 270 CW' | 'Unknown';
335
335
  };
@@ -344,23 +344,23 @@ interface CanonTags {
344
344
  }
345
345
 
346
346
  interface PentaxTags {
347
- PentaxVersion: {
347
+ PentaxVersion?: {
348
348
  value: number[];
349
349
  description: string;
350
350
  };
351
- PentaxModelID: {
351
+ PentaxModelID?: {
352
352
  value: number;
353
353
  description: string;
354
354
  };
355
- Orientation: {
355
+ CameraOrientation?: {
356
356
  value: number;
357
357
  description: 'Horizontal (normal)' | 'Rotate 270 CW' | 'Rotate 180' | 'Rotate 90 CW' | 'Upwards' | 'Downwards' | 'Unknown';
358
358
  };
359
- RollAngle: {
359
+ RollAngle?: {
360
360
  value: number;
361
361
  description: string;
362
362
  };
363
- PitchAngle: {
363
+ PitchAngle?: {
364
364
  value: number;
365
365
  description: string;
366
366
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exifreader",
3
- "version": "4.47.0",
3
+ "version": "4.48.1",
4
4
  "description": "Library that parses Exif metadata in images.",
5
5
  "author": "Mattias Wallander <mattias@wallander.eu>",
6
6
  "repository": {
@@ -25,25 +25,25 @@
25
25
  "exifreader": "bin/cli.js"
26
26
  },
27
27
  "optionalDependencies": {
28
- "@xmldom/xmldom": "^0.9.10"
28
+ "@xmldom/xmldom": "^0.9.12"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@babel/core": "^7.29.7",
32
32
  "@babel/preset-env": "^7.29.7",
33
33
  "@cypress/webpack-preprocessor": "^8.0.0",
34
34
  "@eslint/js": "^9.39.5",
35
- "@types/node": "^26.6.3",
35
+ "@types/node": "^26.6.4",
36
36
  "babel-loader": "^10.0.0",
37
37
  "c8": "^12.0.0",
38
38
  "chai": "^6.2.2",
39
39
  "cross-env": "^10.0.0",
40
- "cypress": "^16.1.0",
40
+ "cypress": "^16.1.1",
41
41
  "eslint": "^9.39.4",
42
42
  "eslint-plugin-cypress": "^6.4.4",
43
- "globals": "^17.12.0",
43
+ "globals": "^17.13.0",
44
44
  "husky": "^9.0.11",
45
45
  "linkedom": "^0.18.13",
46
- "mocha": "^12.0.2",
46
+ "mocha": "^12.0.3",
47
47
  "npm-run-all2": "^9.0.3",
48
48
  "rimraf": "^5.0.5",
49
49
  "string-replace-loader": "^3.1.0",
package/src/canon-tags.js CHANGED
@@ -60,10 +60,11 @@ function read(
60
60
  function parseShotInfo(shotInfoData) {
61
61
  const tags = {};
62
62
 
63
- if (shotInfoData[SHOT_INFO_AUTO_ROTATE] !== undefined) {
63
+ const autoRotate = shotInfoData[SHOT_INFO_AUTO_ROTATE];
64
+ if (Number.isFinite(autoRotate)) {
64
65
  tags['AutoRotate'] = {
65
- value: shotInfoData[SHOT_INFO_AUTO_ROTATE],
66
- description: getAutoRotateDescription(shotInfoData[SHOT_INFO_AUTO_ROTATE])
66
+ value: autoRotate,
67
+ description: getAutoRotateDescription(autoRotate)
67
68
  };
68
69
  }
69
70
 
package/src/composite.js CHANGED
@@ -26,14 +26,13 @@ function get(tags, expanded) {
26
26
  const compositeTags = {};
27
27
  let hasCompositeTags = false;
28
28
 
29
- const focalLength = getTagValue(tags, 'exif', 'FocalLength', expanded);
30
- const focalPlaneXResolution = getTagValue(tags, 'exif', 'FocalPlaneXResolution', expanded);
31
- const focalPlaneYResolution = getTagValue(tags, 'exif', 'FocalPlaneYResolution', expanded);
32
- const focalPlaneResolutionUnit = getTagValue(tags, 'exif', 'FocalPlaneResolutionUnit', expanded);
33
- const imageWidth = getTagValue(tags, 'file', 'Image Width', expanded);
34
- const imageHeight = getTagValue(tags, 'file', 'Image Height', expanded);
35
- const focalLengthIn35mmFilm = getTagValue(tags, 'exif', 'FocalLengthIn35mmFilm', expanded)
36
- || getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, imageWidth, imageHeight, focalLength);
29
+ const focalLength = getPositiveRational(getTagValue(tags, 'exif', 'FocalLength', expanded));
30
+ const focalPlaneXResolution = getPositiveRational(getTagValue(tags, 'exif', 'FocalPlaneXResolution', expanded));
31
+ const focalPlaneYResolution = getPositiveRational(getTagValue(tags, 'exif', 'FocalPlaneYResolution', expanded));
32
+ const focalPlaneResolutionUnit = getPositiveNumber(getTagValue(tags, 'exif', 'FocalPlaneResolutionUnit', expanded));
33
+ const pixelDimensions = getPixelDimensions(tags, expanded);
34
+ const focalLengthIn35mmFilm = getPositiveNumber(getTagValue(tags, 'exif', 'FocalLengthIn35mmFilm', expanded))
35
+ || getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, pixelDimensions.width, pixelDimensions.height, focalLength);
37
36
 
38
37
  if (focalLengthIn35mmFilm) {
39
38
  compositeTags.FocalLength35efl = {
@@ -72,14 +71,70 @@ function getTagValue(tags, group, tagName, expanded) {
72
71
  return undefined;
73
72
  }
74
73
 
74
+ /**
75
+ * Converts an Exif `[numerator, denominator]` array, an XMP `'n/d'` string,
76
+ * or a plain number or numeric string to a number.
77
+ *
78
+ * @returns {number|undefined} The number, or undefined when it, or either part
79
+ * of a rational, is not finite and positive.
80
+ */
81
+ function getPositiveRational(value) {
82
+ if (typeof value === 'string') {
83
+ // The limit keeps a long run of slashes from allocating one part per slash.
84
+ const parts = value.split('/', 3);
85
+ if (parts.length === 1) {
86
+ return getPositiveNumber(value);
87
+ }
88
+ return getPositiveQuotient(parts);
89
+ }
90
+ if (Array.isArray(value)) {
91
+ return getPositiveQuotient(value);
92
+ }
93
+ return getPositiveNumber(value);
94
+ }
95
+
96
+ /**
97
+ * @returns {number|undefined} The value as a number when it is a number or a
98
+ * numeric string that is finite and positive, otherwise undefined.
99
+ */
100
+ function getPositiveNumber(value) {
101
+ let number;
102
+ if (typeof value === 'number') {
103
+ number = value;
104
+ } else if (typeof value === 'string') {
105
+ number = Number(value);
106
+ }
107
+ return number > 0 && number < Infinity ? number : undefined;
108
+ }
109
+
110
+ function getPositiveQuotient(parts) {
111
+ if (parts.length !== 2) {
112
+ return undefined;
113
+ }
114
+ return getPositiveNumber(getPositiveNumber(parts[0]) / getPositiveNumber(parts[1]));
115
+ }
116
+
117
+ function getPixelDimensions(tags, expanded) {
118
+ const pixelXDimension = getPositiveNumber(getTagValue(tags, 'exif', 'PixelXDimension', expanded));
119
+ const pixelYDimension = getPositiveNumber(getTagValue(tags, 'exif', 'PixelYDimension', expanded));
120
+ if (pixelXDimension && pixelYDimension) {
121
+ return {width: pixelXDimension, height: pixelYDimension};
122
+ }
123
+ return {
124
+ width: getPositiveNumber(getTagValue(tags, 'file', 'Image Width', expanded)),
125
+ height: getPositiveNumber(getTagValue(tags, 'file', 'Image Height', expanded))
126
+ };
127
+ }
128
+
75
129
  /**
76
130
  * Calculates the 35mm equivalent focal length from camera sensor data.
77
131
  *
78
132
  * This function determines how the field of view of a camera's sensor compares to a
79
133
  * standard 35mm film frame (36mm × 24mm). The conversion involves:
80
134
  *
81
- * 1. **Sensor dimensions**: Calculated from image pixel count and focal plane
82
- * resolution (pixels per unit area)
135
+ * 1. **Sensor dimensions**: The original image size in pixels (PixelXDimension and
136
+ * PixelYDimension, or the file's size when absent) divided by the focal plane
137
+ * resolution (pixels per unit length)
83
138
  * 2. **Crop factor**: The ratio between the sensor diagonal and the standard
84
139
  * 35mm diagonal (43.27mm)
85
140
  * 3. **Equivalent focal length**: Actual focal length multiplied by the crop factor
@@ -88,53 +143,47 @@ function getTagValue(tags, group, tagName, expanded) {
88
143
  * field of view of a 75mm lens on a 35mm camera. This doesn't change the actual
89
144
  * focal length or depth of field characteristics, only the angle of view.
90
145
  */
91
- function getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, imageWidth, imageHeight, focalLength) {
146
+ function getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, pixelWidth, pixelHeight, focalLength) {
92
147
  // Standard 35mm film diagonal is 43.27mm (calculated from 36mm x 24mm frame)
93
148
  const DIAGONAL_35mm = 43.27;
94
149
 
95
- if (focalPlaneXResolution && focalPlaneYResolution && focalPlaneResolutionUnit && imageWidth && imageHeight && focalLength) {
96
- try {
97
- let resolutionUnitFactor;
98
- switch (focalPlaneResolutionUnit) {
99
- case FOCAL_PLANE_RESOLUTION_UNIT.INCHES:
100
- resolutionUnitFactor = UNIT_FACTORS.INCHES_TO_MM;
101
- break;
102
- case FOCAL_PLANE_RESOLUTION_UNIT.CENTIMETERS:
103
- resolutionUnitFactor = UNIT_FACTORS.CM_TO_MM;
104
- break;
105
- case FOCAL_PLANE_RESOLUTION_UNIT.MILLIMETERS:
106
- resolutionUnitFactor = UNIT_FACTORS.MM_TO_MM;
107
- break;
108
- default:
109
- return undefined;
110
- }
111
-
112
- const focalPlaneXResolutionMm = focalPlaneXResolution[0] / focalPlaneXResolution[1] * resolutionUnitFactor;
113
- const focalPlaneYResolutionMm = focalPlaneYResolution[0] / focalPlaneYResolution[1] * resolutionUnitFactor;
114
-
115
- const sensorWidthMm = imageWidth / focalPlaneXResolutionMm;
116
- const sensorHeightMm = imageHeight / focalPlaneYResolutionMm;
117
-
118
- const sensorDiagonal = Math.sqrt(sensorWidthMm ** 2 + sensorHeightMm ** 2);
119
- const focalLength35mm = (focalLength[0] / focalLength[1]) * (DIAGONAL_35mm / sensorDiagonal);
120
- return focalLength35mm;
121
- } catch (error) {
122
- // Ignore.
150
+ if (focalPlaneXResolution && focalPlaneYResolution && focalPlaneResolutionUnit && pixelWidth && pixelHeight && focalLength) {
151
+ let resolutionUnitFactor;
152
+ switch (focalPlaneResolutionUnit) {
153
+ case FOCAL_PLANE_RESOLUTION_UNIT.INCHES:
154
+ resolutionUnitFactor = UNIT_FACTORS.INCHES_TO_MM;
155
+ break;
156
+ case FOCAL_PLANE_RESOLUTION_UNIT.CENTIMETERS:
157
+ resolutionUnitFactor = UNIT_FACTORS.CM_TO_MM;
158
+ break;
159
+ case FOCAL_PLANE_RESOLUTION_UNIT.MILLIMETERS:
160
+ resolutionUnitFactor = UNIT_FACTORS.MM_TO_MM;
161
+ break;
162
+ default:
163
+ return undefined;
123
164
  }
165
+
166
+ const focalPlaneXResolutionMm = focalPlaneXResolution / resolutionUnitFactor;
167
+ const focalPlaneYResolutionMm = focalPlaneYResolution / resolutionUnitFactor;
168
+
169
+ const sensorWidthMm = pixelWidth / focalPlaneXResolutionMm;
170
+ const sensorHeightMm = pixelHeight / focalPlaneYResolutionMm;
171
+
172
+ const sensorDiagonal = Math.sqrt(sensorWidthMm ** 2 + sensorHeightMm ** 2);
173
+ const focalLength35mm = focalLength * (DIAGONAL_35mm / sensorDiagonal);
174
+ return getPositiveNumber(focalLength35mm);
124
175
  }
125
176
  return undefined;
126
177
  }
127
178
 
128
179
  function getScaleFactorTo35mmEquivalent(focalLength, focalLengthIn35mmFilm) {
129
180
  if (focalLength && focalLengthIn35mmFilm) {
130
- try {
131
- const value = focalLengthIn35mmFilm / (focalLength[0] / focalLength[1]);
181
+ const value = getPositiveNumber(focalLengthIn35mmFilm / focalLength);
182
+ if (value) {
132
183
  return {
133
184
  value,
134
185
  description: value.toFixed(1),
135
186
  };
136
- } catch (error) {
137
- // Ignore.
138
187
  }
139
188
  }
140
189
  return undefined;
@@ -144,14 +193,12 @@ function getFieldOfView(focalLengthIn35mmFilm) {
144
193
  const FULL_FRAME_SENSOR_WIDTH_MM = 36;
145
194
 
146
195
  if (focalLengthIn35mmFilm) {
147
- try {
148
- const value = 2 * Math.atan(FULL_FRAME_SENSOR_WIDTH_MM / (2 * focalLengthIn35mmFilm)) * (180 / Math.PI);
196
+ const value = getPositiveNumber(2 * Math.atan(FULL_FRAME_SENSOR_WIDTH_MM / (2 * focalLengthIn35mmFilm)) * (180 / Math.PI));
197
+ if (value) {
149
198
  return {
150
199
  value,
151
200
  description: value.toFixed(1) + ' deg',
152
201
  };
153
- } catch (error) {
154
- // Ignore.
155
202
  }
156
203
  }
157
204
  return undefined;
@@ -8,7 +8,7 @@
8
8
  */
9
9
  /* global Buffer */
10
10
 
11
- import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getStringValueFromArray, assertPromiseSupport, setProperty} from './utils.js';
11
+ import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getByteString, getStringValueFromArray, assertPromiseSupport, setProperty} from './utils.js';
12
12
  import {isFilePathOrURL, isBrowserFileObject, loadFile, loadFileObject} from './file-loaders.js';
13
13
  import {makeLoadAuto, validateAutoOptions} from './load-auto.js';
14
14
  import Constants from './constants.js';
@@ -17,7 +17,7 @@ import ByteOrder from './byte-order.js';
17
17
  import {getTiffHeaderOffset} from './image-header-iso-bmff.js';
18
18
  import ImageHeader from './image-header.js';
19
19
  import Tags from './tags.js';
20
- import {getValueBudget} from './tags-helpers.js';
20
+ import {getValueBudget, addDecompressedValueAllowance} from './tags-helpers.js';
21
21
  import MpfTags from './mpf-tags.js';
22
22
  import FileTags from './file-tags.js';
23
23
  import JxlFileTags from './jxl-file-tags.js';
@@ -39,6 +39,11 @@ import {createTagFilter} from './tag-filter.js';
39
39
  import {buildTagsFromMergeSteps, isThenable} from './loadview-pipeline.js';
40
40
  import exifErrors from './errors.js';
41
41
 
42
+ // Brob XMP is bounded by the file size, as brob Exif is, plus room for one JPEG
43
+ // standard XMP segment so that a small file can still carry a typical packet.
44
+ const BROB_XMP_SIZE_PER_INPUT_SIZE = 4;
45
+ const BROB_XMP_SIZE_ALLOWANCE = 64 * 1024;
46
+
42
47
  export default {
43
48
  load,
44
49
  loadView,
@@ -216,7 +221,8 @@ export function loadView(
216
221
  parsedExifTags['IPTC-NAA'].value,
217
222
  0,
218
223
  includeUnknown,
219
- tagFilter
224
+ tagFilter,
225
+ valueBudget
220
226
  );
221
227
  const parsedIptcTags =
222
228
  filterTagsForParse('iptc', readIptcTags, tagFilter);
@@ -234,12 +240,12 @@ export function loadView(
234
240
  if (
235
241
  Constants.USE_XMP
236
242
  && parsedExifTags['ApplicationNotes']
237
- && Array.isArray(parsedExifTags['ApplicationNotes'].value)
243
+ && isNumberArray(parsedExifTags['ApplicationNotes'].value)
238
244
  && !hasXmpData(xmpChunks)
239
245
  && tagFilter.shouldParseGroup('xmp')
240
246
  ) {
241
247
  const readXmpTags = XmpTags.read(
242
- getStringValueFromArray(parsedExifTags['ApplicationNotes'].value),
248
+ getByteString(parsedExifTags['ApplicationNotes'].value),
243
249
  undefined,
244
250
  domParser
245
251
  );
@@ -385,7 +391,7 @@ export function loadView(
385
391
  && iptcDataOffset !== undefined
386
392
  && tagFilter.shouldParseGroup('iptc')
387
393
  ) {
388
- const readTags = IptcTags.read(dataView, iptcDataOffset, includeUnknown, tagFilter);
394
+ const readTags = IptcTags.read(dataView, iptcDataOffset, includeUnknown, tagFilter, valueBudget);
389
395
  const parsedIptcTags = filterTagsForParse('iptc', readTags, tagFilter);
390
396
  parsedGroups.iptc = parsedIptcTags;
391
397
 
@@ -428,6 +434,7 @@ export function loadView(
428
434
  decompress(compressedExifData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
429
435
  .then((decompressedDataView) => {
430
436
  const brobTiffHeaderOffset = getTiffHeaderOffset(decompressedDataView, 0);
437
+ addDecompressedValueAllowance(valueBudget, decompressedDataView.byteLength);
431
438
  const {tags: readTags} = Tags.read(
432
439
  decompressedDataView,
433
440
  brobTiffHeaderOffset,
@@ -439,6 +446,9 @@ export function loadView(
439
446
  if (readTags.Thumbnail) {
440
447
  delete readTags.Thumbnail;
441
448
  }
449
+ if (readTags.MakerNote) {
450
+ delete readTags.MakerNote.__offset;
451
+ }
442
452
  deferredResults.brobExif = readTags;
443
453
  })
444
454
  .catch(() => {
@@ -463,6 +473,10 @@ export function loadView(
463
473
  deferredPromises.push(
464
474
  decompress(compressedXmpData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
465
475
  .then((decompressedDataView) => {
476
+ if (exceedsBrobXmpSizeBound(decompressedDataView, dataView)) {
477
+ deferredResults.brobXmp = {};
478
+ return;
479
+ }
466
480
  deferredResults.brobXmp = XmpTags.read(
467
481
  decompressedDataView,
468
482
  [{dataOffset: 0, length: decompressedDataView.byteLength}],
@@ -562,7 +576,7 @@ export function loadView(
562
576
  || tagFilter.shouldParseGroup('iptc')
563
577
  )
564
578
  ) {
565
- const {readTags, readTagsPromise} = PngTextTags.read(
579
+ const {readTags, embeddedExifTags, embeddedIptcTags, embeddedExifThumbnail, readTagsPromise} = PngTextTags.read(
566
580
  dataView,
567
581
  pngTextChunks,
568
582
  async,
@@ -570,13 +584,17 @@ export function loadView(
570
584
  computed,
571
585
  tagFilter,
572
586
  decompressConfig,
573
- valueBudget
587
+ valueBudget,
588
+ getPngTextThumbnailReader(tagFilter)
574
589
  );
575
590
  pngTextIsAsync = !!readTagsPromise;
576
591
 
577
592
  mergeSteps.push({
578
593
  type: 'processPngTextReadTags',
579
594
  readTags,
595
+ embeddedExifTags,
596
+ embeddedIptcTags,
597
+ embeddedExifThumbnail,
580
598
  });
581
599
 
582
600
  if (readTagsPromise) {
@@ -779,7 +797,20 @@ function getBrobDataView(dataView, brobChunk) {
779
797
  // than its header, so bound the view by the bytes present. The JXL header
780
798
  // parser never reports a dataOffset past the end of the view.
781
799
  const length = Math.max(0, Math.min(brobChunk.length, dataView.byteLength - brobChunk.dataOffset));
782
- return new DataView(dataView.buffer, dataView.byteOffset + brobChunk.dataOffset, length);
800
+ if (isDataViewLike(dataView)) {
801
+ return new DataView(dataView.buffer, dataView.byteOffset + brobChunk.dataOffset, length);
802
+ }
803
+ // The Node Buffer wrapper has no ArrayBuffer to view, so copy the bytes out.
804
+ const bytes = new Uint8Array(length);
805
+ for (let i = 0; i < length; i++) {
806
+ bytes[i] = dataView.getUint8(brobChunk.dataOffset + i);
807
+ }
808
+ return new DataView(bytes.buffer);
809
+ }
810
+
811
+ function exceedsBrobXmpSizeBound(decompressedDataView, inputDataView) {
812
+ return decompressedDataView.byteLength
813
+ > BROB_XMP_SIZE_PER_INPUT_SIZE * inputDataView.byteLength + BROB_XMP_SIZE_ALLOWANCE;
783
814
  }
784
815
 
785
816
  function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter) {
@@ -800,6 +831,21 @@ function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed
800
831
  }
801
832
  }
802
833
 
834
+ function getPngTextThumbnailReader(tagFilter) {
835
+ if (
836
+ !Constants.USE_EXIF
837
+ || !Constants.USE_THUMBNAIL
838
+ || !tagFilter.shouldReturnTag('thumbnail', 'Thumbnail')
839
+ ) {
840
+ return undefined;
841
+ }
842
+ return (dataView, thumbnailIfdTags, tiffHeaderOffset) => Thumbnail.get(
843
+ dataView,
844
+ filterTagsForParse('thumbnail', thumbnailIfdTags, tagFilter),
845
+ tiffHeaderOffset
846
+ );
847
+ }
848
+
803
849
  function filterTagsForParse(groupKey, readTags, tagFilter) {
804
850
  if (!tagFilter.isActive) {
805
851
  return readTags;
@@ -973,6 +1019,12 @@ function getGpsGroupFromExifTags(exifTags) {
973
1019
  return gps;
974
1020
  }
975
1021
 
1022
+ // ASCII values hold strings and holes, values of two or more rationals hold
1023
+ // number pairs: neither converts to the character codes of an XMP packet.
1024
+ function isNumberArray(value) {
1025
+ return Array.isArray(value) && typeof value[0] === 'number';
1026
+ }
1027
+
976
1028
  function hasXmpData(xmpChunks) {
977
1029
  return Array.isArray(xmpChunks) && xmpChunks.length > 0;
978
1030
  }
@@ -32,23 +32,30 @@ export function isDataUri(filename) {
32
32
  * in `load()`.
33
33
  *
34
34
  * @param {string} filename URL, data URI, or local file path.
35
- * @param {{length?: number}} [options]
36
- * @returns {Promise<ArrayBuffer|Buffer>} The whole file, or its first `length` bytes if specified.
35
+ * @param {{length?: number}} [options] A fractional `length` is rounded down.
36
+ * @returns {Promise<ArrayBuffer|Buffer>} The whole file, or its first `length` bytes if specified. Rejects when
37
+ * `length` is not `undefined`, `null` or a finite non-negative number, and with the decoder's error when a
38
+ * data URI cannot be decoded.
37
39
  */
38
40
  export function loadFile(filename, options) {
41
+ const range = legacyRange(options);
42
+ if (!range) {
43
+ return rejectInvalidLength();
44
+ }
45
+
39
46
  if (/^\w+:\/\//.test(filename)) {
40
47
  if (typeof fetch !== 'undefined') {
41
- return fetchRange(filename, legacyRange(options)).then((r) => r.buffer);
48
+ return fetchRange(filename, range).then((r) => r.buffer);
42
49
  }
43
50
 
44
- return nodeGetRange(filename, legacyRange(options)).then((r) => r.buffer);
51
+ return nodeGetRange(filename, range).then((r) => r.buffer);
45
52
  }
46
53
 
47
54
  if (isDataUri(filename)) {
48
- return Promise.resolve(dataUriToBuffer(filename));
55
+ return Promise.resolve().then(() => dataUriToBuffer(filename));
49
56
  }
50
57
 
51
- return readLocalFileRange(filename, legacyRange(options)).then((r) => r.buffer);
58
+ return readLocalFileRange(filename, range).then((r) => r.buffer);
52
59
  }
53
60
 
54
61
  /**
@@ -56,18 +63,32 @@ export function loadFile(filename, options) {
56
63
  * code path in `load()`.
57
64
  *
58
65
  * @param {File} file
59
- * @param {{length?: number}} [options]
60
- * @returns {Promise<ArrayBuffer>}
66
+ * @param {{length?: number}} [options] A fractional `length` is rounded down.
67
+ * @returns {Promise<ArrayBuffer>} Rejects when `length` is not `undefined`, `null` or a finite non-negative number.
61
68
  */
62
69
  export function loadFileObject(file, options) {
63
- return readFileObjectRange(file, legacyRange(options)).then((r) => r.buffer);
70
+ const range = legacyRange(options);
71
+ if (!range) {
72
+ return rejectInvalidLength();
73
+ }
74
+
75
+ return readFileObjectRange(file, range).then((r) => r.buffer);
64
76
  }
65
77
 
66
78
  function legacyRange(options) {
67
- if (options && Number.isInteger(options.length) && options.length >= 0) {
68
- return {start: 0, end: options.length, maxBytes: options.length};
79
+ const length = options ? options.length : undefined;
80
+ if (length === undefined || length === null) {
81
+ return {start: 0};
69
82
  }
70
- return {start: 0};
83
+ if (Number.isFinite(length) && length >= 0) {
84
+ const end = Math.floor(length);
85
+ return {start: 0, end, maxBytes: end};
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ function rejectInvalidLength() {
91
+ return Promise.reject(new Error('The length option must be a finite non-negative number or "auto".'));
71
92
  }
72
93
 
73
94
  /**
@@ -76,15 +97,21 @@ function legacyRange(options) {
76
97
  *
77
98
  * @param {string} url
78
99
  * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
79
- * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are kept, for a 2xx
80
- * status and for 416; where the response body is a `ReadableStream` the transfer is stopped once they have
81
- * arrived, otherwise the whole body is read and cut.
100
+ * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are kept on a 2xx
101
+ * response; where the response body is a `ReadableStream` the transfer is stopped once they have arrived,
102
+ * otherwise the whole body is read and cut.
82
103
  * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined, status: number|undefined}>}
83
104
  * `totalSize` is taken from the `Content-Range` or `Content-Length` response header when present.
84
105
  * Rejects with `Could not fetch file: <status>` on non-2xx responses, except 416 which the
85
- * `length: 'auto'` loop consumes as a fall-back signal. Mirrors `nodeGetRange`.
106
+ * `length: 'auto'` loop consumes as a fall-back signal and which resolves with an empty buffer.
107
+ * The body of a 416 or a rejected status is never read; a `ReadableStream` body is cancelled.
108
+ * An empty range (`end <= start`) resolves with an empty buffer without a request.
109
+ * Mirrors `nodeGetRange`.
86
110
  */
87
111
  export function fetchRange(url, {start = 0, end, maxBytes} = {}) {
112
+ if (isEmptyRange(start, end)) {
113
+ return Promise.resolve({buffer: new ArrayBuffer(0), totalSize: undefined, status: undefined});
114
+ }
88
115
  const options = {method: 'GET'};
89
116
  if (start > 0 || (end !== undefined && end !== Infinity)) {
90
117
  options.headers = {range: buildRangeHeader(start, end)};
@@ -92,10 +119,15 @@ export function fetchRange(url, {start = 0, end, maxBytes} = {}) {
92
119
  return fetch(url, options).then((response) => {
93
120
  const status = response && typeof response.status === 'number' ? response.status : undefined;
94
121
  if (status !== undefined && !isAcceptableFetchStatus(status)) {
122
+ cancelQuietly(response.body);
95
123
  const statusText = response.statusText || '';
96
124
  return Promise.reject(new Error(`Could not fetch file: ${status} ${statusText}`.trim()));
97
125
  }
98
126
  const totalSize = totalSizeFromFetchResponse(response);
127
+ if (status === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
128
+ cancelQuietly(response.body);
129
+ return {buffer: new ArrayBuffer(0), totalSize, status};
130
+ }
99
131
  return readFetchBody(response, maxBytes).then((buffer) => ({buffer, totalSize, status}));
100
132
  });
101
133
  }
@@ -146,8 +178,8 @@ function readStreamUpTo(reader, maxBytes) {
146
178
  });
147
179
  }
148
180
 
149
- function cancelQuietly(reader) {
150
- Promise.resolve().then(() => reader.cancel()).then(undefined, () => undefined);
181
+ function cancelQuietly(cancellable) {
182
+ Promise.resolve().then(() => cancellable.cancel()).then(undefined, () => undefined);
151
183
  }
152
184
 
153
185
  /**
@@ -189,6 +221,10 @@ function createByteCollector(maxBytes) {
189
221
  }
190
222
  }
191
223
 
224
+ function isEmptyRange(start, end) {
225
+ return end !== undefined && end !== Infinity && end <= start;
226
+ }
227
+
192
228
  function buildRangeHeader(start, end) {
193
229
  if (end === undefined || end === Infinity) {
194
230
  return `bytes=${start}-`;
@@ -214,7 +250,9 @@ function isAcceptableFetchStatus(status) {
214
250
 
215
251
  /**
216
252
  * Range-aware Node `http(s).get`. Same contract as `fetchRange`. Rejects
217
- * on non-2xx responses with the status line in the error message.
253
+ * on non-2xx responses with the status line in the error message, except
254
+ * 416 which resolves with an empty buffer. The body of a 416 or a rejected
255
+ * status is not read: the response is destroyed.
218
256
  *
219
257
  * @param {string} url
220
258
  * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
@@ -223,6 +261,9 @@ function isAcceptableFetchStatus(status) {
223
261
  * @returns {Promise<{buffer: Buffer, totalSize: number|undefined, status: number|undefined}>}
224
262
  */
225
263
  export function nodeGetRange(url, {start = 0, end, maxBytes} = {}) {
264
+ if (isEmptyRange(start, end)) {
265
+ return Promise.resolve({buffer: Buffer.alloc(0), totalSize: undefined, status: undefined});
266
+ }
226
267
  return new Promise((resolve, reject) => {
227
268
  const options = {};
228
269
  if (start > 0 || (end !== undefined && end !== Infinity)) {
@@ -252,11 +293,12 @@ export function nodeGetRange(url, {start = 0, end, maxBytes} = {}) {
252
293
  } else if (response.statusCode === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
253
294
  // Resolve (rather than reject) so the adaptive `length: 'auto'`
254
295
  // loop can fall back to a full read, mirroring the fetch path.
255
- response.resume();
256
- resolve({buffer: Buffer.alloc(0), totalSize: totalSizeFromNodeResponse(response), status: response.statusCode});
296
+ const totalSize = totalSizeFromNodeResponse(response);
297
+ response.destroy();
298
+ resolve({buffer: Buffer.alloc(0), totalSize, status: response.statusCode});
257
299
  } else {
258
300
  reject(new Error(`Could not fetch file: ${response.statusCode} ${response.statusMessage}`));
259
- response.resume();
301
+ response.destroy();
260
302
  }
261
303
  }).on('error', (error) => reject(error));
262
304
  });
@@ -2,7 +2,7 @@
2
2
  * License, v. 2.0. If a copy of the MPL was not distributed with this
3
3
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
4
 
5
- import {getStringFromDataView} from './utils.js';
5
+ import {getByteString, getStringFromDataView} from './utils.js';
6
6
 
7
7
  export const iccTags = {
8
8
  'desc': {
@@ -119,17 +119,8 @@ function parseDate(dataView, offset) {
119
119
  return new Date(Date.UTC(year, month, day, hours, minutes, seconds));
120
120
  }
121
121
 
122
- // Engines cap the number of arguments Function.prototype.apply can pass
123
- // through, so a large slice is converted in fixed-size chunks.
124
- const MAX_CHARS_PER_CALL = 8192;
125
-
126
122
  export function sliceToString(slice) {
127
- const bytes = new Uint8Array(slice);
128
- const chunks = [];
129
- for (let offset = 0; offset < bytes.length; offset += MAX_CHARS_PER_CALL) {
130
- chunks.push(String.fromCharCode.apply(null, bytes.subarray(offset, offset + MAX_CHARS_PER_CALL)));
131
- }
132
- return chunks.join('');
123
+ return getByteString(new Uint8Array(slice));
133
124
  }
134
125
 
135
126
  function toCompany(value) {