@shaper.org/vite-react-plugin 1.0.8 → 1.0.9

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