source: trip-planner-front/node_modules/esbuild-wasm/lib/browser.js@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 80.4 KB
Line 
1(exports=>{
2var __defProp = Object.defineProperty;
3var __defProps = Object.defineProperties;
4var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6var __hasOwnProp = Object.prototype.hasOwnProperty;
7var __propIsEnum = Object.prototype.propertyIsEnumerable;
8var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9var __spreadValues = (a, b) => {
10 for (var prop in b || (b = {}))
11 if (__hasOwnProp.call(b, prop))
12 __defNormalProp(a, prop, b[prop]);
13 if (__getOwnPropSymbols)
14 for (var prop of __getOwnPropSymbols(b)) {
15 if (__propIsEnum.call(b, prop))
16 __defNormalProp(a, prop, b[prop]);
17 }
18 return a;
19};
20var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
21var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
22var __export = (target, all) => {
23 __markAsModule(target);
24 for (var name in all)
25 __defProp(target, name, { get: all[name], enumerable: true });
26};
27var __async = (__this, __arguments, generator) => {
28 return new Promise((resolve, reject) => {
29 var fulfilled = (value) => {
30 try {
31 step(generator.next(value));
32 } catch (e) {
33 reject(e);
34 }
35 };
36 var rejected = (value) => {
37 try {
38 step(generator.throw(value));
39 } catch (e) {
40 reject(e);
41 }
42 };
43 var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
44 step((generator = generator.apply(__this, __arguments)).next());
45 });
46};
47
48// lib/npm/browser.ts
49__export(exports, {
50 analyzeMetafile: () => analyzeMetafile,
51 analyzeMetafileSync: () => analyzeMetafileSync,
52 build: () => build,
53 buildSync: () => buildSync,
54 formatMessages: () => formatMessages,
55 formatMessagesSync: () => formatMessagesSync,
56 initialize: () => initialize,
57 serve: () => serve,
58 transform: () => transform,
59 transformSync: () => transformSync,
60 version: () => version
61});
62
63// lib/shared/stdio_protocol.ts
64function encodePacket(packet) {
65 let visit = (value) => {
66 if (value === null) {
67 bb.write8(0);
68 } else if (typeof value === "boolean") {
69 bb.write8(1);
70 bb.write8(+value);
71 } else if (typeof value === "number") {
72 bb.write8(2);
73 bb.write32(value | 0);
74 } else if (typeof value === "string") {
75 bb.write8(3);
76 bb.write(encodeUTF8(value));
77 } else if (value instanceof Uint8Array) {
78 bb.write8(4);
79 bb.write(value);
80 } else if (value instanceof Array) {
81 bb.write8(5);
82 bb.write32(value.length);
83 for (let item of value) {
84 visit(item);
85 }
86 } else {
87 let keys = Object.keys(value);
88 bb.write8(6);
89 bb.write32(keys.length);
90 for (let key of keys) {
91 bb.write(encodeUTF8(key));
92 visit(value[key]);
93 }
94 }
95 };
96 let bb = new ByteBuffer();
97 bb.write32(0);
98 bb.write32(packet.id << 1 | +!packet.isRequest);
99 visit(packet.value);
100 writeUInt32LE(bb.buf, bb.len - 4, 0);
101 return bb.buf.subarray(0, bb.len);
102}
103function decodePacket(bytes) {
104 let visit = () => {
105 switch (bb.read8()) {
106 case 0:
107 return null;
108 case 1:
109 return !!bb.read8();
110 case 2:
111 return bb.read32();
112 case 3:
113 return decodeUTF8(bb.read());
114 case 4:
115 return bb.read();
116 case 5: {
117 let count = bb.read32();
118 let value2 = [];
119 for (let i = 0; i < count; i++) {
120 value2.push(visit());
121 }
122 return value2;
123 }
124 case 6: {
125 let count = bb.read32();
126 let value2 = {};
127 for (let i = 0; i < count; i++) {
128 value2[decodeUTF8(bb.read())] = visit();
129 }
130 return value2;
131 }
132 default:
133 throw new Error("Invalid packet");
134 }
135 };
136 let bb = new ByteBuffer(bytes);
137 let id = bb.read32();
138 let isRequest = (id & 1) === 0;
139 id >>>= 1;
140 let value = visit();
141 if (bb.ptr !== bytes.length) {
142 throw new Error("Invalid packet");
143 }
144 return { id, isRequest, value };
145}
146var ByteBuffer = class {
147 constructor(buf = new Uint8Array(1024)) {
148 this.buf = buf;
149 this.len = 0;
150 this.ptr = 0;
151 }
152 _write(delta) {
153 if (this.len + delta > this.buf.length) {
154 let clone = new Uint8Array((this.len + delta) * 2);
155 clone.set(this.buf);
156 this.buf = clone;
157 }
158 this.len += delta;
159 return this.len - delta;
160 }
161 write8(value) {
162 let offset = this._write(1);
163 this.buf[offset] = value;
164 }
165 write32(value) {
166 let offset = this._write(4);
167 writeUInt32LE(this.buf, value, offset);
168 }
169 write(bytes) {
170 let offset = this._write(4 + bytes.length);
171 writeUInt32LE(this.buf, bytes.length, offset);
172 this.buf.set(bytes, offset + 4);
173 }
174 _read(delta) {
175 if (this.ptr + delta > this.buf.length) {
176 throw new Error("Invalid packet");
177 }
178 this.ptr += delta;
179 return this.ptr - delta;
180 }
181 read8() {
182 return this.buf[this._read(1)];
183 }
184 read32() {
185 return readUInt32LE(this.buf, this._read(4));
186 }
187 read() {
188 let length = this.read32();
189 let bytes = new Uint8Array(length);
190 let ptr = this._read(bytes.length);
191 bytes.set(this.buf.subarray(ptr, ptr + length));
192 return bytes;
193 }
194};
195var encodeUTF8;
196var decodeUTF8;
197if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
198 let encoder = new TextEncoder();
199 let decoder = new TextDecoder();
200 encodeUTF8 = (text) => encoder.encode(text);
201 decodeUTF8 = (bytes) => decoder.decode(bytes);
202} else if (typeof Buffer !== "undefined") {
203 encodeUTF8 = (text) => {
204 let buffer = Buffer.from(text);
205 if (!(buffer instanceof Uint8Array)) {
206 buffer = new Uint8Array(buffer);
207 }
208 return buffer;
209 };
210 decodeUTF8 = (bytes) => {
211 let { buffer, byteOffset, byteLength } = bytes;
212 return Buffer.from(buffer, byteOffset, byteLength).toString();
213 };
214} else {
215 throw new Error("No UTF-8 codec found");
216}
217function readUInt32LE(buffer, offset) {
218 return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
219}
220function writeUInt32LE(buffer, value, offset) {
221 buffer[offset++] = value;
222 buffer[offset++] = value >> 8;
223 buffer[offset++] = value >> 16;
224 buffer[offset++] = value >> 24;
225}
226
227// lib/shared/common.ts
228function validateTarget(target) {
229 target += "";
230 if (target.indexOf(",") >= 0)
231 throw new Error(`Invalid target: ${target}`);
232 return target;
233}
234var canBeAnything = () => null;
235var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
236var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object";
237var mustBeString = (value) => typeof value === "string" ? null : "a string";
238var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
239var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
240var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
241var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
242var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
243var mustBeArrayOrRecord = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
244var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
245var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
246var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
247var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
248var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
249function getFlag(object, keys, key, mustBeFn) {
250 let value = object[key];
251 keys[key + ""] = true;
252 if (value === void 0)
253 return void 0;
254 let mustBe = mustBeFn(value);
255 if (mustBe !== null)
256 throw new Error(`"${key}" must be ${mustBe}`);
257 return value;
258}
259function checkForInvalidFlags(object, keys, where) {
260 for (let key in object) {
261 if (!(key in keys)) {
262 throw new Error(`Invalid option ${where}: "${key}"`);
263 }
264 }
265}
266function validateInitializeOptions(options) {
267 let keys = Object.create(null);
268 let wasmURL = getFlag(options, keys, "wasmURL", mustBeString);
269 let worker = getFlag(options, keys, "worker", mustBeBoolean);
270 checkForInvalidFlags(options, keys, "in startService() call");
271 return {
272 wasmURL,
273 worker
274 };
275}
276function pushLogFlags(flags, options, keys, isTTY, logLevelDefault) {
277 let color = getFlag(options, keys, "color", mustBeBoolean);
278 let logLevel = getFlag(options, keys, "logLevel", mustBeString);
279 let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
280 if (color !== void 0)
281 flags.push(`--color=${color}`);
282 else if (isTTY)
283 flags.push(`--color=true`);
284 flags.push(`--log-level=${logLevel || logLevelDefault}`);
285 flags.push(`--log-limit=${logLimit || 0}`);
286}
287function pushCommonFlags(flags, options, keys) {
288 let legalComments = getFlag(options, keys, "legalComments", mustBeString);
289 let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
290 let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
291 let target = getFlag(options, keys, "target", mustBeStringOrArray);
292 let format = getFlag(options, keys, "format", mustBeString);
293 let globalName = getFlag(options, keys, "globalName", mustBeString);
294 let minify = getFlag(options, keys, "minify", mustBeBoolean);
295 let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
296 let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
297 let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
298 let charset = getFlag(options, keys, "charset", mustBeString);
299 let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
300 let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
301 let jsx = getFlag(options, keys, "jsx", mustBeString);
302 let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
303 let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
304 let define = getFlag(options, keys, "define", mustBeObject);
305 let pure = getFlag(options, keys, "pure", mustBeArray);
306 let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
307 if (legalComments)
308 flags.push(`--legal-comments=${legalComments}`);
309 if (sourceRoot !== void 0)
310 flags.push(`--source-root=${sourceRoot}`);
311 if (sourcesContent !== void 0)
312 flags.push(`--sources-content=${sourcesContent}`);
313 if (target) {
314 if (Array.isArray(target))
315 flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
316 else
317 flags.push(`--target=${validateTarget(target)}`);
318 }
319 if (format)
320 flags.push(`--format=${format}`);
321 if (globalName)
322 flags.push(`--global-name=${globalName}`);
323 if (minify)
324 flags.push("--minify");
325 if (minifySyntax)
326 flags.push("--minify-syntax");
327 if (minifyWhitespace)
328 flags.push("--minify-whitespace");
329 if (minifyIdentifiers)
330 flags.push("--minify-identifiers");
331 if (charset)
332 flags.push(`--charset=${charset}`);
333 if (treeShaking !== void 0)
334 flags.push(`--tree-shaking=${treeShaking}`);
335 if (ignoreAnnotations)
336 flags.push(`--ignore-annotations`);
337 if (jsx)
338 flags.push(`--jsx=${jsx}`);
339 if (jsxFactory)
340 flags.push(`--jsx-factory=${jsxFactory}`);
341 if (jsxFragment)
342 flags.push(`--jsx-fragment=${jsxFragment}`);
343 if (define) {
344 for (let key in define) {
345 if (key.indexOf("=") >= 0)
346 throw new Error(`Invalid define: ${key}`);
347 flags.push(`--define:${key}=${define[key]}`);
348 }
349 }
350 if (pure)
351 for (let fn of pure)
352 flags.push(`--pure:${fn}`);
353 if (keepNames)
354 flags.push(`--keep-names`);
355}
356function flagsForBuildOptions(callName, options, isTTY, logLevelDefault, writeDefault) {
357 var _a;
358 let flags = [];
359 let entries = [];
360 let keys = Object.create(null);
361 let stdinContents = null;
362 let stdinResolveDir = null;
363 let watchMode = null;
364 pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
365 pushCommonFlags(flags, options, keys);
366 let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
367 let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
368 let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject);
369 let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
370 let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
371 let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
372 let outfile = getFlag(options, keys, "outfile", mustBeString);
373 let outdir = getFlag(options, keys, "outdir", mustBeString);
374 let outbase = getFlag(options, keys, "outbase", mustBeString);
375 let platform = getFlag(options, keys, "platform", mustBeString);
376 let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
377 let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
378 let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
379 let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
380 let conditions = getFlag(options, keys, "conditions", mustBeArray);
381 let external = getFlag(options, keys, "external", mustBeArray);
382 let loader = getFlag(options, keys, "loader", mustBeObject);
383 let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
384 let publicPath = getFlag(options, keys, "publicPath", mustBeString);
385 let entryNames = getFlag(options, keys, "entryNames", mustBeString);
386 let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
387 let assetNames = getFlag(options, keys, "assetNames", mustBeString);
388 let inject = getFlag(options, keys, "inject", mustBeArray);
389 let banner = getFlag(options, keys, "banner", mustBeObject);
390 let footer = getFlag(options, keys, "footer", mustBeObject);
391 let entryPoints = getFlag(options, keys, "entryPoints", mustBeArrayOrRecord);
392 let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
393 let stdin = getFlag(options, keys, "stdin", mustBeObject);
394 let write = (_a = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a : writeDefault;
395 let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
396 let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true;
397 keys.plugins = true;
398 checkForInvalidFlags(options, keys, `in ${callName}() call`);
399 if (sourcemap)
400 flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
401 if (bundle)
402 flags.push("--bundle");
403 if (allowOverwrite)
404 flags.push("--allow-overwrite");
405 if (watch) {
406 flags.push("--watch");
407 if (typeof watch === "boolean") {
408 watchMode = {};
409 } else {
410 let watchKeys = Object.create(null);
411 let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction);
412 checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`);
413 watchMode = { onRebuild };
414 }
415 }
416 if (splitting)
417 flags.push("--splitting");
418 if (preserveSymlinks)
419 flags.push("--preserve-symlinks");
420 if (metafile)
421 flags.push(`--metafile`);
422 if (outfile)
423 flags.push(`--outfile=${outfile}`);
424 if (outdir)
425 flags.push(`--outdir=${outdir}`);
426 if (outbase)
427 flags.push(`--outbase=${outbase}`);
428 if (platform)
429 flags.push(`--platform=${platform}`);
430 if (tsconfig)
431 flags.push(`--tsconfig=${tsconfig}`);
432 if (resolveExtensions) {
433 let values = [];
434 for (let value of resolveExtensions) {
435 value += "";
436 if (value.indexOf(",") >= 0)
437 throw new Error(`Invalid resolve extension: ${value}`);
438 values.push(value);
439 }
440 flags.push(`--resolve-extensions=${values.join(",")}`);
441 }
442 if (publicPath)
443 flags.push(`--public-path=${publicPath}`);
444 if (entryNames)
445 flags.push(`--entry-names=${entryNames}`);
446 if (chunkNames)
447 flags.push(`--chunk-names=${chunkNames}`);
448 if (assetNames)
449 flags.push(`--asset-names=${assetNames}`);
450 if (mainFields) {
451 let values = [];
452 for (let value of mainFields) {
453 value += "";
454 if (value.indexOf(",") >= 0)
455 throw new Error(`Invalid main field: ${value}`);
456 values.push(value);
457 }
458 flags.push(`--main-fields=${values.join(",")}`);
459 }
460 if (conditions) {
461 let values = [];
462 for (let value of conditions) {
463 value += "";
464 if (value.indexOf(",") >= 0)
465 throw new Error(`Invalid condition: ${value}`);
466 values.push(value);
467 }
468 flags.push(`--conditions=${values.join(",")}`);
469 }
470 if (external)
471 for (let name of external)
472 flags.push(`--external:${name}`);
473 if (banner) {
474 for (let type in banner) {
475 if (type.indexOf("=") >= 0)
476 throw new Error(`Invalid banner file type: ${type}`);
477 flags.push(`--banner:${type}=${banner[type]}`);
478 }
479 }
480 if (footer) {
481 for (let type in footer) {
482 if (type.indexOf("=") >= 0)
483 throw new Error(`Invalid footer file type: ${type}`);
484 flags.push(`--footer:${type}=${footer[type]}`);
485 }
486 }
487 if (inject)
488 for (let path of inject)
489 flags.push(`--inject:${path}`);
490 if (loader) {
491 for (let ext in loader) {
492 if (ext.indexOf("=") >= 0)
493 throw new Error(`Invalid loader extension: ${ext}`);
494 flags.push(`--loader:${ext}=${loader[ext]}`);
495 }
496 }
497 if (outExtension) {
498 for (let ext in outExtension) {
499 if (ext.indexOf("=") >= 0)
500 throw new Error(`Invalid out extension: ${ext}`);
501 flags.push(`--out-extension:${ext}=${outExtension[ext]}`);
502 }
503 }
504 if (entryPoints) {
505 if (Array.isArray(entryPoints)) {
506 for (let entryPoint of entryPoints) {
507 entries.push(["", entryPoint + ""]);
508 }
509 } else {
510 for (let [key, value] of Object.entries(entryPoints)) {
511 entries.push([key + "", value + ""]);
512 }
513 }
514 }
515 if (stdin) {
516 let stdinKeys = Object.create(null);
517 let contents = getFlag(stdin, stdinKeys, "contents", mustBeString);
518 let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
519 let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
520 let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
521 checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
522 if (sourcefile)
523 flags.push(`--sourcefile=${sourcefile}`);
524 if (loader2)
525 flags.push(`--loader=${loader2}`);
526 if (resolveDir)
527 stdinResolveDir = resolveDir + "";
528 stdinContents = contents ? contents + "" : "";
529 }
530 let nodePaths = [];
531 if (nodePathsInput) {
532 for (let value of nodePathsInput) {
533 value += "";
534 nodePaths.push(value);
535 }
536 }
537 return {
538 entries,
539 flags,
540 write,
541 stdinContents,
542 stdinResolveDir,
543 absWorkingDir,
544 incremental,
545 nodePaths,
546 watch: watchMode
547 };
548}
549function flagsForTransformOptions(callName, options, isTTY, logLevelDefault) {
550 let flags = [];
551 let keys = Object.create(null);
552 pushLogFlags(flags, options, keys, isTTY, logLevelDefault);
553 pushCommonFlags(flags, options, keys);
554 let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
555 let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
556 let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
557 let loader = getFlag(options, keys, "loader", mustBeString);
558 let banner = getFlag(options, keys, "banner", mustBeString);
559 let footer = getFlag(options, keys, "footer", mustBeString);
560 checkForInvalidFlags(options, keys, `in ${callName}() call`);
561 if (sourcemap)
562 flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
563 if (tsconfigRaw)
564 flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
565 if (sourcefile)
566 flags.push(`--sourcefile=${sourcefile}`);
567 if (loader)
568 flags.push(`--loader=${loader}`);
569 if (banner)
570 flags.push(`--banner=${banner}`);
571 if (footer)
572 flags.push(`--footer=${footer}`);
573 return flags;
574}
575function createChannel(streamIn) {
576 let responseCallbacks = new Map();
577 let pluginCallbacks = new Map();
578 let watchCallbacks = new Map();
579 let serveCallbacks = new Map();
580 let nextServeID = 0;
581 let isClosed = false;
582 let nextRequestID = 0;
583 let nextBuildKey = 0;
584 let stdout = new Uint8Array(16 * 1024);
585 let stdoutUsed = 0;
586 let readFromStdout = (chunk) => {
587 let limit = stdoutUsed + chunk.length;
588 if (limit > stdout.length) {
589 let swap = new Uint8Array(limit * 2);
590 swap.set(stdout);
591 stdout = swap;
592 }
593 stdout.set(chunk, stdoutUsed);
594 stdoutUsed += chunk.length;
595 let offset = 0;
596 while (offset + 4 <= stdoutUsed) {
597 let length = readUInt32LE(stdout, offset);
598 if (offset + 4 + length > stdoutUsed) {
599 break;
600 }
601 offset += 4;
602 handleIncomingPacket(stdout.subarray(offset, offset + length));
603 offset += length;
604 }
605 if (offset > 0) {
606 stdout.copyWithin(0, offset, stdoutUsed);
607 stdoutUsed -= offset;
608 }
609 };
610 let afterClose = () => {
611 isClosed = true;
612 for (let callback of responseCallbacks.values()) {
613 callback("The service was stopped", null);
614 }
615 responseCallbacks.clear();
616 for (let callbacks of serveCallbacks.values()) {
617 callbacks.onWait("The service was stopped");
618 }
619 serveCallbacks.clear();
620 for (let callback of watchCallbacks.values()) {
621 try {
622 callback(new Error("The service was stopped"), null);
623 } catch (e) {
624 console.error(e);
625 }
626 }
627 watchCallbacks.clear();
628 };
629 let sendRequest = (refs, value, callback) => {
630 if (isClosed)
631 return callback("The service is no longer running", null);
632 let id = nextRequestID++;
633 responseCallbacks.set(id, (error, response) => {
634 try {
635 callback(error, response);
636 } finally {
637 if (refs)
638 refs.unref();
639 }
640 });
641 if (refs)
642 refs.ref();
643 streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
644 };
645 let sendResponse = (id, value) => {
646 if (isClosed)
647 throw new Error("The service is no longer running");
648 streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
649 };
650 let handleRequest = (id, request) => __async(this, null, function* () {
651 try {
652 switch (request.command) {
653 case "ping": {
654 sendResponse(id, {});
655 break;
656 }
657 case "start": {
658 let callback = pluginCallbacks.get(request.key);
659 if (!callback)
660 sendResponse(id, {});
661 else
662 sendResponse(id, yield callback(request));
663 break;
664 }
665 case "resolve": {
666 let callback = pluginCallbacks.get(request.key);
667 if (!callback)
668 sendResponse(id, {});
669 else
670 sendResponse(id, yield callback(request));
671 break;
672 }
673 case "load": {
674 let callback = pluginCallbacks.get(request.key);
675 if (!callback)
676 sendResponse(id, {});
677 else
678 sendResponse(id, yield callback(request));
679 break;
680 }
681 case "serve-request": {
682 let callbacks = serveCallbacks.get(request.serveID);
683 if (callbacks && callbacks.onRequest)
684 callbacks.onRequest(request.args);
685 sendResponse(id, {});
686 break;
687 }
688 case "serve-wait": {
689 let callbacks = serveCallbacks.get(request.serveID);
690 if (callbacks)
691 callbacks.onWait(request.error);
692 sendResponse(id, {});
693 break;
694 }
695 case "watch-rebuild": {
696 let callback = watchCallbacks.get(request.watchID);
697 try {
698 if (callback)
699 callback(null, request.args);
700 } catch (err) {
701 console.error(err);
702 }
703 sendResponse(id, {});
704 break;
705 }
706 default:
707 throw new Error(`Invalid command: ` + request.command);
708 }
709 } catch (e) {
710 sendResponse(id, { errors: [extractErrorMessageV8(e, streamIn, null, void 0, "")] });
711 }
712 });
713 let isFirstPacket = true;
714 let handleIncomingPacket = (bytes) => {
715 if (isFirstPacket) {
716 isFirstPacket = false;
717 let binaryVersion = String.fromCharCode(...bytes);
718 if (binaryVersion !== "0.13.4") {
719 throw new Error(`Cannot start service: Host version "${"0.13.4"}" does not match binary version ${JSON.stringify(binaryVersion)}`);
720 }
721 return;
722 }
723 let packet = decodePacket(bytes);
724 if (packet.isRequest) {
725 handleRequest(packet.id, packet.value);
726 } else {
727 let callback = responseCallbacks.get(packet.id);
728 responseCallbacks.delete(packet.id);
729 if (packet.value.error)
730 callback(packet.value.error, {});
731 else
732 callback(null, packet.value);
733 }
734 };
735 let handlePlugins = (initialOptions, plugins, buildKey, stash) => __async(this, null, function* () {
736 let onStartCallbacks = [];
737 let onEndCallbacks = [];
738 let onResolveCallbacks = {};
739 let onLoadCallbacks = {};
740 let nextCallbackID = 0;
741 let i = 0;
742 let requestPlugins = [];
743 plugins = [...plugins];
744 for (let item of plugins) {
745 let keys = {};
746 if (typeof item !== "object")
747 throw new Error(`Plugin at index ${i} must be an object`);
748 let name = getFlag(item, keys, "name", mustBeString);
749 if (typeof name !== "string" || name === "")
750 throw new Error(`Plugin at index ${i} is missing a name`);
751 try {
752 let setup = getFlag(item, keys, "setup", mustBeFunction);
753 if (typeof setup !== "function")
754 throw new Error(`Plugin is missing a setup function`);
755 checkForInvalidFlags(item, keys, `on plugin ${JSON.stringify(name)}`);
756 let plugin = {
757 name,
758 onResolve: [],
759 onLoad: []
760 };
761 i++;
762 let promise = setup({
763 initialOptions,
764 onStart(callback2) {
765 let registeredText = `This error came from the "onStart" callback registered here`;
766 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
767 onStartCallbacks.push({ name, callback: callback2, note: registeredNote });
768 },
769 onEnd(callback2) {
770 let registeredText = `This error came from the "onEnd" callback registered here`;
771 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
772 onEndCallbacks.push({ name, callback: callback2, note: registeredNote });
773 },
774 onResolve(options, callback2) {
775 let registeredText = `This error came from the "onResolve" callback registered here`;
776 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
777 let keys2 = {};
778 let filter = getFlag(options, keys2, "filter", mustBeRegExp);
779 let namespace = getFlag(options, keys2, "namespace", mustBeString);
780 checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${JSON.stringify(name)}`);
781 if (filter == null)
782 throw new Error(`onResolve() call is missing a filter`);
783 let id = nextCallbackID++;
784 onResolveCallbacks[id] = { name, callback: callback2, note: registeredNote };
785 plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
786 },
787 onLoad(options, callback2) {
788 let registeredText = `This error came from the "onLoad" callback registered here`;
789 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
790 let keys2 = {};
791 let filter = getFlag(options, keys2, "filter", mustBeRegExp);
792 let namespace = getFlag(options, keys2, "namespace", mustBeString);
793 checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${JSON.stringify(name)}`);
794 if (filter == null)
795 throw new Error(`onLoad() call is missing a filter`);
796 let id = nextCallbackID++;
797 onLoadCallbacks[id] = { name, callback: callback2, note: registeredNote };
798 plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
799 }
800 });
801 if (promise)
802 yield promise;
803 requestPlugins.push(plugin);
804 } catch (e) {
805 return { ok: false, error: e, pluginName: name };
806 }
807 }
808 const callback = (request) => __async(this, null, function* () {
809 switch (request.command) {
810 case "start": {
811 let response = { errors: [], warnings: [] };
812 yield Promise.all(onStartCallbacks.map((_0) => __async(this, [_0], function* ({ name, callback: callback2, note }) {
813 try {
814 let result = yield callback2();
815 if (result != null) {
816 if (typeof result !== "object")
817 throw new Error(`Expected onStart() callback in plugin ${JSON.stringify(name)} to return an object`);
818 let keys = {};
819 let errors = getFlag(result, keys, "errors", mustBeArray);
820 let warnings = getFlag(result, keys, "warnings", mustBeArray);
821 checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${JSON.stringify(name)}`);
822 if (errors != null)
823 response.errors.push(...sanitizeMessages(errors, "errors", stash, name));
824 if (warnings != null)
825 response.warnings.push(...sanitizeMessages(warnings, "warnings", stash, name));
826 }
827 } catch (e) {
828 response.errors.push(extractErrorMessageV8(e, streamIn, stash, note && note(), name));
829 }
830 })));
831 return response;
832 }
833 case "resolve": {
834 let response = {}, name = "", callback2, note;
835 for (let id of request.ids) {
836 try {
837 ({ name, callback: callback2, note } = onResolveCallbacks[id]);
838 let result = yield callback2({
839 path: request.path,
840 importer: request.importer,
841 namespace: request.namespace,
842 resolveDir: request.resolveDir,
843 kind: request.kind,
844 pluginData: stash.load(request.pluginData)
845 });
846 if (result != null) {
847 if (typeof result !== "object")
848 throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(name)} to return an object`);
849 let keys = {};
850 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
851 let path = getFlag(result, keys, "path", mustBeString);
852 let namespace = getFlag(result, keys, "namespace", mustBeString);
853 let external = getFlag(result, keys, "external", mustBeBoolean);
854 let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
855 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
856 let errors = getFlag(result, keys, "errors", mustBeArray);
857 let warnings = getFlag(result, keys, "warnings", mustBeArray);
858 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
859 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
860 checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${JSON.stringify(name)}`);
861 response.id = id;
862 if (pluginName != null)
863 response.pluginName = pluginName;
864 if (path != null)
865 response.path = path;
866 if (namespace != null)
867 response.namespace = namespace;
868 if (external != null)
869 response.external = external;
870 if (sideEffects != null)
871 response.sideEffects = sideEffects;
872 if (pluginData != null)
873 response.pluginData = stash.store(pluginData);
874 if (errors != null)
875 response.errors = sanitizeMessages(errors, "errors", stash, name);
876 if (warnings != null)
877 response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
878 if (watchFiles != null)
879 response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
880 if (watchDirs != null)
881 response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
882 break;
883 }
884 } catch (e) {
885 return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
886 }
887 }
888 return response;
889 }
890 case "load": {
891 let response = {}, name = "", callback2, note;
892 for (let id of request.ids) {
893 try {
894 ({ name, callback: callback2, note } = onLoadCallbacks[id]);
895 let result = yield callback2({
896 path: request.path,
897 namespace: request.namespace,
898 pluginData: stash.load(request.pluginData)
899 });
900 if (result != null) {
901 if (typeof result !== "object")
902 throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(name)} to return an object`);
903 let keys = {};
904 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
905 let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
906 let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
907 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
908 let loader = getFlag(result, keys, "loader", mustBeString);
909 let errors = getFlag(result, keys, "errors", mustBeArray);
910 let warnings = getFlag(result, keys, "warnings", mustBeArray);
911 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
912 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
913 checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${JSON.stringify(name)}`);
914 response.id = id;
915 if (pluginName != null)
916 response.pluginName = pluginName;
917 if (contents instanceof Uint8Array)
918 response.contents = contents;
919 else if (contents != null)
920 response.contents = encodeUTF8(contents);
921 if (resolveDir != null)
922 response.resolveDir = resolveDir;
923 if (pluginData != null)
924 response.pluginData = stash.store(pluginData);
925 if (loader != null)
926 response.loader = loader;
927 if (errors != null)
928 response.errors = sanitizeMessages(errors, "errors", stash, name);
929 if (warnings != null)
930 response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
931 if (watchFiles != null)
932 response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
933 if (watchDirs != null)
934 response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
935 break;
936 }
937 } catch (e) {
938 return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
939 }
940 }
941 return response;
942 }
943 default:
944 throw new Error(`Invalid command: ` + request.command);
945 }
946 });
947 let runOnEndCallbacks = (result, logPluginError, done) => done();
948 if (onEndCallbacks.length > 0) {
949 runOnEndCallbacks = (result, logPluginError, done) => {
950 (() => __async(this, null, function* () {
951 for (const { name, callback: callback2, note } of onEndCallbacks) {
952 try {
953 yield callback2(result);
954 } catch (e) {
955 result.errors.push(yield new Promise((resolve) => logPluginError(e, name, note && note(), resolve)));
956 }
957 }
958 }))().then(done);
959 };
960 }
961 let refCount = 0;
962 return {
963 ok: true,
964 requestPlugins,
965 runOnEndCallbacks,
966 pluginRefs: {
967 ref() {
968 if (++refCount === 1)
969 pluginCallbacks.set(buildKey, callback);
970 },
971 unref() {
972 if (--refCount === 0)
973 pluginCallbacks.delete(buildKey);
974 }
975 }
976 };
977 });
978 let buildServeData = (refs, options, request) => {
979 let keys = {};
980 let port = getFlag(options, keys, "port", mustBeInteger);
981 let host = getFlag(options, keys, "host", mustBeString);
982 let servedir = getFlag(options, keys, "servedir", mustBeString);
983 let onRequest = getFlag(options, keys, "onRequest", mustBeFunction);
984 let serveID = nextServeID++;
985 let onWait;
986 let wait = new Promise((resolve, reject) => {
987 onWait = (error) => {
988 serveCallbacks.delete(serveID);
989 if (error !== null)
990 reject(new Error(error));
991 else
992 resolve();
993 };
994 });
995 request.serve = { serveID };
996 checkForInvalidFlags(options, keys, `in serve() call`);
997 if (port !== void 0)
998 request.serve.port = port;
999 if (host !== void 0)
1000 request.serve.host = host;
1001 if (servedir !== void 0)
1002 request.serve.servedir = servedir;
1003 serveCallbacks.set(serveID, {
1004 onRequest,
1005 onWait
1006 });
1007 return {
1008 wait,
1009 stop() {
1010 sendRequest(refs, { command: "serve-stop", serveID }, () => {
1011 });
1012 }
1013 };
1014 };
1015 const buildLogLevelDefault = "warning";
1016 const transformLogLevelDefault = "silent";
1017 let buildOrServe = (args) => {
1018 let key = nextBuildKey++;
1019 const details = createObjectStash();
1020 let plugins;
1021 let { refs, options, isTTY, callback } = args;
1022 if (typeof options === "object") {
1023 let value = options.plugins;
1024 if (value !== void 0) {
1025 if (!Array.isArray(value))
1026 throw new Error(`"plugins" must be an array`);
1027 plugins = value;
1028 }
1029 }
1030 let logPluginError = (e, pluginName, note, done) => {
1031 let flags = [];
1032 try {
1033 pushLogFlags(flags, options, {}, isTTY, buildLogLevelDefault);
1034 } catch (e2) {
1035 }
1036 const message = extractErrorMessageV8(e, streamIn, details, note, pluginName);
1037 sendRequest(refs, { command: "error", flags, error: message }, () => {
1038 message.detail = details.load(message.detail);
1039 done(message);
1040 });
1041 };
1042 let handleError = (e, pluginName) => {
1043 logPluginError(e, pluginName, void 0, (error) => {
1044 callback(failureErrorWithLog("Build failed", [error], []), null);
1045 });
1046 };
1047 if (plugins && plugins.length > 0) {
1048 if (streamIn.isSync)
1049 return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1050 handlePlugins(options, plugins, key, details).then((result) => {
1051 if (!result.ok) {
1052 handleError(result.error, result.pluginName);
1053 } else {
1054 try {
1055 buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1056 key,
1057 details,
1058 logPluginError,
1059 requestPlugins: result.requestPlugins,
1060 runOnEndCallbacks: result.runOnEndCallbacks,
1061 pluginRefs: result.pluginRefs
1062 }));
1063 } catch (e) {
1064 handleError(e, "");
1065 }
1066 }
1067 }, (e) => handleError(e, ""));
1068 } else {
1069 try {
1070 buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1071 key,
1072 details,
1073 logPluginError,
1074 requestPlugins: null,
1075 runOnEndCallbacks: (result, logPluginError2, done) => done(),
1076 pluginRefs: null
1077 }));
1078 } catch (e) {
1079 handleError(e, "");
1080 }
1081 }
1082 };
1083 let buildOrServeContinue = ({
1084 callName,
1085 refs: callerRefs,
1086 serveOptions,
1087 options,
1088 isTTY,
1089 defaultWD,
1090 callback,
1091 key,
1092 details,
1093 logPluginError,
1094 requestPlugins,
1095 runOnEndCallbacks,
1096 pluginRefs
1097 }) => {
1098 const refs = {
1099 ref() {
1100 if (pluginRefs)
1101 pluginRefs.ref();
1102 if (callerRefs)
1103 callerRefs.ref();
1104 },
1105 unref() {
1106 if (pluginRefs)
1107 pluginRefs.unref();
1108 if (callerRefs)
1109 callerRefs.unref();
1110 }
1111 };
1112 let writeDefault = !streamIn.isBrowser;
1113 let {
1114 entries,
1115 flags,
1116 write,
1117 stdinContents,
1118 stdinResolveDir,
1119 absWorkingDir,
1120 incremental,
1121 nodePaths,
1122 watch
1123 } = flagsForBuildOptions(callName, options, isTTY, buildLogLevelDefault, writeDefault);
1124 let request = {
1125 command: "build",
1126 key,
1127 entries,
1128 flags,
1129 write,
1130 stdinContents,
1131 stdinResolveDir,
1132 absWorkingDir: absWorkingDir || defaultWD,
1133 incremental,
1134 nodePaths
1135 };
1136 if (requestPlugins)
1137 request.plugins = requestPlugins;
1138 let serve2 = serveOptions && buildServeData(refs, serveOptions, request);
1139 let rebuild;
1140 let stop;
1141 let copyResponseToResult = (response, result) => {
1142 if (response.outputFiles)
1143 result.outputFiles = response.outputFiles.map(convertOutputFiles);
1144 if (response.metafile)
1145 result.metafile = JSON.parse(response.metafile);
1146 if (response.writeToStdout !== void 0)
1147 console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1148 };
1149 let buildResponseToResult = (response, callback2) => {
1150 let result = {
1151 errors: replaceDetailsInMessages(response.errors, details),
1152 warnings: replaceDetailsInMessages(response.warnings, details)
1153 };
1154 copyResponseToResult(response, result);
1155 runOnEndCallbacks(result, logPluginError, () => {
1156 if (result.errors.length > 0) {
1157 return callback2(failureErrorWithLog("Build failed", result.errors, result.warnings), null);
1158 }
1159 if (response.rebuildID !== void 0) {
1160 if (!rebuild) {
1161 let isDisposed = false;
1162 rebuild = () => new Promise((resolve, reject) => {
1163 if (isDisposed || isClosed)
1164 throw new Error("Cannot rebuild");
1165 sendRequest(refs, { command: "rebuild", rebuildID: response.rebuildID }, (error2, response2) => {
1166 if (error2) {
1167 const message = { pluginName: "", text: error2, location: null, notes: [], detail: void 0 };
1168 return callback2(failureErrorWithLog("Build failed", [message], []), null);
1169 }
1170 buildResponseToResult(response2, (error3, result3) => {
1171 if (error3)
1172 reject(error3);
1173 else
1174 resolve(result3);
1175 });
1176 });
1177 });
1178 refs.ref();
1179 rebuild.dispose = () => {
1180 if (isDisposed)
1181 return;
1182 isDisposed = true;
1183 sendRequest(refs, { command: "rebuild-dispose", rebuildID: response.rebuildID }, () => {
1184 });
1185 refs.unref();
1186 };
1187 }
1188 result.rebuild = rebuild;
1189 }
1190 if (response.watchID !== void 0) {
1191 if (!stop) {
1192 let isStopped = false;
1193 refs.ref();
1194 stop = () => {
1195 if (isStopped)
1196 return;
1197 isStopped = true;
1198 watchCallbacks.delete(response.watchID);
1199 sendRequest(refs, { command: "watch-stop", watchID: response.watchID }, () => {
1200 });
1201 refs.unref();
1202 };
1203 if (watch) {
1204 watchCallbacks.set(response.watchID, (serviceStopError, watchResponse) => {
1205 if (serviceStopError) {
1206 if (watch.onRebuild)
1207 watch.onRebuild(serviceStopError, null);
1208 return;
1209 }
1210 let result2 = {
1211 errors: replaceDetailsInMessages(watchResponse.errors, details),
1212 warnings: replaceDetailsInMessages(watchResponse.warnings, details)
1213 };
1214 copyResponseToResult(watchResponse, result2);
1215 runOnEndCallbacks(result2, logPluginError, () => {
1216 if (result2.errors.length > 0) {
1217 if (watch.onRebuild)
1218 watch.onRebuild(failureErrorWithLog("Build failed", result2.errors, result2.warnings), null);
1219 return;
1220 }
1221 if (watchResponse.rebuildID !== void 0)
1222 result2.rebuild = rebuild;
1223 result2.stop = stop;
1224 if (watch.onRebuild)
1225 watch.onRebuild(null, result2);
1226 });
1227 });
1228 }
1229 }
1230 result.stop = stop;
1231 }
1232 callback2(null, result);
1233 });
1234 };
1235 if (write && streamIn.isBrowser)
1236 throw new Error(`Cannot enable "write" in the browser`);
1237 if (incremental && streamIn.isSync)
1238 throw new Error(`Cannot use "incremental" with a synchronous build`);
1239 if (watch && streamIn.isSync)
1240 throw new Error(`Cannot use "watch" with a synchronous build`);
1241 sendRequest(refs, request, (error, response) => {
1242 if (error)
1243 return callback(new Error(error), null);
1244 if (serve2) {
1245 let serveResponse = response;
1246 let isStopped = false;
1247 refs.ref();
1248 let result = {
1249 port: serveResponse.port,
1250 host: serveResponse.host,
1251 wait: serve2.wait,
1252 stop() {
1253 if (isStopped)
1254 return;
1255 isStopped = true;
1256 serve2.stop();
1257 refs.unref();
1258 }
1259 };
1260 refs.ref();
1261 serve2.wait.then(refs.unref, refs.unref);
1262 return callback(null, result);
1263 }
1264 return buildResponseToResult(response, callback);
1265 });
1266 };
1267 let transform2 = ({ callName, refs, input, options, isTTY, fs, callback }) => {
1268 const details = createObjectStash();
1269 let start = (inputPath) => {
1270 try {
1271 if (typeof input !== "string")
1272 throw new Error('The input to "transform" must be a string');
1273 let flags = flagsForTransformOptions(callName, options, isTTY, transformLogLevelDefault);
1274 let request = {
1275 command: "transform",
1276 flags,
1277 inputFS: inputPath !== null,
1278 input: inputPath !== null ? inputPath : input
1279 };
1280 sendRequest(refs, request, (error, response) => {
1281 if (error)
1282 return callback(new Error(error), null);
1283 let errors = replaceDetailsInMessages(response.errors, details);
1284 let warnings = replaceDetailsInMessages(response.warnings, details);
1285 let outstanding = 1;
1286 let next = () => --outstanding === 0 && callback(null, { warnings, code: response.code, map: response.map });
1287 if (errors.length > 0)
1288 return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1289 if (response.codeFS) {
1290 outstanding++;
1291 fs.readFile(response.code, (err, contents) => {
1292 if (err !== null) {
1293 callback(err, null);
1294 } else {
1295 response.code = contents;
1296 next();
1297 }
1298 });
1299 }
1300 if (response.mapFS) {
1301 outstanding++;
1302 fs.readFile(response.map, (err, contents) => {
1303 if (err !== null) {
1304 callback(err, null);
1305 } else {
1306 response.map = contents;
1307 next();
1308 }
1309 });
1310 }
1311 next();
1312 });
1313 } catch (e) {
1314 let flags = [];
1315 try {
1316 pushLogFlags(flags, options, {}, isTTY, transformLogLevelDefault);
1317 } catch (e2) {
1318 }
1319 const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1320 sendRequest(refs, { command: "error", flags, error }, () => {
1321 error.detail = details.load(error.detail);
1322 callback(failureErrorWithLog("Transform failed", [error], []), null);
1323 });
1324 }
1325 };
1326 if (typeof input === "string" && input.length > 1024 * 1024) {
1327 let next = start;
1328 start = () => fs.writeFile(input, next);
1329 }
1330 start(null);
1331 };
1332 let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1333 let result = sanitizeMessages(messages, "messages", null, "");
1334 if (!options)
1335 throw new Error(`Missing second argument in ${callName}() call`);
1336 let keys = {};
1337 let kind = getFlag(options, keys, "kind", mustBeString);
1338 let color = getFlag(options, keys, "color", mustBeBoolean);
1339 let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1340 checkForInvalidFlags(options, keys, `in ${callName}() call`);
1341 if (kind === void 0)
1342 throw new Error(`Missing "kind" in ${callName}() call`);
1343 if (kind !== "error" && kind !== "warning")
1344 throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1345 let request = {
1346 command: "format-msgs",
1347 messages: result,
1348 isWarning: kind === "warning"
1349 };
1350 if (color !== void 0)
1351 request.color = color;
1352 if (terminalWidth !== void 0)
1353 request.terminalWidth = terminalWidth;
1354 sendRequest(refs, request, (error, response) => {
1355 if (error)
1356 return callback(new Error(error), null);
1357 callback(null, response.messages);
1358 });
1359 };
1360 let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1361 if (options === void 0)
1362 options = {};
1363 let keys = {};
1364 let color = getFlag(options, keys, "color", mustBeBoolean);
1365 let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1366 checkForInvalidFlags(options, keys, `in ${callName}() call`);
1367 let request = {
1368 command: "analyze-metafile",
1369 metafile
1370 };
1371 if (color !== void 0)
1372 request.color = color;
1373 if (verbose !== void 0)
1374 request.verbose = verbose;
1375 sendRequest(refs, request, (error, response) => {
1376 if (error)
1377 return callback(new Error(error), null);
1378 callback(null, response.result);
1379 });
1380 };
1381 return {
1382 readFromStdout,
1383 afterClose,
1384 service: {
1385 buildOrServe,
1386 transform: transform2,
1387 formatMessages: formatMessages2,
1388 analyzeMetafile: analyzeMetafile2
1389 }
1390 };
1391}
1392function createObjectStash() {
1393 const map = new Map();
1394 let nextID = 0;
1395 return {
1396 load(id) {
1397 return map.get(id);
1398 },
1399 store(value) {
1400 if (value === void 0)
1401 return -1;
1402 const id = nextID++;
1403 map.set(id, value);
1404 return id;
1405 }
1406 };
1407}
1408function extractCallerV8(e, streamIn, ident) {
1409 let note;
1410 let tried = false;
1411 return () => {
1412 if (tried)
1413 return note;
1414 tried = true;
1415 try {
1416 let lines = (e.stack + "").split("\n");
1417 lines.splice(1, 1);
1418 let location = parseStackLinesV8(streamIn, lines, ident);
1419 if (location) {
1420 note = { text: e.message, location };
1421 return note;
1422 }
1423 } catch (e2) {
1424 }
1425 };
1426}
1427function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1428 let text = "Internal error";
1429 let location = null;
1430 try {
1431 text = (e && e.message || e) + "";
1432 } catch (e2) {
1433 }
1434 try {
1435 location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1436 } catch (e2) {
1437 }
1438 return { pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1439}
1440function parseStackLinesV8(streamIn, lines, ident) {
1441 let at = " at ";
1442 if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1443 for (let i = 1; i < lines.length; i++) {
1444 let line = lines[i];
1445 if (!line.startsWith(at))
1446 continue;
1447 line = line.slice(at.length);
1448 while (true) {
1449 let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1450 if (match) {
1451 line = match[1];
1452 continue;
1453 }
1454 match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1455 if (match) {
1456 line = match[1];
1457 continue;
1458 }
1459 match = /^(\S+):(\d+):(\d+)$/.exec(line);
1460 if (match) {
1461 let contents;
1462 try {
1463 contents = streamIn.readFileSync(match[1], "utf8");
1464 } catch (e) {
1465 break;
1466 }
1467 let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1468 let column = +match[3] - 1;
1469 let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1470 return {
1471 file: match[1],
1472 namespace: "file",
1473 line: +match[2],
1474 column: encodeUTF8(lineText.slice(0, column)).length,
1475 length: encodeUTF8(lineText.slice(column, column + length)).length,
1476 lineText: lineText + "\n" + lines.slice(1).join("\n"),
1477 suggestion: ""
1478 };
1479 }
1480 break;
1481 }
1482 }
1483 }
1484 return null;
1485}
1486function failureErrorWithLog(text, errors, warnings) {
1487 let limit = 5;
1488 let summary = errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1489 if (i === limit)
1490 return "\n...";
1491 if (!e.location)
1492 return `
1493error: ${e.text}`;
1494 let { file, line, column } = e.location;
1495 let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1496 return `
1497${file}:${line}:${column}: error: ${pluginText}${e.text}`;
1498 }).join("");
1499 let error = new Error(`${text}${summary}`);
1500 error.errors = errors;
1501 error.warnings = warnings;
1502 return error;
1503}
1504function replaceDetailsInMessages(messages, stash) {
1505 for (const message of messages) {
1506 message.detail = stash.load(message.detail);
1507 }
1508 return messages;
1509}
1510function sanitizeLocation(location, where) {
1511 if (location == null)
1512 return null;
1513 let keys = {};
1514 let file = getFlag(location, keys, "file", mustBeString);
1515 let namespace = getFlag(location, keys, "namespace", mustBeString);
1516 let line = getFlag(location, keys, "line", mustBeInteger);
1517 let column = getFlag(location, keys, "column", mustBeInteger);
1518 let length = getFlag(location, keys, "length", mustBeInteger);
1519 let lineText = getFlag(location, keys, "lineText", mustBeString);
1520 let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1521 checkForInvalidFlags(location, keys, where);
1522 return {
1523 file: file || "",
1524 namespace: namespace || "",
1525 line: line || 0,
1526 column: column || 0,
1527 length: length || 0,
1528 lineText: lineText || "",
1529 suggestion: suggestion || ""
1530 };
1531}
1532function sanitizeMessages(messages, property, stash, fallbackPluginName) {
1533 let messagesClone = [];
1534 let index = 0;
1535 for (const message of messages) {
1536 let keys = {};
1537 let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1538 let text = getFlag(message, keys, "text", mustBeString);
1539 let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1540 let notes = getFlag(message, keys, "notes", mustBeArray);
1541 let detail = getFlag(message, keys, "detail", canBeAnything);
1542 let where = `in element ${index} of "${property}"`;
1543 checkForInvalidFlags(message, keys, where);
1544 let notesClone = [];
1545 if (notes) {
1546 for (const note of notes) {
1547 let noteKeys = {};
1548 let noteText = getFlag(note, noteKeys, "text", mustBeString);
1549 let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1550 checkForInvalidFlags(note, noteKeys, where);
1551 notesClone.push({
1552 text: noteText || "",
1553 location: sanitizeLocation(noteLocation, where)
1554 });
1555 }
1556 }
1557 messagesClone.push({
1558 pluginName: pluginName || fallbackPluginName,
1559 text: text || "",
1560 location: sanitizeLocation(location, where),
1561 notes: notesClone,
1562 detail: stash ? stash.store(detail) : -1
1563 });
1564 index++;
1565 }
1566 return messagesClone;
1567}
1568function sanitizeStringArray(values, property) {
1569 const result = [];
1570 for (const value of values) {
1571 if (typeof value !== "string")
1572 throw new Error(`${JSON.stringify(property)} must be an array of strings`);
1573 result.push(value);
1574 }
1575 return result;
1576}
1577function convertOutputFiles({ path, contents }) {
1578 let text = null;
1579 return {
1580 path,
1581 contents,
1582 get text() {
1583 if (text === null)
1584 text = decodeUTF8(contents);
1585 return text;
1586 }
1587 };
1588}
1589
1590// lib/npm/browser.ts
1591var version = "0.13.4";
1592var build = (options) => ensureServiceIsRunning().build(options);
1593var serve = () => {
1594 throw new Error(`The "serve" API only works in node`);
1595};
1596var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1597var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1598var analyzeMetafile = (metafile, options) => ensureServiceIsRunning().analyzeMetafile(metafile, options);
1599var buildSync = () => {
1600 throw new Error(`The "buildSync" API only works in node`);
1601};
1602var transformSync = () => {
1603 throw new Error(`The "transformSync" API only works in node`);
1604};
1605var formatMessagesSync = () => {
1606 throw new Error(`The "formatMessagesSync" API only works in node`);
1607};
1608var analyzeMetafileSync = () => {
1609 throw new Error(`The "analyzeMetafileSync" API only works in node`);
1610};
1611var initializePromise;
1612var longLivedService;
1613var ensureServiceIsRunning = () => {
1614 if (longLivedService)
1615 return longLivedService;
1616 if (initializePromise)
1617 throw new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this');
1618 throw new Error('You need to call "initialize" before calling this');
1619};
1620var initialize = (options) => {
1621 options = validateInitializeOptions(options || {});
1622 let wasmURL = options.wasmURL;
1623 let useWorker = options.worker !== false;
1624 if (!wasmURL)
1625 throw new Error('Must provide the "wasmURL" option');
1626 wasmURL += "";
1627 if (initializePromise)
1628 throw new Error('Cannot call "initialize" more than once');
1629 initializePromise = startRunningService(wasmURL, useWorker);
1630 initializePromise.catch(() => {
1631 initializePromise = void 0;
1632 });
1633 return initializePromise;
1634};
1635var startRunningService = (wasmURL, useWorker) => __async(void 0, null, function* () {
1636 let res = yield fetch(wasmURL);
1637 if (!res.ok)
1638 throw new Error(`Failed to download ${JSON.stringify(wasmURL)}`);
1639 let wasm = yield res.arrayBuffer();
1640 let code = `{let global={};for(let o=self;o;o=Object.getPrototypeOf(o))for(let k of Object.getOwnPropertyNames(o))if(!(k in global))Object.defineProperty(global,k,{get:()=>self[k]});// Copyright 2018 The Go Authors. All rights reserved.
1641// Use of this source code is governed by a BSD-style
1642// license that can be found in the LICENSE file.
1643
1644(() => {
1645 // Map multiple JavaScript environments to a single common API,
1646 // preferring web standards over Node.js API.
1647 //
1648 // Environments considered:
1649 // - Browsers
1650 // - Node.js
1651 // - Electron
1652 // - Parcel
1653 // - Webpack
1654
1655 if (typeof global !== "undefined") {
1656 // global already exists
1657 } else if (typeof window !== "undefined") {
1658 window.global = window;
1659 } else if (typeof self !== "undefined") {
1660 self.global = self;
1661 } else {
1662 throw new Error("cannot export Go (neither global, window nor self is defined)");
1663 }
1664
1665 if (!global.require && typeof require !== "undefined") {
1666 global.require = require;
1667 }
1668
1669 if (!global.fs && global.require) {
1670 const fs = require("fs");
1671 if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
1672
1673 global.fs = Object.assign({}, fs, {
1674 // Hack around a Unicode bug in node: https://github.com/nodejs/node/issues/24550
1675 write(fd, buf, offset, length, position, callback) {
1676 if (offset === 0 && length === buf.length && position === null) {
1677 if (fd === process.stdout.fd) {
1678 try {
1679 process.stdout.write(buf, err => err ? callback(err, 0, null) : callback(null, length, buf));
1680 } catch (err) {
1681 callback(err, 0, null);
1682 }
1683 return;
1684 }
1685 if (fd === process.stderr.fd) {
1686 try {
1687 process.stderr.write(buf, err => err ? callback(err, 0, null) : callback(null, length, buf));
1688 } catch (err) {
1689 callback(err, 0, null);
1690 }
1691 return;
1692 }
1693 }
1694 fs.write(fd, buf, offset, length, position, callback);
1695 },
1696 });
1697
1698 }
1699 }
1700
1701 const enosys = () => {
1702 const err = new Error("not implemented");
1703 err.code = "ENOSYS";
1704 return err;
1705 };
1706
1707 if (!global.fs) {
1708 let outputBuf = "";
1709 global.fs = {
1710 constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
1711 writeSync(fd, buf) {
1712 outputBuf += decoder.decode(buf);
1713 const nl = outputBuf.lastIndexOf("\\n");
1714 if (nl != -1) {
1715 console.log(outputBuf.substr(0, nl));
1716 outputBuf = outputBuf.substr(nl + 1);
1717 }
1718 return buf.length;
1719 },
1720 write(fd, buf, offset, length, position, callback) {
1721 if (offset !== 0 || length !== buf.length || position !== null) {
1722 callback(enosys());
1723 return;
1724 }
1725 const n = this.writeSync(fd, buf);
1726 callback(null, n);
1727 },
1728 chmod(path, mode, callback) { callback(enosys()); },
1729 chown(path, uid, gid, callback) { callback(enosys()); },
1730 close(fd, callback) { callback(enosys()); },
1731 fchmod(fd, mode, callback) { callback(enosys()); },
1732 fchown(fd, uid, gid, callback) { callback(enosys()); },
1733 fstat(fd, callback) { callback(enosys()); },
1734 fsync(fd, callback) { callback(null); },
1735 ftruncate(fd, length, callback) { callback(enosys()); },
1736 lchown(path, uid, gid, callback) { callback(enosys()); },
1737 link(path, link, callback) { callback(enosys()); },
1738 lstat(path, callback) { callback(enosys()); },
1739 mkdir(path, perm, callback) { callback(enosys()); },
1740 open(path, flags, mode, callback) { callback(enosys()); },
1741 read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
1742 readdir(path, callback) { callback(enosys()); },
1743 readlink(path, callback) { callback(enosys()); },
1744 rename(from, to, callback) { callback(enosys()); },
1745 rmdir(path, callback) { callback(enosys()); },
1746 stat(path, callback) { callback(enosys()); },
1747 symlink(path, link, callback) { callback(enosys()); },
1748 truncate(path, length, callback) { callback(enosys()); },
1749 unlink(path, callback) { callback(enosys()); },
1750 utimes(path, atime, mtime, callback) { callback(enosys()); },
1751 };
1752 }
1753
1754 if (!global.process) {
1755 global.process = {
1756 getuid() { return -1; },
1757 getgid() { return -1; },
1758 geteuid() { return -1; },
1759 getegid() { return -1; },
1760 getgroups() { throw enosys(); },
1761 pid: -1,
1762 ppid: -1,
1763 umask() { throw enosys(); },
1764 cwd() { throw enosys(); },
1765 chdir() { throw enosys(); },
1766 }
1767 }
1768
1769 if (!global.crypto && global.require) {
1770 const nodeCrypto = require("crypto");
1771 global.crypto = {
1772 getRandomValues(b) {
1773 nodeCrypto.randomFillSync(b);
1774 },
1775 };
1776 }
1777 if (!global.crypto) {
1778 throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");
1779 }
1780
1781 if (!global.performance) {
1782 global.performance = {
1783 now() {
1784 const [sec, nsec] = process.hrtime();
1785 return sec * 1000 + nsec / 1000000;
1786 },
1787 };
1788 }
1789
1790 if (!global.TextEncoder && global.require) {
1791 global.TextEncoder = require("util").TextEncoder;
1792 }
1793 if (!global.TextEncoder) {
1794 throw new Error("global.TextEncoder is not available, polyfill required");
1795 }
1796
1797 if (!global.TextDecoder && global.require) {
1798 global.TextDecoder = require("util").TextDecoder;
1799 }
1800 if (!global.TextDecoder) {
1801 throw new Error("global.TextDecoder is not available, polyfill required");
1802 }
1803
1804 // End of polyfills for common API.
1805
1806 const encoder = new TextEncoder("utf-8");
1807 const decoder = new TextDecoder("utf-8");
1808
1809 global.Go = class {
1810 constructor() {
1811 this.argv = ["js"];
1812 this.env = {};
1813 this.exit = (code) => {
1814 if (code !== 0) {
1815 console.warn("exit code:", code);
1816 }
1817 };
1818 this._exitPromise = new Promise((resolve) => {
1819 this._resolveExitPromise = resolve;
1820 });
1821 this._pendingEvent = null;
1822 this._scheduledTimeouts = new Map();
1823 this._nextCallbackTimeoutID = 1;
1824
1825 const setInt64 = (addr, v) => {
1826 this.mem.setUint32(addr + 0, v, true);
1827 this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
1828 }
1829
1830 const getInt64 = (addr) => {
1831 const low = this.mem.getUint32(addr + 0, true);
1832 const high = this.mem.getInt32(addr + 4, true);
1833 return low + high * 4294967296;
1834 }
1835
1836 const loadValue = (addr) => {
1837 const f = this.mem.getFloat64(addr, true);
1838 if (f === 0) {
1839 return undefined;
1840 }
1841 if (!isNaN(f)) {
1842 return f;
1843 }
1844
1845 const id = this.mem.getUint32(addr, true);
1846 return this._values[id];
1847 }
1848
1849 const storeValue = (addr, v) => {
1850 const nanHead = 0x7FF80000;
1851
1852 if (typeof v === "number" && v !== 0) {
1853 if (isNaN(v)) {
1854 this.mem.setUint32(addr + 4, nanHead, true);
1855 this.mem.setUint32(addr, 0, true);
1856 return;
1857 }
1858 this.mem.setFloat64(addr, v, true);
1859 return;
1860 }
1861
1862 if (v === undefined) {
1863 this.mem.setFloat64(addr, 0, true);
1864 return;
1865 }
1866
1867 let id = this._ids.get(v);
1868 if (id === undefined) {
1869 id = this._idPool.pop();
1870 if (id === undefined) {
1871 id = this._values.length;
1872 }
1873 this._values[id] = v;
1874 this._goRefCounts[id] = 0;
1875 this._ids.set(v, id);
1876 }
1877 this._goRefCounts[id]++;
1878 let typeFlag = 0;
1879 switch (typeof v) {
1880 case "object":
1881 if (v !== null) {
1882 typeFlag = 1;
1883 }
1884 break;
1885 case "string":
1886 typeFlag = 2;
1887 break;
1888 case "symbol":
1889 typeFlag = 3;
1890 break;
1891 case "function":
1892 typeFlag = 4;
1893 break;
1894 }
1895 this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
1896 this.mem.setUint32(addr, id, true);
1897 }
1898
1899 const loadSlice = (addr) => {
1900 const array = getInt64(addr + 0);
1901 const len = getInt64(addr + 8);
1902 return new Uint8Array(this._inst.exports.mem.buffer, array, len);
1903 }
1904
1905 const loadSliceOfValues = (addr) => {
1906 const array = getInt64(addr + 0);
1907 const len = getInt64(addr + 8);
1908 const a = new Array(len);
1909 for (let i = 0; i < len; i++) {
1910 a[i] = loadValue(array + i * 8);
1911 }
1912 return a;
1913 }
1914
1915 const loadString = (addr) => {
1916 const saddr = getInt64(addr + 0);
1917 const len = getInt64(addr + 8);
1918 return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
1919 }
1920
1921 const timeOrigin = Date.now() - performance.now();
1922 this.importObject = {
1923 go: {
1924 // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
1925 // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
1926 // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
1927 // This changes the SP, thus we have to update the SP used by the imported function.
1928
1929 // func wasmExit(code int32)
1930 "runtime.wasmExit": (sp) => {
1931 sp >>>= 0;
1932 const code = this.mem.getInt32(sp + 8, true);
1933 this.exited = true;
1934 delete this._inst;
1935 delete this._values;
1936 delete this._goRefCounts;
1937 delete this._ids;
1938 delete this._idPool;
1939 this.exit(code);
1940 },
1941
1942 // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
1943 "runtime.wasmWrite": (sp) => {
1944 sp >>>= 0;
1945 const fd = getInt64(sp + 8);
1946 const p = getInt64(sp + 16);
1947 const n = this.mem.getInt32(sp + 24, true);
1948 fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
1949 },
1950
1951 // func resetMemoryDataView()
1952 "runtime.resetMemoryDataView": (sp) => {
1953 sp >>>= 0;
1954 this.mem = new DataView(this._inst.exports.mem.buffer);
1955 },
1956
1957 // func nanotime1() int64
1958 "runtime.nanotime1": (sp) => {
1959 sp >>>= 0;
1960 setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
1961 },
1962
1963 // func walltime() (sec int64, nsec int32)
1964 "runtime.walltime": (sp) => {
1965 sp >>>= 0;
1966 const msec = (new Date).getTime();
1967 setInt64(sp + 8, msec / 1000);
1968 this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
1969 },
1970
1971 // func scheduleTimeoutEvent(delay int64) int32
1972 "runtime.scheduleTimeoutEvent": (sp) => {
1973 sp >>>= 0;
1974 const id = this._nextCallbackTimeoutID;
1975 this._nextCallbackTimeoutID++;
1976 this._scheduledTimeouts.set(id, setTimeout(
1977 () => {
1978 this._resume();
1979 while (this._scheduledTimeouts.has(id)) {
1980 // for some reason Go failed to register the timeout event, log and try again
1981 // (temporary workaround for https://github.com/golang/go/issues/28975)
1982 console.warn("scheduleTimeoutEvent: missed timeout event");
1983 this._resume();
1984 }
1985 },
1986 getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
1987 ));
1988 this.mem.setInt32(sp + 16, id, true);
1989 },
1990
1991 // func clearTimeoutEvent(id int32)
1992 "runtime.clearTimeoutEvent": (sp) => {
1993 sp >>>= 0;
1994 const id = this.mem.getInt32(sp + 8, true);
1995 clearTimeout(this._scheduledTimeouts.get(id));
1996 this._scheduledTimeouts.delete(id);
1997 },
1998
1999 // func getRandomData(r []byte)
2000 "runtime.getRandomData": (sp) => {
2001 sp >>>= 0;
2002 crypto.getRandomValues(loadSlice(sp + 8));
2003 },
2004
2005 // func finalizeRef(v ref)
2006 "syscall/js.finalizeRef": (sp) => {
2007 sp >>>= 0;
2008 const id = this.mem.getUint32(sp + 8, true);
2009 this._goRefCounts[id]--;
2010 if (this._goRefCounts[id] === 0) {
2011 const v = this._values[id];
2012 this._values[id] = null;
2013 this._ids.delete(v);
2014 this._idPool.push(id);
2015 }
2016 },
2017
2018 // func stringVal(value string) ref
2019 "syscall/js.stringVal": (sp) => {
2020 sp >>>= 0;
2021 storeValue(sp + 24, loadString(sp + 8));
2022 },
2023
2024 // func valueGet(v ref, p string) ref
2025 "syscall/js.valueGet": (sp) => {
2026 sp >>>= 0;
2027 const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
2028 sp = this._inst.exports.getsp() >>> 0; // see comment above
2029 storeValue(sp + 32, result);
2030 },
2031
2032 // func valueSet(v ref, p string, x ref)
2033 "syscall/js.valueSet": (sp) => {
2034 sp >>>= 0;
2035 Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
2036 },
2037
2038 // func valueDelete(v ref, p string)
2039 "syscall/js.valueDelete": (sp) => {
2040 sp >>>= 0;
2041 Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
2042 },
2043
2044 // func valueIndex(v ref, i int) ref
2045 "syscall/js.valueIndex": (sp) => {
2046 sp >>>= 0;
2047 storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
2048 },
2049
2050 // valueSetIndex(v ref, i int, x ref)
2051 "syscall/js.valueSetIndex": (sp) => {
2052 sp >>>= 0;
2053 Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
2054 },
2055
2056 // func valueCall(v ref, m string, args []ref) (ref, bool)
2057 "syscall/js.valueCall": (sp) => {
2058 sp >>>= 0;
2059 try {
2060 const v = loadValue(sp + 8);
2061 const m = Reflect.get(v, loadString(sp + 16));
2062 const args = loadSliceOfValues(sp + 32);
2063 const result = Reflect.apply(m, v, args);
2064 sp = this._inst.exports.getsp() >>> 0; // see comment above
2065 storeValue(sp + 56, result);
2066 this.mem.setUint8(sp + 64, 1);
2067 } catch (err) {
2068 sp = this._inst.exports.getsp() >>> 0; // see comment above
2069 storeValue(sp + 56, err);
2070 this.mem.setUint8(sp + 64, 0);
2071 }
2072 },
2073
2074 // func valueInvoke(v ref, args []ref) (ref, bool)
2075 "syscall/js.valueInvoke": (sp) => {
2076 sp >>>= 0;
2077 try {
2078 const v = loadValue(sp + 8);
2079 const args = loadSliceOfValues(sp + 16);
2080 const result = Reflect.apply(v, undefined, args);
2081 sp = this._inst.exports.getsp() >>> 0; // see comment above
2082 storeValue(sp + 40, result);
2083 this.mem.setUint8(sp + 48, 1);
2084 } catch (err) {
2085 sp = this._inst.exports.getsp() >>> 0; // see comment above
2086 storeValue(sp + 40, err);
2087 this.mem.setUint8(sp + 48, 0);
2088 }
2089 },
2090
2091 // func valueNew(v ref, args []ref) (ref, bool)
2092 "syscall/js.valueNew": (sp) => {
2093 sp >>>= 0;
2094 try {
2095 const v = loadValue(sp + 8);
2096 const args = loadSliceOfValues(sp + 16);
2097 const result = Reflect.construct(v, args);
2098 sp = this._inst.exports.getsp() >>> 0; // see comment above
2099 storeValue(sp + 40, result);
2100 this.mem.setUint8(sp + 48, 1);
2101 } catch (err) {
2102 sp = this._inst.exports.getsp() >>> 0; // see comment above
2103 storeValue(sp + 40, err);
2104 this.mem.setUint8(sp + 48, 0);
2105 }
2106 },
2107
2108 // func valueLength(v ref) int
2109 "syscall/js.valueLength": (sp) => {
2110 sp >>>= 0;
2111 setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
2112 },
2113
2114 // valuePrepareString(v ref) (ref, int)
2115 "syscall/js.valuePrepareString": (sp) => {
2116 sp >>>= 0;
2117 const str = encoder.encode(String(loadValue(sp + 8)));
2118 storeValue(sp + 16, str);
2119 setInt64(sp + 24, str.length);
2120 },
2121
2122 // valueLoadString(v ref, b []byte)
2123 "syscall/js.valueLoadString": (sp) => {
2124 sp >>>= 0;
2125 const str = loadValue(sp + 8);
2126 loadSlice(sp + 16).set(str);
2127 },
2128
2129 // func valueInstanceOf(v ref, t ref) bool
2130 "syscall/js.valueInstanceOf": (sp) => {
2131 sp >>>= 0;
2132 this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
2133 },
2134
2135 // func copyBytesToGo(dst []byte, src ref) (int, bool)
2136 "syscall/js.copyBytesToGo": (sp) => {
2137 sp >>>= 0;
2138 const dst = loadSlice(sp + 8);
2139 const src = loadValue(sp + 32);
2140 if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
2141 this.mem.setUint8(sp + 48, 0);
2142 return;
2143 }
2144 const toCopy = src.subarray(0, dst.length);
2145 dst.set(toCopy);
2146 setInt64(sp + 40, toCopy.length);
2147 this.mem.setUint8(sp + 48, 1);
2148 },
2149
2150 // func copyBytesToJS(dst ref, src []byte) (int, bool)
2151 "syscall/js.copyBytesToJS": (sp) => {
2152 sp >>>= 0;
2153 const dst = loadValue(sp + 8);
2154 const src = loadSlice(sp + 16);
2155 if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
2156 this.mem.setUint8(sp + 48, 0);
2157 return;
2158 }
2159 const toCopy = src.subarray(0, dst.length);
2160 dst.set(toCopy);
2161 setInt64(sp + 40, toCopy.length);
2162 this.mem.setUint8(sp + 48, 1);
2163 },
2164
2165 "debug": (value) => {
2166 console.log(value);
2167 },
2168 }
2169 };
2170 }
2171
2172 async run(instance) {
2173 if (!(instance instanceof WebAssembly.Instance)) {
2174 throw new Error("Go.run: WebAssembly.Instance expected");
2175 }
2176 this._inst = instance;
2177 this.mem = new DataView(this._inst.exports.mem.buffer);
2178 this._values = [ // JS values that Go currently has references to, indexed by reference id
2179 NaN,
2180 0,
2181 null,
2182 true,
2183 false,
2184 global,
2185 this,
2186 ];
2187 this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
2188 this._ids = new Map([ // mapping from JS values to reference ids
2189 [0, 1],
2190 [null, 2],
2191 [true, 3],
2192 [false, 4],
2193 [global, 5],
2194 [this, 6],
2195 ]);
2196 this._idPool = []; // unused ids that have been garbage collected
2197 this.exited = false; // whether the Go program has exited
2198
2199 // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
2200 let offset = 4096;
2201
2202 const strPtr = (str) => {
2203 const ptr = offset;
2204 const bytes = encoder.encode(str + "\\0");
2205 new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
2206 offset += bytes.length;
2207 if (offset % 8 !== 0) {
2208 offset += 8 - (offset % 8);
2209 }
2210 return ptr;
2211 };
2212
2213 const argc = this.argv.length;
2214
2215 const argvPtrs = [];
2216 this.argv.forEach((arg) => {
2217 argvPtrs.push(strPtr(arg));
2218 });
2219 argvPtrs.push(0);
2220
2221 const keys = Object.keys(this.env).sort();
2222 keys.forEach((key) => {
2223 argvPtrs.push(strPtr(\`\${key}=\${this.env[key]}\`));
2224 });
2225 argvPtrs.push(0);
2226
2227 const argv = offset;
2228 argvPtrs.forEach((ptr) => {
2229 this.mem.setUint32(offset, ptr, true);
2230 this.mem.setUint32(offset + 4, 0, true);
2231 offset += 8;
2232 });
2233
2234 this._inst.exports.run(argc, argv);
2235 if (this.exited) {
2236 this._resolveExitPromise();
2237 }
2238 await this._exitPromise;
2239 }
2240
2241 _resume() {
2242 if (this.exited) {
2243 throw new Error("Go program has already exited");
2244 }
2245 this._inst.exports.resume();
2246 if (this.exited) {
2247 this._resolveExitPromise();
2248 }
2249 }
2250
2251 _makeFuncWrapper(id) {
2252 const go = this;
2253 return function () {
2254 const event = { id: id, this: this, args: arguments };
2255 go._pendingEvent = event;
2256 go._resume();
2257 return event.result;
2258 };
2259 }
2260 }
2261
2262 if (
2263 typeof module !== "undefined" &&
2264 global.require &&
2265 global.require.main === module &&
2266 global.process &&
2267 global.process.versions &&
2268 !global.process.versions.electron
2269 ) {
2270 if (process.argv.length < 3) {
2271 console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
2272 process.exit(1);
2273 }
2274
2275 const go = new Go();
2276 go.argv = process.argv.slice(2);
2277 go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
2278 go.exit = process.exit;
2279 WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
2280 process.on("exit", (code) => { // Node.js exits if no event handler is pending
2281 if (code === 0 && !go.exited) {
2282 // deadlock, make Go print error and stack traces
2283 go._pendingEvent = { id: 0 };
2284 go._resume();
2285 }
2286 });
2287 return go.run(result.instance);
2288 }).catch((err) => {
2289 console.error(err);
2290 process.exit(1);
2291 });
2292 }
2293})();
2294onmessage = ({ data: wasm }) => {
2295 let decoder = new TextDecoder();
2296 let fs = global.fs;
2297 let stderr = "";
2298 fs.writeSync = (fd, buffer) => {
2299 if (fd === 1) {
2300 postMessage(buffer);
2301 } else if (fd === 2) {
2302 stderr += decoder.decode(buffer);
2303 let parts = stderr.split("\\n");
2304 if (parts.length > 1)
2305 console.log(parts.slice(0, -1).join("\\n"));
2306 stderr = parts[parts.length - 1];
2307 } else {
2308 throw new Error("Bad write");
2309 }
2310 return buffer.length;
2311 };
2312 let stdin = [];
2313 let resumeStdin;
2314 let stdinPos = 0;
2315 onmessage = ({ data }) => {
2316 if (data.length > 0) {
2317 stdin.push(data);
2318 if (resumeStdin)
2319 resumeStdin();
2320 }
2321 };
2322 fs.read = (fd, buffer, offset, length, position, callback) => {
2323 if (fd !== 0 || offset !== 0 || length !== buffer.length || position !== null) {
2324 throw new Error("Bad read");
2325 }
2326 if (stdin.length === 0) {
2327 resumeStdin = () => fs.read(fd, buffer, offset, length, position, callback);
2328 return;
2329 }
2330 let first = stdin[0];
2331 let count = Math.max(0, Math.min(length, first.length - stdinPos));
2332 buffer.set(first.subarray(stdinPos, stdinPos + count), offset);
2333 stdinPos += count;
2334 if (stdinPos === first.length) {
2335 stdin.shift();
2336 stdinPos = 0;
2337 }
2338 callback(null, count);
2339 };
2340 let go = new global.Go();
2341 go.argv = ["", \`--service=\${"0.13.4"}\`];
2342 WebAssembly.instantiate(wasm, go.importObject).then(({ instance }) => go.run(instance));
2343};}`;
2344 let worker;
2345 if (useWorker) {
2346 let blob = new Blob([code], { type: "text/javascript" });
2347 worker = new Worker(URL.createObjectURL(blob));
2348 } else {
2349 let fn = new Function("postMessage", code + `var onmessage; return m => onmessage(m)`);
2350 let onmessage = fn((data) => worker.onmessage({ data }));
2351 worker = {
2352 onmessage: null,
2353 postMessage: (data) => onmessage({ data }),
2354 terminate() {
2355 }
2356 };
2357 }
2358 worker.postMessage(wasm);
2359 worker.onmessage = ({ data }) => readFromStdout(data);
2360 let { readFromStdout, service } = createChannel({
2361 writeToStdin(bytes) {
2362 worker.postMessage(bytes);
2363 },
2364 isSync: false,
2365 isBrowser: true
2366 });
2367 longLivedService = {
2368 build: (options) => new Promise((resolve, reject) => service.buildOrServe({
2369 callName: "build",
2370 refs: null,
2371 serveOptions: null,
2372 options,
2373 isTTY: false,
2374 defaultWD: "/",
2375 callback: (err, res2) => err ? reject(err) : resolve(res2)
2376 })),
2377 transform: (input, options) => new Promise((resolve, reject) => service.transform({
2378 callName: "transform",
2379 refs: null,
2380 input,
2381 options: options || {},
2382 isTTY: false,
2383 fs: {
2384 readFile(_, callback) {
2385 callback(new Error("Internal error"), null);
2386 },
2387 writeFile(_, callback) {
2388 callback(null);
2389 }
2390 },
2391 callback: (err, res2) => err ? reject(err) : resolve(res2)
2392 })),
2393 formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2394 callName: "formatMessages",
2395 refs: null,
2396 messages,
2397 options,
2398 callback: (err, res2) => err ? reject(err) : resolve(res2)
2399 })),
2400 analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2401 callName: "analyzeMetafile",
2402 refs: null,
2403 metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2404 options,
2405 callback: (err, res2) => err ? reject(err) : resolve(res2)
2406 }))
2407 };
2408});
2409})(typeof exports==="object"?exports:(typeof self!=="undefined"?self:this).esbuild={});
Note: See TracBrowser for help on using the repository browser.