source: trip-planner-front/node_modules/esbuild/lib/main.js@ 76712b2

Last change on this file since 76712b2 was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago

primeNG components

  • Property mode set to 100644
File size: 72.7 KB
Line 
1var __create = Object.create;
2var __defProp = Object.defineProperty;
3var __defProps = Object.defineProperties;
4var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6var __getOwnPropNames = Object.getOwnPropertyNames;
7var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8var __getProtoOf = Object.getPrototypeOf;
9var __hasOwnProp = Object.prototype.hasOwnProperty;
10var __propIsEnum = Object.prototype.propertyIsEnumerable;
11var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12var __spreadValues = (a, b) => {
13 for (var prop in b || (b = {}))
14 if (__hasOwnProp.call(b, prop))
15 __defNormalProp(a, prop, b[prop]);
16 if (__getOwnPropSymbols)
17 for (var prop of __getOwnPropSymbols(b)) {
18 if (__propIsEnum.call(b, prop))
19 __defNormalProp(a, prop, b[prop]);
20 }
21 return a;
22};
23var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25var __export = (target, all) => {
26 __markAsModule(target);
27 for (var name in all)
28 __defProp(target, name, { get: all[name], enumerable: true });
29};
30var __reExport = (target, module2, desc) => {
31 if (module2 && typeof module2 === "object" || typeof module2 === "function") {
32 for (let key of __getOwnPropNames(module2))
33 if (!__hasOwnProp.call(target, key) && key !== "default")
34 __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
35 }
36 return target;
37};
38var __toModule = (module2) => {
39 return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
40};
41
42// lib/npm/node.ts
43__export(exports, {
44 analyzeMetafile: () => analyzeMetafile,
45 analyzeMetafileSync: () => analyzeMetafileSync,
46 build: () => build,
47 buildSync: () => buildSync,
48 formatMessages: () => formatMessages,
49 formatMessagesSync: () => formatMessagesSync,
50 initialize: () => initialize,
51 serve: () => serve,
52 transform: () => transform,
53 transformSync: () => transformSync,
54 version: () => version
55});
56
57// lib/shared/stdio_protocol.ts
58function encodePacket(packet) {
59 let visit = (value) => {
60 if (value === null) {
61 bb.write8(0);
62 } else if (typeof value === "boolean") {
63 bb.write8(1);
64 bb.write8(+value);
65 } else if (typeof value === "number") {
66 bb.write8(2);
67 bb.write32(value | 0);
68 } else if (typeof value === "string") {
69 bb.write8(3);
70 bb.write(encodeUTF8(value));
71 } else if (value instanceof Uint8Array) {
72 bb.write8(4);
73 bb.write(value);
74 } else if (value instanceof Array) {
75 bb.write8(5);
76 bb.write32(value.length);
77 for (let item of value) {
78 visit(item);
79 }
80 } else {
81 let keys = Object.keys(value);
82 bb.write8(6);
83 bb.write32(keys.length);
84 for (let key of keys) {
85 bb.write(encodeUTF8(key));
86 visit(value[key]);
87 }
88 }
89 };
90 let bb = new ByteBuffer();
91 bb.write32(0);
92 bb.write32(packet.id << 1 | +!packet.isRequest);
93 visit(packet.value);
94 writeUInt32LE(bb.buf, bb.len - 4, 0);
95 return bb.buf.subarray(0, bb.len);
96}
97function decodePacket(bytes) {
98 let visit = () => {
99 switch (bb.read8()) {
100 case 0:
101 return null;
102 case 1:
103 return !!bb.read8();
104 case 2:
105 return bb.read32();
106 case 3:
107 return decodeUTF8(bb.read());
108 case 4:
109 return bb.read();
110 case 5: {
111 let count = bb.read32();
112 let value2 = [];
113 for (let i = 0; i < count; i++) {
114 value2.push(visit());
115 }
116 return value2;
117 }
118 case 6: {
119 let count = bb.read32();
120 let value2 = {};
121 for (let i = 0; i < count; i++) {
122 value2[decodeUTF8(bb.read())] = visit();
123 }
124 return value2;
125 }
126 default:
127 throw new Error("Invalid packet");
128 }
129 };
130 let bb = new ByteBuffer(bytes);
131 let id = bb.read32();
132 let isRequest = (id & 1) === 0;
133 id >>>= 1;
134 let value = visit();
135 if (bb.ptr !== bytes.length) {
136 throw new Error("Invalid packet");
137 }
138 return { id, isRequest, value };
139}
140var ByteBuffer = class {
141 constructor(buf = new Uint8Array(1024)) {
142 this.buf = buf;
143 this.len = 0;
144 this.ptr = 0;
145 }
146 _write(delta) {
147 if (this.len + delta > this.buf.length) {
148 let clone = new Uint8Array((this.len + delta) * 2);
149 clone.set(this.buf);
150 this.buf = clone;
151 }
152 this.len += delta;
153 return this.len - delta;
154 }
155 write8(value) {
156 let offset = this._write(1);
157 this.buf[offset] = value;
158 }
159 write32(value) {
160 let offset = this._write(4);
161 writeUInt32LE(this.buf, value, offset);
162 }
163 write(bytes) {
164 let offset = this._write(4 + bytes.length);
165 writeUInt32LE(this.buf, bytes.length, offset);
166 this.buf.set(bytes, offset + 4);
167 }
168 _read(delta) {
169 if (this.ptr + delta > this.buf.length) {
170 throw new Error("Invalid packet");
171 }
172 this.ptr += delta;
173 return this.ptr - delta;
174 }
175 read8() {
176 return this.buf[this._read(1)];
177 }
178 read32() {
179 return readUInt32LE(this.buf, this._read(4));
180 }
181 read() {
182 let length = this.read32();
183 let bytes = new Uint8Array(length);
184 let ptr = this._read(bytes.length);
185 bytes.set(this.buf.subarray(ptr, ptr + length));
186 return bytes;
187 }
188};
189var encodeUTF8;
190var decodeUTF8;
191if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
192 let encoder = new TextEncoder();
193 let decoder = new TextDecoder();
194 encodeUTF8 = (text) => encoder.encode(text);
195 decodeUTF8 = (bytes) => decoder.decode(bytes);
196} else if (typeof Buffer !== "undefined") {
197 encodeUTF8 = (text) => {
198 let buffer = Buffer.from(text);
199 if (!(buffer instanceof Uint8Array)) {
200 buffer = new Uint8Array(buffer);
201 }
202 return buffer;
203 };
204 decodeUTF8 = (bytes) => {
205 let { buffer, byteOffset, byteLength } = bytes;
206 return Buffer.from(buffer, byteOffset, byteLength).toString();
207 };
208} else {
209 throw new Error("No UTF-8 codec found");
210}
211function readUInt32LE(buffer, offset) {
212 return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
213}
214function writeUInt32LE(buffer, value, offset) {
215 buffer[offset++] = value;
216 buffer[offset++] = value >> 8;
217 buffer[offset++] = value >> 16;
218 buffer[offset++] = value >> 24;
219}
220
221// lib/shared/common.ts
222function validateTarget(target) {
223 target += "";
224 if (target.indexOf(",") >= 0)
225 throw new Error(`Invalid target: ${target}`);
226 return target;
227}
228var canBeAnything = () => null;
229var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
230var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object";
231var mustBeString = (value) => typeof value === "string" ? null : "a string";
232var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
233var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
234var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
235var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
236var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
237var mustBeArrayOrRecord = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
238var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
239var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
240var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
241var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
242var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
243function getFlag(object, keys, key, mustBeFn) {
244 let value = object[key];
245 keys[key + ""] = true;
246 if (value === void 0)
247 return void 0;
248 let mustBe = mustBeFn(value);
249 if (mustBe !== null)
250 throw new Error(`"${key}" must be ${mustBe}`);
251 return value;
252}
253function checkForInvalidFlags(object, keys, where) {
254 for (let key in object) {
255 if (!(key in keys)) {
256 throw new Error(`Invalid option ${where}: "${key}"`);
257 }
258 }
259}
260function validateInitializeOptions(options) {
261 let keys = Object.create(null);
262 let wasmURL = getFlag(options, keys, "wasmURL", mustBeString);
263 let worker = getFlag(options, keys, "worker", mustBeBoolean);
264 checkForInvalidFlags(options, keys, "in startService() call");
265 return {
266 wasmURL,
267 worker
268 };
269}
270function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
271 let color = getFlag(options, keys, "color", mustBeBoolean);
272 let logLevel = getFlag(options, keys, "logLevel", mustBeString);
273 let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
274 if (color !== void 0)
275 flags.push(`--color=${color}`);
276 else if (isTTY2)
277 flags.push(`--color=true`);
278 flags.push(`--log-level=${logLevel || logLevelDefault}`);
279 flags.push(`--log-limit=${logLimit || 0}`);
280}
281function pushCommonFlags(flags, options, keys) {
282 let legalComments = getFlag(options, keys, "legalComments", mustBeString);
283 let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
284 let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
285 let target = getFlag(options, keys, "target", mustBeStringOrArray);
286 let format = getFlag(options, keys, "format", mustBeString);
287 let globalName = getFlag(options, keys, "globalName", mustBeString);
288 let minify = getFlag(options, keys, "minify", mustBeBoolean);
289 let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
290 let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
291 let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
292 let charset = getFlag(options, keys, "charset", mustBeString);
293 let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
294 let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
295 let jsx = getFlag(options, keys, "jsx", mustBeString);
296 let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
297 let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
298 let define = getFlag(options, keys, "define", mustBeObject);
299 let pure = getFlag(options, keys, "pure", mustBeArray);
300 let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
301 if (legalComments)
302 flags.push(`--legal-comments=${legalComments}`);
303 if (sourceRoot !== void 0)
304 flags.push(`--source-root=${sourceRoot}`);
305 if (sourcesContent !== void 0)
306 flags.push(`--sources-content=${sourcesContent}`);
307 if (target) {
308 if (Array.isArray(target))
309 flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
310 else
311 flags.push(`--target=${validateTarget(target)}`);
312 }
313 if (format)
314 flags.push(`--format=${format}`);
315 if (globalName)
316 flags.push(`--global-name=${globalName}`);
317 if (minify)
318 flags.push("--minify");
319 if (minifySyntax)
320 flags.push("--minify-syntax");
321 if (minifyWhitespace)
322 flags.push("--minify-whitespace");
323 if (minifyIdentifiers)
324 flags.push("--minify-identifiers");
325 if (charset)
326 flags.push(`--charset=${charset}`);
327 if (treeShaking !== void 0)
328 flags.push(`--tree-shaking=${treeShaking}`);
329 if (ignoreAnnotations)
330 flags.push(`--ignore-annotations`);
331 if (jsx)
332 flags.push(`--jsx=${jsx}`);
333 if (jsxFactory)
334 flags.push(`--jsx-factory=${jsxFactory}`);
335 if (jsxFragment)
336 flags.push(`--jsx-fragment=${jsxFragment}`);
337 if (define) {
338 for (let key in define) {
339 if (key.indexOf("=") >= 0)
340 throw new Error(`Invalid define: ${key}`);
341 flags.push(`--define:${key}=${define[key]}`);
342 }
343 }
344 if (pure)
345 for (let fn of pure)
346 flags.push(`--pure:${fn}`);
347 if (keepNames)
348 flags.push(`--keep-names`);
349}
350function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
351 var _a2;
352 let flags = [];
353 let entries = [];
354 let keys = Object.create(null);
355 let stdinContents = null;
356 let stdinResolveDir = null;
357 let watchMode = null;
358 pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
359 pushCommonFlags(flags, options, keys);
360 let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
361 let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
362 let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject);
363 let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
364 let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
365 let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
366 let outfile = getFlag(options, keys, "outfile", mustBeString);
367 let outdir = getFlag(options, keys, "outdir", mustBeString);
368 let outbase = getFlag(options, keys, "outbase", mustBeString);
369 let platform = getFlag(options, keys, "platform", mustBeString);
370 let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
371 let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
372 let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
373 let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
374 let conditions = getFlag(options, keys, "conditions", mustBeArray);
375 let external = getFlag(options, keys, "external", mustBeArray);
376 let loader = getFlag(options, keys, "loader", mustBeObject);
377 let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
378 let publicPath = getFlag(options, keys, "publicPath", mustBeString);
379 let entryNames = getFlag(options, keys, "entryNames", mustBeString);
380 let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
381 let assetNames = getFlag(options, keys, "assetNames", mustBeString);
382 let inject = getFlag(options, keys, "inject", mustBeArray);
383 let banner = getFlag(options, keys, "banner", mustBeObject);
384 let footer = getFlag(options, keys, "footer", mustBeObject);
385 let entryPoints = getFlag(options, keys, "entryPoints", mustBeArrayOrRecord);
386 let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
387 let stdin = getFlag(options, keys, "stdin", mustBeObject);
388 let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
389 let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
390 let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true;
391 keys.plugins = true;
392 checkForInvalidFlags(options, keys, `in ${callName}() call`);
393 if (sourcemap)
394 flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
395 if (bundle)
396 flags.push("--bundle");
397 if (allowOverwrite)
398 flags.push("--allow-overwrite");
399 if (watch) {
400 flags.push("--watch");
401 if (typeof watch === "boolean") {
402 watchMode = {};
403 } else {
404 let watchKeys = Object.create(null);
405 let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction);
406 checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`);
407 watchMode = { onRebuild };
408 }
409 }
410 if (splitting)
411 flags.push("--splitting");
412 if (preserveSymlinks)
413 flags.push("--preserve-symlinks");
414 if (metafile)
415 flags.push(`--metafile`);
416 if (outfile)
417 flags.push(`--outfile=${outfile}`);
418 if (outdir)
419 flags.push(`--outdir=${outdir}`);
420 if (outbase)
421 flags.push(`--outbase=${outbase}`);
422 if (platform)
423 flags.push(`--platform=${platform}`);
424 if (tsconfig)
425 flags.push(`--tsconfig=${tsconfig}`);
426 if (resolveExtensions) {
427 let values = [];
428 for (let value of resolveExtensions) {
429 value += "";
430 if (value.indexOf(",") >= 0)
431 throw new Error(`Invalid resolve extension: ${value}`);
432 values.push(value);
433 }
434 flags.push(`--resolve-extensions=${values.join(",")}`);
435 }
436 if (publicPath)
437 flags.push(`--public-path=${publicPath}`);
438 if (entryNames)
439 flags.push(`--entry-names=${entryNames}`);
440 if (chunkNames)
441 flags.push(`--chunk-names=${chunkNames}`);
442 if (assetNames)
443 flags.push(`--asset-names=${assetNames}`);
444 if (mainFields) {
445 let values = [];
446 for (let value of mainFields) {
447 value += "";
448 if (value.indexOf(",") >= 0)
449 throw new Error(`Invalid main field: ${value}`);
450 values.push(value);
451 }
452 flags.push(`--main-fields=${values.join(",")}`);
453 }
454 if (conditions) {
455 let values = [];
456 for (let value of conditions) {
457 value += "";
458 if (value.indexOf(",") >= 0)
459 throw new Error(`Invalid condition: ${value}`);
460 values.push(value);
461 }
462 flags.push(`--conditions=${values.join(",")}`);
463 }
464 if (external)
465 for (let name of external)
466 flags.push(`--external:${name}`);
467 if (banner) {
468 for (let type in banner) {
469 if (type.indexOf("=") >= 0)
470 throw new Error(`Invalid banner file type: ${type}`);
471 flags.push(`--banner:${type}=${banner[type]}`);
472 }
473 }
474 if (footer) {
475 for (let type in footer) {
476 if (type.indexOf("=") >= 0)
477 throw new Error(`Invalid footer file type: ${type}`);
478 flags.push(`--footer:${type}=${footer[type]}`);
479 }
480 }
481 if (inject)
482 for (let path3 of inject)
483 flags.push(`--inject:${path3}`);
484 if (loader) {
485 for (let ext in loader) {
486 if (ext.indexOf("=") >= 0)
487 throw new Error(`Invalid loader extension: ${ext}`);
488 flags.push(`--loader:${ext}=${loader[ext]}`);
489 }
490 }
491 if (outExtension) {
492 for (let ext in outExtension) {
493 if (ext.indexOf("=") >= 0)
494 throw new Error(`Invalid out extension: ${ext}`);
495 flags.push(`--out-extension:${ext}=${outExtension[ext]}`);
496 }
497 }
498 if (entryPoints) {
499 if (Array.isArray(entryPoints)) {
500 for (let entryPoint of entryPoints) {
501 entries.push(["", entryPoint + ""]);
502 }
503 } else {
504 for (let [key, value] of Object.entries(entryPoints)) {
505 entries.push([key + "", value + ""]);
506 }
507 }
508 }
509 if (stdin) {
510 let stdinKeys = Object.create(null);
511 let contents = getFlag(stdin, stdinKeys, "contents", mustBeString);
512 let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
513 let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
514 let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
515 checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
516 if (sourcefile)
517 flags.push(`--sourcefile=${sourcefile}`);
518 if (loader2)
519 flags.push(`--loader=${loader2}`);
520 if (resolveDir)
521 stdinResolveDir = resolveDir + "";
522 stdinContents = contents ? contents + "" : "";
523 }
524 let nodePaths = [];
525 if (nodePathsInput) {
526 for (let value of nodePathsInput) {
527 value += "";
528 nodePaths.push(value);
529 }
530 }
531 return {
532 entries,
533 flags,
534 write,
535 stdinContents,
536 stdinResolveDir,
537 absWorkingDir,
538 incremental,
539 nodePaths,
540 watch: watchMode
541 };
542}
543function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
544 let flags = [];
545 let keys = Object.create(null);
546 pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
547 pushCommonFlags(flags, options, keys);
548 let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
549 let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
550 let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
551 let loader = getFlag(options, keys, "loader", mustBeString);
552 let banner = getFlag(options, keys, "banner", mustBeString);
553 let footer = getFlag(options, keys, "footer", mustBeString);
554 checkForInvalidFlags(options, keys, `in ${callName}() call`);
555 if (sourcemap)
556 flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
557 if (tsconfigRaw)
558 flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
559 if (sourcefile)
560 flags.push(`--sourcefile=${sourcefile}`);
561 if (loader)
562 flags.push(`--loader=${loader}`);
563 if (banner)
564 flags.push(`--banner=${banner}`);
565 if (footer)
566 flags.push(`--footer=${footer}`);
567 return flags;
568}
569function createChannel(streamIn) {
570 let responseCallbacks = new Map();
571 let pluginCallbacks = new Map();
572 let watchCallbacks = new Map();
573 let serveCallbacks = new Map();
574 let nextServeID = 0;
575 let isClosed = false;
576 let nextRequestID = 0;
577 let nextBuildKey = 0;
578 let stdout = new Uint8Array(16 * 1024);
579 let stdoutUsed = 0;
580 let readFromStdout = (chunk) => {
581 let limit = stdoutUsed + chunk.length;
582 if (limit > stdout.length) {
583 let swap = new Uint8Array(limit * 2);
584 swap.set(stdout);
585 stdout = swap;
586 }
587 stdout.set(chunk, stdoutUsed);
588 stdoutUsed += chunk.length;
589 let offset = 0;
590 while (offset + 4 <= stdoutUsed) {
591 let length = readUInt32LE(stdout, offset);
592 if (offset + 4 + length > stdoutUsed) {
593 break;
594 }
595 offset += 4;
596 handleIncomingPacket(stdout.subarray(offset, offset + length));
597 offset += length;
598 }
599 if (offset > 0) {
600 stdout.copyWithin(0, offset, stdoutUsed);
601 stdoutUsed -= offset;
602 }
603 };
604 let afterClose = () => {
605 isClosed = true;
606 for (let callback of responseCallbacks.values()) {
607 callback("The service was stopped", null);
608 }
609 responseCallbacks.clear();
610 for (let callbacks of serveCallbacks.values()) {
611 callbacks.onWait("The service was stopped");
612 }
613 serveCallbacks.clear();
614 for (let callback of watchCallbacks.values()) {
615 try {
616 callback(new Error("The service was stopped"), null);
617 } catch (e) {
618 console.error(e);
619 }
620 }
621 watchCallbacks.clear();
622 };
623 let sendRequest = (refs, value, callback) => {
624 if (isClosed)
625 return callback("The service is no longer running", null);
626 let id = nextRequestID++;
627 responseCallbacks.set(id, (error, response) => {
628 try {
629 callback(error, response);
630 } finally {
631 if (refs)
632 refs.unref();
633 }
634 });
635 if (refs)
636 refs.ref();
637 streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
638 };
639 let sendResponse = (id, value) => {
640 if (isClosed)
641 throw new Error("The service is no longer running");
642 streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
643 };
644 let handleRequest = async (id, request) => {
645 try {
646 switch (request.command) {
647 case "ping": {
648 sendResponse(id, {});
649 break;
650 }
651 case "start": {
652 let callback = pluginCallbacks.get(request.key);
653 if (!callback)
654 sendResponse(id, {});
655 else
656 sendResponse(id, await callback(request));
657 break;
658 }
659 case "resolve": {
660 let callback = pluginCallbacks.get(request.key);
661 if (!callback)
662 sendResponse(id, {});
663 else
664 sendResponse(id, await callback(request));
665 break;
666 }
667 case "load": {
668 let callback = pluginCallbacks.get(request.key);
669 if (!callback)
670 sendResponse(id, {});
671 else
672 sendResponse(id, await callback(request));
673 break;
674 }
675 case "serve-request": {
676 let callbacks = serveCallbacks.get(request.serveID);
677 if (callbacks && callbacks.onRequest)
678 callbacks.onRequest(request.args);
679 sendResponse(id, {});
680 break;
681 }
682 case "serve-wait": {
683 let callbacks = serveCallbacks.get(request.serveID);
684 if (callbacks)
685 callbacks.onWait(request.error);
686 sendResponse(id, {});
687 break;
688 }
689 case "watch-rebuild": {
690 let callback = watchCallbacks.get(request.watchID);
691 try {
692 if (callback)
693 callback(null, request.args);
694 } catch (err) {
695 console.error(err);
696 }
697 sendResponse(id, {});
698 break;
699 }
700 default:
701 throw new Error(`Invalid command: ` + request.command);
702 }
703 } catch (e) {
704 sendResponse(id, { errors: [extractErrorMessageV8(e, streamIn, null, void 0, "")] });
705 }
706 };
707 let isFirstPacket = true;
708 let handleIncomingPacket = (bytes) => {
709 if (isFirstPacket) {
710 isFirstPacket = false;
711 let binaryVersion = String.fromCharCode(...bytes);
712 if (binaryVersion !== "0.13.8") {
713 throw new Error(`Cannot start service: Host version "${"0.13.8"}" does not match binary version ${JSON.stringify(binaryVersion)}`);
714 }
715 return;
716 }
717 let packet = decodePacket(bytes);
718 if (packet.isRequest) {
719 handleRequest(packet.id, packet.value);
720 } else {
721 let callback = responseCallbacks.get(packet.id);
722 responseCallbacks.delete(packet.id);
723 if (packet.value.error)
724 callback(packet.value.error, {});
725 else
726 callback(null, packet.value);
727 }
728 };
729 let handlePlugins = async (initialOptions, plugins, buildKey, stash) => {
730 let onStartCallbacks = [];
731 let onEndCallbacks = [];
732 let onResolveCallbacks = {};
733 let onLoadCallbacks = {};
734 let nextCallbackID = 0;
735 let i = 0;
736 let requestPlugins = [];
737 plugins = [...plugins];
738 for (let item of plugins) {
739 let keys = {};
740 if (typeof item !== "object")
741 throw new Error(`Plugin at index ${i} must be an object`);
742 let name = getFlag(item, keys, "name", mustBeString);
743 if (typeof name !== "string" || name === "")
744 throw new Error(`Plugin at index ${i} is missing a name`);
745 try {
746 let setup = getFlag(item, keys, "setup", mustBeFunction);
747 if (typeof setup !== "function")
748 throw new Error(`Plugin is missing a setup function`);
749 checkForInvalidFlags(item, keys, `on plugin ${JSON.stringify(name)}`);
750 let plugin = {
751 name,
752 onResolve: [],
753 onLoad: []
754 };
755 i++;
756 let promise = setup({
757 initialOptions,
758 onStart(callback2) {
759 let registeredText = `This error came from the "onStart" callback registered here`;
760 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
761 onStartCallbacks.push({ name, callback: callback2, note: registeredNote });
762 },
763 onEnd(callback2) {
764 let registeredText = `This error came from the "onEnd" callback registered here`;
765 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
766 onEndCallbacks.push({ name, callback: callback2, note: registeredNote });
767 },
768 onResolve(options, callback2) {
769 let registeredText = `This error came from the "onResolve" callback registered here`;
770 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
771 let keys2 = {};
772 let filter = getFlag(options, keys2, "filter", mustBeRegExp);
773 let namespace = getFlag(options, keys2, "namespace", mustBeString);
774 checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${JSON.stringify(name)}`);
775 if (filter == null)
776 throw new Error(`onResolve() call is missing a filter`);
777 let id = nextCallbackID++;
778 onResolveCallbacks[id] = { name, callback: callback2, note: registeredNote };
779 plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
780 },
781 onLoad(options, callback2) {
782 let registeredText = `This error came from the "onLoad" callback registered here`;
783 let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
784 let keys2 = {};
785 let filter = getFlag(options, keys2, "filter", mustBeRegExp);
786 let namespace = getFlag(options, keys2, "namespace", mustBeString);
787 checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${JSON.stringify(name)}`);
788 if (filter == null)
789 throw new Error(`onLoad() call is missing a filter`);
790 let id = nextCallbackID++;
791 onLoadCallbacks[id] = { name, callback: callback2, note: registeredNote };
792 plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
793 }
794 });
795 if (promise)
796 await promise;
797 requestPlugins.push(plugin);
798 } catch (e) {
799 return { ok: false, error: e, pluginName: name };
800 }
801 }
802 const callback = async (request) => {
803 switch (request.command) {
804 case "start": {
805 let response = { errors: [], warnings: [] };
806 await Promise.all(onStartCallbacks.map(async ({ name, callback: callback2, note }) => {
807 try {
808 let result = await callback2();
809 if (result != null) {
810 if (typeof result !== "object")
811 throw new Error(`Expected onStart() callback in plugin ${JSON.stringify(name)} to return an object`);
812 let keys = {};
813 let errors = getFlag(result, keys, "errors", mustBeArray);
814 let warnings = getFlag(result, keys, "warnings", mustBeArray);
815 checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${JSON.stringify(name)}`);
816 if (errors != null)
817 response.errors.push(...sanitizeMessages(errors, "errors", stash, name));
818 if (warnings != null)
819 response.warnings.push(...sanitizeMessages(warnings, "warnings", stash, name));
820 }
821 } catch (e) {
822 response.errors.push(extractErrorMessageV8(e, streamIn, stash, note && note(), name));
823 }
824 }));
825 return response;
826 }
827 case "resolve": {
828 let response = {}, name = "", callback2, note;
829 for (let id of request.ids) {
830 try {
831 ({ name, callback: callback2, note } = onResolveCallbacks[id]);
832 let result = await callback2({
833 path: request.path,
834 importer: request.importer,
835 namespace: request.namespace,
836 resolveDir: request.resolveDir,
837 kind: request.kind,
838 pluginData: stash.load(request.pluginData)
839 });
840 if (result != null) {
841 if (typeof result !== "object")
842 throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(name)} to return an object`);
843 let keys = {};
844 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
845 let path3 = getFlag(result, keys, "path", mustBeString);
846 let namespace = getFlag(result, keys, "namespace", mustBeString);
847 let external = getFlag(result, keys, "external", mustBeBoolean);
848 let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
849 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
850 let errors = getFlag(result, keys, "errors", mustBeArray);
851 let warnings = getFlag(result, keys, "warnings", mustBeArray);
852 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
853 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
854 checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${JSON.stringify(name)}`);
855 response.id = id;
856 if (pluginName != null)
857 response.pluginName = pluginName;
858 if (path3 != null)
859 response.path = path3;
860 if (namespace != null)
861 response.namespace = namespace;
862 if (external != null)
863 response.external = external;
864 if (sideEffects != null)
865 response.sideEffects = sideEffects;
866 if (pluginData != null)
867 response.pluginData = stash.store(pluginData);
868 if (errors != null)
869 response.errors = sanitizeMessages(errors, "errors", stash, name);
870 if (warnings != null)
871 response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
872 if (watchFiles != null)
873 response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
874 if (watchDirs != null)
875 response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
876 break;
877 }
878 } catch (e) {
879 return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
880 }
881 }
882 return response;
883 }
884 case "load": {
885 let response = {}, name = "", callback2, note;
886 for (let id of request.ids) {
887 try {
888 ({ name, callback: callback2, note } = onLoadCallbacks[id]);
889 let result = await callback2({
890 path: request.path,
891 namespace: request.namespace,
892 pluginData: stash.load(request.pluginData)
893 });
894 if (result != null) {
895 if (typeof result !== "object")
896 throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(name)} to return an object`);
897 let keys = {};
898 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
899 let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
900 let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
901 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
902 let loader = getFlag(result, keys, "loader", mustBeString);
903 let errors = getFlag(result, keys, "errors", mustBeArray);
904 let warnings = getFlag(result, keys, "warnings", mustBeArray);
905 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
906 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
907 checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${JSON.stringify(name)}`);
908 response.id = id;
909 if (pluginName != null)
910 response.pluginName = pluginName;
911 if (contents instanceof Uint8Array)
912 response.contents = contents;
913 else if (contents != null)
914 response.contents = encodeUTF8(contents);
915 if (resolveDir != null)
916 response.resolveDir = resolveDir;
917 if (pluginData != null)
918 response.pluginData = stash.store(pluginData);
919 if (loader != null)
920 response.loader = loader;
921 if (errors != null)
922 response.errors = sanitizeMessages(errors, "errors", stash, name);
923 if (warnings != null)
924 response.warnings = sanitizeMessages(warnings, "warnings", stash, name);
925 if (watchFiles != null)
926 response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
927 if (watchDirs != null)
928 response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
929 break;
930 }
931 } catch (e) {
932 return { id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note(), name)] };
933 }
934 }
935 return response;
936 }
937 default:
938 throw new Error(`Invalid command: ` + request.command);
939 }
940 };
941 let runOnEndCallbacks = (result, logPluginError, done) => done();
942 if (onEndCallbacks.length > 0) {
943 runOnEndCallbacks = (result, logPluginError, done) => {
944 (async () => {
945 for (const { name, callback: callback2, note } of onEndCallbacks) {
946 try {
947 await callback2(result);
948 } catch (e) {
949 result.errors.push(await new Promise((resolve) => logPluginError(e, name, note && note(), resolve)));
950 }
951 }
952 })().then(done);
953 };
954 }
955 let refCount = 0;
956 return {
957 ok: true,
958 requestPlugins,
959 runOnEndCallbacks,
960 pluginRefs: {
961 ref() {
962 if (++refCount === 1)
963 pluginCallbacks.set(buildKey, callback);
964 },
965 unref() {
966 if (--refCount === 0)
967 pluginCallbacks.delete(buildKey);
968 }
969 }
970 };
971 };
972 let buildServeData = (refs, options, request) => {
973 let keys = {};
974 let port = getFlag(options, keys, "port", mustBeInteger);
975 let host = getFlag(options, keys, "host", mustBeString);
976 let servedir = getFlag(options, keys, "servedir", mustBeString);
977 let onRequest = getFlag(options, keys, "onRequest", mustBeFunction);
978 let serveID = nextServeID++;
979 let onWait;
980 let wait = new Promise((resolve, reject) => {
981 onWait = (error) => {
982 serveCallbacks.delete(serveID);
983 if (error !== null)
984 reject(new Error(error));
985 else
986 resolve();
987 };
988 });
989 request.serve = { serveID };
990 checkForInvalidFlags(options, keys, `in serve() call`);
991 if (port !== void 0)
992 request.serve.port = port;
993 if (host !== void 0)
994 request.serve.host = host;
995 if (servedir !== void 0)
996 request.serve.servedir = servedir;
997 serveCallbacks.set(serveID, {
998 onRequest,
999 onWait
1000 });
1001 return {
1002 wait,
1003 stop() {
1004 sendRequest(refs, { command: "serve-stop", serveID }, () => {
1005 });
1006 }
1007 };
1008 };
1009 const buildLogLevelDefault = "warning";
1010 const transformLogLevelDefault = "silent";
1011 let buildOrServe = (args) => {
1012 let key = nextBuildKey++;
1013 const details = createObjectStash();
1014 let plugins;
1015 let { refs, options, isTTY: isTTY2, callback } = args;
1016 if (typeof options === "object") {
1017 let value = options.plugins;
1018 if (value !== void 0) {
1019 if (!Array.isArray(value))
1020 throw new Error(`"plugins" must be an array`);
1021 plugins = value;
1022 }
1023 }
1024 let logPluginError = (e, pluginName, note, done) => {
1025 let flags = [];
1026 try {
1027 pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1028 } catch (e2) {
1029 }
1030 const message = extractErrorMessageV8(e, streamIn, details, note, pluginName);
1031 sendRequest(refs, { command: "error", flags, error: message }, () => {
1032 message.detail = details.load(message.detail);
1033 done(message);
1034 });
1035 };
1036 let handleError = (e, pluginName) => {
1037 logPluginError(e, pluginName, void 0, (error) => {
1038 callback(failureErrorWithLog("Build failed", [error], []), null);
1039 });
1040 };
1041 if (plugins && plugins.length > 0) {
1042 if (streamIn.isSync)
1043 return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1044 handlePlugins(options, plugins, key, details).then((result) => {
1045 if (!result.ok) {
1046 handleError(result.error, result.pluginName);
1047 } else {
1048 try {
1049 buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1050 key,
1051 details,
1052 logPluginError,
1053 requestPlugins: result.requestPlugins,
1054 runOnEndCallbacks: result.runOnEndCallbacks,
1055 pluginRefs: result.pluginRefs
1056 }));
1057 } catch (e) {
1058 handleError(e, "");
1059 }
1060 }
1061 }, (e) => handleError(e, ""));
1062 } else {
1063 try {
1064 buildOrServeContinue(__spreadProps(__spreadValues({}, args), {
1065 key,
1066 details,
1067 logPluginError,
1068 requestPlugins: null,
1069 runOnEndCallbacks: (result, logPluginError2, done) => done(),
1070 pluginRefs: null
1071 }));
1072 } catch (e) {
1073 handleError(e, "");
1074 }
1075 }
1076 };
1077 let buildOrServeContinue = ({
1078 callName,
1079 refs: callerRefs,
1080 serveOptions,
1081 options,
1082 isTTY: isTTY2,
1083 defaultWD: defaultWD2,
1084 callback,
1085 key,
1086 details,
1087 logPluginError,
1088 requestPlugins,
1089 runOnEndCallbacks,
1090 pluginRefs
1091 }) => {
1092 const refs = {
1093 ref() {
1094 if (pluginRefs)
1095 pluginRefs.ref();
1096 if (callerRefs)
1097 callerRefs.ref();
1098 },
1099 unref() {
1100 if (pluginRefs)
1101 pluginRefs.unref();
1102 if (callerRefs)
1103 callerRefs.unref();
1104 }
1105 };
1106 let writeDefault = !streamIn.isBrowser;
1107 let {
1108 entries,
1109 flags,
1110 write,
1111 stdinContents,
1112 stdinResolveDir,
1113 absWorkingDir,
1114 incremental,
1115 nodePaths,
1116 watch
1117 } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1118 let request = {
1119 command: "build",
1120 key,
1121 entries,
1122 flags,
1123 write,
1124 stdinContents,
1125 stdinResolveDir,
1126 absWorkingDir: absWorkingDir || defaultWD2,
1127 incremental,
1128 nodePaths
1129 };
1130 if (requestPlugins)
1131 request.plugins = requestPlugins;
1132 let serve2 = serveOptions && buildServeData(refs, serveOptions, request);
1133 let rebuild;
1134 let stop;
1135 let copyResponseToResult = (response, result) => {
1136 if (response.outputFiles)
1137 result.outputFiles = response.outputFiles.map(convertOutputFiles);
1138 if (response.metafile)
1139 result.metafile = JSON.parse(response.metafile);
1140 if (response.writeToStdout !== void 0)
1141 console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1142 };
1143 let buildResponseToResult = (response, callback2) => {
1144 let result = {
1145 errors: replaceDetailsInMessages(response.errors, details),
1146 warnings: replaceDetailsInMessages(response.warnings, details)
1147 };
1148 copyResponseToResult(response, result);
1149 runOnEndCallbacks(result, logPluginError, () => {
1150 if (result.errors.length > 0) {
1151 return callback2(failureErrorWithLog("Build failed", result.errors, result.warnings), null);
1152 }
1153 if (response.rebuildID !== void 0) {
1154 if (!rebuild) {
1155 let isDisposed = false;
1156 rebuild = () => new Promise((resolve, reject) => {
1157 if (isDisposed || isClosed)
1158 throw new Error("Cannot rebuild");
1159 sendRequest(refs, { command: "rebuild", rebuildID: response.rebuildID }, (error2, response2) => {
1160 if (error2) {
1161 const message = { pluginName: "", text: error2, location: null, notes: [], detail: void 0 };
1162 return callback2(failureErrorWithLog("Build failed", [message], []), null);
1163 }
1164 buildResponseToResult(response2, (error3, result3) => {
1165 if (error3)
1166 reject(error3);
1167 else
1168 resolve(result3);
1169 });
1170 });
1171 });
1172 refs.ref();
1173 rebuild.dispose = () => {
1174 if (isDisposed)
1175 return;
1176 isDisposed = true;
1177 sendRequest(refs, { command: "rebuild-dispose", rebuildID: response.rebuildID }, () => {
1178 });
1179 refs.unref();
1180 };
1181 }
1182 result.rebuild = rebuild;
1183 }
1184 if (response.watchID !== void 0) {
1185 if (!stop) {
1186 let isStopped = false;
1187 refs.ref();
1188 stop = () => {
1189 if (isStopped)
1190 return;
1191 isStopped = true;
1192 watchCallbacks.delete(response.watchID);
1193 sendRequest(refs, { command: "watch-stop", watchID: response.watchID }, () => {
1194 });
1195 refs.unref();
1196 };
1197 if (watch) {
1198 watchCallbacks.set(response.watchID, (serviceStopError, watchResponse) => {
1199 if (serviceStopError) {
1200 if (watch.onRebuild)
1201 watch.onRebuild(serviceStopError, null);
1202 return;
1203 }
1204 let result2 = {
1205 errors: replaceDetailsInMessages(watchResponse.errors, details),
1206 warnings: replaceDetailsInMessages(watchResponse.warnings, details)
1207 };
1208 copyResponseToResult(watchResponse, result2);
1209 runOnEndCallbacks(result2, logPluginError, () => {
1210 if (result2.errors.length > 0) {
1211 if (watch.onRebuild)
1212 watch.onRebuild(failureErrorWithLog("Build failed", result2.errors, result2.warnings), null);
1213 return;
1214 }
1215 if (watchResponse.rebuildID !== void 0)
1216 result2.rebuild = rebuild;
1217 result2.stop = stop;
1218 if (watch.onRebuild)
1219 watch.onRebuild(null, result2);
1220 });
1221 });
1222 }
1223 }
1224 result.stop = stop;
1225 }
1226 callback2(null, result);
1227 });
1228 };
1229 if (write && streamIn.isBrowser)
1230 throw new Error(`Cannot enable "write" in the browser`);
1231 if (incremental && streamIn.isSync)
1232 throw new Error(`Cannot use "incremental" with a synchronous build`);
1233 if (watch && streamIn.isSync)
1234 throw new Error(`Cannot use "watch" with a synchronous build`);
1235 sendRequest(refs, request, (error, response) => {
1236 if (error)
1237 return callback(new Error(error), null);
1238 if (serve2) {
1239 let serveResponse = response;
1240 let isStopped = false;
1241 refs.ref();
1242 let result = {
1243 port: serveResponse.port,
1244 host: serveResponse.host,
1245 wait: serve2.wait,
1246 stop() {
1247 if (isStopped)
1248 return;
1249 isStopped = true;
1250 serve2.stop();
1251 refs.unref();
1252 }
1253 };
1254 refs.ref();
1255 serve2.wait.then(refs.unref, refs.unref);
1256 return callback(null, result);
1257 }
1258 return buildResponseToResult(response, callback);
1259 });
1260 };
1261 let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
1262 const details = createObjectStash();
1263 let start = (inputPath) => {
1264 try {
1265 if (typeof input !== "string")
1266 throw new Error('The input to "transform" must be a string');
1267 let flags = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1268 let request = {
1269 command: "transform",
1270 flags,
1271 inputFS: inputPath !== null,
1272 input: inputPath !== null ? inputPath : input
1273 };
1274 sendRequest(refs, request, (error, response) => {
1275 if (error)
1276 return callback(new Error(error), null);
1277 let errors = replaceDetailsInMessages(response.errors, details);
1278 let warnings = replaceDetailsInMessages(response.warnings, details);
1279 let outstanding = 1;
1280 let next = () => --outstanding === 0 && callback(null, { warnings, code: response.code, map: response.map });
1281 if (errors.length > 0)
1282 return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1283 if (response.codeFS) {
1284 outstanding++;
1285 fs3.readFile(response.code, (err, contents) => {
1286 if (err !== null) {
1287 callback(err, null);
1288 } else {
1289 response.code = contents;
1290 next();
1291 }
1292 });
1293 }
1294 if (response.mapFS) {
1295 outstanding++;
1296 fs3.readFile(response.map, (err, contents) => {
1297 if (err !== null) {
1298 callback(err, null);
1299 } else {
1300 response.map = contents;
1301 next();
1302 }
1303 });
1304 }
1305 next();
1306 });
1307 } catch (e) {
1308 let flags = [];
1309 try {
1310 pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1311 } catch (e2) {
1312 }
1313 const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1314 sendRequest(refs, { command: "error", flags, error }, () => {
1315 error.detail = details.load(error.detail);
1316 callback(failureErrorWithLog("Transform failed", [error], []), null);
1317 });
1318 }
1319 };
1320 if (typeof input === "string" && input.length > 1024 * 1024) {
1321 let next = start;
1322 start = () => fs3.writeFile(input, next);
1323 }
1324 start(null);
1325 };
1326 let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1327 let result = sanitizeMessages(messages, "messages", null, "");
1328 if (!options)
1329 throw new Error(`Missing second argument in ${callName}() call`);
1330 let keys = {};
1331 let kind = getFlag(options, keys, "kind", mustBeString);
1332 let color = getFlag(options, keys, "color", mustBeBoolean);
1333 let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1334 checkForInvalidFlags(options, keys, `in ${callName}() call`);
1335 if (kind === void 0)
1336 throw new Error(`Missing "kind" in ${callName}() call`);
1337 if (kind !== "error" && kind !== "warning")
1338 throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1339 let request = {
1340 command: "format-msgs",
1341 messages: result,
1342 isWarning: kind === "warning"
1343 };
1344 if (color !== void 0)
1345 request.color = color;
1346 if (terminalWidth !== void 0)
1347 request.terminalWidth = terminalWidth;
1348 sendRequest(refs, request, (error, response) => {
1349 if (error)
1350 return callback(new Error(error), null);
1351 callback(null, response.messages);
1352 });
1353 };
1354 let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1355 if (options === void 0)
1356 options = {};
1357 let keys = {};
1358 let color = getFlag(options, keys, "color", mustBeBoolean);
1359 let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1360 checkForInvalidFlags(options, keys, `in ${callName}() call`);
1361 let request = {
1362 command: "analyze-metafile",
1363 metafile
1364 };
1365 if (color !== void 0)
1366 request.color = color;
1367 if (verbose !== void 0)
1368 request.verbose = verbose;
1369 sendRequest(refs, request, (error, response) => {
1370 if (error)
1371 return callback(new Error(error), null);
1372 callback(null, response.result);
1373 });
1374 };
1375 return {
1376 readFromStdout,
1377 afterClose,
1378 service: {
1379 buildOrServe,
1380 transform: transform2,
1381 formatMessages: formatMessages2,
1382 analyzeMetafile: analyzeMetafile2
1383 }
1384 };
1385}
1386function createObjectStash() {
1387 const map = new Map();
1388 let nextID = 0;
1389 return {
1390 load(id) {
1391 return map.get(id);
1392 },
1393 store(value) {
1394 if (value === void 0)
1395 return -1;
1396 const id = nextID++;
1397 map.set(id, value);
1398 return id;
1399 }
1400 };
1401}
1402function extractCallerV8(e, streamIn, ident) {
1403 let note;
1404 let tried = false;
1405 return () => {
1406 if (tried)
1407 return note;
1408 tried = true;
1409 try {
1410 let lines = (e.stack + "").split("\n");
1411 lines.splice(1, 1);
1412 let location = parseStackLinesV8(streamIn, lines, ident);
1413 if (location) {
1414 note = { text: e.message, location };
1415 return note;
1416 }
1417 } catch (e2) {
1418 }
1419 };
1420}
1421function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1422 let text = "Internal error";
1423 let location = null;
1424 try {
1425 text = (e && e.message || e) + "";
1426 } catch (e2) {
1427 }
1428 try {
1429 location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1430 } catch (e2) {
1431 }
1432 return { pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1433}
1434function parseStackLinesV8(streamIn, lines, ident) {
1435 let at = " at ";
1436 if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1437 for (let i = 1; i < lines.length; i++) {
1438 let line = lines[i];
1439 if (!line.startsWith(at))
1440 continue;
1441 line = line.slice(at.length);
1442 while (true) {
1443 let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1444 if (match) {
1445 line = match[1];
1446 continue;
1447 }
1448 match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1449 if (match) {
1450 line = match[1];
1451 continue;
1452 }
1453 match = /^(\S+):(\d+):(\d+)$/.exec(line);
1454 if (match) {
1455 let contents;
1456 try {
1457 contents = streamIn.readFileSync(match[1], "utf8");
1458 } catch (e) {
1459 break;
1460 }
1461 let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1462 let column = +match[3] - 1;
1463 let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1464 return {
1465 file: match[1],
1466 namespace: "file",
1467 line: +match[2],
1468 column: encodeUTF8(lineText.slice(0, column)).length,
1469 length: encodeUTF8(lineText.slice(column, column + length)).length,
1470 lineText: lineText + "\n" + lines.slice(1).join("\n"),
1471 suggestion: ""
1472 };
1473 }
1474 break;
1475 }
1476 }
1477 }
1478 return null;
1479}
1480function failureErrorWithLog(text, errors, warnings) {
1481 let limit = 5;
1482 let summary = errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1483 if (i === limit)
1484 return "\n...";
1485 if (!e.location)
1486 return `
1487error: ${e.text}`;
1488 let { file, line, column } = e.location;
1489 let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1490 return `
1491${file}:${line}:${column}: error: ${pluginText}${e.text}`;
1492 }).join("");
1493 let error = new Error(`${text}${summary}`);
1494 error.errors = errors;
1495 error.warnings = warnings;
1496 return error;
1497}
1498function replaceDetailsInMessages(messages, stash) {
1499 for (const message of messages) {
1500 message.detail = stash.load(message.detail);
1501 }
1502 return messages;
1503}
1504function sanitizeLocation(location, where) {
1505 if (location == null)
1506 return null;
1507 let keys = {};
1508 let file = getFlag(location, keys, "file", mustBeString);
1509 let namespace = getFlag(location, keys, "namespace", mustBeString);
1510 let line = getFlag(location, keys, "line", mustBeInteger);
1511 let column = getFlag(location, keys, "column", mustBeInteger);
1512 let length = getFlag(location, keys, "length", mustBeInteger);
1513 let lineText = getFlag(location, keys, "lineText", mustBeString);
1514 let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1515 checkForInvalidFlags(location, keys, where);
1516 return {
1517 file: file || "",
1518 namespace: namespace || "",
1519 line: line || 0,
1520 column: column || 0,
1521 length: length || 0,
1522 lineText: lineText || "",
1523 suggestion: suggestion || ""
1524 };
1525}
1526function sanitizeMessages(messages, property, stash, fallbackPluginName) {
1527 let messagesClone = [];
1528 let index = 0;
1529 for (const message of messages) {
1530 let keys = {};
1531 let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1532 let text = getFlag(message, keys, "text", mustBeString);
1533 let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1534 let notes = getFlag(message, keys, "notes", mustBeArray);
1535 let detail = getFlag(message, keys, "detail", canBeAnything);
1536 let where = `in element ${index} of "${property}"`;
1537 checkForInvalidFlags(message, keys, where);
1538 let notesClone = [];
1539 if (notes) {
1540 for (const note of notes) {
1541 let noteKeys = {};
1542 let noteText = getFlag(note, noteKeys, "text", mustBeString);
1543 let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1544 checkForInvalidFlags(note, noteKeys, where);
1545 notesClone.push({
1546 text: noteText || "",
1547 location: sanitizeLocation(noteLocation, where)
1548 });
1549 }
1550 }
1551 messagesClone.push({
1552 pluginName: pluginName || fallbackPluginName,
1553 text: text || "",
1554 location: sanitizeLocation(location, where),
1555 notes: notesClone,
1556 detail: stash ? stash.store(detail) : -1
1557 });
1558 index++;
1559 }
1560 return messagesClone;
1561}
1562function sanitizeStringArray(values, property) {
1563 const result = [];
1564 for (const value of values) {
1565 if (typeof value !== "string")
1566 throw new Error(`${JSON.stringify(property)} must be an array of strings`);
1567 result.push(value);
1568 }
1569 return result;
1570}
1571function convertOutputFiles({ path: path3, contents }) {
1572 let text = null;
1573 return {
1574 path: path3,
1575 contents,
1576 get text() {
1577 if (text === null)
1578 text = decodeUTF8(contents);
1579 return text;
1580 }
1581 };
1582}
1583
1584// lib/npm/node-platform.ts
1585var fs = require("fs");
1586var os = require("os");
1587var path = require("path");
1588var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1589var knownWindowsPackages = {
1590 "win32 arm64 LE": "esbuild-windows-arm64",
1591 "win32 ia32 LE": "esbuild-windows-32",
1592 "win32 x64 LE": "esbuild-windows-64"
1593};
1594var knownUnixlikePackages = {
1595 "android arm64 LE": "esbuild-android-arm64",
1596 "darwin arm64 LE": "esbuild-darwin-arm64",
1597 "darwin x64 LE": "esbuild-darwin-64",
1598 "freebsd arm64 LE": "esbuild-freebsd-arm64",
1599 "freebsd x64 LE": "esbuild-freebsd-64",
1600 "linux arm LE": "esbuild-linux-arm",
1601 "linux arm64 LE": "esbuild-linux-arm64",
1602 "linux ia32 LE": "esbuild-linux-32",
1603 "linux mips64el LE": "esbuild-linux-mips64le",
1604 "linux ppc64 LE": "esbuild-linux-ppc64le",
1605 "linux x64 LE": "esbuild-linux-64",
1606 "netbsd x64 LE": "esbuild-netbsd-64",
1607 "openbsd x64 LE": "esbuild-openbsd-64",
1608 "sunos x64 LE": "esbuild-sunos-64"
1609};
1610function pkgAndSubpathForCurrentPlatform() {
1611 let pkg;
1612 let subpath;
1613 let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1614 if (platformKey in knownWindowsPackages) {
1615 pkg = knownWindowsPackages[platformKey];
1616 subpath = "esbuild.exe";
1617 } else if (platformKey in knownUnixlikePackages) {
1618 pkg = knownUnixlikePackages[platformKey];
1619 subpath = "bin/esbuild";
1620 } else {
1621 throw new Error(`Unsupported platform: ${platformKey}`);
1622 }
1623 return { pkg, subpath };
1624}
1625function downloadedBinPath(pkg, subpath) {
1626 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
1627 return path.join(esbuildLibDir, `downloaded-${pkg}-${path.basename(subpath)}`);
1628}
1629function generateBinPath() {
1630 if (ESBUILD_BINARY_PATH) {
1631 return ESBUILD_BINARY_PATH;
1632 }
1633 const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
1634 let binPath;
1635 try {
1636 binPath = require.resolve(`${pkg}/${subpath}`);
1637 } catch (e) {
1638 binPath = downloadedBinPath(pkg, subpath);
1639 if (!fs.existsSync(binPath)) {
1640 try {
1641 require.resolve(pkg);
1642 } catch (e2) {
1643 throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1644
1645If you are installing esbuild with npm, make sure that you don't specify the
1646"--no-optional" flag. The "optionalDependencies" package.json feature is used
1647by esbuild to install the correct binary executable for your current platform.`);
1648 }
1649 throw e;
1650 }
1651 }
1652 let isYarnPnP = false;
1653 try {
1654 require("pnpapi");
1655 isYarnPnP = true;
1656 } catch (e) {
1657 }
1658 if (isYarnPnP) {
1659 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
1660 const binTargetPath = path.join(esbuildLibDir, `pnpapi-${pkg}-${path.basename(subpath)}`);
1661 if (!fs.existsSync(binTargetPath)) {
1662 fs.copyFileSync(binPath, binTargetPath);
1663 fs.chmodSync(binTargetPath, 493);
1664 }
1665 return binTargetPath;
1666 }
1667 return binPath;
1668}
1669
1670// lib/npm/node.ts
1671var child_process = require("child_process");
1672var crypto = require("crypto");
1673var path2 = require("path");
1674var fs2 = require("fs");
1675var os2 = require("os");
1676var tty = require("tty");
1677var worker_threads;
1678if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1679 try {
1680 worker_threads = require("worker_threads");
1681 } catch (e) {
1682 }
1683 let [major, minor] = process.versions.node.split(".");
1684 if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
1685 worker_threads = void 0;
1686 }
1687}
1688var _a;
1689var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.13.8";
1690var esbuildCommandAndArgs = () => {
1691 if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
1692 throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
1693
1694More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
1695 }
1696 if (false) {
1697 return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
1698 }
1699 return [generateBinPath(), []];
1700};
1701var isTTY = () => tty.isatty(2);
1702var fsSync = {
1703 readFile(tempFile, callback) {
1704 try {
1705 let contents = fs2.readFileSync(tempFile, "utf8");
1706 try {
1707 fs2.unlinkSync(tempFile);
1708 } catch (e) {
1709 }
1710 callback(null, contents);
1711 } catch (err) {
1712 callback(err, null);
1713 }
1714 },
1715 writeFile(contents, callback) {
1716 try {
1717 let tempFile = randomFileName();
1718 fs2.writeFileSync(tempFile, contents);
1719 callback(tempFile);
1720 } catch (e) {
1721 callback(null);
1722 }
1723 }
1724};
1725var fsAsync = {
1726 readFile(tempFile, callback) {
1727 try {
1728 fs2.readFile(tempFile, "utf8", (err, contents) => {
1729 try {
1730 fs2.unlink(tempFile, () => callback(err, contents));
1731 } catch (e) {
1732 callback(err, contents);
1733 }
1734 });
1735 } catch (err) {
1736 callback(err, null);
1737 }
1738 },
1739 writeFile(contents, callback) {
1740 try {
1741 let tempFile = randomFileName();
1742 fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
1743 } catch (e) {
1744 callback(null);
1745 }
1746 }
1747};
1748var version = "0.13.8";
1749var build = (options) => ensureServiceIsRunning().build(options);
1750var serve = (serveOptions, buildOptions) => ensureServiceIsRunning().serve(serveOptions, buildOptions);
1751var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1752var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1753var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
1754var buildSync = (options) => {
1755 if (worker_threads && !isInternalWorkerThread) {
1756 if (!workerThreadService)
1757 workerThreadService = startWorkerThreadService(worker_threads);
1758 return workerThreadService.buildSync(options);
1759 }
1760 let result;
1761 runServiceSync((service) => service.buildOrServe({
1762 callName: "buildSync",
1763 refs: null,
1764 serveOptions: null,
1765 options,
1766 isTTY: isTTY(),
1767 defaultWD,
1768 callback: (err, res) => {
1769 if (err)
1770 throw err;
1771 result = res;
1772 }
1773 }));
1774 return result;
1775};
1776var transformSync = (input, options) => {
1777 if (worker_threads && !isInternalWorkerThread) {
1778 if (!workerThreadService)
1779 workerThreadService = startWorkerThreadService(worker_threads);
1780 return workerThreadService.transformSync(input, options);
1781 }
1782 let result;
1783 runServiceSync((service) => service.transform({
1784 callName: "transformSync",
1785 refs: null,
1786 input,
1787 options: options || {},
1788 isTTY: isTTY(),
1789 fs: fsSync,
1790 callback: (err, res) => {
1791 if (err)
1792 throw err;
1793 result = res;
1794 }
1795 }));
1796 return result;
1797};
1798var formatMessagesSync = (messages, options) => {
1799 if (worker_threads && !isInternalWorkerThread) {
1800 if (!workerThreadService)
1801 workerThreadService = startWorkerThreadService(worker_threads);
1802 return workerThreadService.formatMessagesSync(messages, options);
1803 }
1804 let result;
1805 runServiceSync((service) => service.formatMessages({
1806 callName: "formatMessagesSync",
1807 refs: null,
1808 messages,
1809 options,
1810 callback: (err, res) => {
1811 if (err)
1812 throw err;
1813 result = res;
1814 }
1815 }));
1816 return result;
1817};
1818var analyzeMetafileSync = (metafile, options) => {
1819 if (worker_threads && !isInternalWorkerThread) {
1820 if (!workerThreadService)
1821 workerThreadService = startWorkerThreadService(worker_threads);
1822 return workerThreadService.analyzeMetafileSync(metafile, options);
1823 }
1824 let result;
1825 runServiceSync((service) => service.analyzeMetafile({
1826 callName: "analyzeMetafileSync",
1827 refs: null,
1828 metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
1829 options,
1830 callback: (err, res) => {
1831 if (err)
1832 throw err;
1833 result = res;
1834 }
1835 }));
1836 return result;
1837};
1838var initializeWasCalled = false;
1839var initialize = (options) => {
1840 options = validateInitializeOptions(options || {});
1841 if (options.wasmURL)
1842 throw new Error(`The "wasmURL" option only works in the browser`);
1843 if (options.worker)
1844 throw new Error(`The "worker" option only works in the browser`);
1845 if (initializeWasCalled)
1846 throw new Error('Cannot call "initialize" more than once');
1847 ensureServiceIsRunning();
1848 initializeWasCalled = true;
1849 return Promise.resolve();
1850};
1851var defaultWD = process.cwd();
1852var longLivedService;
1853var ensureServiceIsRunning = () => {
1854 if (longLivedService)
1855 return longLivedService;
1856 let [command, args] = esbuildCommandAndArgs();
1857 let child = child_process.spawn(command, args.concat(`--service=${"0.13.8"}`, "--ping"), {
1858 windowsHide: true,
1859 stdio: ["pipe", "pipe", "inherit"],
1860 cwd: defaultWD
1861 });
1862 let { readFromStdout, afterClose, service } = createChannel({
1863 writeToStdin(bytes) {
1864 child.stdin.write(bytes);
1865 },
1866 readFileSync: fs2.readFileSync,
1867 isSync: false,
1868 isBrowser: false
1869 });
1870 const stdin = child.stdin;
1871 const stdout = child.stdout;
1872 stdout.on("data", readFromStdout);
1873 stdout.on("end", afterClose);
1874 let refCount = 0;
1875 child.unref();
1876 if (stdin.unref) {
1877 stdin.unref();
1878 }
1879 if (stdout.unref) {
1880 stdout.unref();
1881 }
1882 const refs = {
1883 ref() {
1884 if (++refCount === 1)
1885 child.ref();
1886 },
1887 unref() {
1888 if (--refCount === 0)
1889 child.unref();
1890 }
1891 };
1892 longLivedService = {
1893 build: (options) => {
1894 return new Promise((resolve, reject) => {
1895 service.buildOrServe({
1896 callName: "build",
1897 refs,
1898 serveOptions: null,
1899 options,
1900 isTTY: isTTY(),
1901 defaultWD,
1902 callback: (err, res) => err ? reject(err) : resolve(res)
1903 });
1904 });
1905 },
1906 serve: (serveOptions, buildOptions) => {
1907 if (serveOptions === null || typeof serveOptions !== "object")
1908 throw new Error("The first argument must be an object");
1909 return new Promise((resolve, reject) => service.buildOrServe({
1910 callName: "serve",
1911 refs,
1912 serveOptions,
1913 options: buildOptions,
1914 isTTY: isTTY(),
1915 defaultWD,
1916 callback: (err, res) => err ? reject(err) : resolve(res)
1917 }));
1918 },
1919 transform: (input, options) => {
1920 return new Promise((resolve, reject) => service.transform({
1921 callName: "transform",
1922 refs,
1923 input,
1924 options: options || {},
1925 isTTY: isTTY(),
1926 fs: fsAsync,
1927 callback: (err, res) => err ? reject(err) : resolve(res)
1928 }));
1929 },
1930 formatMessages: (messages, options) => {
1931 return new Promise((resolve, reject) => service.formatMessages({
1932 callName: "formatMessages",
1933 refs,
1934 messages,
1935 options,
1936 callback: (err, res) => err ? reject(err) : resolve(res)
1937 }));
1938 },
1939 analyzeMetafile: (metafile, options) => {
1940 return new Promise((resolve, reject) => service.analyzeMetafile({
1941 callName: "analyzeMetafile",
1942 refs,
1943 metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
1944 options,
1945 callback: (err, res) => err ? reject(err) : resolve(res)
1946 }));
1947 }
1948 };
1949 return longLivedService;
1950};
1951var runServiceSync = (callback) => {
1952 let [command, args] = esbuildCommandAndArgs();
1953 let stdin = new Uint8Array();
1954 let { readFromStdout, afterClose, service } = createChannel({
1955 writeToStdin(bytes) {
1956 if (stdin.length !== 0)
1957 throw new Error("Must run at most one command");
1958 stdin = bytes;
1959 },
1960 isSync: true,
1961 isBrowser: false
1962 });
1963 callback(service);
1964 let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.13.8"}`), {
1965 cwd: defaultWD,
1966 windowsHide: true,
1967 input: stdin,
1968 maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
1969 });
1970 readFromStdout(stdout);
1971 afterClose();
1972};
1973var randomFileName = () => {
1974 return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
1975};
1976var workerThreadService = null;
1977var startWorkerThreadService = (worker_threads2) => {
1978 let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
1979 let worker = new worker_threads2.Worker(__filename, {
1980 workerData: { workerPort, defaultWD, esbuildVersion: "0.13.8" },
1981 transferList: [workerPort],
1982 execArgv: []
1983 });
1984 let nextID = 0;
1985 let wasStopped = false;
1986 let fakeBuildError = (text) => {
1987 let error = new Error(`Build failed with 1 error:
1988error: ${text}`);
1989 let errors = [{ pluginName: "", text, location: null, notes: [], detail: void 0 }];
1990 error.errors = errors;
1991 error.warnings = [];
1992 return error;
1993 };
1994 let validateBuildSyncOptions = (options) => {
1995 if (!options)
1996 return;
1997 let plugins = options.plugins;
1998 let incremental = options.incremental;
1999 let watch = options.watch;
2000 if (plugins && plugins.length > 0)
2001 throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2002 if (incremental)
2003 throw fakeBuildError(`Cannot use "incremental" with a synchronous build`);
2004 if (watch)
2005 throw fakeBuildError(`Cannot use "watch" with a synchronous build`);
2006 };
2007 let applyProperties = (object, properties) => {
2008 for (let key in properties) {
2009 object[key] = properties[key];
2010 }
2011 };
2012 let runCallSync = (command, args) => {
2013 if (wasStopped)
2014 throw new Error("The service was stopped");
2015 let id = nextID++;
2016 let sharedBuffer = new SharedArrayBuffer(8);
2017 let sharedBufferView = new Int32Array(sharedBuffer);
2018 let msg = { sharedBuffer, id, command, args };
2019 worker.postMessage(msg);
2020 let status = Atomics.wait(sharedBufferView, 0, 0);
2021 if (status !== "ok" && status !== "not-equal")
2022 throw new Error("Internal error: Atomics.wait() failed: " + status);
2023 let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2024 if (id !== id2)
2025 throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2026 if (reject) {
2027 applyProperties(reject, properties);
2028 throw reject;
2029 }
2030 return resolve;
2031 };
2032 worker.unref();
2033 return {
2034 buildSync(options) {
2035 validateBuildSyncOptions(options);
2036 return runCallSync("build", [options]);
2037 },
2038 transformSync(input, options) {
2039 return runCallSync("transform", [input, options]);
2040 },
2041 formatMessagesSync(messages, options) {
2042 return runCallSync("formatMessages", [messages, options]);
2043 },
2044 analyzeMetafileSync(metafile, options) {
2045 return runCallSync("analyzeMetafile", [metafile, options]);
2046 }
2047 };
2048};
2049var startSyncServiceWorker = () => {
2050 let workerPort = worker_threads.workerData.workerPort;
2051 let parentPort = worker_threads.parentPort;
2052 let service = ensureServiceIsRunning();
2053 defaultWD = worker_threads.workerData.defaultWD;
2054 let extractProperties = (object) => {
2055 let properties = {};
2056 if (object && typeof object === "object") {
2057 for (let key in object) {
2058 properties[key] = object[key];
2059 }
2060 }
2061 return properties;
2062 };
2063 parentPort.on("message", (msg) => {
2064 (async () => {
2065 let { sharedBuffer, id, command, args } = msg;
2066 let sharedBufferView = new Int32Array(sharedBuffer);
2067 try {
2068 switch (command) {
2069 case "build":
2070 workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2071 break;
2072 case "transform":
2073 workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2074 break;
2075 case "formatMessages":
2076 workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2077 break;
2078 case "analyzeMetafile":
2079 workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2080 break;
2081 default:
2082 throw new Error(`Invalid command: ${command}`);
2083 }
2084 } catch (reject) {
2085 workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2086 }
2087 Atomics.add(sharedBufferView, 0, 1);
2088 Atomics.notify(sharedBufferView, 0, Infinity);
2089 })();
2090 });
2091};
2092if (isInternalWorkerThread) {
2093 startSyncServiceWorker();
2094}
2095// Annotate the CommonJS export names for ESM import in node:
20960 && (module.exports = {
2097 analyzeMetafile,
2098 analyzeMetafileSync,
2099 build,
2100 buildSync,
2101 formatMessages,
2102 formatMessagesSync,
2103 initialize,
2104 serve,
2105 transform,
2106 transformSync,
2107 version
2108});
Note: See TracBrowser for help on using the repository browser.