Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1243 lines (1105 loc) · 40.3 KB
/
Copy pathapp.js
File metadata and controls
1243 lines (1105 loc) · 40.3 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
// app.js
// Copyright 2019-2026, Namhyeon Go <gnh1201@catswords.re.kr>, Catswords OSS, WelsonJS contributors.
// SPDX-License-Identifier: GPL-3.0-or-later
// https://github.com/gnh1201/welsonjs
// #OPENTOWORK
//
// Bootstrap code for running a javascript app in windows. Run as:
// cscript.js app.js <appname> <app arguments> ...
//
"use strict";
var ALLOW_UNSAFE_EVAL = false; // Verify the evaluator with testEvaluator() before using eval().
var STRICT_INTEGRITY = false; // When enabled, only scripts matching a trusted integrity hash may execute.
var INTEGRITY_ALGORITHM = "default"; // "default" uses Adler-32; SHA-256/384/512 use the built-in .NET implementation.
var INTEGRITY_ALLOWED_ALGORITHMS = {
"sha1": false, // Enable only for compatibility with Windows XP and earlier.
"sha256": true,
"sha384": true,
"sha512": true
};
var INTEGRITY_HASHES = {/* // Integrity hashes for the "helloworld" example
"7b5c4d89": true, "779be011": true, "c9dee731": true,
"f1f021aa": true, "31868529": true, "33a07569": true,
"bef1d428": true, "fc87516d": true, "45d5a78b": true,
"38768236": true, "c51e7fc4": true, "cbd7d9d6": true,
"8c47c4c5": true, "3b0772dd": true, "2eb51cc4": true,
"59d846e3": true, "ed349cb7": true, "68b231de": true,
"5e5157c1": true, "e1de4567": true, "98524d82": true
*/};
/**
* @param {number} status The exit status code.
*/
var exit = function(status) {
console.error("Exit", status, "caused");
if (typeof WScript !== "undefined") {
WScript.Quit(status);
return;
} else if (typeof window !== "undefined") {
window.close();
return;
}
// to exit completely
throw new Error("Exit " + status + " caused");
};
/**
* @param {Function} f The function to execute.
* @param {any} defaultValue The default value to return if the function throws an error.
* @param {Function} finalizer The function to execute after the function is executed, regardless of whether it throws an error or not.
* @param {Function} fallback The function to execute if the function throws an error.
* @param {Error} error The error object to pass to the fallback function.
*/
var optional = function(f, defaultValue, finalizer, fallback, error) {
var result = defaultValue;
var currentError = null;
try {
if (typeof f !== "function") {
throw new Error("The first argument must be a function");
}
result = f(error);
} catch (e) {
currentError = e;
if (typeof fallback === "function") {
result = optional(fallback, defaultValue, null, null, currentError); // call fallback with the error
}
} finally {
if (typeof finalizer === "function") {
try {
finalizer(result, currentError);
} catch (e) {
return result; // ignore the error in finalizer
}
}
}
return result;
};
/**
* @type {Object} console The console object for logging messages.
*/
var console = {
_timers: {},
_counters: {},
_messages: [],
_join: function(args, sep) {
args = args || [];
sep = sep || ' ';
var res = '';
for (var i = args.length - 1; i > -1; i--) {
res = (i ? sep : '') + args[i] + res;
}
return res;
},
_muted: (function() {
return optional(function() {
return WScript.Arguments.Named.Exists("quiet");
}, false);
})(),
_stderr: typeof WScript !== "undefined" ? WScript.StdErr : null,
_stdout: typeof WScript !== "undefined" ? WScript.StdOut : null,
_stdin: typeof WScript !== "undefined" ? WScript.StdIn : null,
_echoCallback: function(params, type) {
if (this._muted) return;
if (typeof WScript !== "undefined") {
if (this._muted) {
this._stderr.WriteLine("[*] " + params.message);
return;
}
this._stdout.WriteLine("[*] " + params.message);
}
},
_echo: function(args, type) {
var messages = [];
var params = {
type: type,
scope: [],
message: '',
datetime: new Date().toISOString()
};
var argl = args.length;
for (var i = 0; i < argl; i++) {
switch (typeof args[i]) {
case "string":
messages.push(args[i]);
break;
case "number":
case "boolean":
messages.push(String(args[i]));
break;
case "object":
if ("message" in args[i]) {
messages.push(args[i].message);
for (var k in args[i]) {
params[k] = args[i][k];
}
} else {
messages.push("[object Object]");
}
break;
case "unknown":
messages.push("[unknown]");
break;
}
}
params.message = messages.join(' ');
if (typeof type !== "undefined") {
params.message = type + ": " + params.message;
}
this._echoCallback(params);
this._messages.push(params.message);
if (params.scope.length > 0) {
this._echoCallback(params, type);
}
},
assert: function(assertion) {
if (arguments.length > 1 && assertion === arguments[0]) {
if(!assertion) {
this.error("Assertion failed:", this._join(arguments.slice(1)));
}
}
},
clear: function() {
this._messages = [];
},
log: function() {
this._echo(arguments);
},
error: function() {
this._echo(arguments, "error");
},
info: function() {
this._echo(arguments, "info");
},
warn: function() {
this._echo(arguments, "warn");
},
debug: function() {
this._echo(arguments, "debug");
},
trace: function() {
try {
var callee = arguments.callee.caller.caller;
throw new TraceError("DEBUG", "", callee);
} catch (e) {
this.debug(e.message);
}
},
time: function(label) {
label = label || "default";
if (!(label in this._timers)) {
this._timers[label] = new Date();
}
},
timeLog: function(label, end) {
label = label || "default";
if (label in this._timers) {
console.debug(label + ":", ((new Date()).getTime() - this._timers[label].getTime()) + "ms", (end ? " - timer ended" : ""));
}
},
timeEnd: function(label) {
label = label || "default";
if (label in this._timers) {
this.timeLog();
delete this._timers[label];
}
},
count: function(label) {
label = label || "default";
if (!(label in this._counters)) {
this._counters[label] = 1;
}
},
countReset: function(label) {
label = label || "default";
if (label in this._counters) {
this.timeLog();
delete this._counters[label];
}
}
};
/**
*
* @param {string} severity The severity level of the error (e.g., "ERROR", "WARN", "INFO", "DEBUG").
* @param {string} message The error message.
* @param {Function} callee The function that caused the error (optional).
*/
function TraceError(severity, message, callee) {
var MAX_DEPTH = 20;
var SEVERITY_MAP = {
"": "ERROR",
"LOG": "INFO",
"INFO": "INFO",
"WARN": "WARN",
"WARNING": "WARN",
"ERROR": "ERROR",
"ERR": "ERROR",
"CRITICAL": "ERROR",
"FATAL": "ERROR",
"DEBUG": "DEBUG"
};
var CONSOLE_METHOD_MAP = {
"ERROR": "error",
"WARN": "warn",
"INFO": "info",
"DEBUG": "debug"
};
function fnName(fn) {
return fn ? (fn.__name__ || fn.name || "(anonymous)") : "(null)";
}
function normSeverity(s) {
s = (s == null) ? "" : String(s);
s = s.toUpperCase();
return SEVERITY_MAP[s] || (s || "ERROR");
}
function callersOf(startFn) {
var out = [];
var f = startFn;
var i = 0;
while (f && i < MAX_DEPTH) {
out[out.length] = fnName(f);
try {
f = f.caller;
} catch (e) {
break;
}
i++;
}
return out;
}
function pickConsoleFn(sev) {
if (typeof console === "undefined" || !console)
return null;
var methodName = CONSOLE_METHOD_MAP[sev] || "log";
var fn = console[methodName] || console.log;
if (!fn)
return null;
return (function (fns) {
return function (s) {
var i = 0,
result = false
;
while (!result && i < fns.length) {
result = optional(function() {
fns[i](s);
return true;
}, false);
i++;
};
};
})([
function (s) { fn.call(console, s); }, // 1) severity-specific console
function (s) { console.log(s); }, // 2) generic console.log
function (s) { WScript.StdOut.WriteLine(s); } // 3) WSH fallback
]);
}
function buildMessage(name, sev, msg, chain) {
var s = name + " [" + sev + "]";
if (msg) s += ": " + msg;
if (chain) s += "\r\n" + chain;
return s;
}
this.name = "TraceException";
this.severity = normSeverity(severity);
this.message = message || "";
this.description = this.message; // IE friendly
this.callee = callee || null;
this.callers = callersOf(this.callee);
this.callChain = this.callers.length ? this.callers.join("\r\n <- ") : "";
this.fullMessage = buildMessage(this.name, this.severity, this.message, this.callChain);
this.toString = function () {
return this.fullMessage;
};
this._logFn = pickConsoleFn(this.severity);
this.log = function () {
if (this._logFn)
this._logFn(this.fullMessage);
};
this.log();
}
TraceError.prototype = new Error;
if (typeof CreateObject === "undefined") {
var CreateObject = function(progId, serverName, callback) {
var progIds = (progId instanceof Array ? progId : [progId]);
// Try to create the object using the provided ProgIDs.
for (var i = 0; i < progIds.length; i++) {
try {
var normalizedProgId = String(progIds[i]).toLowerCase();
CreateObject.deprecatedWarning(normalizedProgId);
var progIdPaths = normalizedProgId.split(".");
var obj = (CreateObject.managed != null && CreateObject.unmanaged.indexOf(progIdPaths[0]) < 0)
? CreateObject.managed.CreateObject(progIds[i], serverName)
: CreateObject.make(progIds[i], serverName)
;
if (typeof callback === "function") {
callback(obj, progIds[i]);
}
return obj;
} catch (e) {
console.error(e.message);
};
}
};
CreateObject.make = function(p, s) {
if (typeof WScript !== "undefined") {
if ("CreateObject" in WScript) {
return WScript.CreateObject(p, s);
} else {
console.warn("(Chakra) The standalone engine is not supported. Please use the built-in engine.");
console.warn("(Chakra) hint:", "cscript //NoLogo //E:{1b7cd997-e5ff-4932-a7a6-2a9e636da385} app.js <filename> <...arguments>");
throw new Error("Could not find a COM loader");
}
} else if (typeof ActiveXObject !== "undefined") {
return new ActiveXObject(p);
} else {
throw new Error("Could not find a COM loader");
}
};
CreateObject.managed = (function() {
try {
return CreateObject.make("WelsonJS.ManagedObject", null);
} catch (e) {
return null;
}
})();
CreateObject.unmanaged = ["scripting", "adodb", "wscript"];
CreateObject.deprecatedWarning = function(normalizedProgId) {
if (normalizedProgId === "welsonjs.toolkit") {
console.warn("WelsonJS.Toolkit has been deprecated since version 0.2.7.60. Please migrate to WelsonJS.ManagedObject.");
console.warn("https://www.nuget.org/packages/WelsonJS.ManagedObject");
}
};
}
if (typeof UseObject === "undefined") {
var UseObject = function(progId, callback, dispose, fallback) {
if (typeof callback !== "function") {
return null;
}
if (typeof dispose !== "function") {
dispose = function(obj) {
obj.Close();
obj = null;
};
}
return optional(function() {
var obj = CreateObject(progId);
return callback(obj);
}, null, function() {
dispose(obj);
}, fallback);
}
}
/**
* @param {Function} evaluator The evaluator function to test.
* @returns {boolean} `true` if the evaluator is the built-in `eval` function; otherwise, `false`.
*/
function testEvaluator(evaluator) {
return (ALLOW_UNSAFE_EVAL && evaluator === eval);
}
/**
* @param {string} filename The file name.
* @param {boolean} ignoreUnsafeEval Whether to ignore unsafe eval checks.
*/
function evaluateFile(filename, ignoreUnsafeEval) {
try {
var evaluate = eval;
if (!testEvaluator(evaluate) && !ignoreUnsafeEval) {
throw new Error("Unsafe eval is not allowed. Please set ALLOW_UNSAFE_EVAL to true.");
}
return evaluate(require._load(filename));
} catch (e) {
console.error(e.message);
}
}
/**
*
* @param {string} filename The file name.
*/
function __evalFile__(filename) {
return evaluateFile(filename, true);
}
/**
* @param {Function} f A function object.
* @param {string} name The name of the exported function.
*/
function __export__(f, name) {
if (typeof f !== "function") {
return f; // not a function, return as is
}
if (typeof name !== "string" || name == null) {
name = "(anonymous)";
}
var ignoreException = function(e) {
void(e);
}
try {
f.__name__ = name;
} catch (e) {
ignoreException(e);
}
try {
f.name = name;
} catch (e) {
ignoreException(e);
}
var wrapped = function () {
try {
return f.apply(this, arguments);
} catch (e) {
if (typeof TraceError === "function") {
throw new TraceError(
"ERROR",
(e && (e.message || e.description)) ? (e.message || e.description) : "error",
arguments.callee
);
}
}
};
wrapped.__name__ = name;
wrapped.__target__ = f;
return wrapped;
}
/**
* Computes the Adler-32 checksum (RFC 1950).
*
* @param {string} str Input string.
* @returns {number} Unsigned 32-bit Adler-32 checksum.
* @private
*/
function __hash_adler32__(str) {
var BASE = 65521;
var NMAX = 5552;
var a = 1;
var b = 0;
var i = 0;
var len = str.length;
var n;
while (len > 0) {
n = (len > NMAX) ? NMAX : len;
len -= n;
while (n--) {
a += str.charCodeAt(i++);
b += a;
}
a %= BASE;
b %= BASE;
}
return ((b << 16) | a) >>> 0;
}
/**
* Computes a cryptographic hash using the .NET Framework managed
* cryptography classes exposed through COM.
*
* Supported algorithms:
* - sha256
* - sha384
* - sha512
*
* @param {string} str Input string to hash.
* @param {string} algorithm Hash algorithm identifier ("sha256", "sha384", or "sha512").
* @returns {string} Lowercase hexadecimal hash string.
* @throws {Error} If the specified algorithm is not supported.
* @private
*/
function __hash_dotnetfx_managed__(str, algorithm) {
algorithm = String(algorithm || "").toLowerCase();
var allowed_algorithm = INTEGRITY_ALLOWED_ALGORITHMS;
var encoding = "utf-8";
if (!(algorithm in allowed_algorithm && allowed_algorithm[algorithm])) {
throw new Error("Unsupported hash algorithm: " + algorithm);
}
var resolveProgId = function(alias) {
var map = {
"sha1": "System.Security.Cryptography.SHA1Managed",
"sha256": "System.Security.Cryptography.SHA256Managed",
"sha384": "System.Security.Cryptography.SHA384Managed",
"sha512": "System.Security.Cryptography.SHA512Managed",
"utf-8": "System.Text.UTF8Encoding"
};
alias = (alias || "").toLowerCase();
if (alias in map) {
return map[alias];
}
throw new Error("Not supported algorithm: " + alias);
};
return UseObject(resolveProgId(algorithm), function(hasher) {
return UseObject(resolveProgId(encoding), function(encoder) {
return UseObject("MSXML2.DOMDocument", function(xml) {
var bytes = encoder.GetBytes_4(str);
var digest = hasher.ComputeHash_2(bytes);
var node = xml.createElement("hash");
node.dataType = "bin.hex";
node.nodeTypedValue = digest;
return node.text.toLowerCase();
});
});
}, null, function(error) {
return __hash_capicom__(str, algorithm);
});
}
/**
* Computes the hash of a string using CAPICOM.
*
* The input string is encoded as UTF-8 before hashing. Since ADODB.Stream
* prepends a UTF-8 BOM, the BOM is skipped to ensure the hash is computed
* over the raw UTF-8 byte sequence.
*
* Supported algorithms:
* - sha1
* - sha256
* - sha384
* - sha512
*
* @param {string} str The input string to hash.
* @param {string} algorithm The hash algorithm (e.g. "sha1", "sha256",
* "sha384", or "sha512").
* @returns {string} The hexadecimal hash digest in lowercase.
* @throws {Error} If the specified algorithm is not supported.
*/
function __hash_capicom__(str, algorithm) {
algorithm = String(algorithm || "").toLowerCase();
var allowed_algorithm = INTEGRITY_ALLOWED_ALGORITHMS;
var encoding = "utf-8";
var is_encoding_utf8 = true;
if (!(algorithm in allowed_algorithm && allowed_algorithm[algorithm])) {
throw new Error("Unsupported hash algorithm: " + algorithm);
}
var resolveAlgorithm = function(alias) {
var map = {
"sha1": 0, // CAPICOM_HASH_ALGORITHM_SHA1
"sha256": 4, // CAPICOM_HASH_ALGORITHM_SHA_256
"sha384": 5, // CAPICOM_HASH_ALGORITHM_SHA_384
"sha512": 6 // CAPICOM_HASH_ALGORITHM_SHA_512
};
alias = (alias || "").toLowerCase();
if (alias in map) {
return map[alias];
}
throw new Error("Not supported algorithm: " + alias);
};
return UseObject("ADODB.Stream", function(stream) {
stream.Type = 2; // Text
stream.Charset = encoding;
stream.Open();
stream.WriteText(str);
stream.Position = 0;
stream.Type = 1; // Binary
if (is_encoding_utf8) {
stream.Position = 3; // Skip UTF-8 BOM
}
var bytes = stream.Position < stream.Size ? stream.Read() : null;
return UseObject("CAPICOM.Utilities", function(util) {
return UseObject("CAPICOM.HashedData", function(hashed) {
hashed.Algorithm = resolveAlgorithm(algorithm);
hashed.Hash(bytes !== null ? util.ByteArrayToBinaryString(bytes) : "");
return hashed.Value.toLowerCase();
});
});
});
}
/**
* @param {string} pathname The path of the module to require.
*/
function require(pathname) {
var cache = require._cache = require._cache || {};
var suffix = (function(pos, s) {
return pos < 0 ? '.' : s.substring(pos);
})(pathname.lastIndexOf('.'), pathname);
var FN = pathname;
if ('.js$.jse$.coffee$.ls$.ts$.re$.res$.enc$'.indexOf(suffix + '$') < 0) FN += ".js";
if (cache[FN]) return cache[FN];
var text = null;
var sep = ':', pos = FN.indexOf(sep);
if (pos > -1) {
var scheme = FN.substring(0, pos);
// request a script from a remote server
if (["http", "https"].indexOf(scheme) > -1) {
require._addScriptProvider(function(url) {
try {
return require("lib/http").get(url);
} catch (e) {
return null;
}
});
}
// request a script from LLM based AI services
// e.g. ai:Hello, world!
if (["ai"].indexOf(scheme) > -1) {
require._addScriptProvider(function(url) {
try {
var text = url.substring(pos + sep.length);
return require("lib/language-inference-engine")
.create()
.setProvider("openai")
.inference(text, 0)
.join(' ')
;
} catch (e) {
return null;
}
});
}
// if exists the custom script providers
if (require._scriptProviders.length > 0) {
var i = 0;
while (text == null && i < require._scriptProviders.length) {
try {
text = require._scriptProviders[i](FN) || null;
break;
} catch (e) {
text = null;
}
i++;
}
}
} else {
// load script from a local server
var _filename = (function(fs, path) {
var filepaths = [
FN, // default
path.join(pathname, "index.js"), // default
path.join(FN + '.enc'), // default (encrypted)
path.join(pathname, 'index.js.enc'), // default (encrypted)
path.join("Scripts", FN), // NuGet
path.join("Scripts", pathname, "index.js"), // NuGet
path.join("bower_components", FN), // Bower
path.join("bower_components", pathname, "index.js"), // Bower
path.join("node_modules", FN), // NPM
path.join("node_modules", pathname, "index.js"), // NPM
];
var filename = filepaths[0];
var i = 0;
while (!fs.existsSync(filename) && i < filepaths.length) {
filename = filepaths[i];
i++;
}
return filename;
})({
existsSync: function(filename) {
return UseObject("Scripting.FileSystemObject", function(fso) {
return fso.FileExists(require._getCurrentScriptDirectory() + "\\" + filename);
});
}
}, {
join: function() {
var result = arguments[0];
for (var i = 1; i < arguments.length; i++) {
result += "\\" + arguments[i];
}
return result;
}
});
var _dirname = (function(dirname) {
var currentScriptDirectory = require._getCurrentScriptDirectory();
return dirname.length > 0 ? currentScriptDirectory + "\\" + dirname : currentScriptDirectory;
})(require._getDirectoryName(_filename));
text = require._load(_filename);
// check the suffix again
suffix = (function(pos, s) {
return pos < 0 ? '.' : s.substring(pos);
})(_filename.lastIndexOf('.'), _filename);
}
// transpile
switch (suffix) {
case '.coffee': // CoffeeScript 2
text = require._msie9("app/assets/js/coffeescript-legacy-2.7.0.min", [text], function(p, w, d, l) {
return w.CoffeeScript.compile(p[0], {
"header": true,
"sourceMap": false,
"bare": true
});
});
break;
case ".ls": // LiveScript
text = require._msie9("app/assets/js/livescript-1.6.1.min", [text, "app/assets/ls/prelude.ls"], function(p, w, d, l) {
return w.require("livescript").compile(require._load(p[1]) + "\n\n" + p[0], {
"header": true,
"bare": true
});
});
break;
case ".ts": // TypeScript
text = require._modernie("app/assets/js/typescript-4.9.4", [text], function(p, w, d, l) {
return w.ts.transpile(p[0]);
});
break;
case ".re": // Rescript (aka. BuckleScript, ReasonML)
case ".res":
text = require._modernie("app/assets/js/rescript-compiler-10.1.2", [text], function(p, w, d, l) {
var compiler = w.rescript_compiler.make();
var result = compiler.rescript.compile(p[0]);
return result.js_code;
});
break;
case ".enc": // encrypted script (require WelsonJS.ManagedObject native module)
text = UseObject("WelsonJS.Dialog", function(dialog) {
try {
var s = '', tries = 0, limit = 6;
while (tries < limit && (s.length <= 0 || s.length > 16)) {
if (tries > 0) {
throw new Error("Invalid key length");
}
s = dialog.Confirm("Please enter the password:", "Encrypted script");
tries++;
if (tries >= limit) {
throw new Error("Too many password attempts. Exiting.");
}
}
return UseObject("WelsonJS.Legacy.Cipher", function(cipher) {
return cipher.DecryptString(s, text);
});
} catch (e) {
console.error("Failed to load:", e.message);
return '';
}
});
break;
}
var compiled = new Function(
"global",
"exports",
"require",
"module",
"__filename",
"__dirname",
'"use strict";\n'
+ text
+ "\n\nreturn module.exports;"
+ "\n//# sourceURL=" + FN
);
// execute
try {
var module = new require.__Module__();
cache[FN] = compiled(
require._global,
module.exports,
require,
module,
_filename,
_dirname
);
} catch (e) {
console.error("PARSE ERROR!", e.number + ",", e.description + ",", "FN=" + FN);
}
// print VERSIONINFO and AUTHOR
if (typeof cache[FN] === "object") {
if ("VERSIONINFO" in cache[FN]) {
if ("AUTHOR" in cache[FN]) {
console.log(cache[FN].VERSIONINFO + " by " + cache[FN].AUTHOR);
} else {
console.log(cache[FN].VERSIONINFO);
}
}
}
return cache[FN];
}
require.__Module__ = function() {
this.exports = {};
};
require._global = this;
require._getDirectoryName = function(path) {
var pos = Math.max.apply(null, [path.lastIndexOf("\\"), path.lastIndexOf("/")]);
return (pos > -1 ? path.substring(0, pos) : "");
};
require._getCurrentScriptDirectory = function() {
try {
if (typeof WScript !== "undefined") {
if ("ScriptFullName" in WScript) {
return require._getDirectoryName(WScript.ScriptFullName);
} else {
throw new Error("No detected an absolute path.");
}
} else if (typeof document !== "undefined") {
return (function(dirpath) {
if (dirpath.charAt(0) == '/') {
// A file: URL path is percent-encoded; mshta returns a plain path.
return decodeURIComponent(dirpath.substring(1)).replace(/\//g, "\\");
}
return dirpath;
})(require._getDirectoryName(document.location.pathname));
} else {
throw new Error("No detected an absolute path.");
}
} catch (e) {
console.warn(e.message, "Use the relative path.");
}
return ".";
};
require._load = function(FN) {
// if empty
if (FN == '') return '';
// get filename
var _filename = require._getCurrentScriptDirectory() + "\\" + FN;
// load script file
// use ADODB.Stream instead of Scripting.FileSystemObject, because of supporting UTF-8 (Unicode)
return UseObject("ADODB.Stream", function(stream) {
var text = null;
stream.charSet = "utf-8";
stream.open();
stream.loadFromFile(_filename);
text = stream.readText();
// integrity verification
if (STRICT_INTEGRITY) {
var computed_hash = (function(algorithm) {
return algorithm == "default"
? ("00000000" + __hash_adler32__(text).toString(16)).slice(-8)
: __hash_dotnetfx_managed__(text, algorithm)
;
})(String(INTEGRITY_ALGORITHM).toLowerCase());
var existed_hash = (computed_hash in INTEGRITY_HASHES);
var enabled_hash = existed_hash ? INTEGRITY_HASHES[computed_hash] : false;
if (!enabled_hash) {
throw new Error("Integrity verification failed (" + computed_hash + ")");
}
}
return text;
}, null, function(error) {
var message = error ? (error.description || error.message || String(error)) : "Unknown error";
var code = error && error.number ? error.number : 0;
console.error("LOAD ERROR!", code + ",", message + ",", "FN=" + FN);
});
};
require._msie9 = function(FN, params, callback) {
if (typeof FN !== "string" || FN == null) FN = '';
else if (FN.substring(FN.length - 3) !== '.js') FN += ".js";
return UseObject("htmlfile", function(htmlfile) {
var text = require._load("app/assets/js/core-js-3.26.1.minified.js")
+ "\n\n" + require._load("app/assets/js/html5shiv-printshiv-3.7.3.min.js")
+ "\n\n" + require._load("app/assets/js/modernizr-2.8.3.min.js")
+ "\n\n" + require._load(FN);
htmlfile.write('<meta http-equiv="X-UA-Compatible" content="IE=9">');
htmlfile.write('<script type="text/javascript">//<!--<![CDATA[\n' + text + '\n//]]>--></script>');
if (typeof callback === "function") {
var loadScript = function(FN) {
if (FN.indexOf('://') > -1) {
htmlfile.write('<script type="text/javascript" src="' + FN + '"></script>');
} else {
htmlfile.write('<script type="text/javascript">//<!--<![CDATA[\n' + require._load(FN) + '\n//]]>--></script>');
}
};
//console.log(htmlfile.parentWindow.navigator.userAgent);
return callback(params, htmlfile.parentWindow, htmlfile.parentWindow.document, loadScript);
}
}, null, function(error) {
var message = error ? (error.description || error.message || String(error)) : "Unknown error";
var code = error && error.number ? error.number : 0;
console.error("LOAD ERROR!", code + ",", message + ",", "FN=" + FN);
});
};
require._modernie = function(FN, params, callback) {
if (typeof FN !== "string" || FN == null) FN = '';
else if (FN.substring(FN.length - 3) !== '.js') FN += ".js";
return UseObject("htmlfile", function(htmlfile) {
var ua = '', text = '';