forked from esbuild/deno-esbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.js
1977 lines (1973 loc) · 69.3 KB
/
mod.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
/// <reference types="./mod.d.ts" />
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// lib/deno/mod.ts
var mod_exports = {};
__export(mod_exports, {
analyzeMetafile: () => analyzeMetafile,
analyzeMetafileSync: () => analyzeMetafileSync,
build: () => build,
buildSync: () => buildSync,
formatMessages: () => formatMessages,
formatMessagesSync: () => formatMessagesSync,
initialize: () => initialize,
serve: () => serve,
stop: () => stop,
transform: () => transform,
transformSync: () => transformSync,
version: () => version
});
// lib/shared/stdio_protocol.ts
function encodePacket(packet) {
let visit = (value) => {
if (value === null) {
bb.write8(0);
} else if (typeof value === "boolean") {
bb.write8(1);
bb.write8(+value);
} else if (typeof value === "number") {
bb.write8(2);
bb.write32(value | 0);
} else if (typeof value === "string") {
bb.write8(3);
bb.write(encodeUTF8(value));
} else if (value instanceof Uint8Array) {
bb.write8(4);
bb.write(value);
} else if (value instanceof Array) {
bb.write8(5);
bb.write32(value.length);
for (let item of value) {
visit(item);
}
} else {
let keys = Object.keys(value);
bb.write8(6);
bb.write32(keys.length);
for (let key of keys) {
bb.write(encodeUTF8(key));
visit(value[key]);
}
}
};
let bb = new ByteBuffer();
bb.write32(0);
bb.write32(packet.id << 1 | +!packet.isRequest);
visit(packet.value);
writeUInt32LE(bb.buf, bb.len - 4, 0);
return bb.buf.subarray(0, bb.len);
}
function decodePacket(bytes) {
let visit = () => {
switch (bb.read8()) {
case 0:
return null;
case 1:
return !!bb.read8();
case 2:
return bb.read32();
case 3:
return decodeUTF8(bb.read());
case 4:
return bb.read();
case 5: {
let count = bb.read32();
let value2 = [];
for (let i = 0; i < count; i++) {
value2.push(visit());
}
return value2;
}
case 6: {
let count = bb.read32();
let value2 = {};
for (let i = 0; i < count; i++) {
value2[decodeUTF8(bb.read())] = visit();
}
return value2;
}
default:
throw new Error("Invalid packet");
}
};
let bb = new ByteBuffer(bytes);
let id = bb.read32();
let isRequest = (id & 1) === 0;
id >>>= 1;
let value = visit();
if (bb.ptr !== bytes.length) {
throw new Error("Invalid packet");
}
return { id, isRequest, value };
}
var ByteBuffer = class {
constructor(buf = new Uint8Array(1024)) {
this.buf = buf;
}
len = 0;
ptr = 0;
_write(delta) {
if (this.len + delta > this.buf.length) {
let clone = new Uint8Array((this.len + delta) * 2);
clone.set(this.buf);
this.buf = clone;
}
this.len += delta;
return this.len - delta;
}
write8(value) {
let offset = this._write(1);
this.buf[offset] = value;
}
write32(value) {
let offset = this._write(4);
writeUInt32LE(this.buf, value, offset);
}
write(bytes) {
let offset = this._write(4 + bytes.length);
writeUInt32LE(this.buf, bytes.length, offset);
this.buf.set(bytes, offset + 4);
}
_read(delta) {
if (this.ptr + delta > this.buf.length) {
throw new Error("Invalid packet");
}
this.ptr += delta;
return this.ptr - delta;
}
read8() {
return this.buf[this._read(1)];
}
read32() {
return readUInt32LE(this.buf, this._read(4));
}
read() {
let length = this.read32();
let bytes = new Uint8Array(length);
let ptr = this._read(bytes.length);
bytes.set(this.buf.subarray(ptr, ptr + length));
return bytes;
}
};
var encodeUTF8;
var decodeUTF8;
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
let encoder = new TextEncoder();
let decoder = new TextDecoder();
encodeUTF8 = (text) => encoder.encode(text);
decodeUTF8 = (bytes) => decoder.decode(bytes);
} else if (typeof Buffer !== "undefined") {
encodeUTF8 = (text) => {
let buffer = Buffer.from(text);
if (!(buffer instanceof Uint8Array)) {
buffer = new Uint8Array(buffer);
}
return buffer;
};
decodeUTF8 = (bytes) => {
let { buffer, byteOffset, byteLength } = bytes;
return Buffer.from(buffer, byteOffset, byteLength).toString();
};
} else {
throw new Error("No UTF-8 codec found");
}
function readUInt32LE(buffer, offset) {
return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
}
function writeUInt32LE(buffer, value, offset) {
buffer[offset++] = value;
buffer[offset++] = value >> 8;
buffer[offset++] = value >> 16;
buffer[offset++] = value >> 24;
}
// lib/shared/common.ts
function validateTarget(target) {
target += "";
if (target.indexOf(",") >= 0)
throw new Error(`Invalid target: ${target}`);
return target;
}
var canBeAnything = () => null;
var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object";
var mustBeString = (value) => typeof value === "string" ? null : "a string";
var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
var mustBeArrayOrRecord = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
function getFlag(object, keys, key, mustBeFn) {
let value = object[key];
keys[key + ""] = true;
if (value === void 0)
return void 0;
let mustBe = mustBeFn(value);
if (mustBe !== null)
throw new Error(`"${key}" must be ${mustBe}`);
return value;
}
function checkForInvalidFlags(object, keys, where) {
for (let key in object) {
if (!(key in keys)) {
throw new Error(`Invalid option ${where}: "${key}"`);
}
}
}
function validateInitializeOptions(options) {
let keys = /* @__PURE__ */ Object.create(null);
let wasmURL = getFlag(options, keys, "wasmURL", mustBeString);
let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
let worker = getFlag(options, keys, "worker", mustBeBoolean);
checkForInvalidFlags(options, keys, "in initialize() call");
return {
wasmURL,
wasmModule,
worker
};
}
function validateMangleCache(mangleCache) {
let validated;
if (mangleCache !== void 0) {
validated = /* @__PURE__ */ Object.create(null);
for (let key of Object.keys(mangleCache)) {
let value = mangleCache[key];
if (typeof value === "string" || value === false) {
validated[key] = value;
} else {
throw new Error(`Expected ${JSON.stringify(key)} in mangle cache to map to either a string or false`);
}
}
}
return validated;
}
function pushLogFlags(flags, options, keys, isTTY, logLevelDefault) {
let color = getFlag(options, keys, "color", mustBeBoolean);
let logLevel = getFlag(options, keys, "logLevel", mustBeString);
let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
if (color !== void 0)
flags.push(`--color=${color}`);
else if (isTTY)
flags.push(`--color=true`);
flags.push(`--log-level=${logLevel || logLevelDefault}`);
flags.push(`--log-limit=${logLimit || 0}`);
}
function pushCommonFlags(flags, options, keys) {
let legalComments = getFlag(options, keys, "legalComments", mustBeString);
let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
let target = getFlag(options, keys, "target", mustBeStringOrArray);
let format = getFlag(options, keys, "format", mustBeString);
let globalName = getFlag(options, keys, "globalName", mustBeString);
let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
let minify = getFlag(options, keys, "minify", mustBeBoolean);
let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
let drop = getFlag(options, keys, "drop", mustBeArray);
let charset = getFlag(options, keys, "charset", mustBeString);
let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
let jsx = getFlag(options, keys, "jsx", mustBeString);
let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
let define = getFlag(options, keys, "define", mustBeObject);
let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
let supported = getFlag(options, keys, "supported", mustBeObject);
let pure = getFlag(options, keys, "pure", mustBeArray);
let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
if (legalComments)
flags.push(`--legal-comments=${legalComments}`);
if (sourceRoot !== void 0)
flags.push(`--source-root=${sourceRoot}`);
if (sourcesContent !== void 0)
flags.push(`--sources-content=${sourcesContent}`);
if (target) {
if (Array.isArray(target))
flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
else
flags.push(`--target=${validateTarget(target)}`);
}
if (format)
flags.push(`--format=${format}`);
if (globalName)
flags.push(`--global-name=${globalName}`);
if (minify)
flags.push("--minify");
if (minifySyntax)
flags.push("--minify-syntax");
if (minifyWhitespace)
flags.push("--minify-whitespace");
if (minifyIdentifiers)
flags.push("--minify-identifiers");
if (charset)
flags.push(`--charset=${charset}`);
if (treeShaking !== void 0)
flags.push(`--tree-shaking=${treeShaking}`);
if (ignoreAnnotations)
flags.push(`--ignore-annotations`);
if (drop)
for (let what of drop)
flags.push(`--drop:${what}`);
if (mangleProps)
flags.push(`--mangle-props=${mangleProps.source}`);
if (reserveProps)
flags.push(`--reserve-props=${reserveProps.source}`);
if (mangleQuoted !== void 0)
flags.push(`--mangle-quoted=${mangleQuoted}`);
if (jsx)
flags.push(`--jsx=${jsx}`);
if (jsxFactory)
flags.push(`--jsx-factory=${jsxFactory}`);
if (jsxFragment)
flags.push(`--jsx-fragment=${jsxFragment}`);
if (define) {
for (let key in define) {
if (key.indexOf("=") >= 0)
throw new Error(`Invalid define: ${key}`);
flags.push(`--define:${key}=${define[key]}`);
}
}
if (logOverride) {
for (let key in logOverride) {
if (key.indexOf("=") >= 0)
throw new Error(`Invalid log override: ${key}`);
flags.push(`--log-override:${key}=${logOverride[key]}`);
}
}
if (supported) {
for (let key in supported) {
if (key.indexOf("=") >= 0)
throw new Error(`Invalid supported: ${key}`);
flags.push(`--supported:${key}=${supported[key]}`);
}
}
if (pure)
for (let fn of pure)
flags.push(`--pure:${fn}`);
if (keepNames)
flags.push(`--keep-names`);
}
function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDefault) {
let flags = [];
let entries = [];
let keys = /* @__PURE__ */ Object.create(null);
let stdinContents = null;
let stdinResolveDir = null;
let watchMode = null;
pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
pushCommonFlags(flags, options, keys);
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject);
let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
let outfile = getFlag(options, keys, "outfile", mustBeString);
let outdir = getFlag(options, keys, "outdir", mustBeString);
let outbase = getFlag(options, keys, "outbase", mustBeString);
let platform = getFlag(options, keys, "platform", mustBeString);
let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
let conditions = getFlag(options, keys, "conditions", mustBeArray);
let external = getFlag(options, keys, "external", mustBeArray);
let loader = getFlag(options, keys, "loader", mustBeObject);
let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
let publicPath = getFlag(options, keys, "publicPath", mustBeString);
let entryNames = getFlag(options, keys, "entryNames", mustBeString);
let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
let assetNames = getFlag(options, keys, "assetNames", mustBeString);
let inject = getFlag(options, keys, "inject", mustBeArray);
let banner = getFlag(options, keys, "banner", mustBeObject);
let footer = getFlag(options, keys, "footer", mustBeObject);
let entryPoints = getFlag(options, keys, "entryPoints", mustBeArrayOrRecord);
let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
let stdin = getFlag(options, keys, "stdin", mustBeObject);
let write = getFlag(options, keys, "write", mustBeBoolean) ?? writeDefault;
let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true;
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
keys.plugins = true;
checkForInvalidFlags(options, keys, `in ${callName}() call`);
if (sourcemap)
flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
if (bundle)
flags.push("--bundle");
if (allowOverwrite)
flags.push("--allow-overwrite");
if (watch) {
flags.push("--watch");
if (typeof watch === "boolean") {
watchMode = {};
} else {
let watchKeys = /* @__PURE__ */ Object.create(null);
let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction);
checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`);
watchMode = { onRebuild };
}
}
if (splitting)
flags.push("--splitting");
if (preserveSymlinks)
flags.push("--preserve-symlinks");
if (metafile)
flags.push(`--metafile`);
if (outfile)
flags.push(`--outfile=${outfile}`);
if (outdir)
flags.push(`--outdir=${outdir}`);
if (outbase)
flags.push(`--outbase=${outbase}`);
if (platform)
flags.push(`--platform=${platform}`);
if (tsconfig)
flags.push(`--tsconfig=${tsconfig}`);
if (resolveExtensions) {
let values = [];
for (let value of resolveExtensions) {
value += "";
if (value.indexOf(",") >= 0)
throw new Error(`Invalid resolve extension: ${value}`);
values.push(value);
}
flags.push(`--resolve-extensions=${values.join(",")}`);
}
if (publicPath)
flags.push(`--public-path=${publicPath}`);
if (entryNames)
flags.push(`--entry-names=${entryNames}`);
if (chunkNames)
flags.push(`--chunk-names=${chunkNames}`);
if (assetNames)
flags.push(`--asset-names=${assetNames}`);
if (mainFields) {
let values = [];
for (let value of mainFields) {
value += "";
if (value.indexOf(",") >= 0)
throw new Error(`Invalid main field: ${value}`);
values.push(value);
}
flags.push(`--main-fields=${values.join(",")}`);
}
if (conditions) {
let values = [];
for (let value of conditions) {
value += "";
if (value.indexOf(",") >= 0)
throw new Error(`Invalid condition: ${value}`);
values.push(value);
}
flags.push(`--conditions=${values.join(",")}`);
}
if (external)
for (let name of external)
flags.push(`--external:${name}`);
if (banner) {
for (let type in banner) {
if (type.indexOf("=") >= 0)
throw new Error(`Invalid banner file type: ${type}`);
flags.push(`--banner:${type}=${banner[type]}`);
}
}
if (footer) {
for (let type in footer) {
if (type.indexOf("=") >= 0)
throw new Error(`Invalid footer file type: ${type}`);
flags.push(`--footer:${type}=${footer[type]}`);
}
}
if (inject)
for (let path of inject)
flags.push(`--inject:${path}`);
if (loader) {
for (let ext in loader) {
if (ext.indexOf("=") >= 0)
throw new Error(`Invalid loader extension: ${ext}`);
flags.push(`--loader:${ext}=${loader[ext]}`);
}
}
if (outExtension) {
for (let ext in outExtension) {
if (ext.indexOf("=") >= 0)
throw new Error(`Invalid out extension: ${ext}`);
flags.push(`--out-extension:${ext}=${outExtension[ext]}`);
}
}
if (entryPoints) {
if (Array.isArray(entryPoints)) {
for (let entryPoint of entryPoints) {
entries.push(["", entryPoint + ""]);
}
} else {
for (let [key, value] of Object.entries(entryPoints)) {
entries.push([key + "", value + ""]);
}
}
}
if (stdin) {
let stdinKeys = /* @__PURE__ */ Object.create(null);
let contents = getFlag(stdin, stdinKeys, "contents", mustBeString);
let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
if (sourcefile)
flags.push(`--sourcefile=${sourcefile}`);
if (loader2)
flags.push(`--loader=${loader2}`);
if (resolveDir)
stdinResolveDir = resolveDir + "";
stdinContents = contents ? contents + "" : "";
}
let nodePaths = [];
if (nodePathsInput) {
for (let value of nodePathsInput) {
value += "";
nodePaths.push(value);
}
}
return {
entries,
flags,
write,
stdinContents,
stdinResolveDir,
absWorkingDir,
incremental,
nodePaths,
watch: watchMode,
mangleCache: validateMangleCache(mangleCache)
};
}
function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
let flags = [];
let keys = /* @__PURE__ */ Object.create(null);
pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
pushCommonFlags(flags, options, keys);
let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
let loader = getFlag(options, keys, "loader", mustBeString);
let banner = getFlag(options, keys, "banner", mustBeString);
let footer = getFlag(options, keys, "footer", mustBeString);
let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
checkForInvalidFlags(options, keys, `in ${callName}() call`);
if (sourcemap)
flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
if (tsconfigRaw)
flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
if (sourcefile)
flags.push(`--sourcefile=${sourcefile}`);
if (loader)
flags.push(`--loader=${loader}`);
if (banner)
flags.push(`--banner=${banner}`);
if (footer)
flags.push(`--footer=${footer}`);
return {
flags,
mangleCache: validateMangleCache(mangleCache)
};
}
function createChannel(streamIn) {
let responseCallbacks = /* @__PURE__ */ new Map();
let pluginCallbacks = /* @__PURE__ */ new Map();
let watchCallbacks = /* @__PURE__ */ new Map();
let serveCallbacks = /* @__PURE__ */ new Map();
let closeData = null;
let nextRequestID = 0;
let nextBuildKey = 0;
let stdout = new Uint8Array(16 * 1024);
let stdoutUsed = 0;
let readFromStdout = (chunk) => {
let limit = stdoutUsed + chunk.length;
if (limit > stdout.length) {
let swap = new Uint8Array(limit * 2);
swap.set(stdout);
stdout = swap;
}
stdout.set(chunk, stdoutUsed);
stdoutUsed += chunk.length;
let offset = 0;
while (offset + 4 <= stdoutUsed) {
let length = readUInt32LE(stdout, offset);
if (offset + 4 + length > stdoutUsed) {
break;
}
offset += 4;
handleIncomingPacket(stdout.subarray(offset, offset + length));
offset += length;
}
if (offset > 0) {
stdout.copyWithin(0, offset, stdoutUsed);
stdoutUsed -= offset;
}
};
let afterClose = (error) => {
closeData = { reason: error ? ": " + (error.message || error) : "" };
const text = "The service was stopped" + closeData.reason;
for (let callback of responseCallbacks.values()) {
callback(text, null);
}
responseCallbacks.clear();
for (let callbacks of serveCallbacks.values()) {
callbacks.onWait(text);
}
serveCallbacks.clear();
for (let callback of watchCallbacks.values()) {
try {
callback(new Error(text), null);
} catch (e) {
console.error(e);
}
}
watchCallbacks.clear();
};
let sendRequest = (refs, value, callback) => {
if (closeData)
return callback("The service is no longer running" + closeData.reason, null);
let id = nextRequestID++;
responseCallbacks.set(id, (error, response) => {
try {
callback(error, response);
} finally {
if (refs)
refs.unref();
}
});
if (refs)
refs.ref();
streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
};
let sendResponse = (id, value) => {
if (closeData)
throw new Error("The service is no longer running" + closeData.reason);
streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
};
let handleRequest = async (id, request) => {
try {
switch (request.command) {
case "ping": {
sendResponse(id, {});
break;
}
case "on-start": {
let callback = pluginCallbacks.get(request.key);
if (!callback)
sendResponse(id, {});
else
sendResponse(id, await callback(request));
break;
}
case "on-resolve": {
let callback = pluginCallbacks.get(request.key);
if (!callback)
sendResponse(id, {});
else
sendResponse(id, await callback(request));
break;
}
case "on-load": {
let callback = pluginCallbacks.get(request.key);
if (!callback)
sendResponse(id, {});
else
sendResponse(id, await callback(request));
break;
}
case "serve-request": {
let callbacks = serveCallbacks.get(request.key);
if (callbacks && callbacks.onRequest)
callbacks.onRequest(request.args);
sendResponse(id, {});
break;
}
case "serve-wait": {
let callbacks = serveCallbacks.get(request.key);
if (callbacks)
callbacks.onWait(request.error);
sendResponse(id, {});
break;
}
case "watch-rebuild": {
let callback = watchCallbacks.get(request.key);
try {
if (callback)
callback(null, request.args);
} catch (err) {
console.error(err);
}
sendResponse(id, {});
break;
}
default:
throw new Error(`Invalid command: ` + request.command);
}
} catch (e) {
sendResponse(id, { errors: [extractErrorMessageV8(e, streamIn, null, void 0, "")] });
}
};
let isFirstPacket = true;
let handleIncomingPacket = (bytes) => {
if (isFirstPacket) {
isFirstPacket = false;
let binaryVersion = String.fromCharCode(...bytes);
if (binaryVersion !== "0.14.48") {
throw new Error(`Cannot start service: Host version "${"0.14.48"}" does not match binary version ${JSON.stringify(binaryVersion)}`);
}
return;
}
let packet = decodePacket(bytes);
if (packet.isRequest) {
handleRequest(packet.id, packet.value);
} else {
let callback = responseCallbacks.get(packet.id);
responseCallbacks.delete(packet.id);
if (packet.value.error)
callback(packet.value.error, {});
else
callback(null, packet.value);
}
};
let handlePlugins = async (initialOptions, plugins, buildKey, stash, refs) => {
let onStartCallbacks = [];
let onEndCallbacks = [];
let onResolveCallbacks = {};
let onLoadCallbacks = {};
let nextCallbackID = 0;
let i = 0;
let requestPlugins = [];
let isSetupDone = false;
plugins = [...plugins];
for (let item of plugins) {
let keys = {};
if (typeof item !== "object")
throw new Error(`Plugin at index ${i} must be an object`);
const name = getFlag(item, keys, "name", mustBeString);
if (typeof name !== "string" || name === "")
throw new Error(`Plugin at index ${i} is missing a name`);
try {
let setup = getFlag(item, keys, "setup", mustBeFunction);
if (typeof setup !== "function")
throw new Error(`Plugin is missing a setup function`);
checkForInvalidFlags(item, keys, `on plugin ${JSON.stringify(name)}`);
let plugin = {
name,
onResolve: [],
onLoad: []
};
i++;
let resolve = (path, options = {}) => {
if (!isSetupDone)
throw new Error('Cannot call "resolve" before plugin setup has completed');
if (typeof path !== "string")
throw new Error(`The path to resolve must be a string`);
let keys2 = /* @__PURE__ */ Object.create(null);
let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
let importer = getFlag(options, keys2, "importer", mustBeString);
let namespace = getFlag(options, keys2, "namespace", mustBeString);
let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
let kind = getFlag(options, keys2, "kind", mustBeString);
let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
checkForInvalidFlags(options, keys2, "in resolve() call");
return new Promise((resolve2, reject) => {
const request = {
command: "resolve",
path,
key: buildKey,
pluginName: name
};
if (pluginName != null)
request.pluginName = pluginName;
if (importer != null)
request.importer = importer;
if (namespace != null)
request.namespace = namespace;
if (resolveDir != null)
request.resolveDir = resolveDir;
if (kind != null)
request.kind = kind;
if (pluginData != null)
request.pluginData = stash.store(pluginData);
sendRequest(refs, request, (error, response) => {
if (error !== null)
reject(new Error(error));
else
resolve2({
errors: replaceDetailsInMessages(response.errors, stash),
warnings: replaceDetailsInMessages(response.warnings, stash),
path: response.path,
external: response.external,
sideEffects: response.sideEffects,
namespace: response.namespace,
suffix: response.suffix,
pluginData: stash.load(response.pluginData)
});
});
});
};
let promise = setup({
initialOptions,
resolve,
onStart(callback2) {
let registeredText = `This error came from the "onStart" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
onStartCallbacks.push({ name, callback: callback2, note: registeredNote });
},
onEnd(callback2) {
let registeredText = `This error came from the "onEnd" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
onEndCallbacks.push({ name, callback: callback2, note: registeredNote });
},
onResolve(options, callback2) {
let registeredText = `This error came from the "onResolve" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
let keys2 = {};
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
let namespace = getFlag(options, keys2, "namespace", mustBeString);
checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${JSON.stringify(name)}`);
if (filter == null)
throw new Error(`onResolve() call is missing a filter`);
let id = nextCallbackID++;
onResolveCallbacks[id] = { name, callback: callback2, note: registeredNote };
plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
},
onLoad(options, callback2) {
let registeredText = `This error came from the "onLoad" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
let keys2 = {};
let filter = getFlag(options, keys2, "filter", mustBeRegExp);
let namespace = getFlag(options, keys2, "namespace", mustBeString);
checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${JSON.stringify(name)}`);
if (filter == null)
throw new Error(`onLoad() call is missing a filter`);
let id = nextCallbackID++;
onLoadCallbacks[id] = { name, callback: callback2, note: registeredNote };
plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
},
esbuild: streamIn.esbuild
});
if (promise)
await promise;
requestPlugins.push(plugin);
} catch (e) {
return { ok: false, error: e, pluginName: name };
}
}
const callback = async (request) => {
switch (request.command) {
case "on-start": {
let response = { errors: [], warnings: [] };
await Promise.all(onStartCallbacks.map(async ({ name, callback: callback2, note }) => {
try {
let result = await callback2();
if (result != null) {
if (typeof result !== "object")
throw new Error(`Expected onStart() callback in plugin ${JSON.stringify(name)} to return an object`);
let keys = {};
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${JSON.stringify(name)}`);
if (errors != null)
response.errors.push(...sanitizeMessages(errors, "errors", stash, name));
if (warnings != null)
response.warnings.push(...sanitizeMessages(warnings, "warnings", stash, name));
}
} catch (e) {
response.errors.push(extractErrorMessageV8(e, streamIn, stash, note && note(), name));
}
}));
return response;
}
case "on-resolve": {
let response = {}, name = "", callback2, note;
for (let id of request.ids) {
try {
({ name, callback: callback2, note } = onResolveCallbacks[id]);
let result = await callback2({
path: request.path,
importer: request.importer,
namespace: request.namespace,
resolveDir: request.resolveDir,
kind: request.kind,
pluginData: stash.load(request.pluginData)
});
if (result != null) {
if (typeof result !== "object")
throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(name)} to return an object`);
let keys = {};
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
let path = getFlag(result, keys, "path", mustBeString);
let namespace = getFlag(result, keys, "namespace", mustBeString);
let suffix = getFlag(result, keys, "suffix", mustBeString);
let external = getFlag(result, keys, "external", mustBeBoolean);
let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${JSON.stringify(name)}`);
response.id = id;
if (pluginName != null)
response.pluginName = pluginName;
if (path != null)
response.path = path;
if (namespace != null)
response.namespace = namespace;
if (suffix != null)
response.suffix = suffix;
if (external != null)
response.external = external;
if (sideEffects != null)
response.sideEffects = sideEffects;
if (pluginData != null)
response.pluginData = stash.store(pluginData);
if (errors != null)
response.errors = sanitizeMessages(errors, "errors", stash, name);
if (warnings != null)
response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
if (watchFiles != null)
response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
if (watchDirs != null)
response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
break;
}
} catch (e) {
return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
}
}
return response;
}
case "on-load": {
let response = {}, name = "", callback2, note;
for (let id of request.ids) {
try {
({ name, callback: callback2, note } = onLoadCallbacks[id]);
let result = await callback2({
path: request.path,
namespace: request.namespace,
suffix: request.suffix,
pluginData: stash.load(request.pluginData)
});
if (result != null) {
if (typeof result !== "object")
throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(name)} to return an object`);
let keys = {};
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
let loader = getFlag(result, keys, "loader", mustBeString);
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${JSON.stringify(name)}`);
response.id = id;
if (pluginName != null)
response.pluginName = pluginName;
if (contents instanceof Uint8Array)
response.contents = contents;
else if (contents != null)
response.contents = encodeUTF8(contents);
if (resolveDir != null)
response.resolveDir = resolveDir;
if (pluginData != null)
response.pluginData = stash.store(pluginData);
if (loader != null)
response.loader = loader;
if (errors != null)
response.errors = sanitizeMessages(errors, "errors", stash, name);
if (warnings != null)
response.warnings = sanitizeMessages(warnings, "warnings", stash, name);