-
Notifications
You must be signed in to change notification settings - Fork 351
/
utils.js
1026 lines (959 loc) · 26 KB
/
utils.js
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
if (typeof process === "undefined") {
global.process = {};
}
const path = require("path");
const chai = require("chai");
const { expect } = chai;
const Errors = require("../errors.js");
const PizZip = require("pizzip");
const fs = require("fs");
const { get, unset, omit, uniq, cloneDeep } = require("lodash");
const errorLogger = require("../error-logger.js");
const diff = require("diff");
const AssertionModule = require("./assertion-module.js");
const Docxtemplater = require("../docxtemplater.js");
const { first } = require("../utils.js");
const xmlPrettify = require("./xml-prettify.js");
let countFiles = 1;
let allStarted = false;
let examplesDirectory;
let snapshotFile;
const documentCache = {};
const imageData = {};
const emptyNamespace = /xmlns:[a-z0-9]+=""/;
function unifiedDiff(actual, expected) {
const indent = " ";
function cleanUp(line) {
const firstChar = first(line);
if (firstChar === "+") {
return indent + line;
}
if (firstChar === "-") {
return indent + line;
}
if (line.match(/@@/)) {
return "--";
}
if (line.match(/\\ No newline/)) {
return null;
}
return indent + line;
}
function notBlank(line) {
return typeof line !== "undefined" && line !== null;
}
const msg = diff.createPatch("string", actual, expected);
const lines = msg.split("\n").splice(5);
return (
"\n " +
"+ expected" +
" " +
"- actual" +
"\n\n" +
lines.map(cleanUp).filter(notBlank).join("\n")
);
}
function walk(dir) {
const results = [];
const list = fs.readdirSync(dir);
list.forEach(function (file) {
if (file.indexOf(".") === 0) {
return;
}
file = dir + "/" + file;
const stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
Array.prototype.push.apply(results, walk(file));
} else {
results.push(file);
}
});
return results;
}
function createXmlTemplaterDocxNoRender(content, options = {}) {
const doc = makeDocx(content);
doc.setOptions(options);
doc.setData(options.tags);
return doc;
}
function createXmlTemplaterDocx(content, options = {}) {
const doc = makeDocx(content, options);
doc.setOptions(options);
doc.setData(options.tags);
doc.render();
return doc;
}
function writeFile(expectedName, zip) {
if (path.resolve) {
if (fs.writeFileSync) {
const writeFile =
// eslint-disable-next-line no-process-env
process.env.UPDATE === "true"
? path.resolve(examplesDirectory, expectedName)
: path.resolve(examplesDirectory, "..", expectedName);
fs.writeFileSync(
writeFile,
zip.generate({ type: "nodebuffer", compression: "DEFLATE" })
);
}
if (typeof window !== "undefined" && window.saveAs) {
const out = zip.generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
saveAs(out, expectedName); // comment to see the error
}
}
}
function unlinkFile(expectedName) {
if (path.resolve) {
const writeFile = path.resolve(examplesDirectory, "..", expectedName);
try {
fs.unlinkSync(writeFile);
} catch (e) {
if (e.code !== "ENOENT") {
throw e;
}
}
}
}
function getText(file) {
return file.asText().replace(/\n|\t/g, "");
}
function isBinaryFile(file1, file2) {
return (
file1.name.indexOf(".xml") === -1 &&
file1.name.indexOf(".vml") === -1 &&
file1.name.indexOf(".rels") === -1 &&
(file1.options.binary || file2.options.binary)
);
}
function isZip(text) {
const start = text.substr(0, 9);
const zipSignature = "PK\u0003\u0004\n\u0000\u0000\u0000\u0000";
return start === zipSignature;
}
function zipCompare(zip, expectedZip, expectedName) {
uniq(Object.keys(zip.files).concat(Object.keys(expectedZip.files))).map(
function (filePath) {
const suffix = `for "${filePath}"`;
const file = zip.files[filePath];
const expectedFile = expectedZip.files[filePath];
expect(expectedFile).to.be.an(
"object",
`The file ${filePath} doesn't exist on examples/${expectedName}`
);
expect(file).to.be.an(
"object",
`The file ${filePath} doesn't exist on ${expectedName}`
);
expect(file.name).to.be.equal(
expectedFile.name,
`Name differs ${suffix}`
);
expect(file.options.dir).to.be.equal(
expectedFile.options.dir,
`IsDir differs ${suffix}`
);
if (file.options.dir) {
return;
}
if (isBinaryFile(file, expectedFile)) {
const actualHash = file._data.crc32;
const expectedHash = expectedFile._data.crc32;
const actualText = file.asBinary();
if (isZip(actualText)) {
const expectedText = expectedFile.asBinary();
zipCompare(
new PizZip(actualText),
new PizZip(expectedText),
expectedName
);
} else if (actualHash && expectedHash) {
expect(actualHash).to.be.a("number");
expect(actualHash).to.be.equal(
expectedHash,
"Content differs for " + suffix
);
} else {
const expectedText = expectedFile.asBinary();
expect(actualText).to.equal(
expectedText,
`Binary file ${filePath} differs`
);
}
return;
}
const actualText = getText(file);
const expectedText = getText(expectedFile);
expect(actualText).to.not.match(
emptyNamespace,
`The file ${filePath} has empty namespaces`
);
expect(expectedText).to.not.match(
emptyNamespace,
`The file ${filePath} has empty namespaces`
);
if (actualText === expectedText) {
return;
}
const prettyActualText = xmlPrettify(actualText);
const prettyExpectedText = xmlPrettify(expectedText);
if (prettyActualText !== prettyExpectedText) {
const prettyDiff = unifiedDiff(prettyActualText, prettyExpectedText);
expect(prettyActualText).to.be.equal(
prettyExpectedText,
"Content differs \n" + suffix + "\n" + prettyDiff
);
}
}
);
}
/* eslint-disable no-console */
function shouldBeSame({ doc, expectedName }) {
const zip = doc.getZip();
if (!documentCache[expectedName]) {
writeFile(expectedName, zip);
console.log(
JSON.stringify({ msg: "Expected file does not exists", expectedName })
);
throw new Error(
`File ${expectedName} does not exist in examples directory`
);
}
const expectedZip = documentCache[expectedName].zip;
try {
zipCompare(zip, expectedZip, expectedName);
} catch (e) {
writeFile(expectedName, zip);
console.log(
JSON.stringify({
msg: "Expected file differs from actual file",
expectedName,
})
);
throw e;
}
unlinkFile(expectedName);
}
/* eslint-enable no-console */
function checkLength(e, expectedError, propertyPath) {
const propertyPathLength = propertyPath + "Length";
const property = get(e, propertyPath);
const expectedPropertyLength = get(expectedError, propertyPathLength);
if (property && expectedPropertyLength) {
expect(expectedPropertyLength).to.be.a(
"number",
JSON.stringify(expectedError.properties)
);
expect(expectedPropertyLength).to.equal(property.length);
unset(e, propertyPath);
unset(expectedError, propertyPathLength);
}
}
function cleanRecursive(arr) {
if (arr.lexed) {
cleanRecursive(arr.lexed);
cleanRecursive(arr.parsed);
cleanRecursive(arr.postparsed);
return;
}
arr.forEach(function (p) {
delete p.lIndex;
delete p.endLindex;
delete p.offset;
delete p.raw;
if (p.lastParagrapSectPr === "") {
delete p.lastParagrapSectPr;
}
if (p.subparsed) {
cleanRecursive(p.subparsed);
}
if (p.value && p.value.forEach) {
p.value.forEach(cleanRecursive);
}
if (p.expanded) {
p.expanded.forEach(cleanRecursive);
}
});
}
// eslint-disable-next-line complexity
function cleanError(e, expectedError) {
const message = e.message;
e = omit(e, ["line", "sourceURL", "stack"]);
e.message = message;
if (expectedError.properties && e.properties) {
if (!e.properties.explanation) {
throw new Error("No explanation for this error");
}
if (expectedError.properties.explanation != null) {
const e1 = e.properties.explanation;
const e2 = expectedError.properties.explanation;
expect(e1).to.be.deep.equal(
e2,
`Explanations differ '${e1}' != '${e2}': for ${JSON.stringify(
expectedError
)}`
);
}
delete e.properties.explanation;
delete expectedError.properties.explanation;
if (e.properties.postparsed) {
e.properties.postparsed.forEach(function (p) {
delete p.lIndex;
delete p.endLindex;
delete p.offset;
});
}
if (e.properties.rootError) {
expect(
e.properties.rootError,
JSON.stringify(e.properties)
).to.be.instanceOf(Error, "rootError doesn't have correct type");
expect(
expectedError.properties.rootError,
JSON.stringify(expectedError.properties)
).to.be.instanceOf(Object, "expectedError doesn't have a rootError");
if (expectedError) {
expect(e.properties.rootError.message).to.equal(
expectedError.properties.rootError.message,
"rootError.message"
);
}
delete e.properties.rootError;
delete expectedError.properties.rootError;
}
if (expectedError.properties.offset != null) {
const o1 = e.properties.offset;
const o2 = expectedError.properties.offset;
// offset can be arrays, so deep compare
expect(o1).to.be.deep.equal(
o2,
`Offset differ ${o1} != ${o2}: for ${JSON.stringify(expectedError)}`
);
}
delete expectedError.properties.offset;
delete e.properties.offset;
checkLength(e, expectedError, "properties.paragraphParts");
checkLength(e, expectedError, "properties.postparsed");
checkLength(e, expectedError, "properties.parsed");
}
if (e.stack && expectedError) {
expect(e.stack).to.contain("Error: " + expectedError.message);
}
delete e.stack;
return e;
}
function wrapMultiError(error) {
const type = Object.prototype.toString.call(error);
let errors;
if (type === "[object Array]") {
errors = error;
} else {
errors = [error];
}
return {
name: "TemplateError",
message: "Multi error",
properties: {
id: "multi_error",
errors,
},
};
}
function jsonifyError(e) {
return JSON.parse(
JSON.stringify(e, function (key, value) {
if (value instanceof Promise) {
return {};
}
return value;
})
);
}
function errorVerifier(e, type, expectedError) {
const toShowOnFail = e.stack;
expect(e, "No error has been thrown").not.to.be.equal(null);
expect(e, toShowOnFail).to.be.instanceOf(
Error,
"error is not a Javascript error"
);
expect(e, toShowOnFail).to.be.instanceOf(
type,
"error doesn't have the correct type"
);
e = cloneDeep(e);
expectedError = cloneDeep(expectedError);
expect(e, toShowOnFail).to.be.an("object");
expect(e, toShowOnFail).to.have.property("properties");
expect(e.properties, toShowOnFail).to.be.an("object");
if (type.name && type.name !== "XTInternalError") {
expect(e.properties, toShowOnFail).to.have.property("explanation");
expect(e.properties.explanation, toShowOnFail).to.be.a("string");
expect(e.properties.explanation, toShowOnFail).to.be.a("string");
}
if (e.properties.id) {
expect(e.properties.id, toShowOnFail).to.be.a("string");
}
e = cleanError(e, expectedError);
if (e.properties.errors) {
const msg =
"expected : \n" +
JSON.stringify(expectedError.properties.errors) +
"\nactual : \n" +
JSON.stringify(e.properties.errors);
expect(expectedError.properties.errors).to.be.an("array", msg);
const l1 = e.properties.errors.length;
const l2 = expectedError.properties.errors.length;
expect(l1).to.equal(
l2,
`Expected to have the same amount of e.properties.errors ${l1} !== ${l2} ` +
msg
);
e.properties.errors = e.properties.errors.map(function (suberror, i) {
const cleaned = cleanError(suberror, expectedError.properties.errors[i]);
const jsonified = jsonifyError(cleaned);
return jsonified;
});
}
const realError = jsonifyError(e);
expect(realError).to.be.deep.equal(expectedError);
}
function expectToThrow(fn, type, expectedError) {
let err = null;
try {
fn();
} catch (e) {
err = e;
}
if (!type) {
expect(err).to.satisfy(function (err) {
return !!err;
});
return;
}
errorVerifier(err, type, expectedError);
}
function expectToThrowAsync(fn, type, expectedError) {
return Promise.resolve(null)
.then(function () {
const r = fn();
return r.then(function () {
return null;
});
})
.catch(function (error) {
return error;
})
.then(function (err) {
if (!type) {
expect(err).to.satisfy(function (err) {
return !!err;
});
return;
}
errorVerifier(err, type, expectedError);
});
}
function expectToThrowSnapshot(fn, update) {
let err = null;
try {
fn();
} catch (e) {
err = e;
}
if (!err) {
throw new Error("No error was thrown in this expectToThrowSnapshot");
}
expect(errToObject(err)).to.matchSnapshot(update);
}
function expectToThrowAsyncSnapshot(fn, update) {
let myErr = null;
return Promise.resolve(null)
.then(function () {
const r = fn();
return r.then(function () {
return null;
});
})
.catch(function (error) {
myErr = error;
})
.then(function () {
if (!myErr) {
throw new Error("No error was thrown in this expectToThrowSnapshot");
}
expect(errToObject(myErr)).to.matchSnapshot(update);
});
}
function errToObject(err) {
const obj = {};
if (err instanceof Errors.XTTemplateError) {
obj._type = "XTTemplateError";
} else if (err instanceof Errors.XTAPIVersionError) {
obj._type = "XTAPIVersionError";
} else if (err instanceof Errors.XTRenderingError) {
obj._type = "XTRenderingError";
} else if (err instanceof Errors.XTScopeParserError) {
obj._type = "XTScopeParserError";
} else if (err instanceof Errors.XTInternalError) {
obj._type = "XTInternalError";
} else if (err instanceof Errors.XTAPIVersionError) {
obj._type = "XTAPIVersionError";
}
if (err.name) {
obj.name = err.name;
}
if (err.message) {
obj.message = err.message;
}
if (err.properties) {
obj.properties = {};
Object.keys(err.properties).forEach(function (key) {
const value = err.properties[key];
if (value instanceof Error) {
obj.properties[key] = errToObject(value);
return;
}
if (value instanceof Array) {
obj.properties[key] = value.map(function (value) {
if (value instanceof Error) {
return errToObject(value);
}
return value;
});
return;
}
obj.properties[key] = value;
});
}
return obj;
}
function load(name, content, cache) {
const zip = new PizZip(content);
const doc = new Docxtemplater();
doc.loadZip(zip);
doc.loadedName = name;
doc.loadedContent = content;
cache[name] = doc;
return doc;
}
function loadDocument(name, content) {
return load(name, content, documentCache);
}
function cacheDocument(name, content) {
const zip = new PizZip(content);
documentCache[name] = { loadedName: name, loadedContent: content, zip };
return documentCache[name];
}
function loadImage(name, content) {
imageData[name] = content;
}
function loadFile(name, callback) {
if (fs.readFileSync) {
const path = require("path");
const buffer = fs.readFileSync(path.join(examplesDirectory, name));
return callback(null, name, buffer);
}
return PizZipUtils.getBinaryContent(
"../examples/" + name,
function (err, data) {
if (err) {
return callback(err);
}
return callback(null, name, data);
}
);
}
function unhandledRejectionHandler(reason) {
throw reason;
}
const writeSnapshots =
typeof process !== "undefined" &&
// eslint-disable-next-line no-process-env
process.env &&
// eslint-disable-next-line no-process-env
process.env.WRITE_SNAPSHOTS === "true";
let startFunction;
function setStartFunction(sf, snapshots = {}) {
allStarted = false;
countFiles = 1;
startFunction = sf;
const runnedSnapshots = {};
let fullTestName = "";
function matchSnapshot() {
let ftn = fullTestName;
let i = 0;
while (runnedSnapshots[ftn]) {
i++;
ftn = fullTestName + "-" + i;
}
runnedSnapshots[ftn] = true;
const obj = JSON.parse(JSON.stringify(this.__flags.object));
if (!snapshots[ftn]) {
snapshots[ftn] = obj;
if (!writeSnapshots) {
throw new Error(`Snapshot not found for '${ftn}'`);
}
return;
}
try {
expect(obj).to.deep.equal(snapshots[ftn]);
} catch (e) {
if (writeSnapshots) {
snapshots[ftn] = obj;
return;
}
throw e;
}
}
beforeEach(function () {
function getParentsTitle(a) {
if (a.parent) {
return `${a.parent.title} ${getParentsTitle(a.parent)}`;
}
return "";
}
fullTestName = getParentsTitle(this.currentTest) + this.currentTest.title;
fullTestName = fullTestName.trim().replace(/\s+/g, " ");
});
after(function () {
if (writeSnapshots) {
const sortedKeys = Object.keys(snapshots).sort();
const output =
"/***************** This file is autogenerated *****************************\n\n" +
" Please don't modify it manually !\n" +
" Instead, to update the file, run :\n\n" +
" npm run test:es6:update-snapshots\n*/\n\n" +
sortedKeys
.map(function (key) {
const snap = snapshots[key];
if (typeof snap === "string") {
return "exports[`" + key + "`] = `" + snap + "`";
}
return "exports[`" + key + "`] = " + JSON.stringify(snap, null, 2);
})
.join("\n\n") +
"\n\n";
fs.writeFileSync(snapshotFile, output);
}
});
chai.use(function () {
chai.Assertion.addMethod("matchSnapshot", matchSnapshot);
});
if (typeof window !== "undefined" && window.addEventListener) {
window.addEventListener("unhandledrejection", unhandledRejectionHandler);
} else {
process.on("unhandledRejection", unhandledRejectionHandler);
}
}
function endLoadFile(change) {
change = change || 0;
countFiles += change;
if (countFiles === 0 && allStarted === true) {
const result = startFunction();
if (typeof window !== "undefined") {
return window.mocha.run(() => {
const elemDiv = window.document.getElementById("status");
elemDiv.textContent = "FINISHED";
document.body.appendChild(elemDiv);
});
}
return result;
}
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function endsWithOne(str, suffixes) {
return suffixes.some(function (suffix) {
return endsWith(str, suffix);
});
}
function startsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
/* eslint-disable no-console */
function start() {
afterEach(function () {
if (
this.currentTest.state === "failed" &&
this.currentTest.err.properties
) {
errorLogger(this.currentTest.err, "jsonl");
}
});
let fileNames;
if (typeof global !== "undefined" && global.fileNames) {
fileNames = global.fileNames;
} else {
fileNames = require("./filenames.js");
}
/* eslint-disable import/no-unresolved */
/* eslint-enable import/no-unresolved */
fileNames.forEach(function (fullFileName) {
const fileName = fullFileName.replace(examplesDirectory + "/", "");
let callback;
if (startsWith(fileName, ".") || startsWith(fileName, "~")) {
return;
}
if (
endsWithOne(fileName, [
".docm",
".docx",
".dotm",
".dotx",
".potm",
".potx",
".pptm",
".pptx",
".xlsm",
".xlsx",
".xltm",
".xltx",
])
) {
callback = cacheDocument;
}
if (!callback) {
callback = loadImage;
}
countFiles++;
loadFile(fileName, (e, name, buffer) => {
if (e) {
console.log(e);
throw e;
}
endLoadFile(-1);
callback(name, buffer);
});
});
allStarted = true;
endLoadFile(-1);
}
/* eslint-disable no-console */
function setExamplesDirectory(ed) {
examplesDirectory = ed;
if (fs && fs.writeFileSync) {
const fileNames = walk(examplesDirectory).map(function (f) {
return f.replace(examplesDirectory + "/", "");
});
fs.writeFileSync(
path.resolve(__dirname, "filenames.js"),
"module.exports=" + JSON.stringify(fileNames)
);
global.fileNames = fileNames;
}
}
function setSnapshotFile(file) {
snapshotFile = file;
}
function removeSpaces(text) {
return text.replace(/\n|\t/g, "");
}
const docxContentTypeContent = `<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>`;
const docxRelsContent = `<?xml version="1.0" encoding="utf-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties" Target="docProps/custom.xml"/>
<Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>
`;
const pptxRelsContent = `<?xml version="1.0" encoding="utf-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>
</Relationships>
`;
function makeDocx(content) {
const zip = new PizZip();
zip.file("word/document.xml", content, { createFolders: true });
zip.file("[Content_Types].xml", docxContentTypeContent);
zip.file("_rels/.rels", docxRelsContent);
const doc = new Docxtemplater();
doc.loadZip(zip);
return doc;
}
function makeDocxV4(content, options = {}) {
const zip = new PizZip();
zip.file("word/document.xml", content, { createFolders: true });
zip.file("[Content_Types].xml", docxContentTypeContent);
zip.file("_rels/.rels", docxRelsContent);
return new Docxtemplater(zip, options);
}
const pptxContentTypeContent = `<?xml version="1.0" encoding="utf-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>
</Types>`;
function makePptx(name, content) {
const zip = new PizZip();
zip.file("ppt/slides/slide1.xml", content, { createFolders: true });
zip.file("[Content_Types].xml", pptxContentTypeContent);
zip.file("_rels/.rels", pptxRelsContent);
return load(name, zip.generate({ type: "string" }), documentCache);
}
function makePptxV4(content, options = {}) {
const zip = new PizZip();
zip.file("ppt/slides/slide1.xml", content, { createFolders: true });
zip.file("[Content_Types].xml", pptxContentTypeContent);
zip.file("_rels/.rels", pptxRelsContent);
return new Docxtemplater(zip, options);
}
function createDoc(name, options = {}) {
if (!documentCache[name]) {
throw new Error(
`File "examples/${name}" does not exist, please create the file`
);
}
const doc = loadDocument(name, documentCache[name].loadedContent);
if (options.assertModule == null) {
doc.attachModule(new AssertionModule());
}
delete options.assertModule;
if (options.modules) {
options.modules.forEach(function (module) {
doc.attachModule(module);
});
}
doc.setOptions(options);
return doc;
}
function createDocV4(name, options = {}) {
const zip = getZip(name);
options.modules ||= [];
const moduleNames = options.modules.map(function ({ name }) {
return name;
});
if (
options.assertModule == null &&
moduleNames.indexOf("AssertionModule") === -1
) {
options.modules.push(new AssertionModule());
}
delete options.assertModule;
return new Docxtemplater(zip, options);
}
function getZip(name) {
if (
documentCache[name] === undefined ||
documentCache[name].loadedContent === undefined
) {
throw new Error("The file examples/" + name + " doesn't exist");
}
return new PizZip(documentCache[name].loadedContent);
}
function getLoadedContent(name) {
return documentCache[name].loadedContent;
}
function getContent(doc) {
return doc.getZip().files["word/document.xml"].asText();
}
function resolveSoon(data, time = 1) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(data);
}, time);
});
}
function rejectSoon(data, time = 1) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
reject(data);
}, time);
});
}
function getParameterByName(name) {
if (typeof window === "undefined") {
return null;
}
const url = window.location.href;
name = name.replace(/[[\]]/g, "\\$&");
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) {
return null;
}
if (!results[2]) {
return "";
}
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function browserMatches(regex) {
const currentBrowser = getParameterByName("browser");
if (currentBrowser === null) {
return false;
}
return regex.test(currentBrowser);
}
function getLength(obj) {
if (obj instanceof ArrayBuffer) {
return obj.byteLength;
}
return obj.length;
}
function captureLogs() {
const oldLog = console.log;
const collected = [];
console.log = function (a) {
// oldLog(a);
collected.push(a);
};
return {
logs() {
return collected;
},
stop() {
console.log = oldLog;
},
};
}
module.exports = {
chai,
cleanError,
cleanRecursive,
createDoc,
getLoadedContent,
createXmlTemplaterDocx,
createXmlTemplaterDocxNoRender,
expect,
expectToThrow,
expectToThrowSnapshot,
expectToThrowAsync,
expectToThrowAsyncSnapshot,