-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathutils.test.ts
More file actions
1736 lines (1499 loc) · 61.9 KB
/
utils.test.ts
File metadata and controls
1736 lines (1499 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* node-minify
* Copyright (c) 2011-2026 Rodolphe Stoclin
* MIT Licensed
*/
import { existsSync, lstatSync, unlinkSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Settings } from "@node-minify/types";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
return {
...actual,
lstatSync: vi.fn(actual.lstatSync),
unlinkSync: vi.fn(actual.unlinkSync),
};
});
import { FileOperationError, ValidationError } from "../src/error.ts";
import {
buildArgs,
compressSingleFile,
deleteFile,
ensureStringContent,
getContentFromFiles,
getFilesizeBrotliInBytes,
getFilesizeBrotliRaw,
getFilesizeGzippedInBytes,
getFilesizeGzippedRaw,
getFilesizeInBytes,
isValidFile,
prettyBytes,
readFile,
readFileAsync,
resetDeprecationWarnings,
run,
setFileNameMin,
toBuildArgsOptions,
warnDeprecation,
writeFile,
writeFileAsync,
} from "../src/index.ts";
const fixtureFile = `${__dirname}/../../../tests/fixtures/fixture-content.js`;
describe("Package: utils", () => {
const filesToCleanup = new Set<string>();
afterEach(() => {
for (const file of filesToCleanup) {
try {
if (existsSync(file)) {
deleteFile(file);
}
} catch {
// Ignore cleanup errors
}
}
filesToCleanup.clear();
});
describe("readFile", () => {
test("should return the content", () =>
expect(readFile(fixtureFile)).toMatch("console.log('content');"));
test("should throw an error if file does not exist", () => {
expect(() => readFile("fake.js")).toThrow();
});
test("should throw an error if path is a directory", () => {
expect(() => readFile(__dirname)).toThrow(/EISDIR/);
});
test("should return Buffer when asBuffer is true", () => {
const buffer = readFile(fixtureFile, true);
expect(buffer).toBeInstanceOf(Buffer);
expect(buffer.toString("utf-8")).toMatch("console.log('content');");
});
test("should return string when asBuffer is false", () => {
const content = readFile(fixtureFile, false);
expect(typeof content).toBe("string");
expect(content).toMatch("console.log('content');");
});
});
describe("readFileAsync", () => {
test("should return the content", async () => {
const content = await readFileAsync(fixtureFile);
expect(content).toMatch("console.log('content');");
});
test("should throw FileOperationError if file does not exist", async () => {
await expect(readFileAsync("nonexistent-file.js")).rejects.toThrow(
FileOperationError
);
});
test("should throw FileOperationError if path is a directory", async () => {
await expect(readFileAsync(__dirname)).rejects.toThrow(
FileOperationError
);
});
test("should return Buffer when asBuffer is true", async () => {
const buffer = await readFileAsync(fixtureFile, true);
expect(buffer).toBeInstanceOf(Buffer);
expect(buffer.toString("utf-8")).toMatch("console.log('content');");
});
test("should return string when asBuffer is false", async () => {
const content = await readFileAsync(fixtureFile, false);
expect(typeof content).toBe("string");
expect(content).toMatch("console.log('content');");
});
});
describe("FileOperationError", () => {
test("should chain the original error via cause", () => {
const originalError = new Error("Original failure");
const error = new FileOperationError(
"read",
"test.js",
originalError
);
expect(error.message).toContain("Failed to read file test.js");
expect(error.message).toContain("Original failure");
expect(error.cause).toBe(originalError);
});
test("should handle missing original error", () => {
const error = new FileOperationError("read", "test.js");
expect(error.message).toContain("Failed to read file test.js");
expect(error.cause).toBeUndefined();
});
});
describe("isValidFile", () => {
test("should return true if file exists", () => {
expect(isValidFile(fixtureFile)).toBe(true);
});
test("should return false if file does not exist", () => {
expect(isValidFile("fake.js")).toBe(false);
});
test("should return false if it is a directory", () => {
expect(isValidFile(__dirname)).toBe(false);
});
test("should throw FileOperationError if lstatSync fails", () => {
vi.mocked(lstatSync).mockImplementationOnce(() => {
throw new Error("FS error");
});
expect(() => isValidFile(fixtureFile)).toThrow();
});
});
describe("run", () => {
test("should run the compressor", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const result = await run({
settings: { compressor } as any,
content: "content",
});
expect(result).toBe("minified");
expect(compressor).toHaveBeenCalledWith({
settings: { compressor },
content: "content",
index: undefined,
});
});
test("should throw if no settings", async () => {
await expect(run({} as any)).rejects.toThrow(ValidationError);
});
test("should throw if no compressor", async () => {
await expect(run({ settings: {} } as any)).rejects.toThrow(
ValidationError
);
});
test("should throw if compressor returns invalid result (non-object)", async () => {
const compressor = vi
.fn()
.mockResolvedValue("invalid string result");
await expect(
run({
settings: {
compressor,
compressorLabel: "bad-compressor",
} as any,
content: "content",
})
).rejects.toThrow(
"Compressor 'bad-compressor' returned invalid result. Expected an object with { code: string }."
);
});
test("should throw if compressor returns invalid result (missing code)", async () => {
const compressor = vi
.fn()
.mockResolvedValue({ somethingElse: "foo" });
await expect(
run({
settings: {
compressor,
compressorLabel: "bad-compressor",
} as any,
content: "content",
})
).rejects.toThrow(
"Compressor 'bad-compressor' must return { code: string }."
);
});
});
describe("deleteFile", () => {
test("should delete a file", () => {
const tempFile = `${__dirname}/../../../tests/tmp/delete-me.js`;
writeFile({ file: tempFile, content: "content" });
expect(isValidFile(tempFile)).toBe(true);
deleteFile(tempFile);
expect(isValidFile(tempFile)).toBe(false);
});
test("should throw if file does not exist", () => {
expect(() => deleteFile("fake.js")).toThrow("File does not exist");
});
test("should throw FileOperationError if unlinkSync fails", () => {
const tempFile = `${__dirname}/../../../tests/tmp/delete-fail.js`;
writeFile({ file: tempFile, content: "content" });
vi.mocked(unlinkSync).mockImplementationOnce(() => {
throw new Error("Unlink failed");
});
expect(() => deleteFile(tempFile)).toThrow();
});
});
describe("writeFile", () => {
test("should return the content", () =>
expect(
writeFile({
file: `${__dirname}/../../../tests/tmp/temp.js`,
content: "const foo = 'bar';",
})
).toBe("const foo = 'bar';"));
test("should write content to an array of files", () => {
const files: [string, string] = [
`${__dirname}/../../../tests/tmp/temp1.js`,
`${__dirname}/../../../tests/tmp/temp2.js`,
];
expect(
writeFile({
file: files,
content: "content",
index: 0,
})
).toBe("content");
expect(readFile(files[0])).toBe("content");
});
test("should throw if no target file", () => {
expect(() => writeFile({ file: "", content: "content" })).toThrow(
ValidationError
);
});
test("should throw if no content", () => {
expect(() => writeFile({ file: "foo.js", content: "" })).toThrow(
ValidationError
);
});
test("should throw if target path is a directory", () => {
expect(() =>
writeFile({
file: __dirname,
content: "content",
})
).toThrow();
});
test("should handle index with non-array file", () => {
const file = `${__dirname}/../../../tests/tmp/temp-index.js`;
expect(
writeFile({
file,
content: "content",
index: 0,
})
).toBe("content");
expect(readFile(file)).toBe("content");
});
test("should throw if targetFile is not a string", () => {
expect(() =>
writeFile({
file: [null as any],
content: "content",
index: 0,
})
).toThrow(ValidationError);
});
test("should throw FileOperationError on multi-file failure", () => {
expect(() =>
writeFile({
file: [__dirname],
content: "content",
index: 0,
})
).toThrow();
});
});
describe("writeFileAsync", () => {
test("should return the content", async () => {
const result = await writeFileAsync({
file: `${__dirname}/../../../tests/tmp/temp-async.js`,
content: "const foo = 'bar';",
});
expect(result).toBe("const foo = 'bar';");
});
test("should write content to an array of files", async () => {
const files: [string, string] = [
`${__dirname}/../../../tests/tmp/temp1-async.js`,
`${__dirname}/../../../tests/tmp/temp2-async.js`,
];
const result = await writeFileAsync({
file: files,
content: "content",
index: 0,
});
expect(result).toBe("content");
expect(readFile(files[0])).toBe("content");
});
test("should throw if no target file", async () => {
await expect(
writeFileAsync({ file: "", content: "content" })
).rejects.toThrow(ValidationError);
});
test("should throw if no content", async () => {
await expect(
writeFileAsync({ file: "foo.js", content: "" })
).rejects.toThrow(ValidationError);
});
test("should throw if target path is a directory", async () => {
await expect(
writeFileAsync({
file: __dirname,
content: "content",
})
).rejects.toThrow();
});
test("should handle index with non-array file", async () => {
const file = `${__dirname}/../../../tests/tmp/temp-index-async.js`;
const result = await writeFileAsync({
file,
content: "content",
index: 0,
});
expect(result).toBe("content");
expect(readFile(file)).toBe("content");
});
test("should throw if targetFile is not a string", async () => {
await expect(
writeFileAsync({
file: [null as any],
content: "content",
index: 0,
})
).rejects.toThrow(ValidationError);
});
test("should throw FileOperationError on multi-file failure", async () => {
await expect(
writeFileAsync({
file: [__dirname],
content: "content",
index: 0,
})
).rejects.toThrow();
});
});
describe("buildArgs", () => {
test("should return an array with args", () =>
expect(
buildArgs({
foo: "bar",
})
).toEqual(["--foo", "bar"]));
test("should throw if options is null", () => {
expect(() => buildArgs(null as any)).toThrow(ValidationError);
});
test("should filter out undefined and false values", () => {
expect(
buildArgs({
foo: undefined,
bar: false,
baz: true,
})
).toEqual(["--baz"]);
});
});
describe("getFilesizeInBytes", () => {
test("should return file size", () =>
expect(getFilesizeInBytes(fixtureFile)).toMatch(/(24 B)|(25 B)/));
});
describe("getFilesizeGzippedInBytes", () => {
test("should return file size", (): Promise<void> =>
new Promise<void>((done) => {
getFilesizeGzippedInBytes(fixtureFile).then((size) => {
expect(size).toMatch(/(44 B)|(45 B)/);
done();
});
}));
});
describe("pretty bytes", () => {
test("should throw when not a number", () => {
// @ts-expect-error
expect(() => prettyBytes("a")).toThrow();
});
test("should return a negative number", () =>
expect(prettyBytes(-1)).toBe("-1 B"));
test("should return 0", () => expect(prettyBytes(0)).toBe("0 B"));
});
describe("setFileNameMin", () => {
test("should return file name min", () =>
expect(setFileNameMin("foo.js", "$1.min.js")).toBe("foo.min.js"));
test("should return file name min with public folder", () =>
expect(setFileNameMin("foo.js", "$1.min.js", "public/")).toBe(
"public/foo.min.js"
));
test("should return file name min with public folder without trailing slash", () =>
expect(setFileNameMin("foo.js", "$1.min.js", "public")).toBe(
"public/foo.min.js"
));
test("should return file name min in place", () =>
expect(
setFileNameMin("src/foo.js", "$1.min.js", undefined, true)
).toBe("src/foo.min.js"));
test("should normalize windows-style input separators to forward slashes", () =>
expect(
setFileNameMin("src\\foo.js", "$1.min.js", undefined, true)
).toBe("src/foo.min.js"));
test("should normalize backslash public folder to forward slashes", () =>
expect(setFileNameMin("foo.js", "$1.min.js", "public\\")).toBe(
"public/foo.min.js"
));
test("should throw if no file", () => {
expect(() => setFileNameMin("", "$1.min.js")).toThrow(
ValidationError
);
});
test("should throw if output does not contain $1", () => {
expect(() => setFileNameMin("foo.js", "min.js")).toThrow(
ValidationError
);
});
test("should throw if file has no extension", () => {
expect(() => setFileNameMin("foo", "$1.min.js")).toThrow(
ValidationError
);
});
test("should throw if publicFolder is not a string", () => {
expect(() =>
setFileNameMin("foo.js", "$1.min.js", 123 as any)
).toThrow(ValidationError);
});
test("should throw generic error if something unexpected happens", () => {
const spy = vi.spyOn(path.posix, "parse").mockImplementation(() => {
throw new Error("Unexpected error");
});
try {
expect(() => setFileNameMin("foo.js", "$1.min.js")).toThrow(
ValidationError
);
} finally {
spy.mockRestore();
}
});
});
describe("getFilesizeGzippedInBytes", () => {
test("should return file size", (): Promise<void> =>
new Promise<void>((done) => {
getFilesizeGzippedInBytes(fixtureFile).then((size) => {
expect(size).toMatch(/(44 B)|(45 B)/);
done();
});
}));
test("should throw if file does not exist", async () => {
await expect(
getFilesizeGzippedInBytes("fake.js")
).rejects.toThrow();
});
test("should throw if path is a directory", async () => {
const dirPath = __dirname || ".";
await expect(getFilesizeGzippedInBytes(dirPath)).rejects.toThrow();
});
});
describe("getFilesizeGzippedRaw", () => {
test("should return file size in bytes", async () => {
const size = await getFilesizeGzippedRaw(fixtureFile);
expect(typeof size).toBe("number");
expect(size).toBeGreaterThan(0);
});
test("should throw FileOperationError if file does not exist", async () => {
await expect(getFilesizeGzippedRaw("fake.js")).rejects.toThrow(
FileOperationError
);
});
test("should throw FileOperationError if path is a directory", async () => {
await expect(getFilesizeGzippedRaw(__dirname)).rejects.toThrow(
FileOperationError
);
});
});
describe("getFilesizeBrotliInBytes", () => {
test("should return file size", async () => {
const size = await getFilesizeBrotliInBytes(fixtureFile);
expect(size).toMatch(/\d+ B/);
expect(size.length).toBeGreaterThan(0);
});
test("should throw if file does not exist", async () => {
await expect(getFilesizeBrotliInBytes("fake.js")).rejects.toThrow(
FileOperationError
);
});
test("should throw if path is a directory", async () => {
const dirPath = __dirname || ".";
await expect(getFilesizeBrotliInBytes(dirPath)).rejects.toThrow(
FileOperationError
);
});
test("should throw FileOperationError with correct message", async () => {
try {
await getFilesizeBrotliInBytes("non-existent-file.js");
throw new Error("Expected FileOperationError");
} catch (error) {
expect(error).toBeInstanceOf(FileOperationError);
expect((error as Error).message).toContain("Failed to");
}
});
});
describe("getFilesizeBrotliRaw", () => {
test("should return file size as number", async () => {
const size = await getFilesizeBrotliRaw(fixtureFile);
expect(typeof size).toBe("number");
expect(size).toBeGreaterThan(0);
});
test("should throw if file does not exist", async () => {
await expect(getFilesizeBrotliRaw("fake.js")).rejects.toThrow(
FileOperationError
);
});
test("should throw if path is a directory", async () => {
const dirPath = __dirname || ".";
await expect(getFilesizeBrotliRaw(dirPath)).rejects.toThrow(
FileOperationError
);
});
});
describe("getContentFromFiles", () => {
test("should return content from a single file", () => {
const content = getContentFromFiles(fixtureFile);
expect(content).toContain("console.log('content');");
});
test("should return content from multiple files", () => {
const content = getContentFromFiles([fixtureFile, fixtureFile]);
expect(content).toContain("console.log('content');");
});
test("should return empty string for empty array", () => {
expect(getContentFromFiles([])).toBe("");
});
test("should throw if input is null", () => {
expect(() => getContentFromFiles(null as any)).toThrow();
});
test("should throw if one file does not exist", () => {
expect(() =>
getContentFromFiles([fixtureFile, "fake.js"])
).toThrow();
});
test("should throw if one path is a directory", () => {
expect(() =>
getContentFromFiles([fixtureFile, __dirname])
).toThrow();
});
});
describe("compressSingleFile", () => {
test("should compress with content", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
content: "content",
} as any;
const result = await compressSingleFile(settings);
expect(result).toBe("minified");
});
test("should compress with input file", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
input: fixtureFile,
} as any;
const result = await compressSingleFile(settings);
expect(result).toBe("minified");
});
test("should return empty string if no content or input", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
} as any;
await compressSingleFile(settings);
expect(compressor).toHaveBeenCalledWith(
expect.objectContaining({ content: "" })
);
});
test("should return empty string when input is undefined", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "" });
const settings = {
compressor,
input: undefined,
content: undefined,
} as any;
const result = await compressSingleFile(settings);
expect(result).toBe("");
expect(compressor).toHaveBeenCalledWith(
expect.objectContaining({ content: "" })
);
});
});
describe("warnDeprecation", () => {
beforeEach(() => {
resetDeprecationWarnings();
vi.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});
test("should warn once for a package", () => {
warnDeprecation("test-package", "This is deprecated");
expect(console.warn).toHaveBeenCalledTimes(1);
expect(console.warn).toHaveBeenCalledWith(
"[@node-minify/test-package] DEPRECATED: This is deprecated"
);
});
test("should not warn twice for the same package", () => {
warnDeprecation("test-package", "This is deprecated");
warnDeprecation("test-package", "This is deprecated");
expect(console.warn).toHaveBeenCalledTimes(1);
});
test("should warn separately for different packages", () => {
warnDeprecation("package-a", "Deprecated A");
warnDeprecation("package-b", "Deprecated B");
expect(console.warn).toHaveBeenCalledTimes(2);
});
});
describe("resetDeprecationWarnings", () => {
beforeEach(() => {
vi.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => {
resetDeprecationWarnings();
vi.restoreAllMocks();
});
test("should allow warning again after reset", () => {
warnDeprecation("test-package", "First warning");
expect(console.warn).toHaveBeenCalledTimes(1);
resetDeprecationWarnings();
warnDeprecation("test-package", "Second warning");
expect(console.warn).toHaveBeenCalledTimes(2);
});
});
describe("toBuildArgsOptions", () => {
test("should keep string values", () => {
expect(toBuildArgsOptions({ foo: "bar" })).toEqual({ foo: "bar" });
});
test("should keep number values", () => {
expect(toBuildArgsOptions({ count: 42 })).toEqual({ count: 42 });
});
test("should keep boolean values", () => {
expect(toBuildArgsOptions({ enabled: true })).toEqual({
enabled: true,
});
});
test("should keep undefined values", () => {
expect(toBuildArgsOptions({ opt: undefined })).toEqual({
opt: undefined,
});
});
test("should filter out object values", () => {
expect(toBuildArgsOptions({ nested: { a: 1 } })).toEqual({});
});
test("should filter out array values", () => {
expect(toBuildArgsOptions({ list: [1, 2, 3] })).toEqual({});
});
test("should filter out null values", () => {
expect(toBuildArgsOptions({ empty: null })).toEqual({});
});
test("should handle mixed values", () => {
const input = {
str: "value",
num: 123,
bool: false,
obj: { nested: true },
arr: [1, 2],
undef: undefined,
};
expect(toBuildArgsOptions(input)).toEqual({
str: "value",
num: 123,
bool: false,
undef: undefined,
});
});
});
describe("run with file output", () => {
const tmpDir = `${__dirname}/../../../tests/tmp`;
test("should write output file when output is specified", async () => {
const outputFile = `${tmpDir}/run-output.js`;
filesToCleanup.add(outputFile);
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
} as any;
await run({ settings, content: "content" });
expect(readFile(outputFile)).toBe("minified");
});
test("should write source map when result includes map", async () => {
const outputFile = `${tmpDir}/run-output-map.js`;
const mapFile = `${tmpDir}/run-output-map.js.map`;
filesToCleanup.add(outputFile);
filesToCleanup.add(mapFile);
const compressor = vi.fn().mockResolvedValue({
code: "minified",
map: '{"version":3}',
});
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
options: {
sourceMap: { url: mapFile },
},
} as any;
await run({ settings, content: "content" });
expect(readFile(outputFile)).toBe("minified");
expect(readFile(mapFile)).toBe('{"version":3}');
});
test("should use sourceMap.filename if url not present", async () => {
const outputFile = `${tmpDir}/run-output-filename.js`;
const mapFile = `${tmpDir}/run-output-filename.js.map`;
filesToCleanup.add(outputFile);
filesToCleanup.add(mapFile);
const compressor = vi.fn().mockResolvedValue({
code: "minified",
map: '{"version":3}',
});
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
options: {
sourceMap: { filename: mapFile },
},
} as any;
await run({ settings, content: "content" });
expect(readFile(mapFile)).toBe('{"version":3}');
});
test("should use _sourceMap.url as fallback", async () => {
const outputFile = `${tmpDir}/run-output-underscore.js`;
const mapFile = `${tmpDir}/run-output-underscore.js.map`;
filesToCleanup.add(outputFile);
filesToCleanup.add(mapFile);
const compressor = vi.fn().mockResolvedValue({
code: "minified",
map: '{"version":3}',
});
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
options: {
_sourceMap: { url: mapFile },
},
} as any;
await run({ settings, content: "content" });
expect(readFile(mapFile)).toBe('{"version":3}');
});
test("should not write source map if no url found", async () => {
const outputFile = `${tmpDir}/run-output-nomap.js`;
filesToCleanup.add(outputFile);
const compressor = vi.fn().mockResolvedValue({
code: "minified",
map: '{"version":3}',
});
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
options: {
sourceMap: { inline: true },
},
} as any;
await run({ settings, content: "content" });
expect(readFile(outputFile)).toBe("minified");
});
test("should not write files in memory mode", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
content: "source content",
} as any;
const result = await run({ settings, content: "source content" });
expect(result).toBe("minified");
});
test("should not write files when no output specified", async () => {
const compressor = vi.fn().mockResolvedValue({ code: "minified" });
const settings = {
compressor,
input: fixtureFile,
} as any;
const result = await run({ settings, content: "content" });
expect(result).toBe("minified");
});
test("should not write source map when options is undefined", async () => {
const outputFile = `${tmpDir}/run-output-no-options.js`;
filesToCleanup.add(outputFile);
const compressor = vi.fn().mockResolvedValue({
code: "minified",
map: '{"version":3}',
});
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
} as any;
await run({ settings, content: "content" });
expect(readFile(outputFile)).toBe("minified");
});
});
describe("run with buffer output (image compression)", () => {
const tmpDir = `${__dirname}/../../../tests/tmp`;
test("should write buffer output to file", async () => {
const outputFile = `${tmpDir}/buffer-output.png`;
filesToCleanup.add(outputFile);
const bufferContent = Buffer.from([0x89, 0x50, 0x4e, 0x47]); // PNG header
const compressor = vi.fn().mockResolvedValue({
code: "",
buffer: bufferContent,
});
const settings = {
compressor,
input: `${tmpDir}/input.png`,
output: outputFile,
} as any;
const result = await run({ settings, content: "" });
expect(result).toBe("");
const writtenContent = readFile(outputFile, true);
expect(writtenContent).toBeInstanceOf(Buffer);
expect(Buffer.isBuffer(writtenContent)).toBe(true);
});
test("should not write file in memory mode with buffer", async () => {
const bufferContent = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const compressor = vi.fn().mockResolvedValue({
code: "",
buffer: bufferContent,
});
const settings = {
compressor,
content: "source content",
} as any;
const result = await run({ settings, content: "source content" });
expect(result).toBe("");
});
});
describe("run with allowEmptyOutput", () => {
const tmpDir = `${__dirname}/../../../tests/tmp`;
test("should not write file when allowEmptyOutput is true and result is empty", async () => {
const outputFile = `${tmpDir}/empty-output-allowed.js`;
filesToCleanup.add(outputFile);
const compressor = vi.fn().mockResolvedValue({ code: "" });
const settings = {
compressor,
input: fixtureFile,
output: outputFile,
allowEmptyOutput: true,
} as any;