exifreader 4.46.0 → 4.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@
4
4
 
5
5
  // Specification: http://www.libpng.org/pub/png/spec/1.2/
6
6
 
7
- import {getStringValueFromArray, getStringFromDataView, decompress, COMPRESSION_METHOD_NONE} from './utils.js';
7
+ import {getStringValueFromArray, getStringFromDataView, decompress, setProperty, COMPRESSION_METHOD_NONE} from './utils.js';
8
8
  import TagDecoder from './tag-decoder.js';
9
9
  import {TYPE_TEXT, TYPE_ITXT, TYPE_ZTXT} from './image-header-png.js';
10
10
  import Tags from './tags.js';
@@ -24,6 +24,8 @@ const STATE_TEXT = 'STATE_TEXT';
24
24
  const COMPRESSION_SECTION_ITXT_EXTRA_BYTE = 1;
25
25
  const COMPRESSION_FLAG_COMPRESSED = 1;
26
26
  const EXIF_OFFSET = 6;
27
+ const MAX_COMPRESSED_TEXT_CHUNKS = 255;
28
+ const MAX_DECOMPRESSIONS_IN_FLIGHT = 4;
27
29
 
28
30
  function read(
29
31
  dataView,
@@ -32,76 +34,36 @@ function read(
32
34
  includeUnknown,
33
35
  computed = false,
34
36
  tagFilter = NOOP_TAG_FILTER,
35
- decompressConfig
37
+ decompressConfig,
38
+ valueBudget
36
39
  ) {
37
40
  const tags = {};
38
- const tagsPromises = [];
41
+ const decompressionTasks = [];
39
42
 
40
43
  for (let i = 0; i < pngTextChunks.length; i++) {
41
44
  const {offset, length, type} = pngTextChunks[i];
42
- const nameAndValue = getNameAndValue(dataView, offset, length, type, async, decompressConfig);
43
- if (nameAndValue instanceof Promise) {
44
- tagsPromises.push(nameAndValue.then(({name, value, description}) => {
45
- try {
46
- if (Constants.USE_EXIF && isExifGroupTag(name, value)) {
47
- if (!tagFilter.shouldParseGroup('exif')) {
48
- return {};
49
- }
50
- return {
51
- __exif: Tags.read(
52
- decodeRawData(value),
53
- EXIF_OFFSET,
54
- includeUnknown,
55
- computed,
56
- tagFilter
57
- ).tags
58
- };
59
- } else if (Constants.USE_IPTC && isIptcGroupTag(name, value)) {
60
- if (!tagFilter.shouldParseGroup('iptc')) {
61
- return {};
62
- }
63
- return {
64
- __iptc: IptcTags.read(
65
- decodeRawData(value),
66
- 0,
67
- includeUnknown,
68
- tagFilter
69
- )
70
- };
71
- } else if (name && !isExifGroupTag(name, value) && !isIptcGroupTag(name, value)) {
72
- if (!tagFilter.shouldParseGroup('png')) {
73
- return {};
74
- }
75
- return {
76
- [name]: {
77
- value,
78
- description
79
- }
80
- };
81
- }
82
- } catch (error) {
83
- // Ignore the broken tag.
84
- }
85
- return {};
86
- }));
87
- } else {
88
- const {name, value, description} = nameAndValue;
45
+ const textChunk = parseTextChunk(dataView, offset, length, type);
46
+ if (textChunk.compressionMethod === COMPRESSION_METHOD_NONE) {
47
+ const {name, value, description} = getUncompressedTag(textChunk);
89
48
  if (name && tagFilter.shouldParseGroup('png')) {
90
- tags[name] = {
49
+ setProperty(tags, name, {
91
50
  value,
92
51
  description
93
- };
52
+ });
94
53
  }
54
+ } else if (async && decompressionTasks.length < MAX_COMPRESSED_TEXT_CHUNKS) {
55
+ decompressionTasks.push(() => decompressTextChunk(textChunk, decompressConfig)
56
+ .then((tag) => getTagsFromDecompressedTag(tag, includeUnknown, computed, tagFilter, valueBudget)));
95
57
  }
96
58
  }
97
59
 
98
60
  return {
99
61
  readTags: tags,
100
- readTagsPromise: tagsPromises.length > 0 ? Promise.all(tagsPromises) : undefined
62
+ readTagsPromise: decompressionTasks.length > 0 ? runTasksInOrder(decompressionTasks, MAX_DECOMPRESSIONS_IN_FLIGHT) : undefined
101
63
  };
102
64
  }
103
65
 
104
- function getNameAndValue(dataView, offset, length, type, async, decompressConfig) {
66
+ function parseTextChunk(dataView, offset, length, type) {
105
67
  const keywordChars = [];
106
68
  const langChars = [];
107
69
  const translatedKeywordChars = [];
@@ -137,16 +99,87 @@ function getNameAndValue(dataView, offset, length, type, async, decompressConfig
137
99
  }
138
100
  }
139
101
 
140
- if (compressionMethod !== COMPRESSION_METHOD_NONE && !async) {
141
- return {};
102
+ return {type, keywordChars, langChars, compressionMethod, valueChars};
103
+ }
104
+
105
+ function getUncompressedTag({type, keywordChars, langChars, valueChars}) {
106
+ const decodedValueChars = decompress(valueChars, COMPRESSION_METHOD_NONE, getEncodingFromType(type), 'string');
107
+ return constructTag(decodedValueChars, type, langChars, keywordChars);
108
+ }
109
+
110
+ function decompressTextChunk({type, keywordChars, langChars, compressionMethod, valueChars}, decompressConfig) {
111
+ return decompress(valueChars, compressionMethod, getEncodingFromType(type), 'string', decompressConfig)
112
+ .then((decompressedValueChars) => constructTag(decompressedValueChars, type, langChars, keywordChars))
113
+ .catch(() => constructTag('<text using unknown compression>'.split(''), type, langChars, keywordChars));
114
+ }
115
+
116
+ function getTagsFromDecompressedTag({name, value, description}, includeUnknown, computed, tagFilter, valueBudget) {
117
+ try {
118
+ if (Constants.USE_EXIF && isExifGroupTag(name, value)) {
119
+ if (!tagFilter.shouldParseGroup('exif')) {
120
+ return {};
121
+ }
122
+ return {
123
+ embeddedExifTags: Tags.read(
124
+ decodeRawData(value),
125
+ EXIF_OFFSET,
126
+ includeUnknown,
127
+ computed,
128
+ tagFilter,
129
+ valueBudget
130
+ ).tags
131
+ };
132
+ } else if (Constants.USE_IPTC && isIptcGroupTag(name, value)) {
133
+ if (!tagFilter.shouldParseGroup('iptc')) {
134
+ return {};
135
+ }
136
+ return {
137
+ embeddedIptcTags: IptcTags.read(
138
+ decodeRawData(value),
139
+ 0,
140
+ includeUnknown,
141
+ tagFilter
142
+ )
143
+ };
144
+ } else if (name && !isExifGroupTag(name, value) && !isIptcGroupTag(name, value)) {
145
+ if (!tagFilter.shouldParseGroup('png')) {
146
+ return {};
147
+ }
148
+ const readTags = {};
149
+ setProperty(readTags, name, {
150
+ value,
151
+ description
152
+ });
153
+ return {readTags};
154
+ }
155
+ } catch (error) {
156
+ // Ignore the broken tag.
157
+ }
158
+ return {};
159
+ }
160
+
161
+ function runTasksInOrder(tasks, limit) {
162
+ const results = [];
163
+ const workers = [];
164
+ let nextIndex = 0;
165
+
166
+ for (let i = 0; i < Math.min(limit, tasks.length); i++) {
167
+ workers.push(runNext());
142
168
  }
143
- const decompressedValueChars = decompress(valueChars, compressionMethod, getEncodingFromType(type), 'string', decompressConfig);
144
- if (decompressedValueChars instanceof Promise) {
145
- return decompressedValueChars
146
- .then((_decompressedValueChars) => constructTag(_decompressedValueChars, type, langChars, keywordChars))
147
- .catch(() => constructTag('<text using unknown compression>'.split(''), type, langChars, keywordChars));
169
+ return Promise.all(workers).then(() => results);
170
+
171
+ function runNext() {
172
+ if (nextIndex >= tasks.length) {
173
+ return Promise.resolve();
174
+ }
175
+ const index = nextIndex++;
176
+ // The wrapper turns a synchronous throw from a task into a rejection
177
+ // that Promise.all observes, instead of an exception out of read().
178
+ return new Promise((resolve) => resolve(tasks[index]())).then((result) => {
179
+ results[index] = result;
180
+ return runNext();
181
+ });
148
182
  }
149
- return constructTag(decompressedValueChars, type, langChars, keywordChars);
150
183
  }
151
184
 
152
185
  function getCompressionMethod({type, dataView, offset}) {
@@ -3,7 +3,7 @@
3
3
  * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
4
 
5
5
  import TextDecoder from './text-decoder.js';
6
- import {decodeUtf8ByteString} from './utils.js';
6
+ import {decodeUtf8ByteString, tryDecodeUtf8ByteString} from './utils.js';
7
7
 
8
8
  const TAG_HEADER_SIZE = 5;
9
9
 
@@ -43,16 +43,16 @@ function decode(encoding, tagValue) {
43
43
  }
44
44
 
45
45
  const stringValue = tagValue.map((charCode) => String.fromCharCode(charCode)).join('');
46
- try {
47
- return decodeURIComponent(escape(stringValue));
48
- } catch (error) {
49
- // The bytes are not valid UTF-8. Many real-world IPTC blocks have no
50
- // Coded Character Set tag but use Windows-1252 (en/em dashes,
51
- // ellipsis, smart quotes, etc.). Remap the bytes through CP1252 so
52
- // those characters render correctly instead of staying as C1 control
53
- // characters.
54
- return decodeWindows1252(tagValue);
46
+ const decoded = tryDecodeUtf8ByteString(stringValue);
47
+ if (decoded !== undefined) {
48
+ return decoded;
55
49
  }
50
+ // The bytes are not valid UTF-8. Many real-world IPTC blocks have no
51
+ // Coded Character Set tag but use Windows-1252 (en/em dashes,
52
+ // ellipsis, smart quotes, etc.). Remap the bytes through CP1252 so
53
+ // those characters render correctly instead of staying as C1 control
54
+ // characters.
55
+ return decodeWindows1252(tagValue);
56
56
  }
57
57
 
58
58
  function decodeWindows1252(tagValue) {
package/src/tag-filter.js CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  FILTER_GROUPS,
7
7
  ID_CAPABLE_GROUPS,
8
8
  COMPOSITE_DEPENDENCY_TAGS,
9
+ EXIF_POINTER_TAGS,
9
10
  getExifTagDependenciesForInclude,
10
11
  } from './tag-filter-config.js';
11
12
 
@@ -181,6 +182,7 @@ function getExifIncludeDependencies(includeTags) {
181
182
 
182
183
  if (isGroupRequested(includeTags, 'composite')) {
183
184
  addRequiredTags(requiredTags, COMPOSITE_DEPENDENCY_TAGS.exif);
185
+ requiredTags[EXIF_POINTER_TAGS.exifIfdPointer] = true;
184
186
  }
185
187
 
186
188
  return requiredTags;
@@ -372,10 +372,22 @@ export default {
372
372
  };
373
373
 
374
374
  function decodeXPValue(value) {
375
+ if (!Array.isArray(value)) {
376
+ // A one-element value arrives as a bare number, which Uint8Array would take as a length.
377
+ return '';
378
+ }
375
379
  // The XP tags are encoded as UCS-2 which uses two bytes per character but
376
380
  // it's close to UTF-16 so we can use that to decode them.
377
381
  // https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml
378
382
  const decodedValue = new TextDecoder('utf-16').decode(new Uint8Array(value));
379
383
  // Some softwares pad the string with null characters so we remove them.
380
- return decodedValue.replace(/\u0000+$/, ''); // eslint-disable-line no-control-regex
384
+ return removeTrailingNulls(decodedValue);
385
+ }
386
+
387
+ function removeTrailingNulls(text) {
388
+ let end = text.length;
389
+ while (end > 0 && text.charCodeAt(end - 1) === 0) {
390
+ end--;
391
+ }
392
+ return text.slice(0, end);
381
393
  }
@@ -18,9 +18,12 @@ import {decodeUtf8ByteString} from './utils.js';
18
18
  // array element plus its share of the joined description string.
19
19
  const MAX_VALUE_SIZE_PER_BUFFER_SIZE = 4;
20
20
 
21
+ // Engines cap the number of arguments Function.prototype.apply can pass, and
22
+ // some older ones reject a typed array there, so bytes go in as plain chunks.
23
+ const MAX_CHARS_PER_CALL = 8192;
24
+
21
25
  const getTagValueAt = {
22
26
  1: Types.getByteAt,
23
- 2: Types.getAsciiAt,
24
27
  3: Types.getShortAt,
25
28
  4: Types.getLongAt,
26
29
  5: Types.getRationalAt,
@@ -132,6 +135,11 @@ export function readIfd(
132
135
  * to the input, which is what stops a crafted file from having thousands of
133
136
  * tags decode the same bytes over and over.
134
137
  *
138
+ * loadView shares one budget across the Exif IFDs, then the maker note, then
139
+ * MPF, then the Exif decompressed from PNG text chunks and JPEG XL brob boxes.
140
+ * Once it is used up, later out-of-slot values decode empty, Make included,
141
+ * and an empty Make or MakerNote turns maker note detection off.
142
+ *
135
143
  * @param {DataView} dataView - The buffer the values are decoded from.
136
144
  * @returns {{remaining: number}} The budget, in bytes left to decode.
137
145
  */
@@ -193,8 +201,7 @@ function readTag(
193
201
  }
194
202
 
195
203
  if (tagType === Types.tagTypes['ASCII']) {
196
- tagValue = splitNullSeparatedAsciiString(tagValue);
197
- tagValue = decodeAsciiValue(tagValue);
204
+ tagValue = getAsciiTagValue(tagValue);
198
205
  }
199
206
 
200
207
  let tagDescription = tagValue;
@@ -241,26 +248,35 @@ function tagValueFitsInOffsetSlot(tagType, tagCount) {
241
248
  }
242
249
 
243
250
  function getTagValue(dataView, offset, type, count, byteOrder, forceByteType = false) {
244
- let value = [];
251
+ const value = [];
245
252
 
246
253
  if (forceByteType) {
247
254
  count = count * Types.typeSizes[type];
248
255
  type = Types.tagTypes['BYTE'];
249
256
  }
257
+ if (type === Types.tagTypes['ASCII']) {
258
+ return getAsciiBytes(dataView, offset, count);
259
+ }
250
260
  for (let valueIndex = 0; valueIndex < count; valueIndex++) {
251
261
  value.push(getTagValueAt[type](dataView, offset, byteOrder));
252
262
  offset += Types.typeSizes[type];
253
263
  }
254
264
 
255
- if (type === Types.tagTypes['ASCII']) {
256
- value = Types.getAsciiValue(value);
257
- } else if (value.length === 1) {
258
- value = value[0];
265
+ if (value.length === 1) {
266
+ return value[0];
259
267
  }
260
268
 
261
269
  return value;
262
270
  }
263
271
 
272
+ function getAsciiBytes(dataView, offset, count) {
273
+ const bytes = new Uint8Array(count);
274
+ for (let i = 0; i < count; i++) {
275
+ bytes[i] = Types.getAsciiAt(dataView, offset + i);
276
+ }
277
+ return bytes;
278
+ }
279
+
264
280
  function tagValueFitsInDataView(dataView, offsetOrigin, tagValueOffset, tagType, tagCount) {
265
281
  return offsetOrigin + tagValueOffset + Types.typeSizes[tagType] * tagCount <= dataView.byteLength;
266
282
  }
@@ -279,26 +295,59 @@ function getBoundedTagCount(remainingBudget, tagType, tagCount) {
279
295
  return boundedCount;
280
296
  }
281
297
 
282
- function splitNullSeparatedAsciiString(string) {
283
- const tagValue = [];
284
- let i = 0;
298
+ function getAsciiTagValue(tagValue) {
299
+ if (tagValue instanceof Uint8Array) {
300
+ return getNullSeparatedStrings(tagValue);
301
+ }
302
+ if (typeof tagValue === 'string') {
303
+ return [tagValue];
304
+ }
305
+ // An IPTC-NAA value read as bytes: its numbers have always been joined
306
+ // into one string of decimal digits.
307
+ return tagValue.length > 0 ? [decodeUtf8ByteString(tagValue.join(''))] : [];
308
+ }
285
309
 
286
- for (let j = 0; j < string.length; j++) {
287
- if (string[j] === '\x00') {
288
- i++;
289
- continue;
290
- }
291
- if (tagValue[i] === undefined) {
292
- tagValue[i] = '';
310
+ // Empty strings are left as holes in the array, so each string keeps the
311
+ // index given by the number of NULs before it.
312
+ function getNullSeparatedStrings(bytes) {
313
+ const strings = [];
314
+ const charCodes = [];
315
+ let stringIndex = 0;
316
+ let stringStart = 0;
317
+
318
+ for (let i = 0; i <= bytes.length; i++) {
319
+ if (i === bytes.length || bytes[i] === 0) {
320
+ if (i > stringStart) {
321
+ strings[stringIndex] = decodeUtf8ByteString(getByteString(bytes, stringStart, i, charCodes));
322
+ }
323
+ stringIndex++;
324
+ stringStart = i + 1;
293
325
  }
294
- tagValue[i] += string[j];
295
326
  }
296
327
 
297
- return tagValue;
328
+ return strings;
329
+ }
330
+
331
+ function getByteString(bytes, start, end, charCodes) {
332
+ if (end - start <= MAX_CHARS_PER_CALL) {
333
+ return getChunkString(bytes, start, end, charCodes);
334
+ }
335
+
336
+ const chunks = [];
337
+ for (let chunkStart = start; chunkStart < end; chunkStart += MAX_CHARS_PER_CALL) {
338
+ chunks.push(getChunkString(bytes, chunkStart, Math.min(chunkStart + MAX_CHARS_PER_CALL, end), charCodes));
339
+ }
340
+ return chunks.join('');
298
341
  }
299
342
 
300
- function decodeAsciiValue(asciiValue) {
301
- return asciiValue.map((value) => decodeUtf8ByteString(value));
343
+ // Reuses the caller's array, so a value made of many short strings does not
344
+ // allocate an array per string.
345
+ function getChunkString(bytes, start, end, charCodes) {
346
+ for (let i = start; i < end; i++) {
347
+ charCodes[i - start] = bytes[i];
348
+ }
349
+ charCodes.length = end - start;
350
+ return String.fromCharCode.apply(null, charCodes);
302
351
  }
303
352
 
304
353
  function getDescriptionFromTagValue(tagValue) {
package/src/tags.js CHANGED
@@ -17,11 +17,19 @@ export default {
17
17
  read,
18
18
  };
19
19
 
20
- function read(dataView, tiffHeaderOffset, includeUnknown, computed = false, tagFilter = undefined) {
20
+ // One decoded-value budget is shared by the 0th, sub-, and thumbnail IFD reads
21
+ // so their combined decoded values stay proportional to the input. A caller
22
+ // passes its own to share it with later reads (loadView: maker note, MPF
23
+ // and decompressed Exif).
24
+ function read(
25
+ dataView,
26
+ tiffHeaderOffset,
27
+ includeUnknown,
28
+ computed = false,
29
+ tagFilter = undefined,
30
+ valueBudget = getValueBudget(dataView)
31
+ ) {
21
32
  const byteOrder = ByteOrder.getByteOrder(dataView, tiffHeaderOffset);
22
- // One decoded-value budget shared by the 0th, sub-, and thumbnail IFD
23
- // reads so their combined decoded values stay proportional to the input.
24
- const valueBudget = getValueBudget(dataView);
25
33
  let tags = read0thIfd(dataView, tiffHeaderOffset, byteOrder, includeUnknown, computed, tagFilter, valueBudget);
26
34
  for (let i = 0; i < SUB_IFDS.length; i++) {
27
35
  tags = readSubIfd(SUB_IFDS[i], tags, dataView, tiffHeaderOffset, byteOrder, includeUnknown, computed, tagFilter, valueBudget);
package/src/types.js CHANGED
@@ -29,7 +29,6 @@ const tagTypes = {
29
29
  };
30
30
 
31
31
  export default {
32
- getAsciiValue,
33
32
  getByteAt,
34
33
  getAsciiAt,
35
34
  getShortAt,
@@ -44,10 +43,6 @@ export default {
44
43
  getTypeSize
45
44
  };
46
45
 
47
- function getAsciiValue(charArray) {
48
- return charArray.map((charCode) => String.fromCharCode(charCode));
49
- }
50
-
51
46
  function getByteAt(dataView, offset) {
52
47
  return dataView.getUint8(offset);
53
48
  }
package/src/utils.js CHANGED
@@ -79,11 +79,68 @@ export function decodeUtf8ByteString(byteString) {
79
79
  * is not valid UTF-8.
80
80
  */
81
81
  export function tryDecodeUtf8ByteString(byteString) {
82
- try {
83
- return decodeURIComponent(escape(byteString));
84
- } catch (error) {
85
- return undefined;
82
+ let isAscii = true;
83
+ for (let index = 0; index < byteString.length;) {
84
+ const sequenceLength = getWellFormedUtf8SequenceLength(byteString, index);
85
+ if (sequenceLength === 0) {
86
+ return undefined;
87
+ }
88
+ if (sequenceLength > 1) {
89
+ isAscii = false;
90
+ }
91
+ index += sequenceLength;
92
+ }
93
+ if (isAscii) {
94
+ return byteString;
95
+ }
96
+ return decodeURIComponent(escape(byteString));
97
+ }
98
+
99
+ // Well-formed byte sequences per Unicode Table 3-7, which ECMAScript's Decode
100
+ // (decodeURIComponent) enforces. Returns 0 for an ill-formed or cut-off one.
101
+ function getWellFormedUtf8SequenceLength(byteString, index) {
102
+ const lead = byteString.charCodeAt(index);
103
+ if (lead < 0x80) {
104
+ return 1;
105
+ }
106
+
107
+ let length;
108
+ let secondMin = 0x80;
109
+ let secondMax = 0xbf;
110
+ if (lead >= 0xc2 && lead <= 0xdf) {
111
+ length = 2;
112
+ } else if (lead >= 0xe0 && lead <= 0xef) {
113
+ length = 3;
114
+ if (lead === 0xe0) {
115
+ secondMin = 0xa0;
116
+ } else if (lead === 0xed) {
117
+ secondMax = 0x9f;
118
+ }
119
+ } else if (lead >= 0xf0 && lead <= 0xf4) {
120
+ length = 4;
121
+ if (lead === 0xf0) {
122
+ secondMin = 0x90;
123
+ } else if (lead === 0xf4) {
124
+ secondMax = 0x8f;
125
+ }
126
+ } else {
127
+ return 0;
128
+ }
129
+
130
+ if (index + length > byteString.length) {
131
+ return 0;
132
+ }
133
+ const second = byteString.charCodeAt(index + 1);
134
+ if (!(second >= secondMin && second <= secondMax)) {
135
+ return 0;
136
+ }
137
+ for (let offset = 2; offset < length; offset++) {
138
+ const continuation = byteString.charCodeAt(index + offset);
139
+ if (!(continuation >= 0x80 && continuation <= 0xbf)) {
140
+ return 0;
141
+ }
86
142
  }
143
+ return length;
87
144
  }
88
145
 
89
146
  export function getCharacterArray(string) {
@@ -212,17 +269,39 @@ export const COMPRESSION_METHOD_DEFLATE = 0;
212
269
  export const COMPRESSION_METHOD_BROTLI = 'brotli';
213
270
  export const DEFAULT_MAX_DECOMPRESSED_SIZE = 128 * 1024 * 1024;
214
271
 
272
+ /**
273
+ * Returns a copy of the decompress config whose compressed blocks share one
274
+ * total budget of maxDecompressedSize bytes. The input is never mutated.
275
+ *
276
+ * @param {Object|undefined} decompressConfig - The caller's decompress option.
277
+ * @returns {Object} {brotli, deflate, maxDecompressedSize, budget: {remaining, warned}}
278
+ */
279
+ export function withDecompressBudget(decompressConfig) {
280
+ return {
281
+ brotli: decompressConfig ? decompressConfig.brotli : undefined,
282
+ deflate: decompressConfig ? decompressConfig.deflate : undefined,
283
+ maxDecompressedSize: decompressConfig ? decompressConfig.maxDecompressedSize : undefined,
284
+ budget: {remaining: getMaxDecompressedSize(decompressConfig), warned: false}
285
+ };
286
+ }
287
+
215
288
  export function decompress(dataView, compressionMethod, encoding, returnType = 'string', decompressConfig) {
216
289
  const maxDecompressedSize = getMaxDecompressedSize(decompressConfig);
290
+ const budget = getDecompressBudget(decompressConfig, maxDecompressedSize);
291
+
292
+ if (compressionMethod !== COMPRESSION_METHOD_NONE && budget.remaining < 0) {
293
+ return rejectExceedsMax(budget, maxDecompressedSize);
294
+ }
217
295
 
218
296
  if (decompressConfig && compressionMethod !== COMPRESSION_METHOD_NONE) {
219
297
  const decompressType = compressionMethod === COMPRESSION_METHOD_DEFLATE ? 'deflate' : 'brotli';
220
298
  const customFn = decompressConfig[decompressType];
221
299
  if (typeof customFn === 'function') {
222
- const uint8 = new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength);
223
- return Promise.resolve(customFn(uint8)).then((result) => {
224
- if (getResultByteLength(result) > maxDecompressedSize) {
225
- return rejectExceedsMax(maxDecompressedSize);
300
+ // Called now, not deferred: the input can view the caller's buffer, which may be reused once load() returns.
301
+ return new Promise((resolve) => resolve(customFn(getUint8View(dataView)))).then((result) => {
302
+ budget.remaining -= getResultByteLength(result);
303
+ if (budget.remaining < 0) {
304
+ return rejectExceedsMax(budget, maxDecompressedSize);
226
305
  }
227
306
  if (returnType === 'dataview') {
228
307
  if (result instanceof ArrayBuffer) {
@@ -243,7 +322,7 @@ export function decompress(dataView, compressionMethod, encoding, returnType = '
243
322
 
244
323
  if (compressionMethod === COMPRESSION_METHOD_DEFLATE) {
245
324
  if (typeof DecompressionStream === 'function') {
246
- return readBoundedDecompressedStream(dataView, 'deflate', maxDecompressedSize)
325
+ return readBoundedDecompressedStream(dataView, 'deflate', budget, maxDecompressedSize)
247
326
  .then((arrayBuffer) => decodeBuffer(arrayBuffer, returnType, encoding));
248
327
  }
249
328
  }
@@ -251,7 +330,7 @@ export function decompress(dataView, compressionMethod, encoding, returnType = '
251
330
  if (compressionMethod === COMPRESSION_METHOD_BROTLI) {
252
331
  if (typeof DecompressionStream === 'function') {
253
332
  try {
254
- return readBoundedDecompressedStream(dataView, 'brotli', maxDecompressedSize)
333
+ return readBoundedDecompressedStream(dataView, 'brotli', budget, maxDecompressedSize)
255
334
  .then((arrayBuffer) => decodeBuffer(arrayBuffer, returnType, encoding));
256
335
  } catch (_error) {
257
336
  // brotli not supported by this DecompressionStream implementation
@@ -283,7 +362,18 @@ function getMaxDecompressedSize(decompressConfig) {
283
362
  return DEFAULT_MAX_DECOMPRESSED_SIZE;
284
363
  }
285
364
 
286
- function readBoundedDecompressedStream(dataView, format, maxDecompressedSize) {
365
+ function getDecompressBudget(decompressConfig, maxDecompressedSize) {
366
+ if (decompressConfig && decompressConfig.budget) {
367
+ return decompressConfig.budget;
368
+ }
369
+ return {remaining: maxDecompressedSize, warned: false};
370
+ }
371
+
372
+ function getUint8View(dataView) {
373
+ return new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength);
374
+ }
375
+
376
+ function readBoundedDecompressedStream(dataView, format, budget, maxDecompressedSize) {
287
377
  const decompressionStream = new DecompressionStream(format);
288
378
  const decompressedStream = new Blob([dataView]).stream().pipeThrough(decompressionStream);
289
379
  const reader = decompressedStream.getReader();
@@ -298,8 +388,11 @@ function readBoundedDecompressedStream(dataView, format, maxDecompressedSize) {
298
388
  return concatChunks(chunks, total);
299
389
  }
300
390
  total += value.byteLength;
301
- if (total > maxDecompressedSize) {
302
- return reader.cancel().then(() => rejectExceedsMax(maxDecompressedSize));
391
+ // Charge before checking and never give bytes back, so an
392
+ // exceeded budget stays exhausted for every later block.
393
+ budget.remaining -= value.byteLength;
394
+ if (budget.remaining < 0) {
395
+ return reader.cancel().then(() => rejectExceedsMax(budget, maxDecompressedSize));
303
396
  }
304
397
  chunks.push(value);
305
398
  return pump();
@@ -331,10 +424,11 @@ function getResultByteLength(result) {
331
424
  return 0;
332
425
  }
333
426
 
334
- function rejectExceedsMax(maxDecompressedSize) {
335
- if (typeof console !== 'undefined' && typeof console.warn === 'function') { // eslint-disable-line no-console
427
+ function rejectExceedsMax(budget, maxDecompressedSize) {
428
+ if (!budget.warned && typeof console !== 'undefined' && typeof console.warn === 'function') { // eslint-disable-line no-console
429
+ budget.warned = true;
336
430
  // eslint-disable-next-line no-console
337
- console.warn(`ExifReader: skipped a compressed metadata block that would exceed the maximum decompressed size of ${maxDecompressedSize} bytes.`);
431
+ console.warn(`ExifReader: the total decompressed metadata size for this call would exceed the maximum of ${maxDecompressedSize} bytes, so this and any later compressed metadata blocks are skipped.`);
338
432
  }
339
- return Promise.reject(`Decompressed metadata exceeded the maximum allowed size of ${maxDecompressedSize} bytes.`);
433
+ return Promise.reject(`Decompressed metadata exceeded the maximum allowed total size of ${maxDecompressedSize} bytes.`);
340
434
  }