forked from TypeStrong/tsify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsify.ts
1049 lines (863 loc) · 27.5 KB
/
tsify.ts
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
'use strict';
import os from 'os'
import fs from 'fs'
import path from 'path'
import util from 'util'
import{ EventEmitter } from 'events'
import {Transform} from 'stream'
import ts from 'typescript'
var log = util.debuglog('tsify');
var trace = util.debuglog('tsify-trace');
/* -------------------------------------------------------------------------- */
/* minithrough */
/* -------------------------------------------------------------------------- */
class DestroyableTransform extends Transform {
_destroyed: boolean;
constructor(opts) {
super(opts)
this._destroyed = false
}
destroy = function(err) {
if (this._destroyed) return
this._destroyed = true
var self = this
process.nextTick(function() {
if (err)
self.emit('error', err)
self.emit('close')
})
}
}
// a noop _transform function
function noop (chunk, enc, callback) {
callback(null, chunk)
}
function create (construct) {
return function (options?, transform?, flush?) {
if (typeof options == 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform != 'function')transform = noop
if (typeof flush != 'function')flush = null
return construct(options, transform, flush)
}
}
let through = Object.assign(create(function (options, transform, flush) {
var t2 = new DestroyableTransform(options)
t2._transform = transform
if (flush)t2._flush = flush
return t2
}),
{
obj: create(function (options, transform, flush) {
var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
t2._transform = transform
if (flush) t2._flush = flush
return t2
})
})
/* -------------------------------------------------------------------------- */
/* source map helper */
/* -------------------------------------------------------------------------- */
const commentRegex = new RegExp(/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg)
class Converter {
sourcemap: any;
constructor(sm) {
sm = (v) => v.split(',').pop();
sm = (v) => Buffer.from(v, 'base64').toString();
this.sourcemap = sm;
}
toComment = function () {
return '//# ' + 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + this.toBase64();
};
setProperty = function (key, value) {
this.sourcemap[key] = value;
return this;
};
}
var fromComment = function (comment) {
return new Converter(comment.replace(/^\/\*/g, '//').replace(/\*\/$/g, ''));
};
var time = {
start() {
return process.hrtime();
},
stop(t0, message) {
var tDiff = process.hrtime(t0);
log('%d sec -- %s', (tDiff[0] + (tDiff[1] / 1000000000)).toFixed(4), message);
}
}
/* -------------------------------------------------------------------------- */
/* host */
/* -------------------------------------------------------------------------- */
class Host extends EventEmitter {
isCaseSensitiveFileSystem: any
isCaseSensitive: any;
currentDirectory: any;
outputDirectory: any;
rootDirectory: any;
languageVersion: any;
files: {};
previousFiles: {};
output: {};
version: number;
error: boolean;
constructor(currentDirectory, opts) {
super()
this.currentDirectory = this.getCanonicalFileName(path.resolve(currentDirectory));
this.outputDirectory = this.getCanonicalFileName(path.resolve(opts.outDir));
this.rootDirectory = this.getCanonicalFileName(path.resolve(opts.rootDir));
this.languageVersion = opts.target;
this.files = {};
this.previousFiles = {};
this.output = {};
this.version = 0;
this.error = false;
try {
fs.accessSync(path.join(__dirname, path.basename(__filename).toUpperCase()), fs.constants.R_OK);
this.isCaseSensitiveFileSystem = false;
}
catch (error) {
trace('Case sensitive detection error: %s', error);
this.isCaseSensitiveFileSystem = true;
}
log('Detected case %s file system', this.isCaseSensitiveFileSystem ? 'sensitive' : 'insensitive');
this.isCaseSensitive = !!opts.forceConsistentCasingInFileNames || this.isCaseSensitiveFileSystem;
}
// util.inherits(Host, EventEmitter);
_reset = function () {
this.previousFiles = this.files;
this.files = {};
this.output = {};
this.error = false;
++this.version;
log('Resetting (version %d)', this.version);
};
_addFile = function (filename, root) {
// Ensure that the relative file name is what's passed to
// 'createSourceFile', as that's the name that will be used in error
// messages, etc.
var relative = path.relative(
this.currentDirectory,
this.getCanonicalFileName(path.resolve(this.currentDirectory, filename))
);
var canonical = this._canonical(filename);
trace('Parsing %s', canonical);
var text;
try {
text = fs.readFileSync(filename, 'utf-8');
} catch (ex) {
return;
}
var file;
var current = this.files[canonical];
var previous = this.previousFiles[canonical];
var version;
if (current && current.contents === text) {
file = current.ts;
version = current.version;
trace('Reused current file %s (version %d)', canonical, version);
} else if (previous && previous.contents === text) {
file = previous.ts;
version = previous.version;
trace('Reused previous file %s (version %d)', canonical, version);
} else {
file = ts.createSourceFile(relative, text, this.languageVersion, true);
version = this.version;
trace('New version of source file %s (version %d)', canonical, version);
}
this.files[canonical] = {
filename: relative,
contents: text,
ts: file,
root: root,
version: version,
nodeModule: /\/node_modules\//i.test(canonical) && !/\.d\.ts$/i.test(canonical)
};
this.emit('file', canonical, relative);
return file;
};
getSourceFile = function (filename) {
if (filename === '__lib.d.ts') {
return this.libDefault;
}
var canonical = this._canonical(filename);
if (this.files[canonical]) {
return this.files[canonical].ts;
}
return this._addFile(filename, false);
};
getDefaultLibFileName = function () {
var libPath = path.dirname(ts.sys.getExecutingFilePath());
var libFile = ts.getDefaultLibFileName({ target: this.languageVersion });
return path.join(libPath, libFile)
};
writeFile = function (filename, data) {
var outputCanonical = this._canonical(filename);
log('Cache write %s', outputCanonical);
this.output[outputCanonical] = data;
var sourceCanonical = this._inferSourceCanonical(outputCanonical);
var sourceFollowed = this._follow(path.dirname(sourceCanonical)) + '/' + path.basename(sourceCanonical);
if (sourceFollowed !== sourceCanonical) {
outputCanonical = this._inferOutputCanonical(sourceFollowed);
log('Cache write (followed) %s', outputCanonical);
this.output[outputCanonical] = data;
}
};
getCurrentDirectory = function () {
return this.currentDirectory;
};
// this?
_getCanonicalFileName = function (filename) {
return this.isCaseSensitiveFileSystem ? filename : filename.toLowerCase()
}
getCanonicalFileName = function (filename) {
return this.isCaseSensitive ? filename : filename.toLowerCase()
};
useCaseSensitiveFileNames = function () {
return this.isCaseSensitive;
};
getNewLine = function () {
return os.EOL;
};
fileExists = function (filename) {
return ts.sys.fileExists(filename);
};
readFile = function (filename) {
return ts.sys.readFile(filename);
};
directoryExists = function (dirname) {
return ts.sys.directoryExists(dirname);
};
getDirectories = function (dirname) {
return ts.sys.getDirectories(dirname);
};
//idk?
// getEnvironmentVariable = function (name) {
// return ts.sys.getEnvironmentVariable(name);
// };
realpath = function (name) {
return fs.realpathSync(name);
};
trace = function (message) {
ts.sys.write(message + this.getNewLine());
};
_rootFilenames = function () {
var rootFilenames = [];
for (var filename in this.files) {
if (!Object.hasOwnProperty.call(this.files, filename)) continue;
if (!this.files[filename].root) continue;
rootFilenames.push(filename);
}
return rootFilenames;
}
_nodeModuleFilenames = function () {
var nodeModuleFilenames = [];
for (var filename in this.files) {
if (!Object.hasOwnProperty.call(this.files, filename)) continue;
if (!this.files[filename].nodeModule) continue;
nodeModuleFilenames.push(filename);
}
return nodeModuleFilenames;
}
_compile = function (opts) {
var rootFilenames = this._rootFilenames();
var nodeModuleFilenames = [];
log('Compiling files:');
rootFilenames.forEach(function (file) { log(' %s', file); });
// if (semver.gte(ts.version, '2.0.0')) {
ts.createProgram(rootFilenames, opts, this);
nodeModuleFilenames = this._nodeModuleFilenames();
log(' + %d file(s) found in node_modules', nodeModuleFilenames.length);
// }
return ts.createProgram(rootFilenames.concat(nodeModuleFilenames), opts, this);
}
_output = function (filename) {
var outputCanonical = this._inferOutputCanonical(filename);
log('Cache read %s', outputCanonical);
var output = this.output[outputCanonical];
if (!output) {
log('Cache miss on %s', outputCanonical);
}
return output;
}
_canonical = function (filename) {
return this.getCanonicalFileName(path.resolve(
this.currentDirectory,
filename
));
}
_inferOutputCanonical = function (filename) {
var sourceCanonical = this._canonical(filename);
var outputRelative = path.relative(
this.rootDirectory,
sourceCanonical
);
var outputCanonical = this.getCanonicalFileName(path.resolve(
this.outputDirectory,
outputRelative
));
return outputCanonical;
}
_inferSourceCanonical = function (filename) {
var outputCanonical = this._canonical(filename);
var outputRelative = path.relative(
this.outputDirectory,
outputCanonical
);
var sourceCanonical = this.getCanonicalFileName(path.resolve(
this.rootDirectory,
outputRelative
));
return sourceCanonical;
}
_follow = function (filename) {
filename = this._canonical(filename);
var basename;
var parts = [];
do {
var stats = fs.lstatSync(filename);
if (stats.isSymbolicLink()) {
filename = fs.realpathSync(filename);
} else {
basename = path.basename(filename);
if (basename) {
parts.unshift(basename);
filename = path.dirname(filename);
}
}
} while (basename);
return filename + parts.join('/')
};
}
/* -------------------------------------------------------------------------- */
/* compile error */
/* -------------------------------------------------------------------------- */
//this wierd construct is required to get formatting right
function createCompileError() {
function CompileError(diagnostic) {
SyntaxError.call(this);
this.message = '';
if (diagnostic.file) {
var loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
this.fileName = diagnostic.file.fileName;
this.line = loc.line + 1;
this.column = loc.character + 1;
this.message += this.fileName + '(' + this.line + ',' + this.column + '): ';
}
var category = ts.DiagnosticCategory[diagnostic.category];
this.name = 'TypeScript error';
this.message += category + ' TS' + diagnostic.code + ': ' +
ts.flattenDiagnosticMessageText(diagnostic.messageText, os.EOL);
}
CompileError.prototype = Object.create(SyntaxError.prototype);
return CompileError;
};
const CompileError = createCompileError()
/* -------------------------------------------------------------------------- */
/* tsifier */
/* -------------------------------------------------------------------------- */
var currentDirectory = fs.realpathSync(process.cwd())
var parseJsonConfigFileContent = ts.parseJsonConfigFileContent //|| ts.readConfigFile;
function isTypescript(file) {
return (/\.tsx?$/i).test(file);
}
function isTsx(file) {
return (/\.tsx$/i).test(file);
}
function isJavascript(file) {
return (/\.jsx?$/i).test(file);
}
function isTypescriptDeclaration(file) {
return (/\.d\.ts$/i).test(file);
}
function replaceFileExtension(file, extension) {
return file.replace(/\.\w+$/i, extension);
}
function fileExists(file) {
try {
var stats = fs.lstatSync(file);
return stats.isFile();
} catch (e) {
return false;
}
}
type ExpandedOptions = {
module?: any
project?: any
target?: any
}
function parseOptions(opts, bopts) {
// Expand any short-name, command-line options
var expanded: ExpandedOptions = {};
if (opts.m) { expanded.module = opts.m; }
if (opts.p) { expanded.project = opts.p; }
if (opts.t) { expanded.target = opts.t; }
opts = Object.assign({}, expanded, opts);
var config;
var configFile;
if (typeof opts.project === "object"){
log('Using inline tsconfig');
config = JSON.parse(JSON.stringify(opts.project));
config.compilerOptions = config.compilerOptions || {};
Object.assign(config.compilerOptions, opts);
}
else {
if (fileExists(opts.project)) {
configFile = opts.project;
} else {
configFile = ts.findConfigFile(
// normalize?
(opts.project || bopts.basedir || currentDirectory),
fileExists
);
}
if (configFile) {
log('Using tsconfig file at %s', configFile);
config = JSON.parse(fs.readFileSync(configFile, {encoding: "utf-8"}))
//tsconfig.readFileSync(configFile);
config.compilerOptions = config.compilerOptions || {};
Object.assign(config.compilerOptions, opts);
}
else {
config = {
files: [],
compilerOptions: opts
};
}
}
// Note that subarg parses command line arrays in its own peculiar way:
// https://github.com/substack/subarg
if (opts.exclude) {
config.exclude = opts.exclude._ || opts.exclude;
}
if (opts.files) {
config.files = opts.files._ || opts.files;
}
if (opts.include) {
config.include = opts.include._ || opts.include;
}
var parsed = parseJsonConfigFileContent(
config,
ts.sys,
configFile ? path.resolve(path.dirname(configFile)) : currentDirectory,
null,
configFile ?path.resolve(configFile): undefined
);
// Generate inline sourcemaps if Browserify's --debug option is set
parsed.options.sourceMap = false;
parsed.options.inlineSourceMap = bopts.debug;
parsed.options.inlineSources = bopts.debug;
// Default to CommonJS module mode
parsed.options.module = parsed.options.module || ts.ModuleKind.CommonJS;
// Blacklist --out/--outFile/--noEmit; these should definitely not be set, since we are doing
// concatenation with Browserify instead
delete parsed.options.out;
delete parsed.options.outFile;
delete parsed.options.noEmit;
// Set rootDir and outDir so we know exactly where the TS compiler will be trying to
// write files; the filenames will end up being the keys into our in-memory store.
// The output directory needs to be distinct from the input directory to prevent the TS
// compiler from thinking that it might accidentally overwrite source files, which would
// prevent it from outputting e.g. the results of transpiling ES6 JS files with --allowJs.
parsed.options.rootDir = path.relative('.', '/');
parsed.options.outDir = path.resolve('/__tsify__')
log('Files from tsconfig parse:');
parsed.fileNames.forEach(function (filename) { log(' %s', filename); });
var result = {
options: parsed.options,
fileNames: parsed.fileNames
};
return result;
}
class Tsifier extends EventEmitter {
static isTypescript: (file: any) => boolean;
static isTypescriptDeclaration: (file: any) => boolean;
opts: any;
files: any;
ignoredFiles: any[];
bopts: any;
host: any;
constructor(opts, bopts) {
super()
var parsedOptions = parseOptions(opts, bopts);
this.opts = parsedOptions.options;
this.files = parsedOptions.fileNames;
this.ignoredFiles = [];
this.bopts = bopts;
this.host = new Host(currentDirectory, this.opts);
this.host.on('file', (file, id) => this.emit('file', file, id))
}
//util.inherits(Tsifier, events.EventEmitter);
reset = function () {
var self = this;
self.ignoredFiles = [];
self.host._reset();
self.addFiles(self.files);
};
generateCache = function (files, ignoredFiles) {
if (ignoredFiles) {
this.ignoredFiles = ignoredFiles;
}
this.addFiles(files);
this.compile();
};
addFiles = function (files) {
var self = this;
files.forEach(function (file) {
self.host._addFile(file, true);
});
};
compile = function () {
var self = this;
var createProgram_t0 = time.start();
var program = self.host._compile(self.opts);
time.stop(createProgram_t0, 'createProgram');
var syntaxDiagnostics = self.checkSyntax(program);
if (syntaxDiagnostics.length) {
log('Compilation encountered fatal syntax errors');
return;
}
var semanticDiagnostics = self.checkSemantics(program);
if (semanticDiagnostics.length && self.opts.noEmitOnError) {
log('Compilation encountered fatal semantic errors');
return;
}
var emit_t0 = time.start();
var emitOutput = program.emit();
time.stop(emit_t0, 'emit program');
var emittedDiagnostics = self.checkEmittedOutput(emitOutput);
if (emittedDiagnostics.length && self.opts.noEmitOnError) {
log('Compilation encountered fatal errors during emit');
return;
}
log('Compilation completed without errors');
};
checkSyntax = function (program) {
var self = this;
var syntaxCheck_t0 = time.start();
var syntaxDiagnostics = program.getSyntacticDiagnostics();
time.stop(syntaxCheck_t0, 'syntax checking');
syntaxDiagnostics.forEach(function (error) {
self.emit('error', new CompileError(error));
});
if (syntaxDiagnostics.length) {
self.host.error = true;
}
return syntaxDiagnostics;
};
checkSemantics = function (program) {
var self = this;
var semanticDiagnostics_t0 = time.start();
var semanticDiagnostics = program.getGlobalDiagnostics();
if (semanticDiagnostics.length === 0) {
semanticDiagnostics = program.getSemanticDiagnostics();
}
time.stop(semanticDiagnostics_t0, 'semantic checking');
semanticDiagnostics.forEach(function (error) {
self.emit('error', new CompileError(error));
});
if (semanticDiagnostics.length && self.opts.noEmitOnError) {
self.host.error = true;
}
return semanticDiagnostics;
};
checkEmittedOutput = function (emitOutput) {
var self = this;
var emittedDiagnostics = emitOutput.diagnostics;
emittedDiagnostics.forEach(function (error) {
self.emit('error', new CompileError(error));
});
if (emittedDiagnostics.length && self.opts.noEmitOnError) {
self.host.error = true;
}
return emittedDiagnostics;
};
transform = function (file) {
var self = this;
trace('Transforming %s', file);
if (self.ignoredFiles.indexOf(file) !== -1) {
return through();
}
if (isTypescriptDeclaration(file)) {
return through(transform);
}
if (isTypescript(file) || (isJavascript(file) && self.opts.allowJs)) {
return through(transform, flush);
}
return through();
function transform(chunk, enc, next) {
next();
}
function flush(next) {
if (self.host.error) {
next();
return;
}
var compiled = self.getCompiledFile(file);
if (compiled) {
this.push(compiled);
}
this.push(null);
next();
}
};
getCompiledFile = function (inputFile, alreadyMissedCache) {
var self = this;
var outputExtension = (ts.JsxEmit && self.opts.jsx === ts.JsxEmit.Preserve && isTsx(inputFile)) ? '.jsx' : '.js';
var output = self.host._output(replaceFileExtension(inputFile, outputExtension));
if (output === undefined) {
if (alreadyMissedCache) {
self.emit('error', new Error('tsify: no compiled file for ' + inputFile));
return;
}
self.generateCache([inputFile]);
if (self.host.error)
return;
return self.getCompiledFile(inputFile, true);
}
if (self.opts.inlineSourceMap) {
output = self.setSourcePathInSourcemap(output, inputFile);
}
return output;
};
setSourcePathInSourcemap = function (output, inputFile) {
var self = this;
var normalized = path.relative(
self.bopts.basedir || currentDirectory,
inputFile
);
var sourcemap = fromComment(output);
sourcemap.setProperty('sources', [normalized]);
return output.replace(commentRegex, sourcemap.toComment());
}
}
// var result = Tsifier;
// result.isTypescript = isTypescript;
// result.isTypescriptDeclaration = isTypescriptDeclaration;
// return result;
// };
/* -------------------------------------------------------------------------- */
/* tsify */
/* -------------------------------------------------------------------------- */
function tsify(b, opts) {
if (typeof b === 'string') {
throw new Error('tsify appears to have been configured as a transform; it must be configured as a plugin.');
}
var ts = opts.typescript || require('typescript');
var tsifier = new Tsifier(opts, b._options);
tsifier.on('error', function (error) {
b.pipeline.emit('error', error);
});
tsifier.on('file', function (file, id) {
b.emit('file', file, id);
});
setupPipeline();
var transformOpts = {
global: opts.global
};
b.transform(tsifier.transform.bind(tsifier), transformOpts);
b.on('reset', function () {
setupPipeline();
});
function setupPipeline() {
if (tsifier.opts.jsx && b._extensions.indexOf('.tsx') === -1)
b._extensions.unshift('.tsx');
if (b._extensions.indexOf('.ts') === -1)
b._extensions.unshift('.ts');
b.pipeline.get('record').push(gatherEntryPoints());
}
function gatherEntryPoints() {
var rows = [];
return through.obj(transform, flush);
function transform(row, enc, next) {
rows.push(row);
next();
}
function flush(next) {
var self = this;
var ignoredFiles = [];
var entryFiles = rows
.map(function (row) {
var file = row.file || row.id;
if (file) {
if (row.source !== undefined) {
ignoredFiles.push(file);
} else if (row.basedir) {
return path.resolve(row.basedir, file);
} else if (path.isAbsolute(file)) {
return file;
} else {
ignoredFiles.push(file);
}
}
return null;
})
.filter(function (file) { return file; })
.map(function (file) { return fs.realpathSync(file); });
if (entryFiles.length) {
log('Files from browserify entry points:');
entryFiles.forEach(function (file) { log(' %s', file); });
}
if (ignoredFiles.length) {
log('Ignored browserify entry points:');
ignoredFiles.forEach(function (file) { log(' %s', file); });
}
tsifier.reset();
tsifier.generateCache(entryFiles, ignoredFiles);
rows.forEach(function (row) { self.push(row); });
self.push(null);
next();
}
}
}
// 0 dependency watchify ... bc the fs module is good
//just saved about 2k loc, gg no re
const anymatch = (searchTerm, filepath) => {
let _path = String(filepath)
return _path.includes(searchTerm)
}
function watchify (b, opts?) {
if (!opts) opts = {};
var cache = b._options.cache;
var pkgcache = b._options.packageCache;
var delay = typeof opts.delay === 'number' ? opts.delay : 100;
var changingDeps = {};
var pending = false;
var updating = false;
// unused atm, was a chokadir option, fs method also has this param b
var wopts: any = {
persistent: true
};
var ignored = opts.ignoreWatch || "node_modules"
if (cache) {
b.on('reset', collect);
collect();
}
function collect () {
b.pipeline.get('deps').push(through.obj(function(row, enc, next) {
var file = row.expose ? b._expose[row.id] : row.file;
cache[file] = {
source: row.source,
deps: Object.assign({}, row.deps)
};
this.push(row);
next();
}));
}
b.on('file', function (file) {
watchFile(file);
});
b.on('package', function (pkg) {
var file = path.join(pkg.__dirname, 'package.json');
watchFile(file);
if (pkgcache) pkgcache[file] = pkg;
});
b.on('reset', reset);
reset();
function reset () {
var time = null;
var bytes = 0;
b.pipeline.get('record').on('end', function () {
time = Date.now();
});
b.pipeline.get('wrap').push(through(write, end));
function write (buf, enc, next) {
bytes += buf.length;
this.push(buf);
next();
}
function end () {
var delta = Date.now() - time;
b.emit('time', delta);
b.emit('bytes', bytes);
b.emit('log', bytes + ' bytes written ('
+ (delta / 1000).toFixed(2) + ' seconds)'
);
this.push(null);
}
}
var fwatchers: any = {};
var fwatcherFiles = {};
var ignoredFiles = {};
b.on('transform', function (tr, mfile) {
tr.on('file', function (dep) {
watchFile(mfile, dep);
});
});
b.on('bundle', function (bundle) {
updating = true;
bundle.on('error', onend);
bundle.on('end', onend);
function onend () { updating = false }
});
function watchFile (file, dep?) {
dep = dep || file;
if (ignored) {
if (!ignoredFiles.hasOwnProperty(file)) {
ignoredFiles[file] = anymatch(ignored, file);
//anymatch(ignored, file);
}
if (ignoredFiles[file]) return;
}
if (!fwatchers[file]) fwatchers[file] = [];
if (!fwatcherFiles[file]) fwatcherFiles[file] = [];
if (fwatcherFiles[file].indexOf(dep) >= 0) return;
//idk how to quantify this , but adding a watcher for every dep instead of just letting the fs module do its thing seems dumb af
//fun fact, the node docs mentioned experimental support for fs watch on urls, can finally use a socket as a virtual fs with watch support!
//will try out later with vinyl ws server, there's some rollup plugin that does something similar to my vinyl hacks
//var w = b._watcher(dep, wopts);
var w = fs.watch(path.join(process.cwd(), "src"), {recursive: true});
w.setMaxListeners(0);
w.on('error', b.emit.bind(b, 'error'));
w.on('change', function () {
invalidate(file);
});
fwatchers[file].push(w);
fwatcherFiles[file].push(dep);
}
function invalidate (id) {