source: imaps-frontend/node_modules/esbuild/lib/main.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

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