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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
|
// This implements a simple long-running service over stdin/stdout. Each
// incoming request is an array of strings, and each outgoing response is a map
// of strings to byte slices. All values are length-prefixed using 32-bit
// little endian integers.
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"sync"
"time"
"github.com/evanw/esbuild/internal/cli_helpers"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/helpers"
"github.com/evanw/esbuild/internal/logger"
"github.com/evanw/esbuild/pkg/api"
"github.com/evanw/esbuild/pkg/cli"
)
type responseCallback func(interface{})
type pluginResolveCallback func(uint32, map[string]interface{}) []byte
type activeBuild struct {
ctx api.BuildContext
pluginResolve pluginResolveCallback
mutex sync.Mutex
disposeWaitGroup sync.WaitGroup // Allows "dispose" to wait for all active tasks
// These are guarded by the mutex
rebuildWaitGroup *sync.WaitGroup // Allows "cancel" to wait for all active rebuilds (within mutex because "sync.WaitGroup" isn't thread-safe)
withinRebuildCount int
didGetCancel bool
}
type serviceType struct {
callbacks map[uint32]responseCallback
activeBuilds map[int]*activeBuild
outgoingPackets chan []byte // Always use "sendPacket" instead of sending on this channel
keepAliveWaitGroup *helpers.ThreadSafeWaitGroup
mutex sync.Mutex
nextRequestID uint32
}
func (service *serviceType) getActiveBuild(key int) *activeBuild {
service.mutex.Lock()
activeBuild := service.activeBuilds[key]
service.mutex.Unlock()
return activeBuild
}
func (service *serviceType) createActiveBuild(key int) *activeBuild {
service.mutex.Lock()
defer service.mutex.Unlock()
if service.activeBuilds[key] != nil {
panic("Internal error")
}
activeBuild := &activeBuild{}
service.activeBuilds[key] = activeBuild
// This pairs with "Done()" in "decRefCount"
service.keepAliveWaitGroup.Add(1)
return activeBuild
}
func (service *serviceType) destroyActiveBuild(key int) {
service.mutex.Lock()
if service.activeBuilds[key] == nil {
panic("Internal error")
}
delete(service.activeBuilds, key)
service.mutex.Unlock()
// This pairs with "Add()" in "trackActiveBuild"
service.keepAliveWaitGroup.Done()
}
func runService(sendPings bool) {
logger.API = logger.JSAPI
service := serviceType{
callbacks: make(map[uint32]responseCallback),
activeBuilds: make(map[int]*activeBuild),
outgoingPackets: make(chan []byte),
keepAliveWaitGroup: helpers.MakeThreadSafeWaitGroup(),
}
buffer := make([]byte, 16*1024)
stream := []byte{}
// Write packets on a single goroutine so they aren't interleaved
go func() {
for packet := range service.outgoingPackets {
if _, err := os.Stdout.Write(packet); err != nil {
os.Exit(1) // I/O error
}
service.keepAliveWaitGroup.Done() // This pairs with the "Add()" when putting stuff into "outgoingPackets"
}
}()
// The protocol always starts with the version
os.Stdout.Write(append(writeUint32(nil, uint32(len(esbuildVersion))), esbuildVersion...))
// Wait for the last response to be written to stdout before returning from
// the enclosing function, which will return from "main()" and exit.
service.keepAliveWaitGroup.Add(1)
defer func() {
service.keepAliveWaitGroup.Done()
service.keepAliveWaitGroup.Wait()
}()
// Periodically ping the host even when we're idle. This will catch cases
// where the host has disappeared and will never send us anything else but
// we incorrectly think we are still needed. In that case we will now try
// to write to stdout and fail, and then know that we should exit.
if sendPings {
go func() {
for {
time.Sleep(1 * time.Second)
service.sendRequest(map[string]interface{}{
"command": "ping",
})
}
}()
}
for {
// Read more data from stdin
n, err := os.Stdin.Read(buffer)
if n == 0 || err == io.EOF {
break // End of stdin
}
if err != nil {
panic(err)
}
stream = append(stream, buffer[:n]...)
// Process all complete (i.e. not partial) packets
bytes := stream
for {
packet, afterPacket, ok := readLengthPrefixedSlice(bytes)
if !ok {
break
}
bytes = afterPacket
// Clone the input since slices into it may be used on another goroutine
clone := append([]byte{}, packet...)
service.handleIncomingPacket(clone)
}
// Move the remaining partial packet to the end to avoid reallocating
stream = append(stream[:0], bytes...)
}
}
// Each packet added to "outgoingPackets" must also add to the wait group
func (service *serviceType) sendPacket(packet []byte) {
service.keepAliveWaitGroup.Add(1) // The writer thread will call "Done()"
service.outgoingPackets <- packet
}
// This will either block until the request has been sent and a response has
// been received, or it will return nil to indicate failure to send due to
// stdin being closed.
func (service *serviceType) sendRequest(request interface{}) interface{} {
result := make(chan interface{})
var id uint32
callback := func(response interface{}) {
result <- response
close(result)
}
id = func() uint32 {
service.mutex.Lock()
defer service.mutex.Unlock()
id := service.nextRequestID
service.nextRequestID++
service.callbacks[id] = callback
return id
}()
service.sendPacket(encodePacket(packet{
id: id,
isRequest: true,
value: request,
}))
return <-result
}
// This function deliberately processes incoming packets sequentially on the
// same goroutine as the caller. We want calling "dispose" on a context to take
// effect immediately and to fail all future calls on that context. We don't
// want "dispose" to accidentally be reordered after any future calls on that
// context, since those future calls are supposed to fail.
//
// If processing a packet could potentially take a while, then the remainder of
// the work should be run on another goroutine after decoding the command.
func (service *serviceType) handleIncomingPacket(bytes []byte) {
p, ok := decodePacket(bytes)
if !ok {
return
}
if !p.isRequest {
service.mutex.Lock()
callback := service.callbacks[p.id]
delete(service.callbacks, p.id)
service.mutex.Unlock()
if callback == nil {
panic(fmt.Sprintf("callback nil for id %d, value %v", p.id, p.value))
}
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
callback(p.value)
}()
return
}
// Handle the request
request := p.value.(map[string]interface{})
command := request["command"].(string)
switch command {
case "build":
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
service.sendPacket(service.handleBuildRequest(p.id, request))
}()
case "transform":
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
service.sendPacket(service.handleTransformRequest(p.id, request))
}()
case "resolve":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
pluginResolve := build.pluginResolve
if ctx != nil && pluginResolve != nil {
build.disposeWaitGroup.Add(1)
}
build.mutex.Unlock()
if pluginResolve != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
if ctx != nil {
defer build.disposeWaitGroup.Done()
}
service.sendPacket(pluginResolve(p.id, request))
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"error": "Cannot call \"resolve\" on an inactive build",
},
}))
case "rebuild":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
if ctx != nil {
build.withinRebuildCount++
if build.rebuildWaitGroup == nil {
build.rebuildWaitGroup = &sync.WaitGroup{}
}
build.rebuildWaitGroup.Add(1)
build.disposeWaitGroup.Add(1)
}
build.mutex.Unlock()
if ctx != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
defer build.disposeWaitGroup.Done()
result := ctx.Rebuild()
build.mutex.Lock()
build.withinRebuildCount--
build.rebuildWaitGroup.Done()
if build.withinRebuildCount == 0 {
// Clear the cancel flag now that the last rebuild has finished
build.didGetCancel = false
// Clear this to avoid confusion with the next group of rebuilds
build.rebuildWaitGroup = nil
}
build.mutex.Unlock()
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"errors": encodeMessages(result.Errors),
"warnings": encodeMessages(result.Warnings),
},
}))
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"error": "Cannot rebuild",
},
}))
case "watch":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
if ctx != nil {
build.disposeWaitGroup.Add(1)
}
build.mutex.Unlock()
if ctx != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
defer build.disposeWaitGroup.Done()
var options api.WatchOptions
if value, ok := request["delay"]; ok {
options.Delay = value.(int)
}
if err := ctx.Watch(options); err != nil {
service.sendPacket(encodeErrorPacket(p.id, err))
} else {
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
}
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"error": "Cannot watch",
},
}))
case "serve":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
if ctx != nil {
build.disposeWaitGroup.Add(1)
}
build.mutex.Unlock()
if ctx != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
defer build.disposeWaitGroup.Done()
var options api.ServeOptions
if value, ok := request["host"]; ok {
options.Host = value.(string)
}
if value, ok := request["port"]; ok {
if value == 0 {
// 0 is the default value in Go, which we interpret as "try to
// pick port 8000". So Go uses -1 as the sentinel value instead.
options.Port = -1
} else {
options.Port = value.(int)
}
}
if value, ok := request["servedir"]; ok {
options.Servedir = value.(string)
}
if value, ok := request["keyfile"]; ok {
options.Keyfile = value.(string)
}
if value, ok := request["certfile"]; ok {
options.Certfile = value.(string)
}
if value, ok := request["fallback"]; ok {
options.Fallback = value.(string)
}
if value, ok := request["corsOrigin"].([]interface{}); ok {
for _, it := range value {
options.CORS.Origin = append(options.CORS.Origin, it.(string))
}
}
if request["onRequest"].(bool) {
options.OnRequest = func(args api.ServeOnRequestArgs) {
// This could potentially be called after we return from
// "Dispose()". If it does, then make sure we don't call into
// JavaScript because we'll get an error. Also make sure that
// if we do call into JavaScript, we wait to call "Dispose()"
// until JavaScript has returned back to us.
build.mutex.Lock()
ctx := build.ctx
if ctx != nil {
build.disposeWaitGroup.Add(1)
}
build.mutex.Unlock()
if ctx != nil {
service.sendRequest(map[string]interface{}{
"command": "serve-request",
"key": key,
"args": map[string]interface{}{
"remoteAddress": args.RemoteAddress,
"method": args.Method,
"path": args.Path,
"status": args.Status,
"timeInMS": args.TimeInMS,
},
})
build.disposeWaitGroup.Done()
}
}
}
if result, err := ctx.Serve(options); err != nil {
service.sendPacket(encodeErrorPacket(p.id, err))
} else {
hosts := make([]interface{}, len(result.Hosts))
for i, host := range result.Hosts {
hosts[i] = host
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"port": int(result.Port),
"hosts": hosts,
},
}))
}
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"error": "Cannot serve",
},
}))
case "cancel":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
rebuildWaitGroup := build.rebuildWaitGroup
if build.withinRebuildCount > 0 {
// If Go got a "rebuild" message from JS before this, there's a chance
// that Go hasn't run "ctx.Rebuild()" by the time our "ctx.Cancel()"
// runs below because both of them are on separate goroutines. To
// handle this, we set this flag to tell our "OnStart" plugin to cancel
// the build in case things happen in that order.
build.didGetCancel = true
}
build.mutex.Unlock()
if ctx != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
ctx.Cancel()
// Block until all manual rebuilds that were active at the time the
// "cancel" packet was originally processed have finished. That way
// JS can wait for "cancel" to end and be assured that it can call
// "rebuild" and have it not merge with any other ongoing rebuilds.
if rebuildWaitGroup != nil {
rebuildWaitGroup.Wait()
}
// Only return control to JavaScript once the cancel operation has succeeded
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
case "dispose":
key := request["key"].(int)
if build := service.getActiveBuild(key); build != nil {
build.mutex.Lock()
ctx := build.ctx
build.ctx = nil
build.mutex.Unlock()
// Release this ref count if it was held
if ctx != nil {
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
// While "Dispose()" will wait for any existing operations on the
// context to finish, we also don't want to start any new operations.
// That can happen because operations (e.g. "Rebuild()") are started
// from a separate goroutine without locking the build mutex. This
// uses a WaitGroup to handle this case. If that happened, then we'll
// wait for it here before disposing. Once the wait is over, no more
// operations can happen on the context because we have already
// zeroed out the shared context pointer above.
build.disposeWaitGroup.Done()
build.disposeWaitGroup.Wait()
ctx.Dispose()
service.destroyActiveBuild(key)
// Only return control to JavaScript once everything relating to this
// build has gracefully ended. Otherwise JavaScript will unregister
// everything related to this build and any calls an ongoing build
// makes into JavaScript will cause errors, which may be observable.
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
}()
return
}
}
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
case "error":
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
// This just exists so that errors during JavaScript API setup get printed
// nicely to the console. This matters if the JavaScript API setup code
// swallows thrown errors. We still want to be able to see the error.
flags := decodeStringArray(request["flags"].([]interface{}))
msg := decodeMessageToPrivate(request["error"].(map[string]interface{}))
logger.PrintMessageToStderr(flags, msg)
service.sendPacket(encodePacket(packet{
id: p.id,
value: make(map[string]interface{}),
}))
}()
case "format-msgs":
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
service.sendPacket(service.handleFormatMessagesRequest(p.id, request))
}()
case "analyze-metafile":
service.keepAliveWaitGroup.Add(1)
go func() {
defer service.keepAliveWaitGroup.Done()
service.sendPacket(service.handleAnalyzeMetafileRequest(p.id, request))
}()
default:
service.sendPacket(encodePacket(packet{
id: p.id,
value: map[string]interface{}{
"error": fmt.Sprintf("Invalid command: %s", command),
},
}))
}
}
func encodeErrorPacket(id uint32, err error) []byte {
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"error": err.Error(),
},
})
}
func (service *serviceType) handleBuildRequest(id uint32, request map[string]interface{}) []byte {
isContext := request["context"].(bool)
key := request["key"].(int)
write := request["write"].(bool)
entries := request["entries"].([]interface{})
flags := decodeStringArray(request["flags"].([]interface{}))
options, err := cli.ParseBuildOptions(flags)
options.AbsWorkingDir = request["absWorkingDir"].(string)
options.NodePaths = decodeStringArray(request["nodePaths"].([]interface{}))
options.MangleCache, _ = request["mangleCache"].(map[string]interface{})
for _, entry := range entries {
entry := entry.([]interface{})
key := entry[0].(string)
value := entry[1].(string)
options.EntryPointsAdvanced = append(options.EntryPointsAdvanced, api.EntryPoint{
OutputPath: key,
InputPath: value,
})
}
// Normally when "write" is true and there is no output file/directory then
// the output is written to stdout instead. However, we're currently using
// stdout as a communication channel and writing the build output to stdout
// would corrupt our protocol. Special-case this to channel this back to the
// host process and write it to stdout there.
writeToStdout := err == nil && write && options.Outfile == "" && options.Outdir == ""
if err != nil {
return encodeErrorPacket(id, err)
}
// Optionally allow input from the stdin channel
if stdin, ok := request["stdinContents"].([]byte); ok {
if options.Stdin == nil {
options.Stdin = &api.StdinOptions{}
}
options.Stdin.Contents = string(stdin)
if resolveDir, ok := request["stdinResolveDir"].(string); ok {
options.Stdin.ResolveDir = resolveDir
}
}
activeBuild := service.createActiveBuild(key)
hasOnEndCallbacks := false
if plugins, ok := request["plugins"]; ok {
if plugins, hasOnEnd, err := service.convertPlugins(key, plugins, activeBuild); err != nil {
return encodeErrorPacket(id, err)
} else {
options.Plugins = plugins
hasOnEndCallbacks = hasOnEnd
}
}
resultToResponse := func(result api.BuildResult) map[string]interface{} {
response := map[string]interface{}{
"errors": encodeMessages(result.Errors),
"warnings": encodeMessages(result.Warnings),
}
if !write {
// Pass the output files back to the caller
response["outputFiles"] = encodeOutputFiles(result.OutputFiles)
}
if options.Metafile {
response["metafile"] = result.Metafile
}
if options.MangleCache != nil {
response["mangleCache"] = result.MangleCache
}
if writeToStdout && len(result.OutputFiles) == 1 {
response["writeToStdout"] = result.OutputFiles[0].Contents
}
return response
}
if !writeToStdout {
options.Write = write
}
if isContext {
options.Plugins = append(options.Plugins, api.Plugin{
Name: "onEnd",
Setup: func(build api.PluginBuild) {
build.OnStart(func() (api.OnStartResult, error) {
activeBuild.mutex.Lock()
if currentWaitGroup := activeBuild.rebuildWaitGroup; currentWaitGroup != nil && activeBuild.didGetCancel {
// Cancel the current build now that the current build is active.
// This catches the case where JS does "rebuild()" then "cancel()"
// but Go's scheduler runs the original "ctx.Cancel()" goroutine
// before it runs the "ctx.Rebuild()" goroutine.
//
// This adds to the rebuild wait group that other cancel operations
// are waiting on because we also want those other cancel operations
// to wait on this cancel operation. Go might schedule this new
// goroutine after all currently-active rebuilds end. We don't want
// the user's cancel operation to return to the user and for them
// to start another rebuild before our "ctx.Cancel" below runs
// because our cancel is supposed to cancel the current build, not
// some independent future build.
activeBuild.rebuildWaitGroup.Add(1)
go func() {
activeBuild.ctx.Cancel()
// Lock the mutex because "sync.WaitGroup" isn't thread-safe.
// But use the wait group that was active at the time the
// "OnStart" callback ran instead of the latest one on the
// active build in case this goroutine is delayed.
activeBuild.mutex.Lock()
currentWaitGroup.Done()
activeBuild.mutex.Unlock()
}()
}
activeBuild.mutex.Unlock()
return api.OnStartResult{}, nil
})
build.OnEnd(func(result *api.BuildResult) (api.OnEndResult, error) {
// For performance, we only send JavaScript an "onEnd" message if
// it's needed. It's only needed if one of the following is true:
//
// - There are any "onEnd" callbacks registered
// - JavaScript has called our "rebuild()" function
// - We are writing build output to JavaScript's stdout
//
// This is especially important if "write" is false since otherwise
// we'd unnecessarily send the entire contents of all output files!
//
// "If a tree falls in a forest and no one is
// around to hear it, does it make a sound?"
//
activeBuild.mutex.Lock()
isWithinRebuild := activeBuild.withinRebuildCount > 0
activeBuild.mutex.Unlock()
if !hasOnEndCallbacks && !isWithinRebuild && !writeToStdout {
return api.OnEndResult{}, nil
}
request := resultToResponse(*result)
request["command"] = "on-end"
request["key"] = key
response, ok := service.sendRequest(request).(map[string]interface{})
if !ok {
return api.OnEndResult{}, errors.New("The service was stopped")
}
var errors []api.Message
var warnings []api.Message
if value, ok := response["errors"].([]interface{}); ok {
errors = decodeMessages(value)
}
if value, ok := response["warnings"].([]interface{}); ok {
warnings = decodeMessages(value)
}
return api.OnEndResult{
Errors: errors,
Warnings: warnings,
}, nil
})
},
})
ctx, err := api.Context(options)
if err != nil {
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"errors": encodeMessages(err.Errors),
"warnings": []interface{}{},
},
})
}
// Keep the build alive until "dispose" has been called
activeBuild.disposeWaitGroup.Add(1)
activeBuild.ctx = ctx
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"errors": []interface{}{},
"warnings": []interface{}{},
},
})
}
result := api.Build(options)
response := resultToResponse(result)
service.destroyActiveBuild(key)
return encodePacket(packet{
id: id,
value: response,
})
}
func resolveKindToString(kind api.ResolveKind) string {
switch kind {
case api.ResolveEntryPoint:
return "entry-point"
// JS
case api.ResolveJSImportStatement:
return "import-statement"
case api.ResolveJSRequireCall:
return "require-call"
case api.ResolveJSDynamicImport:
return "dynamic-import"
case api.ResolveJSRequireResolve:
return "require-resolve"
// CSS
case api.ResolveCSSImportRule:
return "import-rule"
case api.ResolveCSSComposesFrom:
return "composes-from"
case api.ResolveCSSURLToken:
return "url-token"
default:
panic("Internal error")
}
}
func stringToResolveKind(kind string) (api.ResolveKind, bool) {
switch kind {
case "entry-point":
return api.ResolveEntryPoint, true
// JS
case "import-statement":
return api.ResolveJSImportStatement, true
case "require-call":
return api.ResolveJSRequireCall, true
case "dynamic-import":
return api.ResolveJSDynamicImport, true
case "require-resolve":
return api.ResolveJSRequireResolve, true
// CSS
case "import-rule":
return api.ResolveCSSImportRule, true
case "composes-from":
return api.ResolveCSSComposesFrom, true
case "url-token":
return api.ResolveCSSURLToken, true
}
return api.ResolveNone, false
}
func (service *serviceType) convertPlugins(key int, jsPlugins interface{}, activeBuild *activeBuild) ([]api.Plugin, bool, error) {
type filteredCallback struct {
filter *regexp.Regexp
pluginName string
namespace string
id int
}
var onResolveCallbacks []filteredCallback
var onLoadCallbacks []filteredCallback
hasOnEnd := false
filteredCallbacks := func(pluginName string, kind string, items []interface{}) (result []filteredCallback, err error) {
for _, item := range items {
item := item.(map[string]interface{})
filter, err := config.CompileFilterForPlugin(pluginName, kind, item["filter"].(string))
if err != nil {
return nil, err
}
result = append(result, filteredCallback{
pluginName: pluginName,
id: item["id"].(int),
filter: filter,
namespace: item["namespace"].(string),
})
}
return
}
for _, p := range jsPlugins.([]interface{}) {
p := p.(map[string]interface{})
pluginName := p["name"].(string)
if p["onEnd"].(bool) {
hasOnEnd = true
}
if callbacks, err := filteredCallbacks(pluginName, "onResolve", p["onResolve"].([]interface{})); err != nil {
return nil, false, err
} else {
onResolveCallbacks = append(onResolveCallbacks, callbacks...)
}
if callbacks, err := filteredCallbacks(pluginName, "onLoad", p["onLoad"].([]interface{})); err != nil {
return nil, false, err
} else {
onLoadCallbacks = append(onLoadCallbacks, callbacks...)
}
}
// We want to minimize the amount of IPC traffic. Instead of adding one Go
// plugin for every JavaScript plugin, we just add a single Go plugin that
// proxies the plugin queries to the list of JavaScript plugins in the host.
return []api.Plugin{{
Name: "JavaScript plugins",
Setup: func(build api.PluginBuild) {
activeBuild.mutex.Lock()
activeBuild.pluginResolve = func(id uint32, request map[string]interface{}) []byte {
path := request["path"].(string)
var options api.ResolveOptions
if value, ok := request["pluginName"]; ok {
options.PluginName = value.(string)
}
if value, ok := request["importer"]; ok {
options.Importer = value.(string)
}
if value, ok := request["namespace"]; ok {
options.Namespace = value.(string)
}
if value, ok := request["resolveDir"]; ok {
options.ResolveDir = value.(string)
}
if value, ok := request["kind"]; ok {
str := value.(string)
kind, ok := stringToResolveKind(str)
if !ok {
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"error": fmt.Sprintf("Invalid kind: %q", str),
},
})
}
options.Kind = kind
}
if value, ok := request["pluginData"]; ok {
options.PluginData = value.(int)
}
if value, ok := request["with"]; ok {
value := value.(map[string]interface{})
options.With = make(map[string]string, len(value))
for k, v := range value {
options.With[k] = v.(string)
}
}
result := build.Resolve(path, options)
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"errors": encodeMessages(result.Errors),
"warnings": encodeMessages(result.Warnings),
"path": result.Path,
"external": result.External,
"sideEffects": result.SideEffects,
"namespace": result.Namespace,
"suffix": result.Suffix,
"pluginData": result.PluginData,
},
})
}
activeBuild.mutex.Unlock()
// Always register "OnStart" to clear "pluginData"
build.OnStart(func() (api.OnStartResult, error) {
response, ok := service.sendRequest(map[string]interface{}{
"command": "on-start",
"key": key,
}).(map[string]interface{})
if !ok {
return api.OnStartResult{}, errors.New("The service was stopped")
}
return api.OnStartResult{
Errors: decodeMessages(response["errors"].([]interface{})),
Warnings: decodeMessages(response["warnings"].([]interface{})),
}, nil
})
// Only register "OnResolve" if needed
if len(onResolveCallbacks) > 0 {
build.OnResolve(api.OnResolveOptions{Filter: ".*"}, func(args api.OnResolveArgs) (api.OnResolveResult, error) {
var ids []interface{}
applyPath := logger.Path{Text: args.Path, Namespace: args.Namespace}
for _, item := range onResolveCallbacks {
if config.PluginAppliesToPath(applyPath, item.filter, item.namespace) {
ids = append(ids, item.id)
}
}
result := api.OnResolveResult{}
if len(ids) == 0 {
return result, nil
}
with := make(map[string]interface{}, len(args.With))
for k, v := range args.With {
with[k] = v
}
response, ok := service.sendRequest(map[string]interface{}{
"command": "on-resolve",
"key": key,
"ids": ids,
"path": args.Path,
"importer": args.Importer,
"namespace": args.Namespace,
"resolveDir": args.ResolveDir,
"kind": resolveKindToString(args.Kind),
"pluginData": args.PluginData,
"with": with,
}).(map[string]interface{})
if !ok {
return result, errors.New("The service was stopped")
}
if value, ok := response["id"]; ok {
id := value.(int)
for _, item := range onResolveCallbacks {
if item.id == id {
result.PluginName = item.pluginName
break
}
}
}
if value, ok := response["error"]; ok {
return result, errors.New(value.(string))
}
if value, ok := response["pluginName"]; ok {
result.PluginName = value.(string)
}
if value, ok := response["path"]; ok {
result.Path = value.(string)
}
if value, ok := response["namespace"]; ok {
result.Namespace = value.(string)
}
if value, ok := response["suffix"]; ok {
result.Suffix = value.(string)
}
if value, ok := response["external"]; ok {
result.External = value.(bool)
}
if value, ok := response["sideEffects"]; ok {
if value.(bool) {
result.SideEffects = api.SideEffectsTrue
} else {
result.SideEffects = api.SideEffectsFalse
}
}
if value, ok := response["pluginData"]; ok {
result.PluginData = value.(int)
}
if value, ok := response["errors"]; ok {
result.Errors = decodeMessages(value.([]interface{}))
}
if value, ok := response["warnings"]; ok {
result.Warnings = decodeMessages(value.([]interface{}))
}
if value, ok := response["watchFiles"]; ok {
result.WatchFiles = decodeStringArray(value.([]interface{}))
}
if value, ok := response["watchDirs"]; ok {
result.WatchDirs = decodeStringArray(value.([]interface{}))
}
return result, nil
})
}
// Only register "OnLoad" if needed
if len(onLoadCallbacks) > 0 {
build.OnLoad(api.OnLoadOptions{Filter: ".*"}, func(args api.OnLoadArgs) (api.OnLoadResult, error) {
var ids []interface{}
applyPath := logger.Path{Text: args.Path, Namespace: args.Namespace}
for _, item := range onLoadCallbacks {
if config.PluginAppliesToPath(applyPath, item.filter, item.namespace) {
ids = append(ids, item.id)
}
}
result := api.OnLoadResult{}
if len(ids) == 0 {
return result, nil
}
with := make(map[string]interface{}, len(args.With))
for k, v := range args.With {
with[k] = v
}
response, ok := service.sendRequest(map[string]interface{}{
"command": "on-load",
"key": key,
"ids": ids,
"path": args.Path,
"namespace": args.Namespace,
"suffix": args.Suffix,
"pluginData": args.PluginData,
"with": with,
}).(map[string]interface{})
if !ok {
return result, errors.New("The service was stopped")
}
if value, ok := response["id"]; ok {
id := value.(int)
for _, item := range onLoadCallbacks {
if item.id == id {
result.PluginName = item.pluginName
break
}
}
}
if value, ok := response["error"]; ok {
return result, errors.New(value.(string))
}
if value, ok := response["pluginName"]; ok {
result.PluginName = value.(string)
}
if value, ok := response["loader"]; ok {
loader, err := cli_helpers.ParseLoader(value.(string))
if err != nil {
return result, errors.New(err.Text)
}
result.Loader = loader
}
if value, ok := response["contents"]; ok {
contents := string(value.([]byte))
result.Contents = &contents
}
if value, ok := response["resolveDir"]; ok {
result.ResolveDir = value.(string)
}
if value, ok := response["pluginData"]; ok {
result.PluginData = value.(int)
}
if value, ok := response["errors"]; ok {
result.Errors = decodeMessages(value.([]interface{}))
}
if value, ok := response["warnings"]; ok {
result.Warnings = decodeMessages(value.([]interface{}))
}
if value, ok := response["watchFiles"]; ok {
result.WatchFiles = decodeStringArray(value.([]interface{}))
}
if value, ok := response["watchDirs"]; ok {
result.WatchDirs = decodeStringArray(value.([]interface{}))
}
return result, nil
})
}
},
}}, hasOnEnd, nil
}
func (service *serviceType) handleTransformRequest(id uint32, request map[string]interface{}) []byte {
inputFS := request["inputFS"].(bool)
input := string(request["input"].([]byte))
flags := decodeStringArray(request["flags"].([]interface{}))
options, err := cli.ParseTransformOptions(flags)
if err != nil {
return encodeErrorPacket(id, err)
}
options.MangleCache, _ = request["mangleCache"].(map[string]interface{})
transformInput := input
if inputFS {
fs.BeforeFileOpen()
bytes, err := ioutil.ReadFile(input)
fs.AfterFileClose()
if err == nil {
err = os.Remove(input)
}
if err != nil {
return encodeErrorPacket(id, err)
}
transformInput = string(bytes)
}
result := api.Transform(transformInput, options)
codeFS := false
mapFS := false
if inputFS && len(result.Code) > 0 {
file := input + ".code"
fs.BeforeFileOpen()
if err := ioutil.WriteFile(file, result.Code, 0644); err == nil {
result.Code = []byte(file)
codeFS = true
}
fs.AfterFileClose()
}
if inputFS && len(result.Map) > 0 {
file := input + ".map"
fs.BeforeFileOpen()
if err := ioutil.WriteFile(file, result.Map, 0644); err == nil {
result.Map = []byte(file)
mapFS = true
}
fs.AfterFileClose()
}
response := map[string]interface{}{
"errors": encodeMessages(result.Errors),
"warnings": encodeMessages(result.Warnings),
"codeFS": codeFS,
"code": string(result.Code),
"mapFS": mapFS,
"map": string(result.Map),
}
if result.LegalComments != nil {
response["legalComments"] = string(result.LegalComments)
}
if result.MangleCache != nil {
response["mangleCache"] = result.MangleCache
}
return encodePacket(packet{
id: id,
value: response,
})
}
func (service *serviceType) handleFormatMessagesRequest(id uint32, request map[string]interface{}) []byte {
msgs := decodeMessages(request["messages"].([]interface{}))
options := api.FormatMessagesOptions{
Kind: api.ErrorMessage,
}
if request["isWarning"].(bool) {
options.Kind = api.WarningMessage
}
if value, ok := request["color"].(bool); ok {
options.Color = value
}
if value, ok := request["terminalWidth"].(int); ok {
options.TerminalWidth = value
}
result := api.FormatMessages(msgs, options)
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"messages": encodeStringArray(result),
},
})
}
func (service *serviceType) handleAnalyzeMetafileRequest(id uint32, request map[string]interface{}) []byte {
metafile := request["metafile"].(string)
options := api.AnalyzeMetafileOptions{}
if value, ok := request["color"].(bool); ok {
options.Color = value
}
if value, ok := request["verbose"].(bool); ok {
options.Verbose = value
}
result := api.AnalyzeMetafile(metafile, options)
return encodePacket(packet{
id: id,
value: map[string]interface{}{
"result": result,
},
})
}
func encodeStringArray(strings []string) []interface{} {
values := make([]interface{}, len(strings))
for i, value := range strings {
values[i] = value
}
return values
}
func decodeStringArray(values []interface{}) []string {
strings := make([]string, len(values))
for i, value := range values {
strings[i] = value.(string)
}
return strings
}
func encodeOutputFiles(outputFiles []api.OutputFile) []interface{} {
values := make([]interface{}, len(outputFiles))
for i, outputFile := range outputFiles {
values[i] = map[string]interface{}{
"path": outputFile.Path,
"contents": outputFile.Contents,
"hash": outputFile.Hash,
}
}
return values
}
func encodeLocation(loc *api.Location) interface{} {
if loc == nil {
return nil
}
return map[string]interface{}{
"file": loc.File,
"namespace": loc.Namespace,
"line": loc.Line,
"column": loc.Column,
"length": loc.Length,
"lineText": loc.LineText,
"suggestion": loc.Suggestion,
}
}
func encodeMessages(msgs []api.Message) []interface{} {
values := make([]interface{}, len(msgs))
for i, msg := range msgs {
value := map[string]interface{}{
"id": msg.ID,
"pluginName": msg.PluginName,
"text": msg.Text,
"location": encodeLocation(msg.Location),
}
values[i] = value
notes := make([]interface{}, len(msg.Notes))
for j, note := range msg.Notes {
notes[j] = map[string]interface{}{
"text": note.Text,
"location": encodeLocation(note.Location),
}
}
value["notes"] = notes
// Send "-1" to mean "undefined"
detail, ok := msg.Detail.(int)
if !ok {
detail = -1
}
value["detail"] = detail
}
return values
}
func decodeLocation(value interface{}) *api.Location {
if value == nil {
return nil
}
loc := value.(map[string]interface{})
namespace := loc["namespace"].(string)
if namespace == "" {
namespace = "file"
}
return &api.Location{
File: loc["file"].(string),
Namespace: namespace,
Line: loc["line"].(int),
Column: loc["column"].(int),
Length: loc["length"].(int),
LineText: loc["lineText"].(string),
Suggestion: loc["suggestion"].(string),
}
}
func decodeMessages(values []interface{}) []api.Message {
msgs := make([]api.Message, len(values))
for i, value := range values {
obj := value.(map[string]interface{})
msg := api.Message{
ID: obj["id"].(string),
PluginName: obj["pluginName"].(string),
Text: obj["text"].(string),
Location: decodeLocation(obj["location"]),
Detail: obj["detail"].(int),
}
for _, note := range obj["notes"].([]interface{}) {
noteObj := note.(map[string]interface{})
msg.Notes = append(msg.Notes, api.Note{
Text: noteObj["text"].(string),
Location: decodeLocation(noteObj["location"]),
})
}
msgs[i] = msg
}
return msgs
}
func decodeLocationToPrivate(value interface{}) *logger.MsgLocation {
if value == nil {
return nil
}
loc := value.(map[string]interface{})
namespace := loc["namespace"].(string)
if namespace == "" {
namespace = "file"
}
file := loc["file"].(string)
return &logger.MsgLocation{
File: logger.PrettyPaths{Abs: file, Rel: file},
Namespace: namespace,
Line: loc["line"].(int),
Column: loc["column"].(int),
Length: loc["length"].(int),
LineText: loc["lineText"].(string),
Suggestion: loc["suggestion"].(string),
}
}
func decodeMessageToPrivate(obj map[string]interface{}) logger.Msg {
msg := logger.Msg{
ID: logger.StringToMaximumMsgID(obj["id"].(string)),
PluginName: obj["pluginName"].(string),
Data: logger.MsgData{
Text: obj["text"].(string),
Location: decodeLocationToPrivate(obj["location"]),
UserDetail: obj["detail"].(int),
},
}
for _, note := range obj["notes"].([]interface{}) {
noteObj := note.(map[string]interface{})
msg.Notes = append(msg.Notes, logger.MsgData{
Text: noteObj["text"].(string),
Location: decodeLocationToPrivate(noteObj["location"]),
})
}
return msg
}
|