@depup/file-type 21.3.0-depup.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.
package/core.js ADDED
@@ -0,0 +1,1938 @@
1
+ /**
2
+ Primary entry point, Node.js specific entry point is index.js
3
+ */
4
+
5
+ import * as Token from 'token-types';
6
+ import * as strtok3 from 'strtok3/core';
7
+ import {ZipHandler, GzipHandler} from '@tokenizer/inflate';
8
+ import {getUintBE} from 'uint8array-extras';
9
+ import {
10
+ stringToBytes,
11
+ tarHeaderChecksumMatches,
12
+ uint32SyncSafeToken,
13
+ } from './util.js';
14
+ import {extensions, mimeTypes} from './supported.js';
15
+
16
+ export const reasonableDetectionSizeInBytes = 4100; // A fair amount of file-types are detectable within this range.
17
+
18
+ export async function fileTypeFromStream(stream, options) {
19
+ return new FileTypeParser(options).fromStream(stream);
20
+ }
21
+
22
+ export async function fileTypeFromBuffer(input, options) {
23
+ return new FileTypeParser(options).fromBuffer(input);
24
+ }
25
+
26
+ export async function fileTypeFromBlob(blob, options) {
27
+ return new FileTypeParser(options).fromBlob(blob);
28
+ }
29
+
30
+ function getFileTypeFromMimeType(mimeType) {
31
+ mimeType = mimeType.toLowerCase();
32
+ switch (mimeType) {
33
+ case 'application/epub+zip':
34
+ return {
35
+ ext: 'epub',
36
+ mime: mimeType,
37
+ };
38
+ case 'application/vnd.oasis.opendocument.text':
39
+ return {
40
+ ext: 'odt',
41
+ mime: mimeType,
42
+ };
43
+ case 'application/vnd.oasis.opendocument.text-template':
44
+ return {
45
+ ext: 'ott',
46
+ mime: mimeType,
47
+ };
48
+ case 'application/vnd.oasis.opendocument.spreadsheet':
49
+ return {
50
+ ext: 'ods',
51
+ mime: mimeType,
52
+ };
53
+ case 'application/vnd.oasis.opendocument.spreadsheet-template':
54
+ return {
55
+ ext: 'ots',
56
+ mime: mimeType,
57
+ };
58
+ case 'application/vnd.oasis.opendocument.presentation':
59
+ return {
60
+ ext: 'odp',
61
+ mime: mimeType,
62
+ };
63
+ case 'application/vnd.oasis.opendocument.presentation-template':
64
+ return {
65
+ ext: 'otp',
66
+ mime: mimeType,
67
+ };
68
+ case 'application/vnd.oasis.opendocument.graphics':
69
+ return {
70
+ ext: 'odg',
71
+ mime: mimeType,
72
+ };
73
+ case 'application/vnd.oasis.opendocument.graphics-template':
74
+ return {
75
+ ext: 'otg',
76
+ mime: mimeType,
77
+ };
78
+ case 'application/vnd.openxmlformats-officedocument.presentationml.slideshow':
79
+ return {
80
+ ext: 'ppsx',
81
+ mime: mimeType,
82
+ };
83
+ case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
84
+ return {
85
+ ext: 'xlsx',
86
+ mime: mimeType,
87
+ };
88
+ case 'application/vnd.ms-excel.sheet.macroenabled':
89
+ return {
90
+ ext: 'xlsm',
91
+ mime: 'application/vnd.ms-excel.sheet.macroenabled.12',
92
+ };
93
+ case 'application/vnd.openxmlformats-officedocument.spreadsheetml.template':
94
+ return {
95
+ ext: 'xltx',
96
+ mime: mimeType,
97
+ };
98
+ case 'application/vnd.ms-excel.template.macroenabled':
99
+ return {
100
+ ext: 'xltm',
101
+ mime: 'application/vnd.ms-excel.template.macroenabled.12',
102
+ };
103
+ case 'application/vnd.ms-powerpoint.slideshow.macroenabled':
104
+ return {
105
+ ext: 'ppsm',
106
+ mime: 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
107
+ };
108
+ case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
109
+ return {
110
+ ext: 'docx',
111
+ mime: mimeType,
112
+ };
113
+ case 'application/vnd.ms-word.document.macroenabled':
114
+ return {
115
+ ext: 'docm',
116
+ mime: 'application/vnd.ms-word.document.macroenabled.12',
117
+ };
118
+ case 'application/vnd.openxmlformats-officedocument.wordprocessingml.template':
119
+ return {
120
+ ext: 'dotx',
121
+ mime: mimeType,
122
+ };
123
+ case 'application/vnd.ms-word.template.macroenabledtemplate':
124
+ return {
125
+ ext: 'dotm',
126
+ mime: 'application/vnd.ms-word.template.macroenabled.12',
127
+ };
128
+ case 'application/vnd.openxmlformats-officedocument.presentationml.template':
129
+ return {
130
+ ext: 'potx',
131
+ mime: mimeType,
132
+ };
133
+ case 'application/vnd.ms-powerpoint.template.macroenabled':
134
+ return {
135
+ ext: 'potm',
136
+ mime: 'application/vnd.ms-powerpoint.template.macroenabled.12',
137
+ };
138
+ case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
139
+ return {
140
+ ext: 'pptx',
141
+ mime: mimeType,
142
+ };
143
+ case 'application/vnd.ms-powerpoint.presentation.macroenabled':
144
+ return {
145
+ ext: 'pptm',
146
+ mime: 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
147
+ };
148
+ case 'application/vnd.ms-visio.drawing':
149
+ return {
150
+ ext: 'vsdx',
151
+ mime: 'application/vnd.visio',
152
+ };
153
+ case 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml':
154
+ return {
155
+ ext: '3mf',
156
+ mime: 'model/3mf',
157
+ };
158
+ default:
159
+ }
160
+ }
161
+
162
+ function _check(buffer, headers, options) {
163
+ options = {
164
+ offset: 0,
165
+ ...options,
166
+ };
167
+
168
+ for (const [index, header] of headers.entries()) {
169
+ // If a bitmask is set
170
+ if (options.mask) {
171
+ // If header doesn't equal `buf` with bits masked off
172
+ if (header !== (options.mask[index] & buffer[index + options.offset])) {
173
+ return false;
174
+ }
175
+ } else if (header !== buffer[index + options.offset]) {
176
+ return false;
177
+ }
178
+ }
179
+
180
+ return true;
181
+ }
182
+
183
+ export async function fileTypeFromTokenizer(tokenizer, options) {
184
+ return new FileTypeParser(options).fromTokenizer(tokenizer);
185
+ }
186
+
187
+ export async function fileTypeStream(webStream, options) {
188
+ return new FileTypeParser(options).toDetectionStream(webStream, options);
189
+ }
190
+
191
+ export class FileTypeParser {
192
+ constructor(options) {
193
+ this.options = {
194
+ mpegOffsetTolerance: 0,
195
+ ...options,
196
+ };
197
+
198
+ this.detectors = [...(options?.customDetectors ?? []),
199
+ {id: 'core', detect: this.detectConfident},
200
+ {id: 'core.imprecise', detect: this.detectImprecise}];
201
+ this.tokenizerOptions = {
202
+ abortSignal: options?.signal,
203
+ };
204
+ }
205
+
206
+ async fromTokenizer(tokenizer) {
207
+ const initialPosition = tokenizer.position;
208
+
209
+ // Iterate through all file-type detectors
210
+ for (const detector of this.detectors) {
211
+ const fileType = await detector.detect(tokenizer);
212
+ if (fileType) {
213
+ return fileType;
214
+ }
215
+
216
+ if (initialPosition !== tokenizer.position) {
217
+ return undefined; // Cannot proceed scanning of the tokenizer is at an arbitrary position
218
+ }
219
+ }
220
+ }
221
+
222
+ async fromBuffer(input) {
223
+ if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) {
224
+ throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof input}\``);
225
+ }
226
+
227
+ const buffer = input instanceof Uint8Array ? input : new Uint8Array(input);
228
+
229
+ if (!(buffer?.length > 1)) {
230
+ return;
231
+ }
232
+
233
+ return this.fromTokenizer(strtok3.fromBuffer(buffer, this.tokenizerOptions));
234
+ }
235
+
236
+ async fromBlob(blob) {
237
+ const tokenizer = strtok3.fromBlob(blob, this.tokenizerOptions);
238
+ try {
239
+ return await this.fromTokenizer(tokenizer);
240
+ } finally {
241
+ await tokenizer.close();
242
+ }
243
+ }
244
+
245
+ async fromStream(stream) {
246
+ const tokenizer = strtok3.fromWebStream(stream, this.tokenizerOptions);
247
+ try {
248
+ return await this.fromTokenizer(tokenizer);
249
+ } finally {
250
+ await tokenizer.close();
251
+ }
252
+ }
253
+
254
+ async toDetectionStream(stream, options) {
255
+ const {sampleSize = reasonableDetectionSizeInBytes} = options;
256
+ let detectedFileType;
257
+ let firstChunk;
258
+
259
+ const reader = stream.getReader({mode: 'byob'});
260
+ try {
261
+ // Read the first chunk from the stream
262
+ const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize));
263
+ firstChunk = chunk;
264
+ if (!done && chunk) {
265
+ try {
266
+ // Attempt to detect the file type from the chunk
267
+ detectedFileType = await this.fromBuffer(chunk.subarray(0, sampleSize));
268
+ } catch (error) {
269
+ if (!(error instanceof strtok3.EndOfStreamError)) {
270
+ throw error; // Re-throw non-EndOfStreamError
271
+ }
272
+
273
+ detectedFileType = undefined;
274
+ }
275
+ }
276
+
277
+ firstChunk = chunk;
278
+ } finally {
279
+ reader.releaseLock(); // Ensure the reader is released
280
+ }
281
+
282
+ // Create a new ReadableStream to manage locking issues
283
+ const transformStream = new TransformStream({
284
+ async start(controller) {
285
+ controller.enqueue(firstChunk); // Enqueue the initial chunk
286
+ },
287
+ transform(chunk, controller) {
288
+ // Pass through the chunks without modification
289
+ controller.enqueue(chunk);
290
+ },
291
+ });
292
+
293
+ const newStream = stream.pipeThrough(transformStream);
294
+ newStream.fileType = detectedFileType;
295
+
296
+ return newStream;
297
+ }
298
+
299
+ check(header, options) {
300
+ return _check(this.buffer, header, options);
301
+ }
302
+
303
+ checkString(header, options) {
304
+ return this.check(stringToBytes(header, options?.encoding), options);
305
+ }
306
+
307
+ // Detections with a high degree of certainty in identifying the correct file type
308
+ detectConfident = async tokenizer => {
309
+ this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);
310
+
311
+ // Keep reading until EOF if the file size is unknown.
312
+ if (tokenizer.fileInfo.size === undefined) {
313
+ tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;
314
+ }
315
+
316
+ this.tokenizer = tokenizer;
317
+
318
+ await tokenizer.peekBuffer(this.buffer, {length: 32, mayBeLess: true});
319
+
320
+ // -- 2-byte signatures --
321
+
322
+ if (this.check([0x42, 0x4D])) {
323
+ return {
324
+ ext: 'bmp',
325
+ mime: 'image/bmp',
326
+ };
327
+ }
328
+
329
+ if (this.check([0x0B, 0x77])) {
330
+ return {
331
+ ext: 'ac3',
332
+ mime: 'audio/vnd.dolby.dd-raw',
333
+ };
334
+ }
335
+
336
+ if (this.check([0x78, 0x01])) {
337
+ return {
338
+ ext: 'dmg',
339
+ mime: 'application/x-apple-diskimage',
340
+ };
341
+ }
342
+
343
+ if (this.check([0x4D, 0x5A])) {
344
+ return {
345
+ ext: 'exe',
346
+ mime: 'application/x-msdownload',
347
+ };
348
+ }
349
+
350
+ if (this.check([0x25, 0x21])) {
351
+ await tokenizer.peekBuffer(this.buffer, {length: 24, mayBeLess: true});
352
+
353
+ if (
354
+ this.checkString('PS-Adobe-', {offset: 2})
355
+ && this.checkString(' EPSF-', {offset: 14})
356
+ ) {
357
+ return {
358
+ ext: 'eps',
359
+ mime: 'application/eps',
360
+ };
361
+ }
362
+
363
+ return {
364
+ ext: 'ps',
365
+ mime: 'application/postscript',
366
+ };
367
+ }
368
+
369
+ if (
370
+ this.check([0x1F, 0xA0])
371
+ || this.check([0x1F, 0x9D])
372
+ ) {
373
+ return {
374
+ ext: 'Z',
375
+ mime: 'application/x-compress',
376
+ };
377
+ }
378
+
379
+ if (this.check([0xC7, 0x71])) {
380
+ return {
381
+ ext: 'cpio',
382
+ mime: 'application/x-cpio',
383
+ };
384
+ }
385
+
386
+ if (this.check([0x60, 0xEA])) {
387
+ return {
388
+ ext: 'arj',
389
+ mime: 'application/x-arj',
390
+ };
391
+ }
392
+
393
+ // -- 3-byte signatures --
394
+
395
+ if (this.check([0xEF, 0xBB, 0xBF])) { // UTF-8-BOM
396
+ // Strip off UTF-8-BOM
397
+ this.tokenizer.ignore(3);
398
+ return this.detectConfident(tokenizer);
399
+ }
400
+
401
+ if (this.check([0x47, 0x49, 0x46])) {
402
+ return {
403
+ ext: 'gif',
404
+ mime: 'image/gif',
405
+ };
406
+ }
407
+
408
+ if (this.check([0x49, 0x49, 0xBC])) {
409
+ return {
410
+ ext: 'jxr',
411
+ mime: 'image/vnd.ms-photo',
412
+ };
413
+ }
414
+
415
+ if (this.check([0x1F, 0x8B, 0x8])) {
416
+ const gzipHandler = new GzipHandler(tokenizer);
417
+
418
+ const stream = gzipHandler.inflate();
419
+ let shouldCancelStream = true;
420
+ try {
421
+ let compressedFileType;
422
+ try {
423
+ compressedFileType = await this.fromStream(stream);
424
+ } catch {
425
+ shouldCancelStream = false;
426
+ }
427
+
428
+ if (compressedFileType && compressedFileType.ext === 'tar') {
429
+ return {
430
+ ext: 'tar.gz',
431
+ mime: 'application/gzip',
432
+ };
433
+ }
434
+ } finally {
435
+ if (shouldCancelStream) {
436
+ await stream.cancel();
437
+ }
438
+ }
439
+
440
+ return {
441
+ ext: 'gz',
442
+ mime: 'application/gzip',
443
+ };
444
+ }
445
+
446
+ if (this.check([0x42, 0x5A, 0x68])) {
447
+ return {
448
+ ext: 'bz2',
449
+ mime: 'application/x-bzip2',
450
+ };
451
+ }
452
+
453
+ if (this.checkString('ID3')) {
454
+ await tokenizer.ignore(6); // Skip ID3 header until the header size
455
+ const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken);
456
+ if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) {
457
+ // Guess file type based on ID3 header for backward compatibility
458
+ return {
459
+ ext: 'mp3',
460
+ mime: 'audio/mpeg',
461
+ };
462
+ }
463
+
464
+ await tokenizer.ignore(id3HeaderLength);
465
+ return this.fromTokenizer(tokenizer); // Skip ID3 header, recursion
466
+ }
467
+
468
+ // Musepack, SV7
469
+ if (this.checkString('MP+')) {
470
+ return {
471
+ ext: 'mpc',
472
+ mime: 'audio/x-musepack',
473
+ };
474
+ }
475
+
476
+ if (
477
+ (this.buffer[0] === 0x43 || this.buffer[0] === 0x46)
478
+ && this.check([0x57, 0x53], {offset: 1})
479
+ ) {
480
+ return {
481
+ ext: 'swf',
482
+ mime: 'application/x-shockwave-flash',
483
+ };
484
+ }
485
+
486
+ // -- 4-byte signatures --
487
+
488
+ // Requires a sample size of 4 bytes
489
+ if (this.check([0xFF, 0xD8, 0xFF])) {
490
+ if (this.check([0xF7], {offset: 3})) { // JPG7/SOF55, indicating a ISO/IEC 14495 / JPEG-LS file
491
+ return {
492
+ ext: 'jls',
493
+ mime: 'image/jls',
494
+ };
495
+ }
496
+
497
+ return {
498
+ ext: 'jpg',
499
+ mime: 'image/jpeg',
500
+ };
501
+ }
502
+
503
+ if (this.check([0x4F, 0x62, 0x6A, 0x01])) {
504
+ return {
505
+ ext: 'avro',
506
+ mime: 'application/avro',
507
+ };
508
+ }
509
+
510
+ if (this.checkString('FLIF')) {
511
+ return {
512
+ ext: 'flif',
513
+ mime: 'image/flif',
514
+ };
515
+ }
516
+
517
+ if (this.checkString('8BPS')) {
518
+ return {
519
+ ext: 'psd',
520
+ mime: 'image/vnd.adobe.photoshop',
521
+ };
522
+ }
523
+
524
+ // Musepack, SV8
525
+ if (this.checkString('MPCK')) {
526
+ return {
527
+ ext: 'mpc',
528
+ mime: 'audio/x-musepack',
529
+ };
530
+ }
531
+
532
+ if (this.checkString('FORM')) {
533
+ return {
534
+ ext: 'aif',
535
+ mime: 'audio/aiff',
536
+ };
537
+ }
538
+
539
+ if (this.checkString('icns', {offset: 0})) {
540
+ return {
541
+ ext: 'icns',
542
+ mime: 'image/icns',
543
+ };
544
+ }
545
+
546
+ // Zip-based file formats
547
+ // Need to be before the `zip` check
548
+ if (this.check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature
549
+ let fileType;
550
+ await new ZipHandler(tokenizer).unzip(zipHeader => {
551
+ switch (zipHeader.filename) {
552
+ case 'META-INF/mozilla.rsa':
553
+ fileType = {
554
+ ext: 'xpi',
555
+ mime: 'application/x-xpinstall',
556
+ };
557
+ return {
558
+ stop: true,
559
+ };
560
+ case 'META-INF/MANIFEST.MF':
561
+ fileType = {
562
+ ext: 'jar',
563
+ mime: 'application/java-archive',
564
+ };
565
+ return {
566
+ stop: true,
567
+ };
568
+ case 'mimetype':
569
+ return {
570
+ async handler(fileData) {
571
+ // Use TextDecoder to decode the UTF-8 encoded data
572
+ const mimeType = new TextDecoder('utf-8').decode(fileData).trim();
573
+ fileType = getFileTypeFromMimeType(mimeType);
574
+ },
575
+ stop: true,
576
+ };
577
+
578
+ case '[Content_Types].xml':
579
+ return {
580
+ async handler(fileData) {
581
+ // Use TextDecoder to decode the UTF-8 encoded data
582
+ let xmlContent = new TextDecoder('utf-8').decode(fileData);
583
+ const endPos = xmlContent.indexOf('.main+xml"');
584
+ if (endPos === -1) {
585
+ const mimeType = 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml';
586
+ if (xmlContent.includes(`ContentType="${mimeType}"`)) {
587
+ fileType = getFileTypeFromMimeType(mimeType);
588
+ }
589
+ } else {
590
+ xmlContent = xmlContent.slice(0, Math.max(0, endPos));
591
+ const firstPos = xmlContent.lastIndexOf('"');
592
+ const mimeType = xmlContent.slice(Math.max(0, firstPos + 1));
593
+ fileType = getFileTypeFromMimeType(mimeType);
594
+ }
595
+ },
596
+ stop: true,
597
+ };
598
+ default:
599
+ if (/classes\d*\.dex/.test(zipHeader.filename)) {
600
+ fileType = {
601
+ ext: 'apk',
602
+ mime: 'application/vnd.android.package-archive',
603
+ };
604
+ return {stop: true};
605
+ }
606
+
607
+ return {};
608
+ }
609
+ }).catch(error => {
610
+ if (!(error instanceof strtok3.EndOfStreamError)) {
611
+ throw error; // Re-throw non-EndOfStreamError
612
+ }
613
+ });
614
+
615
+ return fileType ?? {
616
+ ext: 'zip',
617
+ mime: 'application/zip',
618
+ };
619
+ }
620
+
621
+ if (this.checkString('OggS')) {
622
+ // This is an OGG container
623
+ await tokenizer.ignore(28);
624
+ const type = new Uint8Array(8);
625
+ await tokenizer.readBuffer(type);
626
+
627
+ // Needs to be before `ogg` check
628
+ if (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) {
629
+ return {
630
+ ext: 'opus',
631
+ mime: 'audio/ogg; codecs=opus',
632
+ };
633
+ }
634
+
635
+ // If ' theora' in header.
636
+ if (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) {
637
+ return {
638
+ ext: 'ogv',
639
+ mime: 'video/ogg',
640
+ };
641
+ }
642
+
643
+ // If '\x01video' in header.
644
+ if (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) {
645
+ return {
646
+ ext: 'ogm',
647
+ mime: 'video/ogg',
648
+ };
649
+ }
650
+
651
+ // If ' FLAC' in header https://xiph.org/flac/faq.html
652
+ if (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) {
653
+ return {
654
+ ext: 'oga',
655
+ mime: 'audio/ogg',
656
+ };
657
+ }
658
+
659
+ // 'Speex ' in header https://en.wikipedia.org/wiki/Speex
660
+ if (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) {
661
+ return {
662
+ ext: 'spx',
663
+ mime: 'audio/ogg',
664
+ };
665
+ }
666
+
667
+ // If '\x01vorbis' in header
668
+ if (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) {
669
+ return {
670
+ ext: 'ogg',
671
+ mime: 'audio/ogg',
672
+ };
673
+ }
674
+
675
+ // Default OGG container https://www.iana.org/assignments/media-types/application/ogg
676
+ return {
677
+ ext: 'ogx',
678
+ mime: 'application/ogg',
679
+ };
680
+ }
681
+
682
+ if (
683
+ this.check([0x50, 0x4B])
684
+ && (this.buffer[2] === 0x3 || this.buffer[2] === 0x5 || this.buffer[2] === 0x7)
685
+ && (this.buffer[3] === 0x4 || this.buffer[3] === 0x6 || this.buffer[3] === 0x8)
686
+ ) {
687
+ return {
688
+ ext: 'zip',
689
+ mime: 'application/zip',
690
+ };
691
+ }
692
+
693
+ if (this.checkString('MThd')) {
694
+ return {
695
+ ext: 'mid',
696
+ mime: 'audio/midi',
697
+ };
698
+ }
699
+
700
+ if (
701
+ this.checkString('wOFF')
702
+ && (
703
+ this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
704
+ || this.checkString('OTTO', {offset: 4})
705
+ )
706
+ ) {
707
+ return {
708
+ ext: 'woff',
709
+ mime: 'font/woff',
710
+ };
711
+ }
712
+
713
+ if (
714
+ this.checkString('wOF2')
715
+ && (
716
+ this.check([0x00, 0x01, 0x00, 0x00], {offset: 4})
717
+ || this.checkString('OTTO', {offset: 4})
718
+ )
719
+ ) {
720
+ return {
721
+ ext: 'woff2',
722
+ mime: 'font/woff2',
723
+ };
724
+ }
725
+
726
+ if (this.check([0xD4, 0xC3, 0xB2, 0xA1]) || this.check([0xA1, 0xB2, 0xC3, 0xD4])) {
727
+ return {
728
+ ext: 'pcap',
729
+ mime: 'application/vnd.tcpdump.pcap',
730
+ };
731
+ }
732
+
733
+ // Sony DSD Stream File (DSF)
734
+ if (this.checkString('DSD ')) {
735
+ return {
736
+ ext: 'dsf',
737
+ mime: 'audio/x-dsf', // Non-standard
738
+ };
739
+ }
740
+
741
+ if (this.checkString('LZIP')) {
742
+ return {
743
+ ext: 'lz',
744
+ mime: 'application/x-lzip',
745
+ };
746
+ }
747
+
748
+ if (this.checkString('fLaC')) {
749
+ return {
750
+ ext: 'flac',
751
+ mime: 'audio/flac',
752
+ };
753
+ }
754
+
755
+ if (this.check([0x42, 0x50, 0x47, 0xFB])) {
756
+ return {
757
+ ext: 'bpg',
758
+ mime: 'image/bpg',
759
+ };
760
+ }
761
+
762
+ if (this.checkString('wvpk')) {
763
+ return {
764
+ ext: 'wv',
765
+ mime: 'audio/wavpack',
766
+ };
767
+ }
768
+
769
+ if (this.checkString('%PDF')) {
770
+ // Assume this is just a normal PDF
771
+ return {
772
+ ext: 'pdf',
773
+ mime: 'application/pdf',
774
+ };
775
+ }
776
+
777
+ if (this.check([0x00, 0x61, 0x73, 0x6D])) {
778
+ return {
779
+ ext: 'wasm',
780
+ mime: 'application/wasm',
781
+ };
782
+ }
783
+
784
+ // TIFF, little-endian type
785
+ if (this.check([0x49, 0x49])) {
786
+ const fileType = await this.readTiffHeader(false);
787
+ if (fileType) {
788
+ return fileType;
789
+ }
790
+ }
791
+
792
+ // TIFF, big-endian type
793
+ if (this.check([0x4D, 0x4D])) {
794
+ const fileType = await this.readTiffHeader(true);
795
+ if (fileType) {
796
+ return fileType;
797
+ }
798
+ }
799
+
800
+ if (this.checkString('MAC ')) {
801
+ return {
802
+ ext: 'ape',
803
+ mime: 'audio/ape',
804
+ };
805
+ }
806
+
807
+ // https://github.com/file/file/blob/master/magic/Magdir/matroska
808
+ if (this.check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML
809
+ async function readField() {
810
+ const msb = await tokenizer.peekNumber(Token.UINT8);
811
+ let mask = 0x80;
812
+ let ic = 0; // 0 = A, 1 = B, 2 = C, 3 = D
813
+
814
+ while ((msb & mask) === 0 && mask !== 0) {
815
+ ++ic;
816
+ mask >>= 1;
817
+ }
818
+
819
+ const id = new Uint8Array(ic + 1);
820
+ await tokenizer.readBuffer(id);
821
+ return id;
822
+ }
823
+
824
+ async function readElement() {
825
+ const idField = await readField();
826
+ const lengthField = await readField();
827
+
828
+ lengthField[0] ^= 0x80 >> (lengthField.length - 1);
829
+ const nrLength = Math.min(6, lengthField.length); // JavaScript can max read 6 bytes integer
830
+
831
+ const idView = new DataView(idField.buffer);
832
+ const lengthView = new DataView(lengthField.buffer, lengthField.length - nrLength, nrLength);
833
+
834
+ return {
835
+ id: getUintBE(idView),
836
+ len: getUintBE(lengthView),
837
+ };
838
+ }
839
+
840
+ async function readChildren(children) {
841
+ while (children > 0) {
842
+ const element = await readElement();
843
+ if (element.id === 0x42_82) {
844
+ const rawValue = await tokenizer.readToken(new Token.StringType(element.len));
845
+ return rawValue.replaceAll(/\00.*$/g, ''); // Return DocType
846
+ }
847
+
848
+ await tokenizer.ignore(element.len); // ignore payload
849
+ --children;
850
+ }
851
+ }
852
+
853
+ const re = await readElement();
854
+ const documentType = await readChildren(re.len);
855
+
856
+ switch (documentType) {
857
+ case 'webm':
858
+ return {
859
+ ext: 'webm',
860
+ mime: 'video/webm',
861
+ };
862
+
863
+ case 'matroska':
864
+ return {
865
+ ext: 'mkv',
866
+ mime: 'video/matroska',
867
+ };
868
+
869
+ default:
870
+ return;
871
+ }
872
+ }
873
+
874
+ if (this.checkString('SQLi')) {
875
+ return {
876
+ ext: 'sqlite',
877
+ mime: 'application/x-sqlite3',
878
+ };
879
+ }
880
+
881
+ if (this.check([0x4E, 0x45, 0x53, 0x1A])) {
882
+ return {
883
+ ext: 'nes',
884
+ mime: 'application/x-nintendo-nes-rom',
885
+ };
886
+ }
887
+
888
+ if (this.checkString('Cr24')) {
889
+ return {
890
+ ext: 'crx',
891
+ mime: 'application/x-google-chrome-extension',
892
+ };
893
+ }
894
+
895
+ if (
896
+ this.checkString('MSCF')
897
+ || this.checkString('ISc(')
898
+ ) {
899
+ return {
900
+ ext: 'cab',
901
+ mime: 'application/vnd.ms-cab-compressed',
902
+ };
903
+ }
904
+
905
+ if (this.check([0xED, 0xAB, 0xEE, 0xDB])) {
906
+ return {
907
+ ext: 'rpm',
908
+ mime: 'application/x-rpm',
909
+ };
910
+ }
911
+
912
+ if (this.check([0xC5, 0xD0, 0xD3, 0xC6])) {
913
+ return {
914
+ ext: 'eps',
915
+ mime: 'application/eps',
916
+ };
917
+ }
918
+
919
+ if (this.check([0x28, 0xB5, 0x2F, 0xFD])) {
920
+ return {
921
+ ext: 'zst',
922
+ mime: 'application/zstd',
923
+ };
924
+ }
925
+
926
+ if (this.check([0x7F, 0x45, 0x4C, 0x46])) {
927
+ return {
928
+ ext: 'elf',
929
+ mime: 'application/x-elf',
930
+ };
931
+ }
932
+
933
+ if (this.check([0x21, 0x42, 0x44, 0x4E])) {
934
+ return {
935
+ ext: 'pst',
936
+ mime: 'application/vnd.ms-outlook',
937
+ };
938
+ }
939
+
940
+ if (this.checkString('PAR1') || this.checkString('PARE')) {
941
+ return {
942
+ ext: 'parquet',
943
+ mime: 'application/vnd.apache.parquet',
944
+ };
945
+ }
946
+
947
+ if (this.checkString('ttcf')) {
948
+ return {
949
+ ext: 'ttc',
950
+ mime: 'font/collection',
951
+ };
952
+ }
953
+
954
+ if (
955
+ this.check([0xFE, 0xED, 0xFA, 0xCE]) // 32-bit, big-endian
956
+ || this.check([0xFE, 0xED, 0xFA, 0xCF]) // 64-bit, big-endian
957
+ || this.check([0xCE, 0xFA, 0xED, 0xFE]) // 32-bit, little-endian
958
+ || this.check([0xCF, 0xFA, 0xED, 0xFE]) // 64-bit, little-endian
959
+ ) {
960
+ return {
961
+ ext: 'macho',
962
+ mime: 'application/x-mach-binary',
963
+ };
964
+ }
965
+
966
+ if (this.check([0x04, 0x22, 0x4D, 0x18])) {
967
+ return {
968
+ ext: 'lz4',
969
+ mime: 'application/x-lz4', // Invented by us
970
+ };
971
+ }
972
+
973
+ if (this.checkString('regf')) {
974
+ return {
975
+ ext: 'dat',
976
+ mime: 'application/x-ft-windows-registry-hive',
977
+ };
978
+ }
979
+
980
+ // SPSS Statistical Data File
981
+ if (this.checkString('$FL2') || this.checkString('$FL3')) {
982
+ return {
983
+ ext: 'sav',
984
+ mime: 'application/x-spss-sav',
985
+ };
986
+ }
987
+
988
+ // -- 5-byte signatures --
989
+
990
+ if (this.check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
991
+ return {
992
+ ext: 'otf',
993
+ mime: 'font/otf',
994
+ };
995
+ }
996
+
997
+ if (this.checkString('#!AMR')) {
998
+ return {
999
+ ext: 'amr',
1000
+ mime: 'audio/amr',
1001
+ };
1002
+ }
1003
+
1004
+ if (this.checkString('{\\rtf')) {
1005
+ return {
1006
+ ext: 'rtf',
1007
+ mime: 'application/rtf',
1008
+ };
1009
+ }
1010
+
1011
+ if (this.check([0x46, 0x4C, 0x56, 0x01])) {
1012
+ return {
1013
+ ext: 'flv',
1014
+ mime: 'video/x-flv',
1015
+ };
1016
+ }
1017
+
1018
+ if (this.checkString('IMPM')) {
1019
+ return {
1020
+ ext: 'it',
1021
+ mime: 'audio/x-it',
1022
+ };
1023
+ }
1024
+
1025
+ if (
1026
+ this.checkString('-lh0-', {offset: 2})
1027
+ || this.checkString('-lh1-', {offset: 2})
1028
+ || this.checkString('-lh2-', {offset: 2})
1029
+ || this.checkString('-lh3-', {offset: 2})
1030
+ || this.checkString('-lh4-', {offset: 2})
1031
+ || this.checkString('-lh5-', {offset: 2})
1032
+ || this.checkString('-lh6-', {offset: 2})
1033
+ || this.checkString('-lh7-', {offset: 2})
1034
+ || this.checkString('-lzs-', {offset: 2})
1035
+ || this.checkString('-lz4-', {offset: 2})
1036
+ || this.checkString('-lz5-', {offset: 2})
1037
+ || this.checkString('-lhd-', {offset: 2})
1038
+ ) {
1039
+ return {
1040
+ ext: 'lzh',
1041
+ mime: 'application/x-lzh-compressed',
1042
+ };
1043
+ }
1044
+
1045
+ // MPEG program stream (PS or MPEG-PS)
1046
+ if (this.check([0x00, 0x00, 0x01, 0xBA])) {
1047
+ // MPEG-PS, MPEG-1 Part 1
1048
+ if (this.check([0x21], {offset: 4, mask: [0xF1]})) {
1049
+ return {
1050
+ ext: 'mpg', // May also be .ps, .mpeg
1051
+ mime: 'video/MP1S',
1052
+ };
1053
+ }
1054
+
1055
+ // MPEG-PS, MPEG-2 Part 1
1056
+ if (this.check([0x44], {offset: 4, mask: [0xC4]})) {
1057
+ return {
1058
+ ext: 'mpg', // May also be .mpg, .m2p, .vob or .sub
1059
+ mime: 'video/MP2P',
1060
+ };
1061
+ }
1062
+ }
1063
+
1064
+ if (this.checkString('ITSF')) {
1065
+ return {
1066
+ ext: 'chm',
1067
+ mime: 'application/vnd.ms-htmlhelp',
1068
+ };
1069
+ }
1070
+
1071
+ if (this.check([0xCA, 0xFE, 0xBA, 0xBE])) {
1072
+ // Java bytecode and Mach-O universal binaries have the same magic number.
1073
+ // We disambiguate based on the next 4 bytes, as done by `file`.
1074
+ // See https://github.com/file/file/blob/master/magic/Magdir/cafebabe
1075
+ const machOArchitectureCount = Token.UINT32_BE.get(this.buffer, 4);
1076
+ const javaClassFileMajorVersion = Token.UINT16_BE.get(this.buffer, 6);
1077
+
1078
+ if (machOArchitectureCount > 0 && machOArchitectureCount <= 30) {
1079
+ return {
1080
+ ext: 'macho',
1081
+ mime: 'application/x-mach-binary',
1082
+ };
1083
+ }
1084
+
1085
+ if (javaClassFileMajorVersion > 30) {
1086
+ return {
1087
+ ext: 'class',
1088
+ mime: 'application/java-vm',
1089
+ };
1090
+ }
1091
+ }
1092
+
1093
+ if (this.checkString('.RMF')) {
1094
+ return {
1095
+ ext: 'rm',
1096
+ mime: 'application/vnd.rn-realmedia',
1097
+ };
1098
+ }
1099
+
1100
+ // -- 5-byte signatures --
1101
+
1102
+ if (this.checkString('DRACO')) {
1103
+ return {
1104
+ ext: 'drc',
1105
+ mime: 'application/vnd.google.draco', // Invented by us
1106
+ };
1107
+ }
1108
+
1109
+ // -- 6-byte signatures --
1110
+
1111
+ if (this.check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
1112
+ return {
1113
+ ext: 'xz',
1114
+ mime: 'application/x-xz',
1115
+ };
1116
+ }
1117
+
1118
+ if (this.checkString('<?xml ')) {
1119
+ return {
1120
+ ext: 'xml',
1121
+ mime: 'application/xml',
1122
+ };
1123
+ }
1124
+
1125
+ if (this.check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
1126
+ return {
1127
+ ext: '7z',
1128
+ mime: 'application/x-7z-compressed',
1129
+ };
1130
+ }
1131
+
1132
+ if (
1133
+ this.check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7])
1134
+ && (this.buffer[6] === 0x0 || this.buffer[6] === 0x1)
1135
+ ) {
1136
+ return {
1137
+ ext: 'rar',
1138
+ mime: 'application/x-rar-compressed',
1139
+ };
1140
+ }
1141
+
1142
+ if (this.checkString('solid ')) {
1143
+ return {
1144
+ ext: 'stl',
1145
+ mime: 'model/stl',
1146
+ };
1147
+ }
1148
+
1149
+ if (this.checkString('AC')) {
1150
+ const version = new Token.StringType(4, 'latin1').get(this.buffer, 2);
1151
+ if (version.match('^d*') && version >= 1000 && version <= 1050) {
1152
+ return {
1153
+ ext: 'dwg',
1154
+ mime: 'image/vnd.dwg',
1155
+ };
1156
+ }
1157
+ }
1158
+
1159
+ if (this.checkString('070707')) {
1160
+ return {
1161
+ ext: 'cpio',
1162
+ mime: 'application/x-cpio',
1163
+ };
1164
+ }
1165
+
1166
+ // -- 7-byte signatures --
1167
+
1168
+ if (this.checkString('BLENDER')) {
1169
+ return {
1170
+ ext: 'blend',
1171
+ mime: 'application/x-blender',
1172
+ };
1173
+ }
1174
+
1175
+ if (this.checkString('!<arch>')) {
1176
+ await tokenizer.ignore(8);
1177
+ const string = await tokenizer.readToken(new Token.StringType(13, 'ascii'));
1178
+ if (string === 'debian-binary') {
1179
+ return {
1180
+ ext: 'deb',
1181
+ mime: 'application/x-deb',
1182
+ };
1183
+ }
1184
+
1185
+ return {
1186
+ ext: 'ar',
1187
+ mime: 'application/x-unix-archive',
1188
+ };
1189
+ }
1190
+
1191
+ if (
1192
+ this.checkString('WEBVTT')
1193
+ && (
1194
+ // One of LF, CR, tab, space, or end of file must follow "WEBVTT" per the spec (see `fixture/fixture-vtt-*.vtt` for examples). Note that `\0` is technically the null character (there is no such thing as an EOF character). However, checking for `\0` gives us the same result as checking for the end of the stream.
1195
+ (['\n', '\r', '\t', ' ', '\0'].some(char7 => this.checkString(char7, {offset: 6}))))
1196
+ ) {
1197
+ return {
1198
+ ext: 'vtt',
1199
+ mime: 'text/vtt',
1200
+ };
1201
+ }
1202
+
1203
+ // -- 8-byte signatures --
1204
+
1205
+ if (this.check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
1206
+ // APNG format (https://wiki.mozilla.org/APNG_Specification)
1207
+ // 1. Find the first IDAT (image data) chunk (49 44 41 54)
1208
+ // 2. Check if there is an "acTL" chunk before the IDAT one (61 63 54 4C)
1209
+
1210
+ // Offset calculated as follows:
1211
+ // - 8 bytes: PNG signature
1212
+ // - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk
1213
+
1214
+ await tokenizer.ignore(8); // ignore PNG signature
1215
+
1216
+ async function readChunkHeader() {
1217
+ return {
1218
+ length: await tokenizer.readToken(Token.INT32_BE),
1219
+ type: await tokenizer.readToken(new Token.StringType(4, 'latin1')),
1220
+ };
1221
+ }
1222
+
1223
+ do {
1224
+ const chunk = await readChunkHeader();
1225
+ if (chunk.length < 0) {
1226
+ return; // Invalid chunk length
1227
+ }
1228
+
1229
+ switch (chunk.type) {
1230
+ case 'IDAT':
1231
+ return {
1232
+ ext: 'png',
1233
+ mime: 'image/png',
1234
+ };
1235
+ case 'acTL':
1236
+ return {
1237
+ ext: 'apng',
1238
+ mime: 'image/apng',
1239
+ };
1240
+ default:
1241
+ await tokenizer.ignore(chunk.length + 4); // Ignore chunk-data + CRC
1242
+ }
1243
+ } while (tokenizer.position + 8 < tokenizer.fileInfo.size);
1244
+
1245
+ return {
1246
+ ext: 'png',
1247
+ mime: 'image/png',
1248
+ };
1249
+ }
1250
+
1251
+ if (this.check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) {
1252
+ return {
1253
+ ext: 'arrow',
1254
+ mime: 'application/vnd.apache.arrow.file',
1255
+ };
1256
+ }
1257
+
1258
+ if (this.check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {
1259
+ return {
1260
+ ext: 'glb',
1261
+ mime: 'model/gltf-binary',
1262
+ };
1263
+ }
1264
+
1265
+ // `mov` format variants
1266
+ if (
1267
+ this.check([0x66, 0x72, 0x65, 0x65], {offset: 4}) // `free`
1268
+ || this.check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) // `mdat` MJPEG
1269
+ || this.check([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) // `moov`
1270
+ || this.check([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide`
1271
+ ) {
1272
+ return {
1273
+ ext: 'mov',
1274
+ mime: 'video/quicktime',
1275
+ };
1276
+ }
1277
+
1278
+ // -- 9-byte signatures --
1279
+
1280
+ if (this.check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) {
1281
+ return {
1282
+ ext: 'orf',
1283
+ mime: 'image/x-olympus-orf',
1284
+ };
1285
+ }
1286
+
1287
+ if (this.checkString('gimp xcf ')) {
1288
+ return {
1289
+ ext: 'xcf',
1290
+ mime: 'image/x-xcf',
1291
+ };
1292
+ }
1293
+
1294
+ // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
1295
+ // It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box.
1296
+ // `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.
1297
+ // Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).
1298
+ if (
1299
+ this.checkString('ftyp', {offset: 4})
1300
+ && (this.buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII?
1301
+ ) {
1302
+ // They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect.
1303
+ // For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension.
1304
+ const brandMajor = new Token.StringType(4, 'latin1').get(this.buffer, 8).replace('\0', ' ').trim();
1305
+ switch (brandMajor) {
1306
+ case 'avif':
1307
+ case 'avis':
1308
+ return {ext: 'avif', mime: 'image/avif'};
1309
+ case 'mif1':
1310
+ return {ext: 'heic', mime: 'image/heif'};
1311
+ case 'msf1':
1312
+ return {ext: 'heic', mime: 'image/heif-sequence'};
1313
+ case 'heic':
1314
+ case 'heix':
1315
+ return {ext: 'heic', mime: 'image/heic'};
1316
+ case 'hevc':
1317
+ case 'hevx':
1318
+ return {ext: 'heic', mime: 'image/heic-sequence'};
1319
+ case 'qt':
1320
+ return {ext: 'mov', mime: 'video/quicktime'};
1321
+ case 'M4V':
1322
+ case 'M4VH':
1323
+ case 'M4VP':
1324
+ return {ext: 'm4v', mime: 'video/x-m4v'};
1325
+ case 'M4P':
1326
+ return {ext: 'm4p', mime: 'video/mp4'};
1327
+ case 'M4B':
1328
+ return {ext: 'm4b', mime: 'audio/mp4'};
1329
+ case 'M4A':
1330
+ return {ext: 'm4a', mime: 'audio/x-m4a'};
1331
+ case 'F4V':
1332
+ return {ext: 'f4v', mime: 'video/mp4'};
1333
+ case 'F4P':
1334
+ return {ext: 'f4p', mime: 'video/mp4'};
1335
+ case 'F4A':
1336
+ return {ext: 'f4a', mime: 'audio/mp4'};
1337
+ case 'F4B':
1338
+ return {ext: 'f4b', mime: 'audio/mp4'};
1339
+ case 'crx':
1340
+ return {ext: 'cr3', mime: 'image/x-canon-cr3'};
1341
+ default:
1342
+ if (brandMajor.startsWith('3g')) {
1343
+ if (brandMajor.startsWith('3g2')) {
1344
+ return {ext: '3g2', mime: 'video/3gpp2'};
1345
+ }
1346
+
1347
+ return {ext: '3gp', mime: 'video/3gpp'};
1348
+ }
1349
+
1350
+ return {ext: 'mp4', mime: 'video/mp4'};
1351
+ }
1352
+ }
1353
+
1354
+ // -- 10-byte signatures --
1355
+
1356
+ if (this.checkString('REGEDIT4\r\n')) {
1357
+ return {
1358
+ ext: 'reg',
1359
+ mime: 'application/x-ms-regedit',
1360
+ };
1361
+ }
1362
+
1363
+ // -- 12-byte signatures --
1364
+
1365
+ // RIFF file format which might be AVI, WAV, QCP, etc
1366
+ if (this.check([0x52, 0x49, 0x46, 0x46])) {
1367
+ if (this.checkString('WEBP', {offset: 8})) {
1368
+ return {
1369
+ ext: 'webp',
1370
+ mime: 'image/webp',
1371
+ };
1372
+ }
1373
+
1374
+ if (this.check([0x41, 0x56, 0x49], {offset: 8})) {
1375
+ return {
1376
+ ext: 'avi',
1377
+ mime: 'video/vnd.avi',
1378
+ };
1379
+ }
1380
+
1381
+ if (this.check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {
1382
+ return {
1383
+ ext: 'wav',
1384
+ mime: 'audio/wav',
1385
+ };
1386
+ }
1387
+
1388
+ // QLCM, QCP file
1389
+ if (this.check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {
1390
+ return {
1391
+ ext: 'qcp',
1392
+ mime: 'audio/qcelp',
1393
+ };
1394
+ }
1395
+ }
1396
+
1397
+ if (this.check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) {
1398
+ return {
1399
+ ext: 'rw2',
1400
+ mime: 'image/x-panasonic-rw2',
1401
+ };
1402
+ }
1403
+
1404
+ // ASF_Header_Object first 80 bytes
1405
+ if (this.check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
1406
+ async function readHeader() {
1407
+ const guid = new Uint8Array(16);
1408
+ await tokenizer.readBuffer(guid);
1409
+ return {
1410
+ id: guid,
1411
+ size: Number(await tokenizer.readToken(Token.UINT64_LE)),
1412
+ };
1413
+ }
1414
+
1415
+ await tokenizer.ignore(30);
1416
+ // Search for header should be in first 1KB of file.
1417
+ while (tokenizer.position + 24 < tokenizer.fileInfo.size) {
1418
+ const header = await readHeader();
1419
+ let payload = header.size - 24;
1420
+ if (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) {
1421
+ // Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)
1422
+ const typeId = new Uint8Array(16);
1423
+ payload -= await tokenizer.readBuffer(typeId);
1424
+
1425
+ if (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
1426
+ // Found audio:
1427
+ return {
1428
+ ext: 'asf',
1429
+ mime: 'audio/x-ms-asf',
1430
+ };
1431
+ }
1432
+
1433
+ if (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {
1434
+ // Found video:
1435
+ return {
1436
+ ext: 'asf',
1437
+ mime: 'video/x-ms-asf',
1438
+ };
1439
+ }
1440
+
1441
+ break;
1442
+ }
1443
+
1444
+ await tokenizer.ignore(payload);
1445
+ }
1446
+
1447
+ // Default to ASF generic extension
1448
+ return {
1449
+ ext: 'asf',
1450
+ mime: 'application/vnd.ms-asf',
1451
+ };
1452
+ }
1453
+
1454
+ if (this.check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
1455
+ return {
1456
+ ext: 'ktx',
1457
+ mime: 'image/ktx',
1458
+ };
1459
+ }
1460
+
1461
+ if ((this.check([0x7E, 0x10, 0x04]) || this.check([0x7E, 0x18, 0x04])) && this.check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) {
1462
+ return {
1463
+ ext: 'mie',
1464
+ mime: 'application/x-mie',
1465
+ };
1466
+ }
1467
+
1468
+ if (this.check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) {
1469
+ return {
1470
+ ext: 'shp',
1471
+ mime: 'application/x-esri-shape',
1472
+ };
1473
+ }
1474
+
1475
+ if (this.check([0xFF, 0x4F, 0xFF, 0x51])) {
1476
+ return {
1477
+ ext: 'j2c',
1478
+ mime: 'image/j2c',
1479
+ };
1480
+ }
1481
+
1482
+ if (this.check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
1483
+ // JPEG-2000 family
1484
+
1485
+ await tokenizer.ignore(20);
1486
+ const type = await tokenizer.readToken(new Token.StringType(4, 'ascii'));
1487
+ switch (type) {
1488
+ case 'jp2 ':
1489
+ return {
1490
+ ext: 'jp2',
1491
+ mime: 'image/jp2',
1492
+ };
1493
+ case 'jpx ':
1494
+ return {
1495
+ ext: 'jpx',
1496
+ mime: 'image/jpx',
1497
+ };
1498
+ case 'jpm ':
1499
+ return {
1500
+ ext: 'jpm',
1501
+ mime: 'image/jpm',
1502
+ };
1503
+ case 'mjp2':
1504
+ return {
1505
+ ext: 'mj2',
1506
+ mime: 'image/mj2',
1507
+ };
1508
+ default:
1509
+ return;
1510
+ }
1511
+ }
1512
+
1513
+ if (
1514
+ this.check([0xFF, 0x0A])
1515
+ || this.check([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A])
1516
+ ) {
1517
+ return {
1518
+ ext: 'jxl',
1519
+ mime: 'image/jxl',
1520
+ };
1521
+ }
1522
+
1523
+ if (this.check([0xFE, 0xFF])) { // UTF-16-BOM-BE
1524
+ if (this.checkString('<?xml ', {offset: 2, encoding: 'utf-16be'})) {
1525
+ return {
1526
+ ext: 'xml',
1527
+ mime: 'application/xml',
1528
+ };
1529
+ }
1530
+
1531
+ return undefined; // Some unknown text based format
1532
+ }
1533
+
1534
+ if (this.check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
1535
+ // Detected Microsoft Compound File Binary File (MS-CFB) Format.
1536
+ return {
1537
+ ext: 'cfb',
1538
+ mime: 'application/x-cfb',
1539
+ };
1540
+ }
1541
+
1542
+ // Increase sample size from 32 to 256.
1543
+ await tokenizer.peekBuffer(this.buffer, {length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true});
1544
+
1545
+ if (this.check([0x61, 0x63, 0x73, 0x70], {offset: 36})) {
1546
+ return {
1547
+ ext: 'icc',
1548
+ mime: 'application/vnd.iccprofile',
1549
+ };
1550
+ }
1551
+
1552
+ // ACE: requires 14 bytes in the buffer
1553
+ if (this.checkString('**ACE', {offset: 7}) && this.checkString('**', {offset: 12})) {
1554
+ return {
1555
+ ext: 'ace',
1556
+ mime: 'application/x-ace-compressed',
1557
+ };
1558
+ }
1559
+
1560
+ // -- 15-byte signatures --
1561
+
1562
+ if (this.checkString('BEGIN:')) {
1563
+ if (this.checkString('VCARD', {offset: 6})) {
1564
+ return {
1565
+ ext: 'vcf',
1566
+ mime: 'text/vcard',
1567
+ };
1568
+ }
1569
+
1570
+ if (this.checkString('VCALENDAR', {offset: 6})) {
1571
+ return {
1572
+ ext: 'ics',
1573
+ mime: 'text/calendar',
1574
+ };
1575
+ }
1576
+ }
1577
+
1578
+ // `raf` is here just to keep all the raw image detectors together.
1579
+ if (this.checkString('FUJIFILMCCD-RAW')) {
1580
+ return {
1581
+ ext: 'raf',
1582
+ mime: 'image/x-fujifilm-raf',
1583
+ };
1584
+ }
1585
+
1586
+ if (this.checkString('Extended Module:')) {
1587
+ return {
1588
+ ext: 'xm',
1589
+ mime: 'audio/x-xm',
1590
+ };
1591
+ }
1592
+
1593
+ if (this.checkString('Creative Voice File')) {
1594
+ return {
1595
+ ext: 'voc',
1596
+ mime: 'audio/x-voc',
1597
+ };
1598
+ }
1599
+
1600
+ if (this.check([0x04, 0x00, 0x00, 0x00]) && this.buffer.length >= 16) { // Rough & quick check Pickle/ASAR
1601
+ const jsonSize = new DataView(this.buffer.buffer).getUint32(12, true);
1602
+
1603
+ if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) {
1604
+ try {
1605
+ const header = new TextDecoder().decode(this.buffer.subarray(16, jsonSize + 16));
1606
+ const json = JSON.parse(header);
1607
+ // Check if Pickle is ASAR
1608
+ if (json.files) { // Final check, assuring Pickle/ASAR format
1609
+ return {
1610
+ ext: 'asar',
1611
+ mime: 'application/x-asar',
1612
+ };
1613
+ }
1614
+ } catch {}
1615
+ }
1616
+ }
1617
+
1618
+ if (this.check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
1619
+ return {
1620
+ ext: 'mxf',
1621
+ mime: 'application/mxf',
1622
+ };
1623
+ }
1624
+
1625
+ if (this.checkString('SCRM', {offset: 44})) {
1626
+ return {
1627
+ ext: 's3m',
1628
+ mime: 'audio/x-s3m',
1629
+ };
1630
+ }
1631
+
1632
+ // Raw MPEG-2 transport stream (188-byte packets)
1633
+ if (this.check([0x47]) && this.check([0x47], {offset: 188})) {
1634
+ return {
1635
+ ext: 'mts',
1636
+ mime: 'video/mp2t',
1637
+ };
1638
+ }
1639
+
1640
+ // Blu-ray Disc Audio-Video (BDAV) MPEG-2 transport stream has 4-byte TP_extra_header before each 188-byte packet
1641
+ if (this.check([0x47], {offset: 4}) && this.check([0x47], {offset: 196})) {
1642
+ return {
1643
+ ext: 'mts',
1644
+ mime: 'video/mp2t',
1645
+ };
1646
+ }
1647
+
1648
+ if (this.check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {
1649
+ return {
1650
+ ext: 'mobi',
1651
+ mime: 'application/x-mobipocket-ebook',
1652
+ };
1653
+ }
1654
+
1655
+ if (this.check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) {
1656
+ return {
1657
+ ext: 'dcm',
1658
+ mime: 'application/dicom',
1659
+ };
1660
+ }
1661
+
1662
+ if (this.check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) {
1663
+ return {
1664
+ ext: 'lnk',
1665
+ mime: 'application/x.ms.shortcut', // Invented by us
1666
+ };
1667
+ }
1668
+
1669
+ if (this.check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) {
1670
+ return {
1671
+ ext: 'alias',
1672
+ mime: 'application/x.apple.alias', // Invented by us
1673
+ };
1674
+ }
1675
+
1676
+ if (this.checkString('Kaydara FBX Binary \u0000')) {
1677
+ return {
1678
+ ext: 'fbx',
1679
+ mime: 'application/x.autodesk.fbx', // Invented by us
1680
+ };
1681
+ }
1682
+
1683
+ if (
1684
+ this.check([0x4C, 0x50], {offset: 34})
1685
+ && (
1686
+ this.check([0x00, 0x00, 0x01], {offset: 8})
1687
+ || this.check([0x01, 0x00, 0x02], {offset: 8})
1688
+ || this.check([0x02, 0x00, 0x02], {offset: 8})
1689
+ )
1690
+ ) {
1691
+ return {
1692
+ ext: 'eot',
1693
+ mime: 'application/vnd.ms-fontobject',
1694
+ };
1695
+ }
1696
+
1697
+ if (this.check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) {
1698
+ return {
1699
+ ext: 'indd',
1700
+ mime: 'application/x-indesign',
1701
+ };
1702
+ }
1703
+
1704
+ // -- 16-byte signatures --
1705
+
1706
+ // JMP files - check for both Little Endian and Big Endian signatures
1707
+ if (this.check([0xFF, 0xFF, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00])
1708
+ || this.check([0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x01])) {
1709
+ return {
1710
+ ext: 'jmp',
1711
+ mime: 'application/x-jmp-data',
1712
+ };
1713
+ }
1714
+
1715
+ // Increase sample size from 256 to 512
1716
+ await tokenizer.peekBuffer(this.buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true});
1717
+
1718
+ // Requires a buffer size of 512 bytes
1719
+ if ((this.checkString('ustar', {offset: 257}) && (this.checkString('\0', {offset: 262}) || this.checkString(' ', {offset: 262})))
1720
+ || (this.check([0, 0, 0, 0, 0, 0], {offset: 257}) && tarHeaderChecksumMatches(this.buffer))) {
1721
+ return {
1722
+ ext: 'tar',
1723
+ mime: 'application/x-tar',
1724
+ };
1725
+ }
1726
+
1727
+ if (this.check([0xFF, 0xFE])) { // UTF-16-BOM-LE
1728
+ const encoding = 'utf-16le';
1729
+ if (this.checkString('<?xml ', {offset: 2, encoding})) {
1730
+ return {
1731
+ ext: 'xml',
1732
+ mime: 'application/xml',
1733
+ };
1734
+ }
1735
+
1736
+ if (this.check([0xFF, 0x0E], {offset: 2}) && this.checkString('SketchUp Model', {offset: 4, encoding})) {
1737
+ return {
1738
+ ext: 'skp',
1739
+ mime: 'application/vnd.sketchup.skp',
1740
+ };
1741
+ }
1742
+
1743
+ if (this.checkString('Windows Registry Editor Version 5.00\r\n', {offset: 2, encoding})) {
1744
+ return {
1745
+ ext: 'reg',
1746
+ mime: 'application/x-ms-regedit',
1747
+ };
1748
+ }
1749
+
1750
+ return undefined; // Some text based format
1751
+ }
1752
+
1753
+ if (this.checkString('-----BEGIN PGP MESSAGE-----')) {
1754
+ return {
1755
+ ext: 'pgp',
1756
+ mime: 'application/pgp-encrypted',
1757
+ };
1758
+ }
1759
+ };
1760
+ // Detections with limited supporting data, resulting in a higher likelihood of false positives
1761
+ detectImprecise = async tokenizer => {
1762
+ this.buffer = new Uint8Array(reasonableDetectionSizeInBytes);
1763
+
1764
+ // Read initial sample size of 8 bytes
1765
+ await tokenizer.peekBuffer(this.buffer, {length: Math.min(8, tokenizer.fileInfo.size), mayBeLess: true});
1766
+
1767
+ if (
1768
+ this.check([0x0, 0x0, 0x1, 0xBA])
1769
+ || this.check([0x0, 0x0, 0x1, 0xB3])
1770
+ ) {
1771
+ return {
1772
+ ext: 'mpg',
1773
+ mime: 'video/mpeg',
1774
+ };
1775
+ }
1776
+
1777
+ if (this.check([0x00, 0x01, 0x00, 0x00, 0x00])) {
1778
+ return {
1779
+ ext: 'ttf',
1780
+ mime: 'font/ttf',
1781
+ };
1782
+ }
1783
+
1784
+ if (this.check([0x00, 0x00, 0x01, 0x00])) {
1785
+ return {
1786
+ ext: 'ico',
1787
+ mime: 'image/x-icon',
1788
+ };
1789
+ }
1790
+
1791
+ if (this.check([0x00, 0x00, 0x02, 0x00])) {
1792
+ return {
1793
+ ext: 'cur',
1794
+ mime: 'image/x-icon',
1795
+ };
1796
+ }
1797
+
1798
+ // Adjust buffer to `mpegOffsetTolerance`
1799
+ await tokenizer.peekBuffer(this.buffer, {length: Math.min(2 + this.options.mpegOffsetTolerance, tokenizer.fileInfo.size), mayBeLess: true});
1800
+
1801
+ // Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE)
1802
+ if (this.buffer.length >= (2 + this.options.mpegOffsetTolerance)) {
1803
+ for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) {
1804
+ const type = this.scanMpeg(depth);
1805
+ if (type) {
1806
+ return type;
1807
+ }
1808
+ }
1809
+ }
1810
+ };
1811
+
1812
+ async readTiffTag(bigEndian) {
1813
+ const tagId = await this.tokenizer.readToken(bigEndian ? Token.UINT16_BE : Token.UINT16_LE);
1814
+ this.tokenizer.ignore(10);
1815
+ switch (tagId) {
1816
+ case 50_341:
1817
+ return {
1818
+ ext: 'arw',
1819
+ mime: 'image/x-sony-arw',
1820
+ };
1821
+ case 50_706:
1822
+ return {
1823
+ ext: 'dng',
1824
+ mime: 'image/x-adobe-dng',
1825
+ };
1826
+ default:
1827
+ }
1828
+ }
1829
+
1830
+ async readTiffIFD(bigEndian) {
1831
+ const numberOfTags = await this.tokenizer.readToken(bigEndian ? Token.UINT16_BE : Token.UINT16_LE);
1832
+ for (let n = 0; n < numberOfTags; ++n) {
1833
+ const fileType = await this.readTiffTag(bigEndian);
1834
+ if (fileType) {
1835
+ return fileType;
1836
+ }
1837
+ }
1838
+ }
1839
+
1840
+ async readTiffHeader(bigEndian) {
1841
+ const version = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 2);
1842
+ const ifdOffset = (bigEndian ? Token.UINT32_BE : Token.UINT32_LE).get(this.buffer, 4);
1843
+
1844
+ if (version === 42) {
1845
+ // TIFF file header
1846
+ if (ifdOffset >= 6) {
1847
+ if (this.checkString('CR', {offset: 8})) {
1848
+ return {
1849
+ ext: 'cr2',
1850
+ mime: 'image/x-canon-cr2',
1851
+ };
1852
+ }
1853
+
1854
+ if (ifdOffset >= 8) {
1855
+ const someId1 = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 8);
1856
+ const someId2 = (bigEndian ? Token.UINT16_BE : Token.UINT16_LE).get(this.buffer, 10);
1857
+
1858
+ if (
1859
+ (someId1 === 0x1C && someId2 === 0xFE)
1860
+ || (someId1 === 0x1F && someId2 === 0x0B)) {
1861
+ return {
1862
+ ext: 'nef',
1863
+ mime: 'image/x-nikon-nef',
1864
+ };
1865
+ }
1866
+ }
1867
+ }
1868
+
1869
+ await this.tokenizer.ignore(ifdOffset);
1870
+ const fileType = await this.readTiffIFD(bigEndian);
1871
+ return fileType ?? {
1872
+ ext: 'tif',
1873
+ mime: 'image/tiff',
1874
+ };
1875
+ }
1876
+
1877
+ if (version === 43) { // Big TIFF file header
1878
+ return {
1879
+ ext: 'tif',
1880
+ mime: 'image/tiff',
1881
+ };
1882
+ }
1883
+ }
1884
+
1885
+ /**
1886
+ Scan check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE).
1887
+
1888
+ @param offset - Offset to scan for sync-preamble.
1889
+ @returns {{ext: string, mime: string}}
1890
+ */
1891
+ scanMpeg(offset) {
1892
+ if (this.check([0xFF, 0xE0], {offset, mask: [0xFF, 0xE0]})) {
1893
+ if (this.check([0x10], {offset: offset + 1, mask: [0x16]})) {
1894
+ // Check for (ADTS) MPEG-2
1895
+ if (this.check([0x08], {offset: offset + 1, mask: [0x08]})) {
1896
+ return {
1897
+ ext: 'aac',
1898
+ mime: 'audio/aac',
1899
+ };
1900
+ }
1901
+
1902
+ // Must be (ADTS) MPEG-4
1903
+ return {
1904
+ ext: 'aac',
1905
+ mime: 'audio/aac',
1906
+ };
1907
+ }
1908
+
1909
+ // MPEG 1 or 2 Layer 3 header
1910
+ // Check for MPEG layer 3
1911
+ if (this.check([0x02], {offset: offset + 1, mask: [0x06]})) {
1912
+ return {
1913
+ ext: 'mp3',
1914
+ mime: 'audio/mpeg',
1915
+ };
1916
+ }
1917
+
1918
+ // Check for MPEG layer 2
1919
+ if (this.check([0x04], {offset: offset + 1, mask: [0x06]})) {
1920
+ return {
1921
+ ext: 'mp2',
1922
+ mime: 'audio/mpeg',
1923
+ };
1924
+ }
1925
+
1926
+ // Check for MPEG layer 1
1927
+ if (this.check([0x06], {offset: offset + 1, mask: [0x06]})) {
1928
+ return {
1929
+ ext: 'mp1',
1930
+ mime: 'audio/mpeg',
1931
+ };
1932
+ }
1933
+ }
1934
+ }
1935
+ }
1936
+
1937
+ export const supportedExtensions = new Set(extensions);
1938
+ export const supportedMimeTypes = new Set(mimeTypes);