source: node_modules/esbuild/lib/main.js

Last change on this file was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

  • Property mode set to 100644
File size: 85.8 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.24.2") {
666 throw new Error(`Cannot start service: Host version "${"0.24.2"}" 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 details.clear();
1202 let response = { errors: [], warnings: [] };
1203 await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1204 try {
1205 let result = await callback();
1206 if (result != null) {
1207 if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1208 let keys = {};
1209 let errors = getFlag(result, keys, "errors", mustBeArray);
1210 let warnings = getFlag(result, keys, "warnings", mustBeArray);
1211 checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1212 if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1213 if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1214 }
1215 } catch (e) {
1216 response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1217 }
1218 }));
1219 sendResponse(id, response);
1220 };
1221 requestCallbacks["on-resolve"] = async (id, request) => {
1222 let response = {}, name = "", callback, note;
1223 for (let id2 of request.ids) {
1224 try {
1225 ({ name, callback, note } = onResolveCallbacks[id2]);
1226 let result = await callback({
1227 path: request.path,
1228 importer: request.importer,
1229 namespace: request.namespace,
1230 resolveDir: request.resolveDir,
1231 kind: request.kind,
1232 pluginData: details.load(request.pluginData),
1233 with: request.with
1234 });
1235 if (result != null) {
1236 if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1237 let keys = {};
1238 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1239 let path3 = getFlag(result, keys, "path", mustBeString);
1240 let namespace = getFlag(result, keys, "namespace", mustBeString);
1241 let suffix = getFlag(result, keys, "suffix", mustBeString);
1242 let external = getFlag(result, keys, "external", mustBeBoolean);
1243 let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1244 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1245 let errors = getFlag(result, keys, "errors", mustBeArray);
1246 let warnings = getFlag(result, keys, "warnings", mustBeArray);
1247 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1248 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1249 checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1250 response.id = id2;
1251 if (pluginName != null) response.pluginName = pluginName;
1252 if (path3 != null) response.path = path3;
1253 if (namespace != null) response.namespace = namespace;
1254 if (suffix != null) response.suffix = suffix;
1255 if (external != null) response.external = external;
1256 if (sideEffects != null) response.sideEffects = sideEffects;
1257 if (pluginData != null) response.pluginData = details.store(pluginData);
1258 if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1259 if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1260 if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1261 if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1262 break;
1263 }
1264 } catch (e) {
1265 response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1266 break;
1267 }
1268 }
1269 sendResponse(id, response);
1270 };
1271 requestCallbacks["on-load"] = async (id, request) => {
1272 let response = {}, name = "", callback, note;
1273 for (let id2 of request.ids) {
1274 try {
1275 ({ name, callback, note } = onLoadCallbacks[id2]);
1276 let result = await callback({
1277 path: request.path,
1278 namespace: request.namespace,
1279 suffix: request.suffix,
1280 pluginData: details.load(request.pluginData),
1281 with: request.with
1282 });
1283 if (result != null) {
1284 if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1285 let keys = {};
1286 let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1287 let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1288 let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1289 let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1290 let loader = getFlag(result, keys, "loader", mustBeString);
1291 let errors = getFlag(result, keys, "errors", mustBeArray);
1292 let warnings = getFlag(result, keys, "warnings", mustBeArray);
1293 let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1294 let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1295 checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1296 response.id = id2;
1297 if (pluginName != null) response.pluginName = pluginName;
1298 if (contents instanceof Uint8Array) response.contents = contents;
1299 else if (contents != null) response.contents = encodeUTF8(contents);
1300 if (resolveDir != null) response.resolveDir = resolveDir;
1301 if (pluginData != null) response.pluginData = details.store(pluginData);
1302 if (loader != null) response.loader = loader;
1303 if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1304 if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1305 if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1306 if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1307 break;
1308 }
1309 } catch (e) {
1310 response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1311 break;
1312 }
1313 }
1314 sendResponse(id, response);
1315 };
1316 let runOnEndCallbacks = (result, done) => done([], []);
1317 if (onEndCallbacks.length > 0) {
1318 runOnEndCallbacks = (result, done) => {
1319 (async () => {
1320 const onEndErrors = [];
1321 const onEndWarnings = [];
1322 for (const { name, callback, note } of onEndCallbacks) {
1323 let newErrors;
1324 let newWarnings;
1325 try {
1326 const value = await callback(result);
1327 if (value != null) {
1328 if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1329 let keys = {};
1330 let errors = getFlag(value, keys, "errors", mustBeArray);
1331 let warnings = getFlag(value, keys, "warnings", mustBeArray);
1332 checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1333 if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1334 if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1335 }
1336 } catch (e) {
1337 newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1338 }
1339 if (newErrors) {
1340 onEndErrors.push(...newErrors);
1341 try {
1342 result.errors.push(...newErrors);
1343 } catch {
1344 }
1345 }
1346 if (newWarnings) {
1347 onEndWarnings.push(...newWarnings);
1348 try {
1349 result.warnings.push(...newWarnings);
1350 } catch {
1351 }
1352 }
1353 }
1354 done(onEndErrors, onEndWarnings);
1355 })();
1356 };
1357 }
1358 let scheduleOnDisposeCallbacks = () => {
1359 for (const cb of onDisposeCallbacks) {
1360 setTimeout(() => cb(), 0);
1361 }
1362 };
1363 isSetupDone = true;
1364 return {
1365 ok: true,
1366 requestPlugins,
1367 runOnEndCallbacks,
1368 scheduleOnDisposeCallbacks
1369 };
1370};
1371function createObjectStash() {
1372 const map = /* @__PURE__ */ new Map();
1373 let nextID = 0;
1374 return {
1375 clear() {
1376 map.clear();
1377 },
1378 load(id) {
1379 return map.get(id);
1380 },
1381 store(value) {
1382 if (value === void 0) return -1;
1383 const id = nextID++;
1384 map.set(id, value);
1385 return id;
1386 }
1387 };
1388}
1389function extractCallerV8(e, streamIn, ident) {
1390 let note;
1391 let tried = false;
1392 return () => {
1393 if (tried) return note;
1394 tried = true;
1395 try {
1396 let lines = (e.stack + "").split("\n");
1397 lines.splice(1, 1);
1398 let location = parseStackLinesV8(streamIn, lines, ident);
1399 if (location) {
1400 note = { text: e.message, location };
1401 return note;
1402 }
1403 } catch {
1404 }
1405 };
1406}
1407function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1408 let text = "Internal error";
1409 let location = null;
1410 try {
1411 text = (e && e.message || e) + "";
1412 } catch {
1413 }
1414 try {
1415 location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1416 } catch {
1417 }
1418 return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1419}
1420function parseStackLinesV8(streamIn, lines, ident) {
1421 let at = " at ";
1422 if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1423 for (let i = 1; i < lines.length; i++) {
1424 let line = lines[i];
1425 if (!line.startsWith(at)) continue;
1426 line = line.slice(at.length);
1427 while (true) {
1428 let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1429 if (match) {
1430 line = match[1];
1431 continue;
1432 }
1433 match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1434 if (match) {
1435 line = match[1];
1436 continue;
1437 }
1438 match = /^(\S+):(\d+):(\d+)$/.exec(line);
1439 if (match) {
1440 let contents;
1441 try {
1442 contents = streamIn.readFileSync(match[1], "utf8");
1443 } catch {
1444 break;
1445 }
1446 let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1447 let column = +match[3] - 1;
1448 let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1449 return {
1450 file: match[1],
1451 namespace: "file",
1452 line: +match[2],
1453 column: encodeUTF8(lineText.slice(0, column)).length,
1454 length: encodeUTF8(lineText.slice(column, column + length)).length,
1455 lineText: lineText + "\n" + lines.slice(1).join("\n"),
1456 suggestion: ""
1457 };
1458 }
1459 break;
1460 }
1461 }
1462 }
1463 return null;
1464}
1465function failureErrorWithLog(text, errors, warnings) {
1466 let limit = 5;
1467 text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1468 if (i === limit) return "\n...";
1469 if (!e.location) return `
1470error: ${e.text}`;
1471 let { file, line, column } = e.location;
1472 let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1473 return `
1474${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1475 }).join("");
1476 let error = new Error(text);
1477 for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1478 Object.defineProperty(error, key, {
1479 configurable: true,
1480 enumerable: true,
1481 get: () => value,
1482 set: (value2) => Object.defineProperty(error, key, {
1483 configurable: true,
1484 enumerable: true,
1485 value: value2
1486 })
1487 });
1488 }
1489 return error;
1490}
1491function replaceDetailsInMessages(messages, stash) {
1492 for (const message of messages) {
1493 message.detail = stash.load(message.detail);
1494 }
1495 return messages;
1496}
1497function sanitizeLocation(location, where, terminalWidth) {
1498 if (location == null) return null;
1499 let keys = {};
1500 let file = getFlag(location, keys, "file", mustBeString);
1501 let namespace = getFlag(location, keys, "namespace", mustBeString);
1502 let line = getFlag(location, keys, "line", mustBeInteger);
1503 let column = getFlag(location, keys, "column", mustBeInteger);
1504 let length = getFlag(location, keys, "length", mustBeInteger);
1505 let lineText = getFlag(location, keys, "lineText", mustBeString);
1506 let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1507 checkForInvalidFlags(location, keys, where);
1508 if (lineText) {
1509 const relevantASCII = lineText.slice(
1510 0,
1511 (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
1512 );
1513 if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1514 lineText = relevantASCII;
1515 }
1516 }
1517 return {
1518 file: file || "",
1519 namespace: namespace || "",
1520 line: line || 0,
1521 column: column || 0,
1522 length: length || 0,
1523 lineText: lineText || "",
1524 suggestion: suggestion || ""
1525 };
1526}
1527function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1528 let messagesClone = [];
1529 let index = 0;
1530 for (const message of messages) {
1531 let keys = {};
1532 let id = getFlag(message, keys, "id", mustBeString);
1533 let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1534 let text = getFlag(message, keys, "text", mustBeString);
1535 let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1536 let notes = getFlag(message, keys, "notes", mustBeArray);
1537 let detail = getFlag(message, keys, "detail", canBeAnything);
1538 let where = `in element ${index} of "${property}"`;
1539 checkForInvalidFlags(message, keys, where);
1540 let notesClone = [];
1541 if (notes) {
1542 for (const note of notes) {
1543 let noteKeys = {};
1544 let noteText = getFlag(note, noteKeys, "text", mustBeString);
1545 let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1546 checkForInvalidFlags(note, noteKeys, where);
1547 notesClone.push({
1548 text: noteText || "",
1549 location: sanitizeLocation(noteLocation, where, terminalWidth)
1550 });
1551 }
1552 }
1553 messagesClone.push({
1554 id: id || "",
1555 pluginName: pluginName || fallbackPluginName,
1556 text: text || "",
1557 location: sanitizeLocation(location, where, terminalWidth),
1558 notes: notesClone,
1559 detail: stash ? stash.store(detail) : -1
1560 });
1561 index++;
1562 }
1563 return messagesClone;
1564}
1565function sanitizeStringArray(values, property) {
1566 const result = [];
1567 for (const value of values) {
1568 if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1569 result.push(value);
1570 }
1571 return result;
1572}
1573function sanitizeStringMap(map, property) {
1574 const result = /* @__PURE__ */ Object.create(null);
1575 for (const key in map) {
1576 const value = map[key];
1577 if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1578 result[key] = value;
1579 }
1580 return result;
1581}
1582function convertOutputFiles({ path: path3, contents, hash }) {
1583 let text = null;
1584 return {
1585 path: path3,
1586 contents,
1587 hash,
1588 get text() {
1589 const binary = this.contents;
1590 if (text === null || binary !== contents) {
1591 contents = binary;
1592 text = decodeUTF8(binary);
1593 }
1594 return text;
1595 }
1596 };
1597}
1598
1599// lib/npm/node-platform.ts
1600var fs = require("fs");
1601var os = require("os");
1602var path = require("path");
1603var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1604var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1605var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1606var packageDarwin_x64 = "@esbuild/darwin-x64";
1607var knownWindowsPackages = {
1608 "win32 arm64 LE": "@esbuild/win32-arm64",
1609 "win32 ia32 LE": "@esbuild/win32-ia32",
1610 "win32 x64 LE": "@esbuild/win32-x64"
1611};
1612var knownUnixlikePackages = {
1613 "aix ppc64 BE": "@esbuild/aix-ppc64",
1614 "android arm64 LE": "@esbuild/android-arm64",
1615 "darwin arm64 LE": "@esbuild/darwin-arm64",
1616 "darwin x64 LE": "@esbuild/darwin-x64",
1617 "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1618 "freebsd x64 LE": "@esbuild/freebsd-x64",
1619 "linux arm LE": "@esbuild/linux-arm",
1620 "linux arm64 LE": "@esbuild/linux-arm64",
1621 "linux ia32 LE": "@esbuild/linux-ia32",
1622 "linux mips64el LE": "@esbuild/linux-mips64el",
1623 "linux ppc64 LE": "@esbuild/linux-ppc64",
1624 "linux riscv64 LE": "@esbuild/linux-riscv64",
1625 "linux s390x BE": "@esbuild/linux-s390x",
1626 "linux x64 LE": "@esbuild/linux-x64",
1627 "linux loong64 LE": "@esbuild/linux-loong64",
1628 "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1629 "netbsd x64 LE": "@esbuild/netbsd-x64",
1630 "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1631 "openbsd x64 LE": "@esbuild/openbsd-x64",
1632 "sunos x64 LE": "@esbuild/sunos-x64"
1633};
1634var knownWebAssemblyFallbackPackages = {
1635 "android arm LE": "@esbuild/android-arm",
1636 "android x64 LE": "@esbuild/android-x64"
1637};
1638function pkgAndSubpathForCurrentPlatform() {
1639 let pkg;
1640 let subpath;
1641 let isWASM = false;
1642 let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1643 if (platformKey in knownWindowsPackages) {
1644 pkg = knownWindowsPackages[platformKey];
1645 subpath = "esbuild.exe";
1646 } else if (platformKey in knownUnixlikePackages) {
1647 pkg = knownUnixlikePackages[platformKey];
1648 subpath = "bin/esbuild";
1649 } else if (platformKey in knownWebAssemblyFallbackPackages) {
1650 pkg = knownWebAssemblyFallbackPackages[platformKey];
1651 subpath = "bin/esbuild";
1652 isWASM = true;
1653 } else {
1654 throw new Error(`Unsupported platform: ${platformKey}`);
1655 }
1656 return { pkg, subpath, isWASM };
1657}
1658function pkgForSomeOtherPlatform() {
1659 const libMainJS = require.resolve("esbuild");
1660 const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
1661 if (path.basename(nodeModulesDirectory) === "node_modules") {
1662 for (const unixKey in knownUnixlikePackages) {
1663 try {
1664 const pkg = knownUnixlikePackages[unixKey];
1665 if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
1666 } catch {
1667 }
1668 }
1669 for (const windowsKey in knownWindowsPackages) {
1670 try {
1671 const pkg = knownWindowsPackages[windowsKey];
1672 if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
1673 } catch {
1674 }
1675 }
1676 }
1677 return null;
1678}
1679function downloadedBinPath(pkg, subpath) {
1680 const esbuildLibDir = path.dirname(require.resolve("esbuild"));
1681 return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
1682}
1683function generateBinPath() {
1684 if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1685 if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
1686 console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1687 } else {
1688 return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1689 }
1690 }
1691 const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1692 let binPath;
1693 try {
1694 binPath = require.resolve(`${pkg}/${subpath}`);
1695 } catch (e) {
1696 binPath = downloadedBinPath(pkg, subpath);
1697 if (!fs.existsSync(binPath)) {
1698 try {
1699 require.resolve(pkg);
1700 } catch {
1701 const otherPkg = pkgForSomeOtherPlatform();
1702 if (otherPkg) {
1703 let suggestions = `
1704Specifically the "${otherPkg}" package is present but this platform
1705needs the "${pkg}" package instead. People often get into this
1706situation by installing esbuild on Windows or macOS and copying "node_modules"
1707into a Docker image that runs Linux, or by copying "node_modules" between
1708Windows and WSL environments.
1709
1710If you are installing with npm, you can try not copying the "node_modules"
1711directory when you copy the files over, and running "npm ci" or "npm install"
1712on the destination platform after the copy. Or you could consider using yarn
1713instead of npm which has built-in support for installing a package on multiple
1714platforms simultaneously.
1715
1716If you are installing with yarn, you can try listing both this platform and the
1717other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1718feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1719Keep in mind that this means multiple copies of esbuild will be present.
1720`;
1721 if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
1722 suggestions = `
1723Specifically the "${otherPkg}" package is present but this platform
1724needs the "${pkg}" package instead. People often get into this
1725situation by installing esbuild with npm running inside of Rosetta 2 and then
1726trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
17272 is Apple's on-the-fly x86_64-to-arm64 translation service).
1728
1729If you are installing with npm, you can try ensuring that both npm and node are
1730not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1731changing how you installed npm and/or node. For example, installing node with
1732the universal installer here should work: https://nodejs.org/en/download/. Or
1733you could consider using yarn instead of npm which has built-in support for
1734installing a package on multiple platforms simultaneously.
1735
1736If you are installing with yarn, you can try listing both "arm64" and "x64"
1737in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1738https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1739Keep in mind that this means multiple copies of esbuild will be present.
1740`;
1741 }
1742 throw new Error(`
1743You installed esbuild for another platform than the one you're currently using.
1744This won't work because esbuild is written with native code and needs to
1745install a platform-specific binary executable.
1746${suggestions}
1747Another alternative is to use the "esbuild-wasm" package instead, which works
1748the same way on all platforms. But it comes with a heavy performance cost and
1749can sometimes be 10x slower than the "esbuild" package, so you may also not
1750want to do that.
1751`);
1752 }
1753 throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1754
1755If you are installing esbuild with npm, make sure that you don't specify the
1756"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1757of "package.json" is used by esbuild to install the correct binary executable
1758for your current platform.`);
1759 }
1760 throw e;
1761 }
1762 }
1763 if (/\.zip\//.test(binPath)) {
1764 let pnpapi;
1765 try {
1766 pnpapi = require("pnpapi");
1767 } catch (e) {
1768 }
1769 if (pnpapi) {
1770 const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1771 const binTargetPath = path.join(
1772 root,
1773 "node_modules",
1774 ".cache",
1775 "esbuild",
1776 `pnpapi-${pkg.replace("/", "-")}-${"0.24.2"}-${path.basename(subpath)}`
1777 );
1778 if (!fs.existsSync(binTargetPath)) {
1779 fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
1780 fs.copyFileSync(binPath, binTargetPath);
1781 fs.chmodSync(binTargetPath, 493);
1782 }
1783 return { binPath: binTargetPath, isWASM };
1784 }
1785 }
1786 return { binPath, isWASM };
1787}
1788
1789// lib/npm/node.ts
1790var child_process = require("child_process");
1791var crypto = require("crypto");
1792var path2 = require("path");
1793var fs2 = require("fs");
1794var os2 = require("os");
1795var tty = require("tty");
1796var worker_threads;
1797if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1798 try {
1799 worker_threads = require("worker_threads");
1800 } catch {
1801 }
1802 let [major, minor] = process.versions.node.split(".");
1803 if (
1804 // <v12.17.0 does not work
1805 +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
1806 ) {
1807 worker_threads = void 0;
1808 }
1809}
1810var _a;
1811var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.24.2";
1812var esbuildCommandAndArgs = () => {
1813 if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
1814 throw new Error(
1815 `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
1816
1817More 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.`
1818 );
1819 }
1820 if (false) {
1821 return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]];
1822 } else {
1823 const { binPath, isWASM } = generateBinPath();
1824 if (isWASM) {
1825 return ["node", [binPath]];
1826 } else {
1827 return [binPath, []];
1828 }
1829 }
1830};
1831var isTTY = () => tty.isatty(2);
1832var fsSync = {
1833 readFile(tempFile, callback) {
1834 try {
1835 let contents = fs2.readFileSync(tempFile, "utf8");
1836 try {
1837 fs2.unlinkSync(tempFile);
1838 } catch {
1839 }
1840 callback(null, contents);
1841 } catch (err) {
1842 callback(err, null);
1843 }
1844 },
1845 writeFile(contents, callback) {
1846 try {
1847 let tempFile = randomFileName();
1848 fs2.writeFileSync(tempFile, contents);
1849 callback(tempFile);
1850 } catch {
1851 callback(null);
1852 }
1853 }
1854};
1855var fsAsync = {
1856 readFile(tempFile, callback) {
1857 try {
1858 fs2.readFile(tempFile, "utf8", (err, contents) => {
1859 try {
1860 fs2.unlink(tempFile, () => callback(err, contents));
1861 } catch {
1862 callback(err, contents);
1863 }
1864 });
1865 } catch (err) {
1866 callback(err, null);
1867 }
1868 },
1869 writeFile(contents, callback) {
1870 try {
1871 let tempFile = randomFileName();
1872 fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
1873 } catch {
1874 callback(null);
1875 }
1876 }
1877};
1878var version = "0.24.2";
1879var build = (options) => ensureServiceIsRunning().build(options);
1880var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
1881var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
1882var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
1883var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
1884var buildSync = (options) => {
1885 if (worker_threads && !isInternalWorkerThread) {
1886 if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1887 return workerThreadService.buildSync(options);
1888 }
1889 let result;
1890 runServiceSync((service) => service.buildOrContext({
1891 callName: "buildSync",
1892 refs: null,
1893 options,
1894 isTTY: isTTY(),
1895 defaultWD,
1896 callback: (err, res) => {
1897 if (err) throw err;
1898 result = res;
1899 }
1900 }));
1901 return result;
1902};
1903var transformSync = (input, options) => {
1904 if (worker_threads && !isInternalWorkerThread) {
1905 if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1906 return workerThreadService.transformSync(input, options);
1907 }
1908 let result;
1909 runServiceSync((service) => service.transform({
1910 callName: "transformSync",
1911 refs: null,
1912 input,
1913 options: options || {},
1914 isTTY: isTTY(),
1915 fs: fsSync,
1916 callback: (err, res) => {
1917 if (err) throw err;
1918 result = res;
1919 }
1920 }));
1921 return result;
1922};
1923var formatMessagesSync = (messages, options) => {
1924 if (worker_threads && !isInternalWorkerThread) {
1925 if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1926 return workerThreadService.formatMessagesSync(messages, options);
1927 }
1928 let result;
1929 runServiceSync((service) => service.formatMessages({
1930 callName: "formatMessagesSync",
1931 refs: null,
1932 messages,
1933 options,
1934 callback: (err, res) => {
1935 if (err) throw err;
1936 result = res;
1937 }
1938 }));
1939 return result;
1940};
1941var analyzeMetafileSync = (metafile, options) => {
1942 if (worker_threads && !isInternalWorkerThread) {
1943 if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
1944 return workerThreadService.analyzeMetafileSync(metafile, options);
1945 }
1946 let result;
1947 runServiceSync((service) => service.analyzeMetafile({
1948 callName: "analyzeMetafileSync",
1949 refs: null,
1950 metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
1951 options,
1952 callback: (err, res) => {
1953 if (err) throw err;
1954 result = res;
1955 }
1956 }));
1957 return result;
1958};
1959var stop = () => {
1960 if (stopService) stopService();
1961 if (workerThreadService) workerThreadService.stop();
1962 return Promise.resolve();
1963};
1964var initializeWasCalled = false;
1965var initialize = (options) => {
1966 options = validateInitializeOptions(options || {});
1967 if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
1968 if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
1969 if (options.worker) throw new Error(`The "worker" option only works in the browser`);
1970 if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
1971 ensureServiceIsRunning();
1972 initializeWasCalled = true;
1973 return Promise.resolve();
1974};
1975var defaultWD = process.cwd();
1976var longLivedService;
1977var stopService;
1978var ensureServiceIsRunning = () => {
1979 if (longLivedService) return longLivedService;
1980 let [command, args] = esbuildCommandAndArgs();
1981 let child = child_process.spawn(command, args.concat(`--service=${"0.24.2"}`, "--ping"), {
1982 windowsHide: true,
1983 stdio: ["pipe", "pipe", "inherit"],
1984 cwd: defaultWD
1985 });
1986 let { readFromStdout, afterClose, service } = createChannel({
1987 writeToStdin(bytes) {
1988 child.stdin.write(bytes, (err) => {
1989 if (err) afterClose(err);
1990 });
1991 },
1992 readFileSync: fs2.readFileSync,
1993 isSync: false,
1994 hasFS: true,
1995 esbuild: node_exports
1996 });
1997 child.stdin.on("error", afterClose);
1998 child.on("error", afterClose);
1999 const stdin = child.stdin;
2000 const stdout = child.stdout;
2001 stdout.on("data", readFromStdout);
2002 stdout.on("end", afterClose);
2003 stopService = () => {
2004 stdin.destroy();
2005 stdout.destroy();
2006 child.kill();
2007 initializeWasCalled = false;
2008 longLivedService = void 0;
2009 stopService = void 0;
2010 };
2011 let refCount = 0;
2012 child.unref();
2013 if (stdin.unref) {
2014 stdin.unref();
2015 }
2016 if (stdout.unref) {
2017 stdout.unref();
2018 }
2019 const refs = {
2020 ref() {
2021 if (++refCount === 1) child.ref();
2022 },
2023 unref() {
2024 if (--refCount === 0) child.unref();
2025 }
2026 };
2027 longLivedService = {
2028 build: (options) => new Promise((resolve, reject) => {
2029 service.buildOrContext({
2030 callName: "build",
2031 refs,
2032 options,
2033 isTTY: isTTY(),
2034 defaultWD,
2035 callback: (err, res) => err ? reject(err) : resolve(res)
2036 });
2037 }),
2038 context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2039 callName: "context",
2040 refs,
2041 options,
2042 isTTY: isTTY(),
2043 defaultWD,
2044 callback: (err, res) => err ? reject(err) : resolve(res)
2045 })),
2046 transform: (input, options) => new Promise((resolve, reject) => service.transform({
2047 callName: "transform",
2048 refs,
2049 input,
2050 options: options || {},
2051 isTTY: isTTY(),
2052 fs: fsAsync,
2053 callback: (err, res) => err ? reject(err) : resolve(res)
2054 })),
2055 formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2056 callName: "formatMessages",
2057 refs,
2058 messages,
2059 options,
2060 callback: (err, res) => err ? reject(err) : resolve(res)
2061 })),
2062 analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2063 callName: "analyzeMetafile",
2064 refs,
2065 metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2066 options,
2067 callback: (err, res) => err ? reject(err) : resolve(res)
2068 }))
2069 };
2070 return longLivedService;
2071};
2072var runServiceSync = (callback) => {
2073 let [command, args] = esbuildCommandAndArgs();
2074 let stdin = new Uint8Array();
2075 let { readFromStdout, afterClose, service } = createChannel({
2076 writeToStdin(bytes) {
2077 if (stdin.length !== 0) throw new Error("Must run at most one command");
2078 stdin = bytes;
2079 },
2080 isSync: true,
2081 hasFS: true,
2082 esbuild: node_exports
2083 });
2084 callback(service);
2085 let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.24.2"}`), {
2086 cwd: defaultWD,
2087 windowsHide: true,
2088 input: stdin,
2089 // We don't know how large the output could be. If it's too large, the
2090 // command will fail with ENOBUFS. Reserve 16mb for now since that feels
2091 // like it should be enough. Also allow overriding this with an environment
2092 // variable.
2093 maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2094 });
2095 readFromStdout(stdout);
2096 afterClose(null);
2097};
2098var randomFileName = () => {
2099 return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2100};
2101var workerThreadService = null;
2102var startWorkerThreadService = (worker_threads2) => {
2103 let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2104 let worker = new worker_threads2.Worker(__filename, {
2105 workerData: { workerPort, defaultWD, esbuildVersion: "0.24.2" },
2106 transferList: [workerPort],
2107 // From node's documentation: https://nodejs.org/api/worker_threads.html
2108 //
2109 // Take care when launching worker threads from preload scripts (scripts loaded
2110 // and run using the `-r` command line flag). Unless the `execArgv` option is
2111 // explicitly set, new Worker threads automatically inherit the command line flags
2112 // from the running process and will preload the same preload scripts as the main
2113 // thread. If the preload script unconditionally launches a worker thread, every
2114 // thread spawned will spawn another until the application crashes.
2115 //
2116 execArgv: []
2117 });
2118 let nextID = 0;
2119 let fakeBuildError = (text) => {
2120 let error = new Error(`Build failed with 1 error:
2121error: ${text}`);
2122 let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
2123 error.errors = errors;
2124 error.warnings = [];
2125 return error;
2126 };
2127 let validateBuildSyncOptions = (options) => {
2128 if (!options) return;
2129 let plugins = options.plugins;
2130 if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2131 };
2132 let applyProperties = (object, properties) => {
2133 for (let key in properties) {
2134 object[key] = properties[key];
2135 }
2136 };
2137 let runCallSync = (command, args) => {
2138 let id = nextID++;
2139 let sharedBuffer = new SharedArrayBuffer(8);
2140 let sharedBufferView = new Int32Array(sharedBuffer);
2141 let msg = { sharedBuffer, id, command, args };
2142 worker.postMessage(msg);
2143 let status = Atomics.wait(sharedBufferView, 0, 0);
2144 if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2145 let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2146 if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2147 if (reject) {
2148 applyProperties(reject, properties);
2149 throw reject;
2150 }
2151 return resolve;
2152 };
2153 worker.unref();
2154 return {
2155 buildSync(options) {
2156 validateBuildSyncOptions(options);
2157 return runCallSync("build", [options]);
2158 },
2159 transformSync(input, options) {
2160 return runCallSync("transform", [input, options]);
2161 },
2162 formatMessagesSync(messages, options) {
2163 return runCallSync("formatMessages", [messages, options]);
2164 },
2165 analyzeMetafileSync(metafile, options) {
2166 return runCallSync("analyzeMetafile", [metafile, options]);
2167 },
2168 stop() {
2169 worker.terminate();
2170 workerThreadService = null;
2171 }
2172 };
2173};
2174var startSyncServiceWorker = () => {
2175 let workerPort = worker_threads.workerData.workerPort;
2176 let parentPort = worker_threads.parentPort;
2177 let extractProperties = (object) => {
2178 let properties = {};
2179 if (object && typeof object === "object") {
2180 for (let key in object) {
2181 properties[key] = object[key];
2182 }
2183 }
2184 return properties;
2185 };
2186 try {
2187 let service = ensureServiceIsRunning();
2188 defaultWD = worker_threads.workerData.defaultWD;
2189 parentPort.on("message", (msg) => {
2190 (async () => {
2191 let { sharedBuffer, id, command, args } = msg;
2192 let sharedBufferView = new Int32Array(sharedBuffer);
2193 try {
2194 switch (command) {
2195 case "build":
2196 workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2197 break;
2198 case "transform":
2199 workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2200 break;
2201 case "formatMessages":
2202 workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2203 break;
2204 case "analyzeMetafile":
2205 workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2206 break;
2207 default:
2208 throw new Error(`Invalid command: ${command}`);
2209 }
2210 } catch (reject) {
2211 workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2212 }
2213 Atomics.add(sharedBufferView, 0, 1);
2214 Atomics.notify(sharedBufferView, 0, Infinity);
2215 })();
2216 });
2217 } catch (reject) {
2218 parentPort.on("message", (msg) => {
2219 let { sharedBuffer, id } = msg;
2220 let sharedBufferView = new Int32Array(sharedBuffer);
2221 workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2222 Atomics.add(sharedBufferView, 0, 1);
2223 Atomics.notify(sharedBufferView, 0, Infinity);
2224 });
2225 }
2226};
2227if (isInternalWorkerThread) {
2228 startSyncServiceWorker();
2229}
2230var node_default = node_exports;
2231// Annotate the CommonJS export names for ESM import in node:
22320 && (module.exports = {
2233 analyzeMetafile,
2234 analyzeMetafileSync,
2235 build,
2236 buildSync,
2237 context,
2238 formatMessages,
2239 formatMessagesSync,
2240 initialize,
2241 stop,
2242 transform,
2243 transformSync,
2244 version
2245});
Note: See TracBrowser for help on using the repository browser.