@wordpress-flow/cli 1.0.4 → 1.0.5

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.
@@ -0,0 +1,4385 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+
21
+ // ../../node_modules/esbuild/lib/main.js
22
+ var require_main = __commonJS((exports, module) => {
23
+ var __dirname = "/Users/pkrasinski/Clients/RekinySukcesu.pl/wordpress-test/node_modules/esbuild/lib", __filename = "/Users/pkrasinski/Clients/RekinySukcesu.pl/wordpress-test/node_modules/esbuild/lib/main.js";
24
+ var __defProp2 = Object.defineProperty;
25
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
26
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
27
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
28
+ var __export = (target, all) => {
29
+ for (var name in all)
30
+ __defProp2(target, name, { get: all[name], enumerable: true });
31
+ };
32
+ var __copyProps = (to, from, except, desc) => {
33
+ if (from && typeof from === "object" || typeof from === "function") {
34
+ for (let key of __getOwnPropNames2(from))
35
+ if (!__hasOwnProp2.call(to, key) && key !== except)
36
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
37
+ }
38
+ return to;
39
+ };
40
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
41
+ var node_exports = {};
42
+ __export(node_exports, {
43
+ analyzeMetafile: () => analyzeMetafile,
44
+ analyzeMetafileSync: () => analyzeMetafileSync,
45
+ build: () => build,
46
+ buildSync: () => buildSync,
47
+ context: () => context,
48
+ default: () => node_default,
49
+ formatMessages: () => formatMessages,
50
+ formatMessagesSync: () => formatMessagesSync,
51
+ initialize: () => initialize,
52
+ stop: () => stop,
53
+ transform: () => transform,
54
+ transformSync: () => transformSync,
55
+ version: () => version
56
+ });
57
+ module.exports = __toCommonJS(node_exports);
58
+ function encodePacket(packet) {
59
+ let visit = (value) => {
60
+ if (value === null) {
61
+ bb.write8(0);
62
+ } else if (typeof value === "boolean") {
63
+ bb.write8(1);
64
+ bb.write8(+value);
65
+ } else if (typeof value === "number") {
66
+ bb.write8(2);
67
+ bb.write32(value | 0);
68
+ } else if (typeof value === "string") {
69
+ bb.write8(3);
70
+ bb.write(encodeUTF8(value));
71
+ } else if (value instanceof Uint8Array) {
72
+ bb.write8(4);
73
+ bb.write(value);
74
+ } else if (value instanceof Array) {
75
+ bb.write8(5);
76
+ bb.write32(value.length);
77
+ for (let item of value) {
78
+ visit(item);
79
+ }
80
+ } else {
81
+ let keys = Object.keys(value);
82
+ bb.write8(6);
83
+ bb.write32(keys.length);
84
+ for (let key of keys) {
85
+ bb.write(encodeUTF8(key));
86
+ visit(value[key]);
87
+ }
88
+ }
89
+ };
90
+ let bb = new ByteBuffer;
91
+ bb.write32(0);
92
+ bb.write32(packet.id << 1 | +!packet.isRequest);
93
+ visit(packet.value);
94
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
95
+ return bb.buf.subarray(0, bb.len);
96
+ }
97
+ function decodePacket(bytes) {
98
+ let visit = () => {
99
+ switch (bb.read8()) {
100
+ case 0:
101
+ return null;
102
+ case 1:
103
+ return !!bb.read8();
104
+ case 2:
105
+ return bb.read32();
106
+ case 3:
107
+ return decodeUTF8(bb.read());
108
+ case 4:
109
+ return bb.read();
110
+ case 5: {
111
+ let count = bb.read32();
112
+ let value2 = [];
113
+ for (let i = 0;i < count; i++) {
114
+ value2.push(visit());
115
+ }
116
+ return value2;
117
+ }
118
+ case 6: {
119
+ let count = bb.read32();
120
+ let value2 = {};
121
+ for (let i = 0;i < count; i++) {
122
+ value2[decodeUTF8(bb.read())] = visit();
123
+ }
124
+ return value2;
125
+ }
126
+ default:
127
+ throw new Error("Invalid packet");
128
+ }
129
+ };
130
+ let bb = new ByteBuffer(bytes);
131
+ let id = bb.read32();
132
+ let isRequest = (id & 1) === 0;
133
+ id >>>= 1;
134
+ let value = visit();
135
+ if (bb.ptr !== bytes.length) {
136
+ throw new Error("Invalid packet");
137
+ }
138
+ return { id, isRequest, value };
139
+ }
140
+ var ByteBuffer = class {
141
+ constructor(buf = new Uint8Array(1024)) {
142
+ this.buf = buf;
143
+ this.len = 0;
144
+ this.ptr = 0;
145
+ }
146
+ _write(delta) {
147
+ if (this.len + delta > this.buf.length) {
148
+ let clone = new Uint8Array((this.len + delta) * 2);
149
+ clone.set(this.buf);
150
+ this.buf = clone;
151
+ }
152
+ this.len += delta;
153
+ return this.len - delta;
154
+ }
155
+ write8(value) {
156
+ let offset = this._write(1);
157
+ this.buf[offset] = value;
158
+ }
159
+ write32(value) {
160
+ let offset = this._write(4);
161
+ writeUInt32LE(this.buf, value, offset);
162
+ }
163
+ write(bytes) {
164
+ let offset = this._write(4 + bytes.length);
165
+ writeUInt32LE(this.buf, bytes.length, offset);
166
+ this.buf.set(bytes, offset + 4);
167
+ }
168
+ _read(delta) {
169
+ if (this.ptr + delta > this.buf.length) {
170
+ throw new Error("Invalid packet");
171
+ }
172
+ this.ptr += delta;
173
+ return this.ptr - delta;
174
+ }
175
+ read8() {
176
+ return this.buf[this._read(1)];
177
+ }
178
+ read32() {
179
+ return readUInt32LE(this.buf, this._read(4));
180
+ }
181
+ read() {
182
+ let length = this.read32();
183
+ let bytes = new Uint8Array(length);
184
+ let ptr = this._read(bytes.length);
185
+ bytes.set(this.buf.subarray(ptr, ptr + length));
186
+ return bytes;
187
+ }
188
+ };
189
+ var encodeUTF8;
190
+ var decodeUTF8;
191
+ var encodeInvariant;
192
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
193
+ let encoder = new TextEncoder;
194
+ let decoder = new TextDecoder;
195
+ encodeUTF8 = (text) => encoder.encode(text);
196
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
197
+ encodeInvariant = 'new TextEncoder().encode("")';
198
+ } else if (typeof Buffer !== "undefined") {
199
+ encodeUTF8 = (text) => Buffer.from(text);
200
+ decodeUTF8 = (bytes) => {
201
+ let { buffer, byteOffset, byteLength } = bytes;
202
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
203
+ };
204
+ encodeInvariant = 'Buffer.from("")';
205
+ } else {
206
+ throw new Error("No UTF-8 codec found");
207
+ }
208
+ if (!(encodeUTF8("") instanceof Uint8Array))
209
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
210
+
211
+ This indicates that your JavaScript environment is broken. You cannot use
212
+ esbuild in this environment because esbuild relies on this invariant. This
213
+ is not a problem with esbuild. You need to fix your environment instead.
214
+ `);
215
+ function readUInt32LE(buffer, offset) {
216
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
217
+ }
218
+ function writeUInt32LE(buffer, value, offset) {
219
+ buffer[offset++] = value;
220
+ buffer[offset++] = value >> 8;
221
+ buffer[offset++] = value >> 16;
222
+ buffer[offset++] = value >> 24;
223
+ }
224
+ var quote = JSON.stringify;
225
+ var buildLogLevelDefault = "warning";
226
+ var transformLogLevelDefault = "silent";
227
+ function validateTarget(target) {
228
+ validateStringValue(target, "target");
229
+ if (target.indexOf(",") >= 0)
230
+ throw new Error(`Invalid target: ${target}`);
231
+ return target;
232
+ }
233
+ var canBeAnything = () => null;
234
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
235
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
236
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
237
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
238
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
239
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
240
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
241
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
242
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
243
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
244
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
245
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
246
+ var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
247
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
248
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
249
+ function getFlag(object, keys, key, mustBeFn) {
250
+ let value = object[key];
251
+ keys[key + ""] = true;
252
+ if (value === undefined)
253
+ return;
254
+ let mustBe = mustBeFn(value);
255
+ if (mustBe !== null)
256
+ throw new Error(`${quote(key)} must be ${mustBe}`);
257
+ return value;
258
+ }
259
+ function checkForInvalidFlags(object, keys, where) {
260
+ for (let key in object) {
261
+ if (!(key in keys)) {
262
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
263
+ }
264
+ }
265
+ }
266
+ function validateInitializeOptions(options) {
267
+ let keys = /* @__PURE__ */ Object.create(null);
268
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
269
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
270
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
271
+ checkForInvalidFlags(options, keys, "in initialize() call");
272
+ return {
273
+ wasmURL,
274
+ wasmModule,
275
+ worker
276
+ };
277
+ }
278
+ function validateMangleCache(mangleCache) {
279
+ let validated;
280
+ if (mangleCache !== undefined) {
281
+ validated = /* @__PURE__ */ Object.create(null);
282
+ for (let key in mangleCache) {
283
+ let value = mangleCache[key];
284
+ if (typeof value === "string" || value === false) {
285
+ validated[key] = value;
286
+ } else {
287
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
288
+ }
289
+ }
290
+ }
291
+ return validated;
292
+ }
293
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
294
+ let color = getFlag(options, keys, "color", mustBeBoolean);
295
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
296
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
297
+ if (color !== undefined)
298
+ flags.push(`--color=${color}`);
299
+ else if (isTTY2)
300
+ 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") {
306
+ throw new Error(`Expected value for ${what}${key !== undefined ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
307
+ }
308
+ return value;
309
+ }
310
+ function pushCommonFlags(flags, options, keys) {
311
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
312
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
313
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
314
+ let target = getFlag(options, keys, "target", mustBeStringOrArray);
315
+ let format = getFlag(options, keys, "format", mustBeString);
316
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
317
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
318
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
319
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
320
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
321
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
322
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
323
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
324
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
325
+ let drop = getFlag(options, keys, "drop", mustBeArray);
326
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray);
327
+ let charset = getFlag(options, keys, "charset", mustBeString);
328
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
329
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
330
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
331
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
332
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
333
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
334
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
335
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
336
+ let define = getFlag(options, keys, "define", mustBeObject);
337
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
338
+ let supported = getFlag(options, keys, "supported", mustBeObject);
339
+ let pure = getFlag(options, keys, "pure", mustBeArray);
340
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
341
+ let platform = getFlag(options, keys, "platform", mustBeString);
342
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
343
+ if (legalComments)
344
+ flags.push(`--legal-comments=${legalComments}`);
345
+ if (sourceRoot !== undefined)
346
+ flags.push(`--source-root=${sourceRoot}`);
347
+ if (sourcesContent !== undefined)
348
+ flags.push(`--sources-content=${sourcesContent}`);
349
+ if (target) {
350
+ if (Array.isArray(target))
351
+ flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
352
+ else
353
+ flags.push(`--target=${validateTarget(target)}`);
354
+ }
355
+ if (format)
356
+ flags.push(`--format=${format}`);
357
+ if (globalName)
358
+ flags.push(`--global-name=${globalName}`);
359
+ if (platform)
360
+ flags.push(`--platform=${platform}`);
361
+ if (tsconfigRaw)
362
+ flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
363
+ if (minify)
364
+ flags.push("--minify");
365
+ if (minifySyntax)
366
+ flags.push("--minify-syntax");
367
+ if (minifyWhitespace)
368
+ flags.push("--minify-whitespace");
369
+ if (minifyIdentifiers)
370
+ flags.push("--minify-identifiers");
371
+ if (lineLimit)
372
+ flags.push(`--line-limit=${lineLimit}`);
373
+ if (charset)
374
+ flags.push(`--charset=${charset}`);
375
+ if (treeShaking !== undefined)
376
+ flags.push(`--tree-shaking=${treeShaking}`);
377
+ if (ignoreAnnotations)
378
+ flags.push(`--ignore-annotations`);
379
+ if (drop)
380
+ for (let what of drop)
381
+ flags.push(`--drop:${validateStringValue(what, "drop")}`);
382
+ if (dropLabels)
383
+ flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`);
384
+ if (mangleProps)
385
+ flags.push(`--mangle-props=${mangleProps.source}`);
386
+ if (reserveProps)
387
+ flags.push(`--reserve-props=${reserveProps.source}`);
388
+ if (mangleQuoted !== undefined)
389
+ flags.push(`--mangle-quoted=${mangleQuoted}`);
390
+ if (jsx)
391
+ flags.push(`--jsx=${jsx}`);
392
+ if (jsxFactory)
393
+ flags.push(`--jsx-factory=${jsxFactory}`);
394
+ if (jsxFragment)
395
+ flags.push(`--jsx-fragment=${jsxFragment}`);
396
+ if (jsxImportSource)
397
+ flags.push(`--jsx-import-source=${jsxImportSource}`);
398
+ if (jsxDev)
399
+ flags.push(`--jsx-dev`);
400
+ if (jsxSideEffects)
401
+ flags.push(`--jsx-side-effects`);
402
+ if (define) {
403
+ for (let key in define) {
404
+ if (key.indexOf("=") >= 0)
405
+ throw new Error(`Invalid define: ${key}`);
406
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
407
+ }
408
+ }
409
+ if (logOverride) {
410
+ for (let key in logOverride) {
411
+ if (key.indexOf("=") >= 0)
412
+ throw new Error(`Invalid log override: ${key}`);
413
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
414
+ }
415
+ }
416
+ if (supported) {
417
+ for (let key in supported) {
418
+ if (key.indexOf("=") >= 0)
419
+ throw new Error(`Invalid supported: ${key}`);
420
+ const value = supported[key];
421
+ if (typeof value !== "boolean")
422
+ throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
423
+ flags.push(`--supported:${key}=${value}`);
424
+ }
425
+ }
426
+ if (pure)
427
+ for (let fn of pure)
428
+ flags.push(`--pure:${validateStringValue(fn, "pure")}`);
429
+ if (keepNames)
430
+ flags.push(`--keep-names`);
431
+ }
432
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
433
+ var _a2;
434
+ let flags = [];
435
+ let entries = [];
436
+ let keys = /* @__PURE__ */ Object.create(null);
437
+ let stdinContents = null;
438
+ let stdinResolveDir = null;
439
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
440
+ pushCommonFlags(flags, options, keys);
441
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
442
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
443
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
444
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
445
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
446
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
447
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
448
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
449
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
450
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
451
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
452
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
453
+ let conditions = getFlag(options, keys, "conditions", mustBeArray);
454
+ let external = getFlag(options, keys, "external", mustBeArray);
455
+ let packages = getFlag(options, keys, "packages", mustBeString);
456
+ let alias = getFlag(options, keys, "alias", mustBeObject);
457
+ let loader = getFlag(options, keys, "loader", mustBeObject);
458
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
459
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
460
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
461
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
462
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
463
+ let inject = getFlag(options, keys, "inject", mustBeArray);
464
+ let banner = getFlag(options, keys, "banner", mustBeObject);
465
+ let footer = getFlag(options, keys, "footer", mustBeObject);
466
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
467
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
468
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
469
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
470
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
471
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
472
+ keys.plugins = true;
473
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
474
+ if (sourcemap)
475
+ flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
476
+ if (bundle)
477
+ flags.push("--bundle");
478
+ if (allowOverwrite)
479
+ flags.push("--allow-overwrite");
480
+ if (splitting)
481
+ flags.push("--splitting");
482
+ if (preserveSymlinks)
483
+ flags.push("--preserve-symlinks");
484
+ if (metafile)
485
+ flags.push(`--metafile`);
486
+ if (outfile)
487
+ flags.push(`--outfile=${outfile}`);
488
+ if (outdir)
489
+ flags.push(`--outdir=${outdir}`);
490
+ if (outbase)
491
+ flags.push(`--outbase=${outbase}`);
492
+ if (tsconfig)
493
+ flags.push(`--tsconfig=${tsconfig}`);
494
+ if (packages)
495
+ flags.push(`--packages=${packages}`);
496
+ if (resolveExtensions) {
497
+ let values = [];
498
+ for (let value of resolveExtensions) {
499
+ validateStringValue(value, "resolve extension");
500
+ if (value.indexOf(",") >= 0)
501
+ throw new Error(`Invalid resolve extension: ${value}`);
502
+ values.push(value);
503
+ }
504
+ flags.push(`--resolve-extensions=${values.join(",")}`);
505
+ }
506
+ if (publicPath)
507
+ flags.push(`--public-path=${publicPath}`);
508
+ if (entryNames)
509
+ flags.push(`--entry-names=${entryNames}`);
510
+ if (chunkNames)
511
+ flags.push(`--chunk-names=${chunkNames}`);
512
+ if (assetNames)
513
+ flags.push(`--asset-names=${assetNames}`);
514
+ if (mainFields) {
515
+ let values = [];
516
+ for (let value of mainFields) {
517
+ validateStringValue(value, "main field");
518
+ if (value.indexOf(",") >= 0)
519
+ throw new Error(`Invalid main field: ${value}`);
520
+ values.push(value);
521
+ }
522
+ flags.push(`--main-fields=${values.join(",")}`);
523
+ }
524
+ if (conditions) {
525
+ let values = [];
526
+ for (let value of conditions) {
527
+ validateStringValue(value, "condition");
528
+ if (value.indexOf(",") >= 0)
529
+ throw new Error(`Invalid condition: ${value}`);
530
+ values.push(value);
531
+ }
532
+ flags.push(`--conditions=${values.join(",")}`);
533
+ }
534
+ if (external)
535
+ for (let name of external)
536
+ flags.push(`--external:${validateStringValue(name, "external")}`);
537
+ if (alias) {
538
+ for (let old in alias) {
539
+ if (old.indexOf("=") >= 0)
540
+ throw new Error(`Invalid package name in alias: ${old}`);
541
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
542
+ }
543
+ }
544
+ if (banner) {
545
+ for (let type in banner) {
546
+ if (type.indexOf("=") >= 0)
547
+ throw new Error(`Invalid banner file type: ${type}`);
548
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
549
+ }
550
+ }
551
+ if (footer) {
552
+ for (let type in footer) {
553
+ if (type.indexOf("=") >= 0)
554
+ throw new Error(`Invalid footer file type: ${type}`);
555
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
556
+ }
557
+ }
558
+ if (inject)
559
+ for (let path3 of inject)
560
+ flags.push(`--inject:${validateStringValue(path3, "inject")}`);
561
+ if (loader) {
562
+ for (let ext in loader) {
563
+ if (ext.indexOf("=") >= 0)
564
+ throw new Error(`Invalid loader extension: ${ext}`);
565
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
566
+ }
567
+ }
568
+ if (outExtension) {
569
+ for (let ext in outExtension) {
570
+ if (ext.indexOf("=") >= 0)
571
+ throw new Error(`Invalid out extension: ${ext}`);
572
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
573
+ }
574
+ }
575
+ if (entryPoints) {
576
+ if (Array.isArray(entryPoints)) {
577
+ for (let i = 0, n = entryPoints.length;i < n; i++) {
578
+ let entryPoint = entryPoints[i];
579
+ if (typeof entryPoint === "object" && entryPoint !== null) {
580
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
581
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
582
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
583
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
584
+ if (input === undefined)
585
+ throw new Error('Missing property "in" for entry point at index ' + i);
586
+ if (output === undefined)
587
+ throw new Error('Missing property "out" for entry point at index ' + i);
588
+ entries.push([output, input]);
589
+ } else {
590
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
591
+ }
592
+ }
593
+ } else {
594
+ for (let key in entryPoints) {
595
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
596
+ }
597
+ }
598
+ }
599
+ if (stdin) {
600
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
601
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
602
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
603
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
604
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
605
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
606
+ if (sourcefile)
607
+ flags.push(`--sourcefile=${sourcefile}`);
608
+ if (loader2)
609
+ flags.push(`--loader=${loader2}`);
610
+ if (resolveDir)
611
+ stdinResolveDir = resolveDir;
612
+ if (typeof contents === "string")
613
+ stdinContents = encodeUTF8(contents);
614
+ else if (contents instanceof Uint8Array)
615
+ stdinContents = contents;
616
+ }
617
+ let nodePaths = [];
618
+ if (nodePathsInput) {
619
+ for (let value of nodePathsInput) {
620
+ value += "";
621
+ nodePaths.push(value);
622
+ }
623
+ }
624
+ return {
625
+ entries,
626
+ flags,
627
+ write,
628
+ stdinContents,
629
+ stdinResolveDir,
630
+ absWorkingDir,
631
+ nodePaths,
632
+ mangleCache: validateMangleCache(mangleCache)
633
+ };
634
+ }
635
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
636
+ let flags = [];
637
+ let keys = /* @__PURE__ */ Object.create(null);
638
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
639
+ pushCommonFlags(flags, options, keys);
640
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
641
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
642
+ let loader = getFlag(options, keys, "loader", mustBeString);
643
+ let banner = getFlag(options, keys, "banner", mustBeString);
644
+ let footer = getFlag(options, keys, "footer", mustBeString);
645
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
646
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
647
+ if (sourcemap)
648
+ flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
649
+ if (sourcefile)
650
+ flags.push(`--sourcefile=${sourcefile}`);
651
+ if (loader)
652
+ flags.push(`--loader=${loader}`);
653
+ if (banner)
654
+ flags.push(`--banner=${banner}`);
655
+ if (footer)
656
+ flags.push(`--footer=${footer}`);
657
+ return {
658
+ flags,
659
+ mangleCache: validateMangleCache(mangleCache)
660
+ };
661
+ }
662
+ function createChannel(streamIn) {
663
+ const requestCallbacksByKey = {};
664
+ const closeData = { didClose: false, reason: "" };
665
+ let responseCallbacks = {};
666
+ let nextRequestID = 0;
667
+ let nextBuildKey = 0;
668
+ let stdout = new Uint8Array(16 * 1024);
669
+ let stdoutUsed = 0;
670
+ let readFromStdout = (chunk) => {
671
+ let limit = stdoutUsed + chunk.length;
672
+ if (limit > stdout.length) {
673
+ let swap = new Uint8Array(limit * 2);
674
+ swap.set(stdout);
675
+ stdout = swap;
676
+ }
677
+ stdout.set(chunk, stdoutUsed);
678
+ stdoutUsed += chunk.length;
679
+ let offset = 0;
680
+ while (offset + 4 <= stdoutUsed) {
681
+ let length = readUInt32LE(stdout, offset);
682
+ if (offset + 4 + length > stdoutUsed) {
683
+ break;
684
+ }
685
+ offset += 4;
686
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
687
+ offset += length;
688
+ }
689
+ if (offset > 0) {
690
+ stdout.copyWithin(0, offset, stdoutUsed);
691
+ stdoutUsed -= offset;
692
+ }
693
+ };
694
+ let afterClose = (error) => {
695
+ closeData.didClose = true;
696
+ if (error)
697
+ closeData.reason = ": " + (error.message || error);
698
+ const text = "The service was stopped" + closeData.reason;
699
+ for (let id in responseCallbacks) {
700
+ responseCallbacks[id](text, null);
701
+ }
702
+ responseCallbacks = {};
703
+ };
704
+ let sendRequest = (refs, value, callback) => {
705
+ if (closeData.didClose)
706
+ return callback("The service is no longer running" + closeData.reason, null);
707
+ let id = nextRequestID++;
708
+ responseCallbacks[id] = (error, response) => {
709
+ try {
710
+ callback(error, response);
711
+ } finally {
712
+ if (refs)
713
+ refs.unref();
714
+ }
715
+ };
716
+ if (refs)
717
+ refs.ref();
718
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
719
+ };
720
+ let sendResponse = (id, value) => {
721
+ if (closeData.didClose)
722
+ throw new Error("The service is no longer running" + closeData.reason);
723
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
724
+ };
725
+ let handleRequest = async (id, request) => {
726
+ try {
727
+ if (request.command === "ping") {
728
+ sendResponse(id, {});
729
+ return;
730
+ }
731
+ if (typeof request.key === "number") {
732
+ const requestCallbacks = requestCallbacksByKey[request.key];
733
+ if (!requestCallbacks) {
734
+ return;
735
+ }
736
+ const callback = requestCallbacks[request.command];
737
+ if (callback) {
738
+ await callback(id, request);
739
+ return;
740
+ }
741
+ }
742
+ throw new Error(`Invalid command: ` + request.command);
743
+ } catch (e) {
744
+ const errors = [extractErrorMessageV8(e, streamIn, null, undefined, "")];
745
+ try {
746
+ sendResponse(id, { errors });
747
+ } catch {}
748
+ }
749
+ };
750
+ let isFirstPacket = true;
751
+ let handleIncomingPacket = (bytes) => {
752
+ if (isFirstPacket) {
753
+ isFirstPacket = false;
754
+ let binaryVersion = String.fromCharCode(...bytes);
755
+ if (binaryVersion !== "0.19.12") {
756
+ throw new Error(`Cannot start service: Host version "${"0.19.12"}" does not match binary version ${quote(binaryVersion)}`);
757
+ }
758
+ return;
759
+ }
760
+ let packet = decodePacket(bytes);
761
+ if (packet.isRequest) {
762
+ handleRequest(packet.id, packet.value);
763
+ } else {
764
+ let callback = responseCallbacks[packet.id];
765
+ delete responseCallbacks[packet.id];
766
+ if (packet.value.error)
767
+ callback(packet.value.error, {});
768
+ else
769
+ callback(null, packet.value);
770
+ }
771
+ };
772
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
773
+ let refCount = 0;
774
+ const buildKey = nextBuildKey++;
775
+ const requestCallbacks = {};
776
+ const buildRefs = {
777
+ ref() {
778
+ if (++refCount === 1) {
779
+ if (refs)
780
+ refs.ref();
781
+ }
782
+ },
783
+ unref() {
784
+ if (--refCount === 0) {
785
+ delete requestCallbacksByKey[buildKey];
786
+ if (refs)
787
+ refs.unref();
788
+ }
789
+ }
790
+ };
791
+ requestCallbacksByKey[buildKey] = requestCallbacks;
792
+ buildRefs.ref();
793
+ buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
794
+ try {
795
+ callback(err, res);
796
+ } finally {
797
+ buildRefs.unref();
798
+ }
799
+ });
800
+ };
801
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
802
+ const details = createObjectStash();
803
+ let start = (inputPath) => {
804
+ try {
805
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
806
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
807
+ let {
808
+ flags,
809
+ mangleCache
810
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
811
+ let request = {
812
+ command: "transform",
813
+ flags,
814
+ inputFS: inputPath !== null,
815
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
816
+ };
817
+ if (mangleCache)
818
+ request.mangleCache = mangleCache;
819
+ sendRequest(refs, request, (error, response) => {
820
+ if (error)
821
+ return callback(new Error(error), null);
822
+ let errors = replaceDetailsInMessages(response.errors, details);
823
+ let warnings = replaceDetailsInMessages(response.warnings, details);
824
+ let outstanding = 1;
825
+ let next = () => {
826
+ if (--outstanding === 0) {
827
+ let result = {
828
+ warnings,
829
+ code: response.code,
830
+ map: response.map,
831
+ mangleCache: undefined,
832
+ legalComments: undefined
833
+ };
834
+ if ("legalComments" in response)
835
+ result.legalComments = response == null ? undefined : response.legalComments;
836
+ if (response.mangleCache)
837
+ result.mangleCache = response == null ? undefined : response.mangleCache;
838
+ callback(null, result);
839
+ }
840
+ };
841
+ if (errors.length > 0)
842
+ return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
843
+ if (response.codeFS) {
844
+ outstanding++;
845
+ fs3.readFile(response.code, (err, contents) => {
846
+ if (err !== null) {
847
+ callback(err, null);
848
+ } else {
849
+ response.code = contents;
850
+ next();
851
+ }
852
+ });
853
+ }
854
+ if (response.mapFS) {
855
+ outstanding++;
856
+ fs3.readFile(response.map, (err, contents) => {
857
+ if (err !== null) {
858
+ callback(err, null);
859
+ } else {
860
+ response.map = contents;
861
+ next();
862
+ }
863
+ });
864
+ }
865
+ next();
866
+ });
867
+ } catch (e) {
868
+ let flags = [];
869
+ try {
870
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
871
+ } catch {}
872
+ const error = extractErrorMessageV8(e, streamIn, details, undefined, "");
873
+ sendRequest(refs, { command: "error", flags, error }, () => {
874
+ error.detail = details.load(error.detail);
875
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
876
+ });
877
+ }
878
+ };
879
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
880
+ let next = start;
881
+ start = () => fs3.writeFile(input, next);
882
+ }
883
+ start(null);
884
+ };
885
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
886
+ if (!options)
887
+ throw new Error(`Missing second argument in ${callName}() call`);
888
+ let keys = {};
889
+ let kind = getFlag(options, keys, "kind", mustBeString);
890
+ let color = getFlag(options, keys, "color", mustBeBoolean);
891
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
892
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
893
+ if (kind === undefined)
894
+ throw new Error(`Missing "kind" in ${callName}() call`);
895
+ if (kind !== "error" && kind !== "warning")
896
+ throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
897
+ let request = {
898
+ command: "format-msgs",
899
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
900
+ isWarning: kind === "warning"
901
+ };
902
+ if (color !== undefined)
903
+ request.color = color;
904
+ if (terminalWidth !== undefined)
905
+ request.terminalWidth = terminalWidth;
906
+ sendRequest(refs, request, (error, response) => {
907
+ if (error)
908
+ return callback(new Error(error), null);
909
+ callback(null, response.messages);
910
+ });
911
+ };
912
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
913
+ if (options === undefined)
914
+ options = {};
915
+ let keys = {};
916
+ let color = getFlag(options, keys, "color", mustBeBoolean);
917
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
918
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
919
+ let request = {
920
+ command: "analyze-metafile",
921
+ metafile
922
+ };
923
+ if (color !== undefined)
924
+ request.color = color;
925
+ if (verbose !== undefined)
926
+ request.verbose = verbose;
927
+ sendRequest(refs, request, (error, response) => {
928
+ if (error)
929
+ return callback(new Error(error), null);
930
+ callback(null, response.result);
931
+ });
932
+ };
933
+ return {
934
+ readFromStdout,
935
+ afterClose,
936
+ service: {
937
+ buildOrContext,
938
+ transform: transform2,
939
+ formatMessages: formatMessages2,
940
+ analyzeMetafile: analyzeMetafile2
941
+ }
942
+ };
943
+ }
944
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
945
+ const details = createObjectStash();
946
+ const isContext = callName === "context";
947
+ const handleError = (e, pluginName) => {
948
+ const flags = [];
949
+ try {
950
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
951
+ } catch {}
952
+ const message = extractErrorMessageV8(e, streamIn, details, undefined, pluginName);
953
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
954
+ message.detail = details.load(message.detail);
955
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
956
+ });
957
+ };
958
+ let plugins;
959
+ if (typeof options === "object") {
960
+ const value = options.plugins;
961
+ if (value !== undefined) {
962
+ if (!Array.isArray(value))
963
+ return handleError(new Error(`"plugins" must be an array`), "");
964
+ plugins = value;
965
+ }
966
+ }
967
+ if (plugins && plugins.length > 0) {
968
+ if (streamIn.isSync)
969
+ return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
970
+ handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
971
+ if (!result.ok)
972
+ return handleError(result.error, result.pluginName);
973
+ try {
974
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
975
+ } catch (e) {
976
+ handleError(e, "");
977
+ }
978
+ }, (e) => handleError(e, ""));
979
+ return;
980
+ }
981
+ try {
982
+ buildOrContextContinue(null, (result, done) => done([], []), () => {});
983
+ } catch (e) {
984
+ handleError(e, "");
985
+ }
986
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
987
+ const writeDefault = streamIn.hasFS;
988
+ const {
989
+ entries,
990
+ flags,
991
+ write,
992
+ stdinContents,
993
+ stdinResolveDir,
994
+ absWorkingDir,
995
+ nodePaths,
996
+ mangleCache
997
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
998
+ if (write && !streamIn.hasFS)
999
+ throw new Error(`The "write" option is unavailable in this environment`);
1000
+ const request = {
1001
+ command: "build",
1002
+ key: buildKey,
1003
+ entries,
1004
+ flags,
1005
+ write,
1006
+ stdinContents,
1007
+ stdinResolveDir,
1008
+ absWorkingDir: absWorkingDir || defaultWD2,
1009
+ nodePaths,
1010
+ context: isContext
1011
+ };
1012
+ if (requestPlugins)
1013
+ request.plugins = requestPlugins;
1014
+ if (mangleCache)
1015
+ request.mangleCache = mangleCache;
1016
+ const buildResponseToResult = (response, callback2) => {
1017
+ const result = {
1018
+ errors: replaceDetailsInMessages(response.errors, details),
1019
+ warnings: replaceDetailsInMessages(response.warnings, details),
1020
+ outputFiles: undefined,
1021
+ metafile: undefined,
1022
+ mangleCache: undefined
1023
+ };
1024
+ const originalErrors = result.errors.slice();
1025
+ const originalWarnings = result.warnings.slice();
1026
+ if (response.outputFiles)
1027
+ result.outputFiles = response.outputFiles.map(convertOutputFiles);
1028
+ if (response.metafile)
1029
+ result.metafile = JSON.parse(response.metafile);
1030
+ if (response.mangleCache)
1031
+ result.mangleCache = response.mangleCache;
1032
+ if (response.writeToStdout !== undefined)
1033
+ console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1034
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1035
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1036
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1037
+ return callback2(error, null, onEndErrors, onEndWarnings);
1038
+ }
1039
+ callback2(null, result, onEndErrors, onEndWarnings);
1040
+ });
1041
+ };
1042
+ let latestResultPromise;
1043
+ let provideLatestResult;
1044
+ if (isContext)
1045
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1046
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1047
+ const response = {
1048
+ errors: onEndErrors,
1049
+ warnings: onEndWarnings
1050
+ };
1051
+ if (provideLatestResult)
1052
+ provideLatestResult(err, result);
1053
+ latestResultPromise = undefined;
1054
+ provideLatestResult = undefined;
1055
+ sendResponse(id, response);
1056
+ resolve();
1057
+ });
1058
+ });
1059
+ sendRequest(refs, request, (error, response) => {
1060
+ if (error)
1061
+ return callback(new Error(error), null);
1062
+ if (!isContext) {
1063
+ return buildResponseToResult(response, (err, res) => {
1064
+ scheduleOnDisposeCallbacks();
1065
+ return callback(err, res);
1066
+ });
1067
+ }
1068
+ if (response.errors.length > 0) {
1069
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1070
+ }
1071
+ let didDispose = false;
1072
+ const result = {
1073
+ rebuild: () => {
1074
+ if (!latestResultPromise)
1075
+ latestResultPromise = new Promise((resolve, reject) => {
1076
+ let settlePromise;
1077
+ provideLatestResult = (err, result2) => {
1078
+ if (!settlePromise)
1079
+ settlePromise = () => err ? reject(err) : resolve(result2);
1080
+ };
1081
+ const triggerAnotherBuild = () => {
1082
+ const request2 = {
1083
+ command: "rebuild",
1084
+ key: buildKey
1085
+ };
1086
+ sendRequest(refs, request2, (error2, response2) => {
1087
+ if (error2) {
1088
+ reject(new Error(error2));
1089
+ } else if (settlePromise) {
1090
+ settlePromise();
1091
+ } else {
1092
+ triggerAnotherBuild();
1093
+ }
1094
+ });
1095
+ };
1096
+ triggerAnotherBuild();
1097
+ });
1098
+ return latestResultPromise;
1099
+ },
1100
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1101
+ if (!streamIn.hasFS)
1102
+ throw new Error(`Cannot use the "watch" API in this environment`);
1103
+ const keys = {};
1104
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1105
+ const request2 = {
1106
+ command: "watch",
1107
+ key: buildKey
1108
+ };
1109
+ sendRequest(refs, request2, (error2) => {
1110
+ if (error2)
1111
+ reject(new Error(error2));
1112
+ else
1113
+ resolve(undefined);
1114
+ });
1115
+ }),
1116
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1117
+ if (!streamIn.hasFS)
1118
+ throw new Error(`Cannot use the "serve" API in this environment`);
1119
+ const keys = {};
1120
+ const port = getFlag(options2, keys, "port", mustBeInteger);
1121
+ const host = getFlag(options2, keys, "host", mustBeString);
1122
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1123
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1124
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1125
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1126
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1127
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1128
+ const request2 = {
1129
+ command: "serve",
1130
+ key: buildKey,
1131
+ onRequest: !!onRequest
1132
+ };
1133
+ if (port !== undefined)
1134
+ request2.port = port;
1135
+ if (host !== undefined)
1136
+ request2.host = host;
1137
+ if (servedir !== undefined)
1138
+ request2.servedir = servedir;
1139
+ if (keyfile !== undefined)
1140
+ request2.keyfile = keyfile;
1141
+ if (certfile !== undefined)
1142
+ request2.certfile = certfile;
1143
+ if (fallback !== undefined)
1144
+ request2.fallback = fallback;
1145
+ sendRequest(refs, request2, (error2, response2) => {
1146
+ if (error2)
1147
+ return reject(new Error(error2));
1148
+ if (onRequest) {
1149
+ requestCallbacks["serve-request"] = (id, request3) => {
1150
+ onRequest(request3.args);
1151
+ sendResponse(id, {});
1152
+ };
1153
+ }
1154
+ resolve(response2);
1155
+ });
1156
+ }),
1157
+ cancel: () => new Promise((resolve) => {
1158
+ if (didDispose)
1159
+ return resolve();
1160
+ const request2 = {
1161
+ command: "cancel",
1162
+ key: buildKey
1163
+ };
1164
+ sendRequest(refs, request2, () => {
1165
+ resolve();
1166
+ });
1167
+ }),
1168
+ dispose: () => new Promise((resolve) => {
1169
+ if (didDispose)
1170
+ return resolve();
1171
+ didDispose = true;
1172
+ const request2 = {
1173
+ command: "dispose",
1174
+ key: buildKey
1175
+ };
1176
+ sendRequest(refs, request2, () => {
1177
+ resolve();
1178
+ scheduleOnDisposeCallbacks();
1179
+ refs.unref();
1180
+ });
1181
+ })
1182
+ };
1183
+ refs.ref();
1184
+ callback(null, result);
1185
+ });
1186
+ }
1187
+ }
1188
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1189
+ let onStartCallbacks = [];
1190
+ let onEndCallbacks = [];
1191
+ let onResolveCallbacks = {};
1192
+ let onLoadCallbacks = {};
1193
+ let onDisposeCallbacks = [];
1194
+ let nextCallbackID = 0;
1195
+ let i = 0;
1196
+ let requestPlugins = [];
1197
+ let isSetupDone = false;
1198
+ plugins = [...plugins];
1199
+ for (let item of plugins) {
1200
+ let keys = {};
1201
+ if (typeof item !== "object")
1202
+ throw new Error(`Plugin at index ${i} must be an object`);
1203
+ const name = getFlag(item, keys, "name", mustBeString);
1204
+ if (typeof name !== "string" || name === "")
1205
+ throw new Error(`Plugin at index ${i} is missing a name`);
1206
+ try {
1207
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1208
+ if (typeof setup !== "function")
1209
+ throw new Error(`Plugin is missing a setup function`);
1210
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1211
+ let plugin = {
1212
+ name,
1213
+ onStart: false,
1214
+ onEnd: false,
1215
+ onResolve: [],
1216
+ onLoad: []
1217
+ };
1218
+ i++;
1219
+ let resolve = (path3, options = {}) => {
1220
+ if (!isSetupDone)
1221
+ throw new Error('Cannot call "resolve" before plugin setup has completed');
1222
+ if (typeof path3 !== "string")
1223
+ throw new Error(`The path to resolve must be a string`);
1224
+ let keys2 = /* @__PURE__ */ Object.create(null);
1225
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1226
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1227
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1228
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1229
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1230
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1231
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1232
+ return new Promise((resolve2, reject) => {
1233
+ const request = {
1234
+ command: "resolve",
1235
+ path: path3,
1236
+ key: buildKey,
1237
+ pluginName: name
1238
+ };
1239
+ if (pluginName != null)
1240
+ request.pluginName = pluginName;
1241
+ if (importer != null)
1242
+ request.importer = importer;
1243
+ if (namespace != null)
1244
+ request.namespace = namespace;
1245
+ if (resolveDir != null)
1246
+ request.resolveDir = resolveDir;
1247
+ if (kind != null)
1248
+ request.kind = kind;
1249
+ else
1250
+ throw new Error(`Must specify "kind" when calling "resolve"`);
1251
+ if (pluginData != null)
1252
+ request.pluginData = details.store(pluginData);
1253
+ sendRequest(refs, request, (error, response) => {
1254
+ if (error !== null)
1255
+ reject(new Error(error));
1256
+ else
1257
+ resolve2({
1258
+ errors: replaceDetailsInMessages(response.errors, details),
1259
+ warnings: replaceDetailsInMessages(response.warnings, details),
1260
+ path: response.path,
1261
+ external: response.external,
1262
+ sideEffects: response.sideEffects,
1263
+ namespace: response.namespace,
1264
+ suffix: response.suffix,
1265
+ pluginData: details.load(response.pluginData)
1266
+ });
1267
+ });
1268
+ });
1269
+ };
1270
+ let promise = setup({
1271
+ initialOptions,
1272
+ resolve,
1273
+ onStart(callback) {
1274
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1275
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1276
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1277
+ plugin.onStart = true;
1278
+ },
1279
+ onEnd(callback) {
1280
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1281
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1282
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1283
+ plugin.onEnd = true;
1284
+ },
1285
+ onResolve(options, callback) {
1286
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1287
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1288
+ let keys2 = {};
1289
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1290
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1291
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1292
+ if (filter == null)
1293
+ throw new Error(`onResolve() call is missing a filter`);
1294
+ let id = nextCallbackID++;
1295
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1296
+ plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
1297
+ },
1298
+ onLoad(options, callback) {
1299
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1300
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1301
+ let keys2 = {};
1302
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1303
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1304
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1305
+ if (filter == null)
1306
+ throw new Error(`onLoad() call is missing a filter`);
1307
+ let id = nextCallbackID++;
1308
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1309
+ plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
1310
+ },
1311
+ onDispose(callback) {
1312
+ onDisposeCallbacks.push(callback);
1313
+ },
1314
+ esbuild: streamIn.esbuild
1315
+ });
1316
+ if (promise)
1317
+ await promise;
1318
+ requestPlugins.push(plugin);
1319
+ } catch (e) {
1320
+ return { ok: false, error: e, pluginName: name };
1321
+ }
1322
+ }
1323
+ requestCallbacks["on-start"] = async (id, request) => {
1324
+ let response = { errors: [], warnings: [] };
1325
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1326
+ try {
1327
+ let result = await callback();
1328
+ if (result != null) {
1329
+ if (typeof result !== "object")
1330
+ throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1331
+ let keys = {};
1332
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1333
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1334
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1335
+ if (errors != null)
1336
+ response.errors.push(...sanitizeMessages(errors, "errors", details, name, undefined));
1337
+ if (warnings != null)
1338
+ response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, undefined));
1339
+ }
1340
+ } catch (e) {
1341
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1342
+ }
1343
+ }));
1344
+ sendResponse(id, response);
1345
+ };
1346
+ requestCallbacks["on-resolve"] = async (id, request) => {
1347
+ let response = {}, name = "", callback, note;
1348
+ for (let id2 of request.ids) {
1349
+ try {
1350
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1351
+ let result = await callback({
1352
+ path: request.path,
1353
+ importer: request.importer,
1354
+ namespace: request.namespace,
1355
+ resolveDir: request.resolveDir,
1356
+ kind: request.kind,
1357
+ pluginData: details.load(request.pluginData)
1358
+ });
1359
+ if (result != null) {
1360
+ if (typeof result !== "object")
1361
+ throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1362
+ let keys = {};
1363
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1364
+ let path3 = getFlag(result, keys, "path", mustBeString);
1365
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1366
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1367
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1368
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1369
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1370
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1371
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1372
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1373
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1374
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1375
+ response.id = id2;
1376
+ if (pluginName != null)
1377
+ response.pluginName = pluginName;
1378
+ if (path3 != null)
1379
+ response.path = path3;
1380
+ if (namespace != null)
1381
+ response.namespace = namespace;
1382
+ if (suffix != null)
1383
+ response.suffix = suffix;
1384
+ if (external != null)
1385
+ response.external = external;
1386
+ if (sideEffects != null)
1387
+ response.sideEffects = sideEffects;
1388
+ if (pluginData != null)
1389
+ response.pluginData = details.store(pluginData);
1390
+ if (errors != null)
1391
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1392
+ if (warnings != null)
1393
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1394
+ if (watchFiles != null)
1395
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1396
+ if (watchDirs != null)
1397
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1398
+ break;
1399
+ }
1400
+ } catch (e) {
1401
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1402
+ break;
1403
+ }
1404
+ }
1405
+ sendResponse(id, response);
1406
+ };
1407
+ requestCallbacks["on-load"] = async (id, request) => {
1408
+ let response = {}, name = "", callback, note;
1409
+ for (let id2 of request.ids) {
1410
+ try {
1411
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1412
+ let result = await callback({
1413
+ path: request.path,
1414
+ namespace: request.namespace,
1415
+ suffix: request.suffix,
1416
+ pluginData: details.load(request.pluginData),
1417
+ with: request.with
1418
+ });
1419
+ if (result != null) {
1420
+ if (typeof result !== "object")
1421
+ throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1422
+ let keys = {};
1423
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1424
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1425
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1426
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1427
+ let loader = getFlag(result, keys, "loader", mustBeString);
1428
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1429
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1430
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1431
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1432
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1433
+ response.id = id2;
1434
+ if (pluginName != null)
1435
+ response.pluginName = pluginName;
1436
+ if (contents instanceof Uint8Array)
1437
+ response.contents = contents;
1438
+ else if (contents != null)
1439
+ response.contents = encodeUTF8(contents);
1440
+ if (resolveDir != null)
1441
+ response.resolveDir = resolveDir;
1442
+ if (pluginData != null)
1443
+ response.pluginData = details.store(pluginData);
1444
+ if (loader != null)
1445
+ response.loader = loader;
1446
+ if (errors != null)
1447
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1448
+ if (warnings != null)
1449
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1450
+ if (watchFiles != null)
1451
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1452
+ if (watchDirs != null)
1453
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1454
+ break;
1455
+ }
1456
+ } catch (e) {
1457
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1458
+ break;
1459
+ }
1460
+ }
1461
+ sendResponse(id, response);
1462
+ };
1463
+ let runOnEndCallbacks = (result, done) => done([], []);
1464
+ if (onEndCallbacks.length > 0) {
1465
+ runOnEndCallbacks = (result, done) => {
1466
+ (async () => {
1467
+ const onEndErrors = [];
1468
+ const onEndWarnings = [];
1469
+ for (const { name, callback, note } of onEndCallbacks) {
1470
+ let newErrors;
1471
+ let newWarnings;
1472
+ try {
1473
+ const value = await callback(result);
1474
+ if (value != null) {
1475
+ if (typeof value !== "object")
1476
+ throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1477
+ let keys = {};
1478
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1479
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1480
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1481
+ if (errors != null)
1482
+ newErrors = sanitizeMessages(errors, "errors", details, name, undefined);
1483
+ if (warnings != null)
1484
+ newWarnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1485
+ }
1486
+ } catch (e) {
1487
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1488
+ }
1489
+ if (newErrors) {
1490
+ onEndErrors.push(...newErrors);
1491
+ try {
1492
+ result.errors.push(...newErrors);
1493
+ } catch {}
1494
+ }
1495
+ if (newWarnings) {
1496
+ onEndWarnings.push(...newWarnings);
1497
+ try {
1498
+ result.warnings.push(...newWarnings);
1499
+ } catch {}
1500
+ }
1501
+ }
1502
+ done(onEndErrors, onEndWarnings);
1503
+ })();
1504
+ };
1505
+ }
1506
+ let scheduleOnDisposeCallbacks = () => {
1507
+ for (const cb of onDisposeCallbacks) {
1508
+ setTimeout(() => cb(), 0);
1509
+ }
1510
+ };
1511
+ isSetupDone = true;
1512
+ return {
1513
+ ok: true,
1514
+ requestPlugins,
1515
+ runOnEndCallbacks,
1516
+ scheduleOnDisposeCallbacks
1517
+ };
1518
+ };
1519
+ function createObjectStash() {
1520
+ const map = /* @__PURE__ */ new Map;
1521
+ let nextID = 0;
1522
+ return {
1523
+ load(id) {
1524
+ return map.get(id);
1525
+ },
1526
+ store(value) {
1527
+ if (value === undefined)
1528
+ return -1;
1529
+ const id = nextID++;
1530
+ map.set(id, value);
1531
+ return id;
1532
+ }
1533
+ };
1534
+ }
1535
+ function extractCallerV8(e, streamIn, ident) {
1536
+ let note;
1537
+ let tried = false;
1538
+ return () => {
1539
+ if (tried)
1540
+ return note;
1541
+ tried = true;
1542
+ try {
1543
+ let lines = (e.stack + "").split(`
1544
+ `);
1545
+ lines.splice(1, 1);
1546
+ let location = parseStackLinesV8(streamIn, lines, ident);
1547
+ if (location) {
1548
+ note = { text: e.message, location };
1549
+ return note;
1550
+ }
1551
+ } catch {}
1552
+ };
1553
+ }
1554
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1555
+ let text = "Internal error";
1556
+ let location = null;
1557
+ try {
1558
+ text = (e && e.message || e) + "";
1559
+ } catch {}
1560
+ try {
1561
+ location = parseStackLinesV8(streamIn, (e.stack + "").split(`
1562
+ `), "");
1563
+ } catch {}
1564
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1565
+ }
1566
+ function parseStackLinesV8(streamIn, lines, ident) {
1567
+ let at = " at ";
1568
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1569
+ for (let i = 1;i < lines.length; i++) {
1570
+ let line = lines[i];
1571
+ if (!line.startsWith(at))
1572
+ continue;
1573
+ line = line.slice(at.length);
1574
+ while (true) {
1575
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1576
+ if (match) {
1577
+ line = match[1];
1578
+ continue;
1579
+ }
1580
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1581
+ if (match) {
1582
+ line = match[1];
1583
+ continue;
1584
+ }
1585
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1586
+ if (match) {
1587
+ let contents;
1588
+ try {
1589
+ contents = streamIn.readFileSync(match[1], "utf8");
1590
+ } catch {
1591
+ break;
1592
+ }
1593
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1594
+ let column = +match[3] - 1;
1595
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1596
+ return {
1597
+ file: match[1],
1598
+ namespace: "file",
1599
+ line: +match[2],
1600
+ column: encodeUTF8(lineText.slice(0, column)).length,
1601
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1602
+ lineText: lineText + `
1603
+ ` + lines.slice(1).join(`
1604
+ `),
1605
+ suggestion: ""
1606
+ };
1607
+ }
1608
+ break;
1609
+ }
1610
+ }
1611
+ }
1612
+ return null;
1613
+ }
1614
+ function failureErrorWithLog(text, errors, warnings) {
1615
+ let limit = 5;
1616
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1617
+ if (i === limit)
1618
+ return `
1619
+ ...`;
1620
+ if (!e.location)
1621
+ return `
1622
+ error: ${e.text}`;
1623
+ let { file, line, column } = e.location;
1624
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1625
+ return `
1626
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1627
+ }).join("");
1628
+ let error = new Error(text);
1629
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1630
+ Object.defineProperty(error, key, {
1631
+ configurable: true,
1632
+ enumerable: true,
1633
+ get: () => value,
1634
+ set: (value2) => Object.defineProperty(error, key, {
1635
+ configurable: true,
1636
+ enumerable: true,
1637
+ value: value2
1638
+ })
1639
+ });
1640
+ }
1641
+ return error;
1642
+ }
1643
+ function replaceDetailsInMessages(messages, stash) {
1644
+ for (const message of messages) {
1645
+ message.detail = stash.load(message.detail);
1646
+ }
1647
+ return messages;
1648
+ }
1649
+ function sanitizeLocation(location, where, terminalWidth) {
1650
+ if (location == null)
1651
+ return null;
1652
+ let keys = {};
1653
+ let file = getFlag(location, keys, "file", mustBeString);
1654
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1655
+ let line = getFlag(location, keys, "line", mustBeInteger);
1656
+ let column = getFlag(location, keys, "column", mustBeInteger);
1657
+ let length = getFlag(location, keys, "length", mustBeInteger);
1658
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1659
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1660
+ checkForInvalidFlags(location, keys, where);
1661
+ if (lineText) {
1662
+ const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1663
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1664
+ lineText = relevantASCII;
1665
+ }
1666
+ }
1667
+ return {
1668
+ file: file || "",
1669
+ namespace: namespace || "",
1670
+ line: line || 0,
1671
+ column: column || 0,
1672
+ length: length || 0,
1673
+ lineText: lineText || "",
1674
+ suggestion: suggestion || ""
1675
+ };
1676
+ }
1677
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1678
+ let messagesClone = [];
1679
+ let index = 0;
1680
+ for (const message of messages) {
1681
+ let keys = {};
1682
+ let id = getFlag(message, keys, "id", mustBeString);
1683
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1684
+ let text = getFlag(message, keys, "text", mustBeString);
1685
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1686
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1687
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1688
+ let where = `in element ${index} of "${property}"`;
1689
+ checkForInvalidFlags(message, keys, where);
1690
+ let notesClone = [];
1691
+ if (notes) {
1692
+ for (const note of notes) {
1693
+ let noteKeys = {};
1694
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1695
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1696
+ checkForInvalidFlags(note, noteKeys, where);
1697
+ notesClone.push({
1698
+ text: noteText || "",
1699
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1700
+ });
1701
+ }
1702
+ }
1703
+ messagesClone.push({
1704
+ id: id || "",
1705
+ pluginName: pluginName || fallbackPluginName,
1706
+ text: text || "",
1707
+ location: sanitizeLocation(location, where, terminalWidth),
1708
+ notes: notesClone,
1709
+ detail: stash ? stash.store(detail) : -1
1710
+ });
1711
+ index++;
1712
+ }
1713
+ return messagesClone;
1714
+ }
1715
+ function sanitizeStringArray(values, property) {
1716
+ const result = [];
1717
+ for (const value of values) {
1718
+ if (typeof value !== "string")
1719
+ throw new Error(`${quote(property)} must be an array of strings`);
1720
+ result.push(value);
1721
+ }
1722
+ return result;
1723
+ }
1724
+ function convertOutputFiles({ path: path3, contents, hash }) {
1725
+ let text = null;
1726
+ return {
1727
+ path: path3,
1728
+ contents,
1729
+ hash,
1730
+ get text() {
1731
+ const binary = this.contents;
1732
+ if (text === null || binary !== contents) {
1733
+ contents = binary;
1734
+ text = decodeUTF8(binary);
1735
+ }
1736
+ return text;
1737
+ }
1738
+ };
1739
+ }
1740
+ var fs = __require("fs");
1741
+ var os = __require("os");
1742
+ var path = __require("path");
1743
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1744
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1745
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1746
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1747
+ var knownWindowsPackages = {
1748
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1749
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1750
+ "win32 x64 LE": "@esbuild/win32-x64"
1751
+ };
1752
+ var knownUnixlikePackages = {
1753
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1754
+ "android arm64 LE": "@esbuild/android-arm64",
1755
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1756
+ "darwin x64 LE": "@esbuild/darwin-x64",
1757
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1758
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1759
+ "linux arm LE": "@esbuild/linux-arm",
1760
+ "linux arm64 LE": "@esbuild/linux-arm64",
1761
+ "linux ia32 LE": "@esbuild/linux-ia32",
1762
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1763
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1764
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1765
+ "linux s390x BE": "@esbuild/linux-s390x",
1766
+ "linux x64 LE": "@esbuild/linux-x64",
1767
+ "linux loong64 LE": "@esbuild/linux-loong64",
1768
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1769
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1770
+ "sunos x64 LE": "@esbuild/sunos-x64"
1771
+ };
1772
+ var knownWebAssemblyFallbackPackages = {
1773
+ "android arm LE": "@esbuild/android-arm",
1774
+ "android x64 LE": "@esbuild/android-x64"
1775
+ };
1776
+ function pkgAndSubpathForCurrentPlatform() {
1777
+ let pkg;
1778
+ let subpath;
1779
+ let isWASM = false;
1780
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1781
+ if (platformKey in knownWindowsPackages) {
1782
+ pkg = knownWindowsPackages[platformKey];
1783
+ subpath = "esbuild.exe";
1784
+ } else if (platformKey in knownUnixlikePackages) {
1785
+ pkg = knownUnixlikePackages[platformKey];
1786
+ subpath = "bin/esbuild";
1787
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1788
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1789
+ subpath = "bin/esbuild";
1790
+ isWASM = true;
1791
+ } else {
1792
+ throw new Error(`Unsupported platform: ${platformKey}`);
1793
+ }
1794
+ return { pkg, subpath, isWASM };
1795
+ }
1796
+ function pkgForSomeOtherPlatform() {
1797
+ const libMainJS = __require.resolve("esbuild");
1798
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
1799
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
1800
+ for (const unixKey in knownUnixlikePackages) {
1801
+ try {
1802
+ const pkg = knownUnixlikePackages[unixKey];
1803
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1804
+ return pkg;
1805
+ } catch {}
1806
+ }
1807
+ for (const windowsKey in knownWindowsPackages) {
1808
+ try {
1809
+ const pkg = knownWindowsPackages[windowsKey];
1810
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1811
+ return pkg;
1812
+ } catch {}
1813
+ }
1814
+ }
1815
+ return null;
1816
+ }
1817
+ function downloadedBinPath(pkg, subpath) {
1818
+ const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
1819
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
1820
+ }
1821
+ function generateBinPath() {
1822
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1823
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
1824
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1825
+ } else {
1826
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1827
+ }
1828
+ }
1829
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1830
+ let binPath;
1831
+ try {
1832
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1833
+ } catch (e) {
1834
+ binPath = downloadedBinPath(pkg, subpath);
1835
+ if (!fs.existsSync(binPath)) {
1836
+ try {
1837
+ __require.resolve(pkg);
1838
+ } catch {
1839
+ const otherPkg = pkgForSomeOtherPlatform();
1840
+ if (otherPkg) {
1841
+ let suggestions = `
1842
+ Specifically the "${otherPkg}" package is present but this platform
1843
+ needs the "${pkg}" package instead. People often get into this
1844
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
1845
+ into a Docker image that runs Linux, or by copying "node_modules" between
1846
+ Windows and WSL environments.
1847
+
1848
+ If you are installing with npm, you can try not copying the "node_modules"
1849
+ directory when you copy the files over, and running "npm ci" or "npm install"
1850
+ on the destination platform after the copy. Or you could consider using yarn
1851
+ instead of npm which has built-in support for installing a package on multiple
1852
+ platforms simultaneously.
1853
+
1854
+ If you are installing with yarn, you can try listing both this platform and the
1855
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1856
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1857
+ Keep in mind that this means multiple copies of esbuild will be present.
1858
+ `;
1859
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
1860
+ suggestions = `
1861
+ Specifically the "${otherPkg}" package is present but this platform
1862
+ needs the "${pkg}" package instead. People often get into this
1863
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
1864
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
1865
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
1866
+
1867
+ If you are installing with npm, you can try ensuring that both npm and node are
1868
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1869
+ changing how you installed npm and/or node. For example, installing node with
1870
+ the universal installer here should work: https://nodejs.org/en/download/. Or
1871
+ you could consider using yarn instead of npm which has built-in support for
1872
+ installing a package on multiple platforms simultaneously.
1873
+
1874
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
1875
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1876
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1877
+ Keep in mind that this means multiple copies of esbuild will be present.
1878
+ `;
1879
+ }
1880
+ throw new Error(`
1881
+ You installed esbuild for another platform than the one you're currently using.
1882
+ This won't work because esbuild is written with native code and needs to
1883
+ install a platform-specific binary executable.
1884
+ ${suggestions}
1885
+ Another alternative is to use the "esbuild-wasm" package instead, which works
1886
+ the same way on all platforms. But it comes with a heavy performance cost and
1887
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
1888
+ want to do that.
1889
+ `);
1890
+ }
1891
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1892
+
1893
+ If you are installing esbuild with npm, make sure that you don't specify the
1894
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1895
+ of "package.json" is used by esbuild to install the correct binary executable
1896
+ for your current platform.`);
1897
+ }
1898
+ throw e;
1899
+ }
1900
+ }
1901
+ if (/\.zip\//.test(binPath)) {
1902
+ let pnpapi;
1903
+ try {
1904
+ pnpapi = (()=>{throw new Error("Cannot require module "+"pnpapi");})();
1905
+ } catch (e) {}
1906
+ if (pnpapi) {
1907
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1908
+ const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.19.12"}-${path.basename(subpath)}`);
1909
+ if (!fs.existsSync(binTargetPath)) {
1910
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
1911
+ fs.copyFileSync(binPath, binTargetPath);
1912
+ fs.chmodSync(binTargetPath, 493);
1913
+ }
1914
+ return { binPath: binTargetPath, isWASM };
1915
+ }
1916
+ }
1917
+ return { binPath, isWASM };
1918
+ }
1919
+ var child_process = __require("child_process");
1920
+ var crypto = __require("crypto");
1921
+ var path2 = __require("path");
1922
+ var fs2 = __require("fs");
1923
+ var os2 = __require("os");
1924
+ var tty = __require("tty");
1925
+ var worker_threads;
1926
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1927
+ try {
1928
+ worker_threads = __require("worker_threads");
1929
+ } catch {}
1930
+ let [major, minor] = process.versions.node.split(".");
1931
+ if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
1932
+ worker_threads = undefined;
1933
+ }
1934
+ }
1935
+ var _a;
1936
+ var isInternalWorkerThread = ((_a = worker_threads == null ? undefined : worker_threads.workerData) == null ? undefined : _a.esbuildVersion) === "0.19.12";
1937
+ var esbuildCommandAndArgs = () => {
1938
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
1939
+ 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.
1940
+
1941
+ 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.`);
1942
+ }
1943
+ if (false) {} else {
1944
+ const { binPath, isWASM } = generateBinPath();
1945
+ if (isWASM) {
1946
+ return ["node", [binPath]];
1947
+ } else {
1948
+ return [binPath, []];
1949
+ }
1950
+ }
1951
+ };
1952
+ var isTTY = () => tty.isatty(2);
1953
+ var fsSync = {
1954
+ readFile(tempFile, callback) {
1955
+ try {
1956
+ let contents = fs2.readFileSync(tempFile, "utf8");
1957
+ try {
1958
+ fs2.unlinkSync(tempFile);
1959
+ } catch {}
1960
+ callback(null, contents);
1961
+ } catch (err) {
1962
+ callback(err, null);
1963
+ }
1964
+ },
1965
+ writeFile(contents, callback) {
1966
+ try {
1967
+ let tempFile = randomFileName();
1968
+ fs2.writeFileSync(tempFile, contents);
1969
+ callback(tempFile);
1970
+ } catch {
1971
+ callback(null);
1972
+ }
1973
+ }
1974
+ };
1975
+ var fsAsync = {
1976
+ readFile(tempFile, callback) {
1977
+ try {
1978
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
1979
+ try {
1980
+ fs2.unlink(tempFile, () => callback(err, contents));
1981
+ } catch {
1982
+ callback(err, contents);
1983
+ }
1984
+ });
1985
+ } catch (err) {
1986
+ callback(err, null);
1987
+ }
1988
+ },
1989
+ writeFile(contents, callback) {
1990
+ try {
1991
+ let tempFile = randomFileName();
1992
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
1993
+ } catch {
1994
+ callback(null);
1995
+ }
1996
+ }
1997
+ };
1998
+ var version = "0.19.12";
1999
+ var build = (options) => ensureServiceIsRunning().build(options);
2000
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2001
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2002
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2003
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2004
+ var buildSync = (options) => {
2005
+ if (worker_threads && !isInternalWorkerThread) {
2006
+ if (!workerThreadService)
2007
+ workerThreadService = startWorkerThreadService(worker_threads);
2008
+ return workerThreadService.buildSync(options);
2009
+ }
2010
+ let result;
2011
+ runServiceSync((service) => service.buildOrContext({
2012
+ callName: "buildSync",
2013
+ refs: null,
2014
+ options,
2015
+ isTTY: isTTY(),
2016
+ defaultWD,
2017
+ callback: (err, res) => {
2018
+ if (err)
2019
+ throw err;
2020
+ result = res;
2021
+ }
2022
+ }));
2023
+ return result;
2024
+ };
2025
+ var transformSync = (input, options) => {
2026
+ if (worker_threads && !isInternalWorkerThread) {
2027
+ if (!workerThreadService)
2028
+ workerThreadService = startWorkerThreadService(worker_threads);
2029
+ return workerThreadService.transformSync(input, options);
2030
+ }
2031
+ let result;
2032
+ runServiceSync((service) => service.transform({
2033
+ callName: "transformSync",
2034
+ refs: null,
2035
+ input,
2036
+ options: options || {},
2037
+ isTTY: isTTY(),
2038
+ fs: fsSync,
2039
+ callback: (err, res) => {
2040
+ if (err)
2041
+ throw err;
2042
+ result = res;
2043
+ }
2044
+ }));
2045
+ return result;
2046
+ };
2047
+ var formatMessagesSync = (messages, options) => {
2048
+ if (worker_threads && !isInternalWorkerThread) {
2049
+ if (!workerThreadService)
2050
+ workerThreadService = startWorkerThreadService(worker_threads);
2051
+ return workerThreadService.formatMessagesSync(messages, options);
2052
+ }
2053
+ let result;
2054
+ runServiceSync((service) => service.formatMessages({
2055
+ callName: "formatMessagesSync",
2056
+ refs: null,
2057
+ messages,
2058
+ options,
2059
+ callback: (err, res) => {
2060
+ if (err)
2061
+ throw err;
2062
+ result = res;
2063
+ }
2064
+ }));
2065
+ return result;
2066
+ };
2067
+ var analyzeMetafileSync = (metafile, options) => {
2068
+ if (worker_threads && !isInternalWorkerThread) {
2069
+ if (!workerThreadService)
2070
+ workerThreadService = startWorkerThreadService(worker_threads);
2071
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2072
+ }
2073
+ let result;
2074
+ runServiceSync((service) => service.analyzeMetafile({
2075
+ callName: "analyzeMetafileSync",
2076
+ refs: null,
2077
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2078
+ options,
2079
+ callback: (err, res) => {
2080
+ if (err)
2081
+ throw err;
2082
+ result = res;
2083
+ }
2084
+ }));
2085
+ return result;
2086
+ };
2087
+ var stop = () => {
2088
+ if (stopService)
2089
+ stopService();
2090
+ if (workerThreadService)
2091
+ workerThreadService.stop();
2092
+ };
2093
+ var initializeWasCalled = false;
2094
+ var initialize = (options) => {
2095
+ options = validateInitializeOptions(options || {});
2096
+ if (options.wasmURL)
2097
+ throw new Error(`The "wasmURL" option only works in the browser`);
2098
+ if (options.wasmModule)
2099
+ throw new Error(`The "wasmModule" option only works in the browser`);
2100
+ if (options.worker)
2101
+ throw new Error(`The "worker" option only works in the browser`);
2102
+ if (initializeWasCalled)
2103
+ throw new Error('Cannot call "initialize" more than once');
2104
+ ensureServiceIsRunning();
2105
+ initializeWasCalled = true;
2106
+ return Promise.resolve();
2107
+ };
2108
+ var defaultWD = process.cwd();
2109
+ var longLivedService;
2110
+ var stopService;
2111
+ var ensureServiceIsRunning = () => {
2112
+ if (longLivedService)
2113
+ return longLivedService;
2114
+ let [command, args] = esbuildCommandAndArgs();
2115
+ let child = child_process.spawn(command, args.concat(`--service=${"0.19.12"}`, "--ping"), {
2116
+ windowsHide: true,
2117
+ stdio: ["pipe", "pipe", "inherit"],
2118
+ cwd: defaultWD
2119
+ });
2120
+ let { readFromStdout, afterClose, service } = createChannel({
2121
+ writeToStdin(bytes) {
2122
+ child.stdin.write(bytes, (err) => {
2123
+ if (err)
2124
+ afterClose(err);
2125
+ });
2126
+ },
2127
+ readFileSync: fs2.readFileSync,
2128
+ isSync: false,
2129
+ hasFS: true,
2130
+ esbuild: node_exports
2131
+ });
2132
+ child.stdin.on("error", afterClose);
2133
+ child.on("error", afterClose);
2134
+ const stdin = child.stdin;
2135
+ const stdout = child.stdout;
2136
+ stdout.on("data", readFromStdout);
2137
+ stdout.on("end", afterClose);
2138
+ stopService = () => {
2139
+ stdin.destroy();
2140
+ stdout.destroy();
2141
+ child.kill();
2142
+ initializeWasCalled = false;
2143
+ longLivedService = undefined;
2144
+ stopService = undefined;
2145
+ };
2146
+ let refCount = 0;
2147
+ child.unref();
2148
+ if (stdin.unref) {
2149
+ stdin.unref();
2150
+ }
2151
+ if (stdout.unref) {
2152
+ stdout.unref();
2153
+ }
2154
+ const refs = {
2155
+ ref() {
2156
+ if (++refCount === 1)
2157
+ child.ref();
2158
+ },
2159
+ unref() {
2160
+ if (--refCount === 0)
2161
+ child.unref();
2162
+ }
2163
+ };
2164
+ longLivedService = {
2165
+ build: (options) => new Promise((resolve, reject) => {
2166
+ service.buildOrContext({
2167
+ callName: "build",
2168
+ refs,
2169
+ options,
2170
+ isTTY: isTTY(),
2171
+ defaultWD,
2172
+ callback: (err, res) => err ? reject(err) : resolve(res)
2173
+ });
2174
+ }),
2175
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2176
+ callName: "context",
2177
+ refs,
2178
+ options,
2179
+ isTTY: isTTY(),
2180
+ defaultWD,
2181
+ callback: (err, res) => err ? reject(err) : resolve(res)
2182
+ })),
2183
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2184
+ callName: "transform",
2185
+ refs,
2186
+ input,
2187
+ options: options || {},
2188
+ isTTY: isTTY(),
2189
+ fs: fsAsync,
2190
+ callback: (err, res) => err ? reject(err) : resolve(res)
2191
+ })),
2192
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2193
+ callName: "formatMessages",
2194
+ refs,
2195
+ messages,
2196
+ options,
2197
+ callback: (err, res) => err ? reject(err) : resolve(res)
2198
+ })),
2199
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2200
+ callName: "analyzeMetafile",
2201
+ refs,
2202
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2203
+ options,
2204
+ callback: (err, res) => err ? reject(err) : resolve(res)
2205
+ }))
2206
+ };
2207
+ return longLivedService;
2208
+ };
2209
+ var runServiceSync = (callback) => {
2210
+ let [command, args] = esbuildCommandAndArgs();
2211
+ let stdin = new Uint8Array;
2212
+ let { readFromStdout, afterClose, service } = createChannel({
2213
+ writeToStdin(bytes) {
2214
+ if (stdin.length !== 0)
2215
+ throw new Error("Must run at most one command");
2216
+ stdin = bytes;
2217
+ },
2218
+ isSync: true,
2219
+ hasFS: true,
2220
+ esbuild: node_exports
2221
+ });
2222
+ callback(service);
2223
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.19.12"}`), {
2224
+ cwd: defaultWD,
2225
+ windowsHide: true,
2226
+ input: stdin,
2227
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2228
+ });
2229
+ readFromStdout(stdout);
2230
+ afterClose(null);
2231
+ };
2232
+ var randomFileName = () => {
2233
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2234
+ };
2235
+ var workerThreadService = null;
2236
+ var startWorkerThreadService = (worker_threads2) => {
2237
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel;
2238
+ let worker = new worker_threads2.Worker(__filename, {
2239
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.19.12" },
2240
+ transferList: [workerPort],
2241
+ execArgv: []
2242
+ });
2243
+ let nextID = 0;
2244
+ let fakeBuildError = (text) => {
2245
+ let error = new Error(`Build failed with 1 error:
2246
+ error: ${text}`);
2247
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: undefined }];
2248
+ error.errors = errors;
2249
+ error.warnings = [];
2250
+ return error;
2251
+ };
2252
+ let validateBuildSyncOptions = (options) => {
2253
+ if (!options)
2254
+ return;
2255
+ let plugins = options.plugins;
2256
+ if (plugins && plugins.length > 0)
2257
+ throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2258
+ };
2259
+ let applyProperties = (object, properties) => {
2260
+ for (let key in properties) {
2261
+ object[key] = properties[key];
2262
+ }
2263
+ };
2264
+ let runCallSync = (command, args) => {
2265
+ let id = nextID++;
2266
+ let sharedBuffer = new SharedArrayBuffer(8);
2267
+ let sharedBufferView = new Int32Array(sharedBuffer);
2268
+ let msg = { sharedBuffer, id, command, args };
2269
+ worker.postMessage(msg);
2270
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2271
+ if (status !== "ok" && status !== "not-equal")
2272
+ throw new Error("Internal error: Atomics.wait() failed: " + status);
2273
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2274
+ if (id !== id2)
2275
+ throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2276
+ if (reject) {
2277
+ applyProperties(reject, properties);
2278
+ throw reject;
2279
+ }
2280
+ return resolve;
2281
+ };
2282
+ worker.unref();
2283
+ return {
2284
+ buildSync(options) {
2285
+ validateBuildSyncOptions(options);
2286
+ return runCallSync("build", [options]);
2287
+ },
2288
+ transformSync(input, options) {
2289
+ return runCallSync("transform", [input, options]);
2290
+ },
2291
+ formatMessagesSync(messages, options) {
2292
+ return runCallSync("formatMessages", [messages, options]);
2293
+ },
2294
+ analyzeMetafileSync(metafile, options) {
2295
+ return runCallSync("analyzeMetafile", [metafile, options]);
2296
+ },
2297
+ stop() {
2298
+ worker.terminate();
2299
+ workerThreadService = null;
2300
+ }
2301
+ };
2302
+ };
2303
+ var startSyncServiceWorker = () => {
2304
+ let workerPort = worker_threads.workerData.workerPort;
2305
+ let parentPort = worker_threads.parentPort;
2306
+ let extractProperties = (object) => {
2307
+ let properties = {};
2308
+ if (object && typeof object === "object") {
2309
+ for (let key in object) {
2310
+ properties[key] = object[key];
2311
+ }
2312
+ }
2313
+ return properties;
2314
+ };
2315
+ try {
2316
+ let service = ensureServiceIsRunning();
2317
+ defaultWD = worker_threads.workerData.defaultWD;
2318
+ parentPort.on("message", (msg) => {
2319
+ (async () => {
2320
+ let { sharedBuffer, id, command, args } = msg;
2321
+ let sharedBufferView = new Int32Array(sharedBuffer);
2322
+ try {
2323
+ switch (command) {
2324
+ case "build":
2325
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2326
+ break;
2327
+ case "transform":
2328
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2329
+ break;
2330
+ case "formatMessages":
2331
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2332
+ break;
2333
+ case "analyzeMetafile":
2334
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2335
+ break;
2336
+ default:
2337
+ throw new Error(`Invalid command: ${command}`);
2338
+ }
2339
+ } catch (reject) {
2340
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2341
+ }
2342
+ Atomics.add(sharedBufferView, 0, 1);
2343
+ Atomics.notify(sharedBufferView, 0, Infinity);
2344
+ })();
2345
+ });
2346
+ } catch (reject) {
2347
+ parentPort.on("message", (msg) => {
2348
+ let { sharedBuffer, id } = msg;
2349
+ let sharedBufferView = new Int32Array(sharedBuffer);
2350
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2351
+ Atomics.add(sharedBufferView, 0, 1);
2352
+ Atomics.notify(sharedBufferView, 0, Infinity);
2353
+ });
2354
+ }
2355
+ };
2356
+ if (isInternalWorkerThread) {
2357
+ startSyncServiceWorker();
2358
+ }
2359
+ var node_default = node_exports;
2360
+ });
2361
+
2362
+ // ../../node_modules/react/cjs/react.development.js
2363
+ var require_react_development = __commonJS((exports, module) => {
2364
+ if (true) {
2365
+ (function() {
2366
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
2367
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);
2368
+ }
2369
+ var ReactVersion = "18.3.1";
2370
+ var REACT_ELEMENT_TYPE = Symbol.for("react.element");
2371
+ var REACT_PORTAL_TYPE = Symbol.for("react.portal");
2372
+ var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
2373
+ var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
2374
+ var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
2375
+ var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
2376
+ var REACT_CONTEXT_TYPE = Symbol.for("react.context");
2377
+ var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
2378
+ var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
2379
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
2380
+ var REACT_MEMO_TYPE = Symbol.for("react.memo");
2381
+ var REACT_LAZY_TYPE = Symbol.for("react.lazy");
2382
+ var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
2383
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
2384
+ var FAUX_ITERATOR_SYMBOL = "@@iterator";
2385
+ function getIteratorFn(maybeIterable) {
2386
+ if (maybeIterable === null || typeof maybeIterable !== "object") {
2387
+ return null;
2388
+ }
2389
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
2390
+ if (typeof maybeIterator === "function") {
2391
+ return maybeIterator;
2392
+ }
2393
+ return null;
2394
+ }
2395
+ var ReactCurrentDispatcher = {
2396
+ current: null
2397
+ };
2398
+ var ReactCurrentBatchConfig = {
2399
+ transition: null
2400
+ };
2401
+ var ReactCurrentActQueue = {
2402
+ current: null,
2403
+ isBatchingLegacy: false,
2404
+ didScheduleLegacyUpdate: false
2405
+ };
2406
+ var ReactCurrentOwner = {
2407
+ current: null
2408
+ };
2409
+ var ReactDebugCurrentFrame = {};
2410
+ var currentExtraStackFrame = null;
2411
+ function setExtraStackFrame(stack) {
2412
+ {
2413
+ currentExtraStackFrame = stack;
2414
+ }
2415
+ }
2416
+ {
2417
+ ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
2418
+ {
2419
+ currentExtraStackFrame = stack;
2420
+ }
2421
+ };
2422
+ ReactDebugCurrentFrame.getCurrentStack = null;
2423
+ ReactDebugCurrentFrame.getStackAddendum = function() {
2424
+ var stack = "";
2425
+ if (currentExtraStackFrame) {
2426
+ stack += currentExtraStackFrame;
2427
+ }
2428
+ var impl = ReactDebugCurrentFrame.getCurrentStack;
2429
+ if (impl) {
2430
+ stack += impl() || "";
2431
+ }
2432
+ return stack;
2433
+ };
2434
+ }
2435
+ var enableScopeAPI = false;
2436
+ var enableCacheElement = false;
2437
+ var enableTransitionTracing = false;
2438
+ var enableLegacyHidden = false;
2439
+ var enableDebugTracing = false;
2440
+ var ReactSharedInternals = {
2441
+ ReactCurrentDispatcher,
2442
+ ReactCurrentBatchConfig,
2443
+ ReactCurrentOwner
2444
+ };
2445
+ {
2446
+ ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
2447
+ ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
2448
+ }
2449
+ function warn(format) {
2450
+ {
2451
+ {
2452
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1;_key < _len; _key++) {
2453
+ args[_key - 1] = arguments[_key];
2454
+ }
2455
+ printWarning("warn", format, args);
2456
+ }
2457
+ }
2458
+ }
2459
+ function error(format) {
2460
+ {
2461
+ {
2462
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1;_key2 < _len2; _key2++) {
2463
+ args[_key2 - 1] = arguments[_key2];
2464
+ }
2465
+ printWarning("error", format, args);
2466
+ }
2467
+ }
2468
+ }
2469
+ function printWarning(level, format, args) {
2470
+ {
2471
+ var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
2472
+ var stack = ReactDebugCurrentFrame2.getStackAddendum();
2473
+ if (stack !== "") {
2474
+ format += "%s";
2475
+ args = args.concat([stack]);
2476
+ }
2477
+ var argsWithFormat = args.map(function(item) {
2478
+ return String(item);
2479
+ });
2480
+ argsWithFormat.unshift("Warning: " + format);
2481
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
2482
+ }
2483
+ }
2484
+ var didWarnStateUpdateForUnmountedComponent = {};
2485
+ function warnNoop(publicInstance, callerName) {
2486
+ {
2487
+ var _constructor = publicInstance.constructor;
2488
+ var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass";
2489
+ var warningKey = componentName + "." + callerName;
2490
+ if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
2491
+ return;
2492
+ }
2493
+ error("Can't call %s on a component that is not yet mounted. " + "This is a no-op, but it might indicate a bug in your application. " + "Instead, assign to `this.state` directly or define a `state = {};` " + "class property with the desired state in the %s component.", callerName, componentName);
2494
+ didWarnStateUpdateForUnmountedComponent[warningKey] = true;
2495
+ }
2496
+ }
2497
+ var ReactNoopUpdateQueue = {
2498
+ isMounted: function(publicInstance) {
2499
+ return false;
2500
+ },
2501
+ enqueueForceUpdate: function(publicInstance, callback, callerName) {
2502
+ warnNoop(publicInstance, "forceUpdate");
2503
+ },
2504
+ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
2505
+ warnNoop(publicInstance, "replaceState");
2506
+ },
2507
+ enqueueSetState: function(publicInstance, partialState, callback, callerName) {
2508
+ warnNoop(publicInstance, "setState");
2509
+ }
2510
+ };
2511
+ var assign = Object.assign;
2512
+ var emptyObject = {};
2513
+ {
2514
+ Object.freeze(emptyObject);
2515
+ }
2516
+ function Component(props, context, updater) {
2517
+ this.props = props;
2518
+ this.context = context;
2519
+ this.refs = emptyObject;
2520
+ this.updater = updater || ReactNoopUpdateQueue;
2521
+ }
2522
+ Component.prototype.isReactComponent = {};
2523
+ Component.prototype.setState = function(partialState, callback) {
2524
+ if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) {
2525
+ throw new Error("setState(...): takes an object of state variables to update or a " + "function which returns an object of state variables.");
2526
+ }
2527
+ this.updater.enqueueSetState(this, partialState, callback, "setState");
2528
+ };
2529
+ Component.prototype.forceUpdate = function(callback) {
2530
+ this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
2531
+ };
2532
+ {
2533
+ var deprecatedAPIs = {
2534
+ isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in " + "componentWillUnmount to prevent memory leaks."],
2535
+ replaceState: ["replaceState", "Refactor your code to use setState instead (see " + "https://github.com/facebook/react/issues/3236)."]
2536
+ };
2537
+ var defineDeprecationWarning = function(methodName, info) {
2538
+ Object.defineProperty(Component.prototype, methodName, {
2539
+ get: function() {
2540
+ warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
2541
+ return;
2542
+ }
2543
+ });
2544
+ };
2545
+ for (var fnName in deprecatedAPIs) {
2546
+ if (deprecatedAPIs.hasOwnProperty(fnName)) {
2547
+ defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
2548
+ }
2549
+ }
2550
+ }
2551
+ function ComponentDummy() {}
2552
+ ComponentDummy.prototype = Component.prototype;
2553
+ function PureComponent(props, context, updater) {
2554
+ this.props = props;
2555
+ this.context = context;
2556
+ this.refs = emptyObject;
2557
+ this.updater = updater || ReactNoopUpdateQueue;
2558
+ }
2559
+ var pureComponentPrototype = PureComponent.prototype = new ComponentDummy;
2560
+ pureComponentPrototype.constructor = PureComponent;
2561
+ assign(pureComponentPrototype, Component.prototype);
2562
+ pureComponentPrototype.isPureReactComponent = true;
2563
+ function createRef() {
2564
+ var refObject = {
2565
+ current: null
2566
+ };
2567
+ {
2568
+ Object.seal(refObject);
2569
+ }
2570
+ return refObject;
2571
+ }
2572
+ var isArrayImpl = Array.isArray;
2573
+ function isArray(a) {
2574
+ return isArrayImpl(a);
2575
+ }
2576
+ function typeName(value) {
2577
+ {
2578
+ var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
2579
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
2580
+ return type;
2581
+ }
2582
+ }
2583
+ function willCoercionThrow(value) {
2584
+ {
2585
+ try {
2586
+ testStringCoercion(value);
2587
+ return false;
2588
+ } catch (e) {
2589
+ return true;
2590
+ }
2591
+ }
2592
+ }
2593
+ function testStringCoercion(value) {
2594
+ return "" + value;
2595
+ }
2596
+ function checkKeyStringCoercion(value) {
2597
+ {
2598
+ if (willCoercionThrow(value)) {
2599
+ error("The provided key is an unsupported type %s." + " This value must be coerced to a string before before using it here.", typeName(value));
2600
+ return testStringCoercion(value);
2601
+ }
2602
+ }
2603
+ }
2604
+ function getWrappedName(outerType, innerType, wrapperName) {
2605
+ var displayName = outerType.displayName;
2606
+ if (displayName) {
2607
+ return displayName;
2608
+ }
2609
+ var functionName = innerType.displayName || innerType.name || "";
2610
+ return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
2611
+ }
2612
+ function getContextName(type) {
2613
+ return type.displayName || "Context";
2614
+ }
2615
+ function getComponentNameFromType(type) {
2616
+ if (type == null) {
2617
+ return null;
2618
+ }
2619
+ {
2620
+ if (typeof type.tag === "number") {
2621
+ error("Received an unexpected object in getComponentNameFromType(). " + "This is likely a bug in React. Please file an issue.");
2622
+ }
2623
+ }
2624
+ if (typeof type === "function") {
2625
+ return type.displayName || type.name || null;
2626
+ }
2627
+ if (typeof type === "string") {
2628
+ return type;
2629
+ }
2630
+ switch (type) {
2631
+ case REACT_FRAGMENT_TYPE:
2632
+ return "Fragment";
2633
+ case REACT_PORTAL_TYPE:
2634
+ return "Portal";
2635
+ case REACT_PROFILER_TYPE:
2636
+ return "Profiler";
2637
+ case REACT_STRICT_MODE_TYPE:
2638
+ return "StrictMode";
2639
+ case REACT_SUSPENSE_TYPE:
2640
+ return "Suspense";
2641
+ case REACT_SUSPENSE_LIST_TYPE:
2642
+ return "SuspenseList";
2643
+ }
2644
+ if (typeof type === "object") {
2645
+ switch (type.$$typeof) {
2646
+ case REACT_CONTEXT_TYPE:
2647
+ var context = type;
2648
+ return getContextName(context) + ".Consumer";
2649
+ case REACT_PROVIDER_TYPE:
2650
+ var provider = type;
2651
+ return getContextName(provider._context) + ".Provider";
2652
+ case REACT_FORWARD_REF_TYPE:
2653
+ return getWrappedName(type, type.render, "ForwardRef");
2654
+ case REACT_MEMO_TYPE:
2655
+ var outerName = type.displayName || null;
2656
+ if (outerName !== null) {
2657
+ return outerName;
2658
+ }
2659
+ return getComponentNameFromType(type.type) || "Memo";
2660
+ case REACT_LAZY_TYPE: {
2661
+ var lazyComponent = type;
2662
+ var payload = lazyComponent._payload;
2663
+ var init = lazyComponent._init;
2664
+ try {
2665
+ return getComponentNameFromType(init(payload));
2666
+ } catch (x) {
2667
+ return null;
2668
+ }
2669
+ }
2670
+ }
2671
+ }
2672
+ return null;
2673
+ }
2674
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
2675
+ var RESERVED_PROPS = {
2676
+ key: true,
2677
+ ref: true,
2678
+ __self: true,
2679
+ __source: true
2680
+ };
2681
+ var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
2682
+ {
2683
+ didWarnAboutStringRefs = {};
2684
+ }
2685
+ function hasValidRef(config) {
2686
+ {
2687
+ if (hasOwnProperty.call(config, "ref")) {
2688
+ var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
2689
+ if (getter && getter.isReactWarning) {
2690
+ return false;
2691
+ }
2692
+ }
2693
+ }
2694
+ return config.ref !== undefined;
2695
+ }
2696
+ function hasValidKey(config) {
2697
+ {
2698
+ if (hasOwnProperty.call(config, "key")) {
2699
+ var getter = Object.getOwnPropertyDescriptor(config, "key").get;
2700
+ if (getter && getter.isReactWarning) {
2701
+ return false;
2702
+ }
2703
+ }
2704
+ }
2705
+ return config.key !== undefined;
2706
+ }
2707
+ function defineKeyPropWarningGetter(props, displayName) {
2708
+ var warnAboutAccessingKey = function() {
2709
+ {
2710
+ if (!specialPropKeyWarningShown) {
2711
+ specialPropKeyWarningShown = true;
2712
+ error("%s: `key` is not a prop. Trying to access it will result " + "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", displayName);
2713
+ }
2714
+ }
2715
+ };
2716
+ warnAboutAccessingKey.isReactWarning = true;
2717
+ Object.defineProperty(props, "key", {
2718
+ get: warnAboutAccessingKey,
2719
+ configurable: true
2720
+ });
2721
+ }
2722
+ function defineRefPropWarningGetter(props, displayName) {
2723
+ var warnAboutAccessingRef = function() {
2724
+ {
2725
+ if (!specialPropRefWarningShown) {
2726
+ specialPropRefWarningShown = true;
2727
+ error("%s: `ref` is not a prop. Trying to access it will result " + "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", displayName);
2728
+ }
2729
+ }
2730
+ };
2731
+ warnAboutAccessingRef.isReactWarning = true;
2732
+ Object.defineProperty(props, "ref", {
2733
+ get: warnAboutAccessingRef,
2734
+ configurable: true
2735
+ });
2736
+ }
2737
+ function warnIfStringRefCannotBeAutoConverted(config) {
2738
+ {
2739
+ if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
2740
+ var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
2741
+ if (!didWarnAboutStringRefs[componentName]) {
2742
+ error('Component "%s" contains the string ref "%s". ' + "Support for string refs will be removed in a future major release. " + "This case cannot be automatically converted to an arrow function. " + "We ask you to manually fix this case by using useRef() or createRef() instead. " + "Learn more about using refs safely here: " + "https://reactjs.org/link/strict-mode-string-ref", componentName, config.ref);
2743
+ didWarnAboutStringRefs[componentName] = true;
2744
+ }
2745
+ }
2746
+ }
2747
+ }
2748
+ var ReactElement = function(type, key, ref, self, source, owner, props) {
2749
+ var element = {
2750
+ $$typeof: REACT_ELEMENT_TYPE,
2751
+ type,
2752
+ key,
2753
+ ref,
2754
+ props,
2755
+ _owner: owner
2756
+ };
2757
+ {
2758
+ element._store = {};
2759
+ Object.defineProperty(element._store, "validated", {
2760
+ configurable: false,
2761
+ enumerable: false,
2762
+ writable: true,
2763
+ value: false
2764
+ });
2765
+ Object.defineProperty(element, "_self", {
2766
+ configurable: false,
2767
+ enumerable: false,
2768
+ writable: false,
2769
+ value: self
2770
+ });
2771
+ Object.defineProperty(element, "_source", {
2772
+ configurable: false,
2773
+ enumerable: false,
2774
+ writable: false,
2775
+ value: source
2776
+ });
2777
+ if (Object.freeze) {
2778
+ Object.freeze(element.props);
2779
+ Object.freeze(element);
2780
+ }
2781
+ }
2782
+ return element;
2783
+ };
2784
+ function createElement(type, config, children) {
2785
+ var propName;
2786
+ var props = {};
2787
+ var key = null;
2788
+ var ref = null;
2789
+ var self = null;
2790
+ var source = null;
2791
+ if (config != null) {
2792
+ if (hasValidRef(config)) {
2793
+ ref = config.ref;
2794
+ {
2795
+ warnIfStringRefCannotBeAutoConverted(config);
2796
+ }
2797
+ }
2798
+ if (hasValidKey(config)) {
2799
+ {
2800
+ checkKeyStringCoercion(config.key);
2801
+ }
2802
+ key = "" + config.key;
2803
+ }
2804
+ self = config.__self === undefined ? null : config.__self;
2805
+ source = config.__source === undefined ? null : config.__source;
2806
+ for (propName in config) {
2807
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
2808
+ props[propName] = config[propName];
2809
+ }
2810
+ }
2811
+ }
2812
+ var childrenLength = arguments.length - 2;
2813
+ if (childrenLength === 1) {
2814
+ props.children = children;
2815
+ } else if (childrenLength > 1) {
2816
+ var childArray = Array(childrenLength);
2817
+ for (var i = 0;i < childrenLength; i++) {
2818
+ childArray[i] = arguments[i + 2];
2819
+ }
2820
+ {
2821
+ if (Object.freeze) {
2822
+ Object.freeze(childArray);
2823
+ }
2824
+ }
2825
+ props.children = childArray;
2826
+ }
2827
+ if (type && type.defaultProps) {
2828
+ var defaultProps = type.defaultProps;
2829
+ for (propName in defaultProps) {
2830
+ if (props[propName] === undefined) {
2831
+ props[propName] = defaultProps[propName];
2832
+ }
2833
+ }
2834
+ }
2835
+ {
2836
+ if (key || ref) {
2837
+ var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
2838
+ if (key) {
2839
+ defineKeyPropWarningGetter(props, displayName);
2840
+ }
2841
+ if (ref) {
2842
+ defineRefPropWarningGetter(props, displayName);
2843
+ }
2844
+ }
2845
+ }
2846
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
2847
+ }
2848
+ function cloneAndReplaceKey(oldElement, newKey) {
2849
+ var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
2850
+ return newElement;
2851
+ }
2852
+ function cloneElement(element, config, children) {
2853
+ if (element === null || element === undefined) {
2854
+ throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
2855
+ }
2856
+ var propName;
2857
+ var props = assign({}, element.props);
2858
+ var key = element.key;
2859
+ var ref = element.ref;
2860
+ var self = element._self;
2861
+ var source = element._source;
2862
+ var owner = element._owner;
2863
+ if (config != null) {
2864
+ if (hasValidRef(config)) {
2865
+ ref = config.ref;
2866
+ owner = ReactCurrentOwner.current;
2867
+ }
2868
+ if (hasValidKey(config)) {
2869
+ {
2870
+ checkKeyStringCoercion(config.key);
2871
+ }
2872
+ key = "" + config.key;
2873
+ }
2874
+ var defaultProps;
2875
+ if (element.type && element.type.defaultProps) {
2876
+ defaultProps = element.type.defaultProps;
2877
+ }
2878
+ for (propName in config) {
2879
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
2880
+ if (config[propName] === undefined && defaultProps !== undefined) {
2881
+ props[propName] = defaultProps[propName];
2882
+ } else {
2883
+ props[propName] = config[propName];
2884
+ }
2885
+ }
2886
+ }
2887
+ }
2888
+ var childrenLength = arguments.length - 2;
2889
+ if (childrenLength === 1) {
2890
+ props.children = children;
2891
+ } else if (childrenLength > 1) {
2892
+ var childArray = Array(childrenLength);
2893
+ for (var i = 0;i < childrenLength; i++) {
2894
+ childArray[i] = arguments[i + 2];
2895
+ }
2896
+ props.children = childArray;
2897
+ }
2898
+ return ReactElement(element.type, key, ref, self, source, owner, props);
2899
+ }
2900
+ function isValidElement(object) {
2901
+ return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
2902
+ }
2903
+ var SEPARATOR = ".";
2904
+ var SUBSEPARATOR = ":";
2905
+ function escape(key) {
2906
+ var escapeRegex = /[=:]/g;
2907
+ var escaperLookup = {
2908
+ "=": "=0",
2909
+ ":": "=2"
2910
+ };
2911
+ var escapedString = key.replace(escapeRegex, function(match) {
2912
+ return escaperLookup[match];
2913
+ });
2914
+ return "$" + escapedString;
2915
+ }
2916
+ var didWarnAboutMaps = false;
2917
+ var userProvidedKeyEscapeRegex = /\/+/g;
2918
+ function escapeUserProvidedKey(text) {
2919
+ return text.replace(userProvidedKeyEscapeRegex, "$&/");
2920
+ }
2921
+ function getElementKey(element, index) {
2922
+ if (typeof element === "object" && element !== null && element.key != null) {
2923
+ {
2924
+ checkKeyStringCoercion(element.key);
2925
+ }
2926
+ return escape("" + element.key);
2927
+ }
2928
+ return index.toString(36);
2929
+ }
2930
+ function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
2931
+ var type = typeof children;
2932
+ if (type === "undefined" || type === "boolean") {
2933
+ children = null;
2934
+ }
2935
+ var invokeCallback = false;
2936
+ if (children === null) {
2937
+ invokeCallback = true;
2938
+ } else {
2939
+ switch (type) {
2940
+ case "string":
2941
+ case "number":
2942
+ invokeCallback = true;
2943
+ break;
2944
+ case "object":
2945
+ switch (children.$$typeof) {
2946
+ case REACT_ELEMENT_TYPE:
2947
+ case REACT_PORTAL_TYPE:
2948
+ invokeCallback = true;
2949
+ }
2950
+ }
2951
+ }
2952
+ if (invokeCallback) {
2953
+ var _child = children;
2954
+ var mappedChild = callback(_child);
2955
+ var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
2956
+ if (isArray(mappedChild)) {
2957
+ var escapedChildKey = "";
2958
+ if (childKey != null) {
2959
+ escapedChildKey = escapeUserProvidedKey(childKey) + "/";
2960
+ }
2961
+ mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) {
2962
+ return c;
2963
+ });
2964
+ } else if (mappedChild != null) {
2965
+ if (isValidElement(mappedChild)) {
2966
+ {
2967
+ if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
2968
+ checkKeyStringCoercion(mappedChild.key);
2969
+ }
2970
+ }
2971
+ mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey);
2972
+ }
2973
+ array.push(mappedChild);
2974
+ }
2975
+ return 1;
2976
+ }
2977
+ var child;
2978
+ var nextName;
2979
+ var subtreeCount = 0;
2980
+ var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR;
2981
+ if (isArray(children)) {
2982
+ for (var i = 0;i < children.length; i++) {
2983
+ child = children[i];
2984
+ nextName = nextNamePrefix + getElementKey(child, i);
2985
+ subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
2986
+ }
2987
+ } else {
2988
+ var iteratorFn = getIteratorFn(children);
2989
+ if (typeof iteratorFn === "function") {
2990
+ var iterableChildren = children;
2991
+ {
2992
+ if (iteratorFn === iterableChildren.entries) {
2993
+ if (!didWarnAboutMaps) {
2994
+ warn("Using Maps as children is not supported. " + "Use an array of keyed ReactElements instead.");
2995
+ }
2996
+ didWarnAboutMaps = true;
2997
+ }
2998
+ }
2999
+ var iterator = iteratorFn.call(iterableChildren);
3000
+ var step;
3001
+ var ii = 0;
3002
+ while (!(step = iterator.next()).done) {
3003
+ child = step.value;
3004
+ nextName = nextNamePrefix + getElementKey(child, ii++);
3005
+ subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
3006
+ }
3007
+ } else if (type === "object") {
3008
+ var childrenString = String(children);
3009
+ throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). " + "If you meant to render a collection of children, use an array " + "instead.");
3010
+ }
3011
+ }
3012
+ return subtreeCount;
3013
+ }
3014
+ function mapChildren(children, func, context) {
3015
+ if (children == null) {
3016
+ return children;
3017
+ }
3018
+ var result = [];
3019
+ var count = 0;
3020
+ mapIntoArray(children, result, "", "", function(child) {
3021
+ return func.call(context, child, count++);
3022
+ });
3023
+ return result;
3024
+ }
3025
+ function countChildren(children) {
3026
+ var n = 0;
3027
+ mapChildren(children, function() {
3028
+ n++;
3029
+ });
3030
+ return n;
3031
+ }
3032
+ function forEachChildren(children, forEachFunc, forEachContext) {
3033
+ mapChildren(children, function() {
3034
+ forEachFunc.apply(this, arguments);
3035
+ }, forEachContext);
3036
+ }
3037
+ function toArray(children) {
3038
+ return mapChildren(children, function(child) {
3039
+ return child;
3040
+ }) || [];
3041
+ }
3042
+ function onlyChild(children) {
3043
+ if (!isValidElement(children)) {
3044
+ throw new Error("React.Children.only expected to receive a single React element child.");
3045
+ }
3046
+ return children;
3047
+ }
3048
+ function createContext(defaultValue) {
3049
+ var context = {
3050
+ $$typeof: REACT_CONTEXT_TYPE,
3051
+ _currentValue: defaultValue,
3052
+ _currentValue2: defaultValue,
3053
+ _threadCount: 0,
3054
+ Provider: null,
3055
+ Consumer: null,
3056
+ _defaultValue: null,
3057
+ _globalName: null
3058
+ };
3059
+ context.Provider = {
3060
+ $$typeof: REACT_PROVIDER_TYPE,
3061
+ _context: context
3062
+ };
3063
+ var hasWarnedAboutUsingNestedContextConsumers = false;
3064
+ var hasWarnedAboutUsingConsumerProvider = false;
3065
+ var hasWarnedAboutDisplayNameOnConsumer = false;
3066
+ {
3067
+ var Consumer = {
3068
+ $$typeof: REACT_CONTEXT_TYPE,
3069
+ _context: context
3070
+ };
3071
+ Object.defineProperties(Consumer, {
3072
+ Provider: {
3073
+ get: function() {
3074
+ if (!hasWarnedAboutUsingConsumerProvider) {
3075
+ hasWarnedAboutUsingConsumerProvider = true;
3076
+ error("Rendering <Context.Consumer.Provider> is not supported and will be removed in " + "a future major release. Did you mean to render <Context.Provider> instead?");
3077
+ }
3078
+ return context.Provider;
3079
+ },
3080
+ set: function(_Provider) {
3081
+ context.Provider = _Provider;
3082
+ }
3083
+ },
3084
+ _currentValue: {
3085
+ get: function() {
3086
+ return context._currentValue;
3087
+ },
3088
+ set: function(_currentValue) {
3089
+ context._currentValue = _currentValue;
3090
+ }
3091
+ },
3092
+ _currentValue2: {
3093
+ get: function() {
3094
+ return context._currentValue2;
3095
+ },
3096
+ set: function(_currentValue2) {
3097
+ context._currentValue2 = _currentValue2;
3098
+ }
3099
+ },
3100
+ _threadCount: {
3101
+ get: function() {
3102
+ return context._threadCount;
3103
+ },
3104
+ set: function(_threadCount) {
3105
+ context._threadCount = _threadCount;
3106
+ }
3107
+ },
3108
+ Consumer: {
3109
+ get: function() {
3110
+ if (!hasWarnedAboutUsingNestedContextConsumers) {
3111
+ hasWarnedAboutUsingNestedContextConsumers = true;
3112
+ error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in " + "a future major release. Did you mean to render <Context.Consumer> instead?");
3113
+ }
3114
+ return context.Consumer;
3115
+ }
3116
+ },
3117
+ displayName: {
3118
+ get: function() {
3119
+ return context.displayName;
3120
+ },
3121
+ set: function(displayName) {
3122
+ if (!hasWarnedAboutDisplayNameOnConsumer) {
3123
+ warn("Setting `displayName` on Context.Consumer has no effect. " + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
3124
+ hasWarnedAboutDisplayNameOnConsumer = true;
3125
+ }
3126
+ }
3127
+ }
3128
+ });
3129
+ context.Consumer = Consumer;
3130
+ }
3131
+ {
3132
+ context._currentRenderer = null;
3133
+ context._currentRenderer2 = null;
3134
+ }
3135
+ return context;
3136
+ }
3137
+ var Uninitialized = -1;
3138
+ var Pending = 0;
3139
+ var Resolved = 1;
3140
+ var Rejected = 2;
3141
+ function lazyInitializer(payload) {
3142
+ if (payload._status === Uninitialized) {
3143
+ var ctor = payload._result;
3144
+ var thenable = ctor();
3145
+ thenable.then(function(moduleObject2) {
3146
+ if (payload._status === Pending || payload._status === Uninitialized) {
3147
+ var resolved = payload;
3148
+ resolved._status = Resolved;
3149
+ resolved._result = moduleObject2;
3150
+ }
3151
+ }, function(error2) {
3152
+ if (payload._status === Pending || payload._status === Uninitialized) {
3153
+ var rejected = payload;
3154
+ rejected._status = Rejected;
3155
+ rejected._result = error2;
3156
+ }
3157
+ });
3158
+ if (payload._status === Uninitialized) {
3159
+ var pending = payload;
3160
+ pending._status = Pending;
3161
+ pending._result = thenable;
3162
+ }
3163
+ }
3164
+ if (payload._status === Resolved) {
3165
+ var moduleObject = payload._result;
3166
+ {
3167
+ if (moduleObject === undefined) {
3168
+ error("lazy: Expected the result of a dynamic imp" + "ort() call. " + `Instead received: %s
3169
+
3170
+ Your code should look like:
3171
+ ` + "const MyComponent = lazy(() => imp" + `ort('./MyComponent'))
3172
+
3173
+ ` + "Did you accidentally put curly braces around the import?", moduleObject);
3174
+ }
3175
+ }
3176
+ {
3177
+ if (!("default" in moduleObject)) {
3178
+ error("lazy: Expected the result of a dynamic imp" + "ort() call. " + `Instead received: %s
3179
+
3180
+ Your code should look like:
3181
+ ` + "const MyComponent = lazy(() => imp" + "ort('./MyComponent'))", moduleObject);
3182
+ }
3183
+ }
3184
+ return moduleObject.default;
3185
+ } else {
3186
+ throw payload._result;
3187
+ }
3188
+ }
3189
+ function lazy(ctor) {
3190
+ var payload = {
3191
+ _status: Uninitialized,
3192
+ _result: ctor
3193
+ };
3194
+ var lazyType = {
3195
+ $$typeof: REACT_LAZY_TYPE,
3196
+ _payload: payload,
3197
+ _init: lazyInitializer
3198
+ };
3199
+ {
3200
+ var defaultProps;
3201
+ var propTypes;
3202
+ Object.defineProperties(lazyType, {
3203
+ defaultProps: {
3204
+ configurable: true,
3205
+ get: function() {
3206
+ return defaultProps;
3207
+ },
3208
+ set: function(newDefaultProps) {
3209
+ error("React.lazy(...): It is not supported to assign `defaultProps` to " + "a lazy component import. Either specify them where the component " + "is defined, or create a wrapping component around it.");
3210
+ defaultProps = newDefaultProps;
3211
+ Object.defineProperty(lazyType, "defaultProps", {
3212
+ enumerable: true
3213
+ });
3214
+ }
3215
+ },
3216
+ propTypes: {
3217
+ configurable: true,
3218
+ get: function() {
3219
+ return propTypes;
3220
+ },
3221
+ set: function(newPropTypes) {
3222
+ error("React.lazy(...): It is not supported to assign `propTypes` to " + "a lazy component import. Either specify them where the component " + "is defined, or create a wrapping component around it.");
3223
+ propTypes = newPropTypes;
3224
+ Object.defineProperty(lazyType, "propTypes", {
3225
+ enumerable: true
3226
+ });
3227
+ }
3228
+ }
3229
+ });
3230
+ }
3231
+ return lazyType;
3232
+ }
3233
+ function forwardRef(render) {
3234
+ {
3235
+ if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
3236
+ error("forwardRef requires a render function but received a `memo` " + "component. Instead of forwardRef(memo(...)), use " + "memo(forwardRef(...)).");
3237
+ } else if (typeof render !== "function") {
3238
+ error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render);
3239
+ } else {
3240
+ if (render.length !== 0 && render.length !== 2) {
3241
+ error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
3242
+ }
3243
+ }
3244
+ if (render != null) {
3245
+ if (render.defaultProps != null || render.propTypes != null) {
3246
+ error("forwardRef render functions do not support propTypes or defaultProps. " + "Did you accidentally pass a React component?");
3247
+ }
3248
+ }
3249
+ }
3250
+ var elementType = {
3251
+ $$typeof: REACT_FORWARD_REF_TYPE,
3252
+ render
3253
+ };
3254
+ {
3255
+ var ownName;
3256
+ Object.defineProperty(elementType, "displayName", {
3257
+ enumerable: false,
3258
+ configurable: true,
3259
+ get: function() {
3260
+ return ownName;
3261
+ },
3262
+ set: function(name) {
3263
+ ownName = name;
3264
+ if (!render.name && !render.displayName) {
3265
+ render.displayName = name;
3266
+ }
3267
+ }
3268
+ });
3269
+ }
3270
+ return elementType;
3271
+ }
3272
+ var REACT_MODULE_REFERENCE;
3273
+ {
3274
+ REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
3275
+ }
3276
+ function isValidElementType(type) {
3277
+ if (typeof type === "string" || typeof type === "function") {
3278
+ return true;
3279
+ }
3280
+ if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
3281
+ return true;
3282
+ }
3283
+ if (typeof type === "object" && type !== null) {
3284
+ if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
3285
+ return true;
3286
+ }
3287
+ }
3288
+ return false;
3289
+ }
3290
+ function memo(type, compare) {
3291
+ {
3292
+ if (!isValidElementType(type)) {
3293
+ error("memo: The first argument must be a component. Instead " + "received: %s", type === null ? "null" : typeof type);
3294
+ }
3295
+ }
3296
+ var elementType = {
3297
+ $$typeof: REACT_MEMO_TYPE,
3298
+ type,
3299
+ compare: compare === undefined ? null : compare
3300
+ };
3301
+ {
3302
+ var ownName;
3303
+ Object.defineProperty(elementType, "displayName", {
3304
+ enumerable: false,
3305
+ configurable: true,
3306
+ get: function() {
3307
+ return ownName;
3308
+ },
3309
+ set: function(name) {
3310
+ ownName = name;
3311
+ if (!type.name && !type.displayName) {
3312
+ type.displayName = name;
3313
+ }
3314
+ }
3315
+ });
3316
+ }
3317
+ return elementType;
3318
+ }
3319
+ function resolveDispatcher() {
3320
+ var dispatcher = ReactCurrentDispatcher.current;
3321
+ {
3322
+ if (dispatcher === null) {
3323
+ error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for" + ` one of the following reasons:
3324
+ ` + `1. You might have mismatching versions of React and the renderer (such as React DOM)
3325
+ ` + `2. You might be breaking the Rules of Hooks
3326
+ ` + `3. You might have more than one copy of React in the same app
3327
+ ` + "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
3328
+ }
3329
+ }
3330
+ return dispatcher;
3331
+ }
3332
+ function useContext(Context) {
3333
+ var dispatcher = resolveDispatcher();
3334
+ {
3335
+ if (Context._context !== undefined) {
3336
+ var realContext = Context._context;
3337
+ if (realContext.Consumer === Context) {
3338
+ error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be " + "removed in a future major release. Did you mean to call useContext(Context) instead?");
3339
+ } else if (realContext.Provider === Context) {
3340
+ error("Calling useContext(Context.Provider) is not supported. " + "Did you mean to call useContext(Context) instead?");
3341
+ }
3342
+ }
3343
+ }
3344
+ return dispatcher.useContext(Context);
3345
+ }
3346
+ function useState(initialState) {
3347
+ var dispatcher = resolveDispatcher();
3348
+ return dispatcher.useState(initialState);
3349
+ }
3350
+ function useReducer(reducer, initialArg, init) {
3351
+ var dispatcher = resolveDispatcher();
3352
+ return dispatcher.useReducer(reducer, initialArg, init);
3353
+ }
3354
+ function useRef(initialValue) {
3355
+ var dispatcher = resolveDispatcher();
3356
+ return dispatcher.useRef(initialValue);
3357
+ }
3358
+ function useEffect(create, deps) {
3359
+ var dispatcher = resolveDispatcher();
3360
+ return dispatcher.useEffect(create, deps);
3361
+ }
3362
+ function useInsertionEffect(create, deps) {
3363
+ var dispatcher = resolveDispatcher();
3364
+ return dispatcher.useInsertionEffect(create, deps);
3365
+ }
3366
+ function useLayoutEffect(create, deps) {
3367
+ var dispatcher = resolveDispatcher();
3368
+ return dispatcher.useLayoutEffect(create, deps);
3369
+ }
3370
+ function useCallback(callback, deps) {
3371
+ var dispatcher = resolveDispatcher();
3372
+ return dispatcher.useCallback(callback, deps);
3373
+ }
3374
+ function useMemo(create, deps) {
3375
+ var dispatcher = resolveDispatcher();
3376
+ return dispatcher.useMemo(create, deps);
3377
+ }
3378
+ function useImperativeHandle(ref, create, deps) {
3379
+ var dispatcher = resolveDispatcher();
3380
+ return dispatcher.useImperativeHandle(ref, create, deps);
3381
+ }
3382
+ function useDebugValue(value, formatterFn) {
3383
+ {
3384
+ var dispatcher = resolveDispatcher();
3385
+ return dispatcher.useDebugValue(value, formatterFn);
3386
+ }
3387
+ }
3388
+ function useTransition() {
3389
+ var dispatcher = resolveDispatcher();
3390
+ return dispatcher.useTransition();
3391
+ }
3392
+ function useDeferredValue(value) {
3393
+ var dispatcher = resolveDispatcher();
3394
+ return dispatcher.useDeferredValue(value);
3395
+ }
3396
+ function useId() {
3397
+ var dispatcher = resolveDispatcher();
3398
+ return dispatcher.useId();
3399
+ }
3400
+ function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
3401
+ var dispatcher = resolveDispatcher();
3402
+ return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
3403
+ }
3404
+ var disabledDepth = 0;
3405
+ var prevLog;
3406
+ var prevInfo;
3407
+ var prevWarn;
3408
+ var prevError;
3409
+ var prevGroup;
3410
+ var prevGroupCollapsed;
3411
+ var prevGroupEnd;
3412
+ function disabledLog() {}
3413
+ disabledLog.__reactDisabledLog = true;
3414
+ function disableLogs() {
3415
+ {
3416
+ if (disabledDepth === 0) {
3417
+ prevLog = console.log;
3418
+ prevInfo = console.info;
3419
+ prevWarn = console.warn;
3420
+ prevError = console.error;
3421
+ prevGroup = console.group;
3422
+ prevGroupCollapsed = console.groupCollapsed;
3423
+ prevGroupEnd = console.groupEnd;
3424
+ var props = {
3425
+ configurable: true,
3426
+ enumerable: true,
3427
+ value: disabledLog,
3428
+ writable: true
3429
+ };
3430
+ Object.defineProperties(console, {
3431
+ info: props,
3432
+ log: props,
3433
+ warn: props,
3434
+ error: props,
3435
+ group: props,
3436
+ groupCollapsed: props,
3437
+ groupEnd: props
3438
+ });
3439
+ }
3440
+ disabledDepth++;
3441
+ }
3442
+ }
3443
+ function reenableLogs() {
3444
+ {
3445
+ disabledDepth--;
3446
+ if (disabledDepth === 0) {
3447
+ var props = {
3448
+ configurable: true,
3449
+ enumerable: true,
3450
+ writable: true
3451
+ };
3452
+ Object.defineProperties(console, {
3453
+ log: assign({}, props, {
3454
+ value: prevLog
3455
+ }),
3456
+ info: assign({}, props, {
3457
+ value: prevInfo
3458
+ }),
3459
+ warn: assign({}, props, {
3460
+ value: prevWarn
3461
+ }),
3462
+ error: assign({}, props, {
3463
+ value: prevError
3464
+ }),
3465
+ group: assign({}, props, {
3466
+ value: prevGroup
3467
+ }),
3468
+ groupCollapsed: assign({}, props, {
3469
+ value: prevGroupCollapsed
3470
+ }),
3471
+ groupEnd: assign({}, props, {
3472
+ value: prevGroupEnd
3473
+ })
3474
+ });
3475
+ }
3476
+ if (disabledDepth < 0) {
3477
+ error("disabledDepth fell below zero. " + "This is a bug in React. Please file an issue.");
3478
+ }
3479
+ }
3480
+ }
3481
+ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
3482
+ var prefix;
3483
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
3484
+ {
3485
+ if (prefix === undefined) {
3486
+ try {
3487
+ throw Error();
3488
+ } catch (x) {
3489
+ var match = x.stack.trim().match(/\n( *(at )?)/);
3490
+ prefix = match && match[1] || "";
3491
+ }
3492
+ }
3493
+ return `
3494
+ ` + prefix + name;
3495
+ }
3496
+ }
3497
+ var reentry = false;
3498
+ var componentFrameCache;
3499
+ {
3500
+ var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
3501
+ componentFrameCache = new PossiblyWeakMap;
3502
+ }
3503
+ function describeNativeComponentFrame(fn, construct) {
3504
+ if (!fn || reentry) {
3505
+ return "";
3506
+ }
3507
+ {
3508
+ var frame = componentFrameCache.get(fn);
3509
+ if (frame !== undefined) {
3510
+ return frame;
3511
+ }
3512
+ }
3513
+ var control;
3514
+ reentry = true;
3515
+ var previousPrepareStackTrace = Error.prepareStackTrace;
3516
+ Error.prepareStackTrace = undefined;
3517
+ var previousDispatcher;
3518
+ {
3519
+ previousDispatcher = ReactCurrentDispatcher$1.current;
3520
+ ReactCurrentDispatcher$1.current = null;
3521
+ disableLogs();
3522
+ }
3523
+ try {
3524
+ if (construct) {
3525
+ var Fake = function() {
3526
+ throw Error();
3527
+ };
3528
+ Object.defineProperty(Fake.prototype, "props", {
3529
+ set: function() {
3530
+ throw Error();
3531
+ }
3532
+ });
3533
+ if (typeof Reflect === "object" && Reflect.construct) {
3534
+ try {
3535
+ Reflect.construct(Fake, []);
3536
+ } catch (x) {
3537
+ control = x;
3538
+ }
3539
+ Reflect.construct(fn, [], Fake);
3540
+ } else {
3541
+ try {
3542
+ Fake.call();
3543
+ } catch (x) {
3544
+ control = x;
3545
+ }
3546
+ fn.call(Fake.prototype);
3547
+ }
3548
+ } else {
3549
+ try {
3550
+ throw Error();
3551
+ } catch (x) {
3552
+ control = x;
3553
+ }
3554
+ fn();
3555
+ }
3556
+ } catch (sample) {
3557
+ if (sample && control && typeof sample.stack === "string") {
3558
+ var sampleLines = sample.stack.split(`
3559
+ `);
3560
+ var controlLines = control.stack.split(`
3561
+ `);
3562
+ var s = sampleLines.length - 1;
3563
+ var c = controlLines.length - 1;
3564
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
3565
+ c--;
3566
+ }
3567
+ for (;s >= 1 && c >= 0; s--, c--) {
3568
+ if (sampleLines[s] !== controlLines[c]) {
3569
+ if (s !== 1 || c !== 1) {
3570
+ do {
3571
+ s--;
3572
+ c--;
3573
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
3574
+ var _frame = `
3575
+ ` + sampleLines[s].replace(" at new ", " at ");
3576
+ if (fn.displayName && _frame.includes("<anonymous>")) {
3577
+ _frame = _frame.replace("<anonymous>", fn.displayName);
3578
+ }
3579
+ {
3580
+ if (typeof fn === "function") {
3581
+ componentFrameCache.set(fn, _frame);
3582
+ }
3583
+ }
3584
+ return _frame;
3585
+ }
3586
+ } while (s >= 1 && c >= 0);
3587
+ }
3588
+ break;
3589
+ }
3590
+ }
3591
+ }
3592
+ } finally {
3593
+ reentry = false;
3594
+ {
3595
+ ReactCurrentDispatcher$1.current = previousDispatcher;
3596
+ reenableLogs();
3597
+ }
3598
+ Error.prepareStackTrace = previousPrepareStackTrace;
3599
+ }
3600
+ var name = fn ? fn.displayName || fn.name : "";
3601
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
3602
+ {
3603
+ if (typeof fn === "function") {
3604
+ componentFrameCache.set(fn, syntheticFrame);
3605
+ }
3606
+ }
3607
+ return syntheticFrame;
3608
+ }
3609
+ function describeFunctionComponentFrame(fn, source, ownerFn) {
3610
+ {
3611
+ return describeNativeComponentFrame(fn, false);
3612
+ }
3613
+ }
3614
+ function shouldConstruct(Component2) {
3615
+ var prototype = Component2.prototype;
3616
+ return !!(prototype && prototype.isReactComponent);
3617
+ }
3618
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
3619
+ if (type == null) {
3620
+ return "";
3621
+ }
3622
+ if (typeof type === "function") {
3623
+ {
3624
+ return describeNativeComponentFrame(type, shouldConstruct(type));
3625
+ }
3626
+ }
3627
+ if (typeof type === "string") {
3628
+ return describeBuiltInComponentFrame(type);
3629
+ }
3630
+ switch (type) {
3631
+ case REACT_SUSPENSE_TYPE:
3632
+ return describeBuiltInComponentFrame("Suspense");
3633
+ case REACT_SUSPENSE_LIST_TYPE:
3634
+ return describeBuiltInComponentFrame("SuspenseList");
3635
+ }
3636
+ if (typeof type === "object") {
3637
+ switch (type.$$typeof) {
3638
+ case REACT_FORWARD_REF_TYPE:
3639
+ return describeFunctionComponentFrame(type.render);
3640
+ case REACT_MEMO_TYPE:
3641
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
3642
+ case REACT_LAZY_TYPE: {
3643
+ var lazyComponent = type;
3644
+ var payload = lazyComponent._payload;
3645
+ var init = lazyComponent._init;
3646
+ try {
3647
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
3648
+ } catch (x) {}
3649
+ }
3650
+ }
3651
+ }
3652
+ return "";
3653
+ }
3654
+ var loggedTypeFailures = {};
3655
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3656
+ function setCurrentlyValidatingElement(element) {
3657
+ {
3658
+ if (element) {
3659
+ var owner = element._owner;
3660
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
3661
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
3662
+ } else {
3663
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
3664
+ }
3665
+ }
3666
+ }
3667
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
3668
+ {
3669
+ var has = Function.call.bind(hasOwnProperty);
3670
+ for (var typeSpecName in typeSpecs) {
3671
+ if (has(typeSpecs, typeSpecName)) {
3672
+ var error$1 = undefined;
3673
+ try {
3674
+ if (typeof typeSpecs[typeSpecName] !== "function") {
3675
+ var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; " + "it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`." + "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
3676
+ err.name = "Invariant Violation";
3677
+ throw err;
3678
+ }
3679
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
3680
+ } catch (ex) {
3681
+ error$1 = ex;
3682
+ }
3683
+ if (error$1 && !(error$1 instanceof Error)) {
3684
+ setCurrentlyValidatingElement(element);
3685
+ error("%s: type specification of %s" + " `%s` is invalid; the type checker " + "function must return `null` or an `Error` but returned a %s. " + "You may have forgotten to pass an argument to the type checker " + "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + "shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
3686
+ setCurrentlyValidatingElement(null);
3687
+ }
3688
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
3689
+ loggedTypeFailures[error$1.message] = true;
3690
+ setCurrentlyValidatingElement(element);
3691
+ error("Failed %s type: %s", location, error$1.message);
3692
+ setCurrentlyValidatingElement(null);
3693
+ }
3694
+ }
3695
+ }
3696
+ }
3697
+ }
3698
+ function setCurrentlyValidatingElement$1(element) {
3699
+ {
3700
+ if (element) {
3701
+ var owner = element._owner;
3702
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
3703
+ setExtraStackFrame(stack);
3704
+ } else {
3705
+ setExtraStackFrame(null);
3706
+ }
3707
+ }
3708
+ }
3709
+ var propTypesMisspellWarningShown;
3710
+ {
3711
+ propTypesMisspellWarningShown = false;
3712
+ }
3713
+ function getDeclarationErrorAddendum() {
3714
+ if (ReactCurrentOwner.current) {
3715
+ var name = getComponentNameFromType(ReactCurrentOwner.current.type);
3716
+ if (name) {
3717
+ return `
3718
+
3719
+ Check the render method of \`` + name + "`.";
3720
+ }
3721
+ }
3722
+ return "";
3723
+ }
3724
+ function getSourceInfoErrorAddendum(source) {
3725
+ if (source !== undefined) {
3726
+ var fileName = source.fileName.replace(/^.*[\\\/]/, "");
3727
+ var lineNumber = source.lineNumber;
3728
+ return `
3729
+
3730
+ Check your code at ` + fileName + ":" + lineNumber + ".";
3731
+ }
3732
+ return "";
3733
+ }
3734
+ function getSourceInfoErrorAddendumForProps(elementProps) {
3735
+ if (elementProps !== null && elementProps !== undefined) {
3736
+ return getSourceInfoErrorAddendum(elementProps.__source);
3737
+ }
3738
+ return "";
3739
+ }
3740
+ var ownerHasKeyUseWarning = {};
3741
+ function getCurrentComponentErrorInfo(parentType) {
3742
+ var info = getDeclarationErrorAddendum();
3743
+ if (!info) {
3744
+ var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
3745
+ if (parentName) {
3746
+ info = `
3747
+
3748
+ Check the top-level render call using <` + parentName + ">.";
3749
+ }
3750
+ }
3751
+ return info;
3752
+ }
3753
+ function validateExplicitKey(element, parentType) {
3754
+ if (!element._store || element._store.validated || element.key != null) {
3755
+ return;
3756
+ }
3757
+ element._store.validated = true;
3758
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
3759
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
3760
+ return;
3761
+ }
3762
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
3763
+ var childOwner = "";
3764
+ if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
3765
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
3766
+ }
3767
+ {
3768
+ setCurrentlyValidatingElement$1(element);
3769
+ error('Each child in a list should have a unique "key" prop.' + "%s%s See https://reactjs.org/link/warning-keys for more information.", currentComponentErrorInfo, childOwner);
3770
+ setCurrentlyValidatingElement$1(null);
3771
+ }
3772
+ }
3773
+ function validateChildKeys(node, parentType) {
3774
+ if (typeof node !== "object") {
3775
+ return;
3776
+ }
3777
+ if (isArray(node)) {
3778
+ for (var i = 0;i < node.length; i++) {
3779
+ var child = node[i];
3780
+ if (isValidElement(child)) {
3781
+ validateExplicitKey(child, parentType);
3782
+ }
3783
+ }
3784
+ } else if (isValidElement(node)) {
3785
+ if (node._store) {
3786
+ node._store.validated = true;
3787
+ }
3788
+ } else if (node) {
3789
+ var iteratorFn = getIteratorFn(node);
3790
+ if (typeof iteratorFn === "function") {
3791
+ if (iteratorFn !== node.entries) {
3792
+ var iterator = iteratorFn.call(node);
3793
+ var step;
3794
+ while (!(step = iterator.next()).done) {
3795
+ if (isValidElement(step.value)) {
3796
+ validateExplicitKey(step.value, parentType);
3797
+ }
3798
+ }
3799
+ }
3800
+ }
3801
+ }
3802
+ }
3803
+ function validatePropTypes(element) {
3804
+ {
3805
+ var type = element.type;
3806
+ if (type === null || type === undefined || typeof type === "string") {
3807
+ return;
3808
+ }
3809
+ var propTypes;
3810
+ if (typeof type === "function") {
3811
+ propTypes = type.propTypes;
3812
+ } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) {
3813
+ propTypes = type.propTypes;
3814
+ } else {
3815
+ return;
3816
+ }
3817
+ if (propTypes) {
3818
+ var name = getComponentNameFromType(type);
3819
+ checkPropTypes(propTypes, element.props, "prop", name, element);
3820
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
3821
+ propTypesMisspellWarningShown = true;
3822
+ var _name = getComponentNameFromType(type);
3823
+ error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
3824
+ }
3825
+ if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
3826
+ error("getDefaultProps is only used on classic React.createClass " + "definitions. Use a static property named `defaultProps` instead.");
3827
+ }
3828
+ }
3829
+ }
3830
+ function validateFragmentProps(fragment) {
3831
+ {
3832
+ var keys = Object.keys(fragment.props);
3833
+ for (var i = 0;i < keys.length; i++) {
3834
+ var key = keys[i];
3835
+ if (key !== "children" && key !== "key") {
3836
+ setCurrentlyValidatingElement$1(fragment);
3837
+ error("Invalid prop `%s` supplied to `React.Fragment`. " + "React.Fragment can only have `key` and `children` props.", key);
3838
+ setCurrentlyValidatingElement$1(null);
3839
+ break;
3840
+ }
3841
+ }
3842
+ if (fragment.ref !== null) {
3843
+ setCurrentlyValidatingElement$1(fragment);
3844
+ error("Invalid attribute `ref` supplied to `React.Fragment`.");
3845
+ setCurrentlyValidatingElement$1(null);
3846
+ }
3847
+ }
3848
+ }
3849
+ function createElementWithValidation(type, props, children) {
3850
+ var validType = isValidElementType(type);
3851
+ if (!validType) {
3852
+ var info = "";
3853
+ if (type === undefined || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
3854
+ info += " You likely forgot to export your component from the file " + "it's defined in, or you might have mixed up default and named imports.";
3855
+ }
3856
+ var sourceInfo = getSourceInfoErrorAddendumForProps(props);
3857
+ if (sourceInfo) {
3858
+ info += sourceInfo;
3859
+ } else {
3860
+ info += getDeclarationErrorAddendum();
3861
+ }
3862
+ var typeString;
3863
+ if (type === null) {
3864
+ typeString = "null";
3865
+ } else if (isArray(type)) {
3866
+ typeString = "array";
3867
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
3868
+ typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />";
3869
+ info = " Did you accidentally export a JSX literal instead of a component?";
3870
+ } else {
3871
+ typeString = typeof type;
3872
+ }
3873
+ {
3874
+ error("React.createElement: type is invalid -- expected a string (for " + "built-in components) or a class/function (for composite " + "components) but got: %s.%s", typeString, info);
3875
+ }
3876
+ }
3877
+ var element = createElement.apply(this, arguments);
3878
+ if (element == null) {
3879
+ return element;
3880
+ }
3881
+ if (validType) {
3882
+ for (var i = 2;i < arguments.length; i++) {
3883
+ validateChildKeys(arguments[i], type);
3884
+ }
3885
+ }
3886
+ if (type === REACT_FRAGMENT_TYPE) {
3887
+ validateFragmentProps(element);
3888
+ } else {
3889
+ validatePropTypes(element);
3890
+ }
3891
+ return element;
3892
+ }
3893
+ var didWarnAboutDeprecatedCreateFactory = false;
3894
+ function createFactoryWithValidation(type) {
3895
+ var validatedFactory = createElementWithValidation.bind(null, type);
3896
+ validatedFactory.type = type;
3897
+ {
3898
+ if (!didWarnAboutDeprecatedCreateFactory) {
3899
+ didWarnAboutDeprecatedCreateFactory = true;
3900
+ warn("React.createFactory() is deprecated and will be removed in " + "a future major release. Consider using JSX " + "or use React.createElement() directly instead.");
3901
+ }
3902
+ Object.defineProperty(validatedFactory, "type", {
3903
+ enumerable: false,
3904
+ get: function() {
3905
+ warn("Factory.type is deprecated. Access the class directly " + "before passing it to createFactory.");
3906
+ Object.defineProperty(this, "type", {
3907
+ value: type
3908
+ });
3909
+ return type;
3910
+ }
3911
+ });
3912
+ }
3913
+ return validatedFactory;
3914
+ }
3915
+ function cloneElementWithValidation(element, props, children) {
3916
+ var newElement = cloneElement.apply(this, arguments);
3917
+ for (var i = 2;i < arguments.length; i++) {
3918
+ validateChildKeys(arguments[i], newElement.type);
3919
+ }
3920
+ validatePropTypes(newElement);
3921
+ return newElement;
3922
+ }
3923
+ function startTransition(scope, options) {
3924
+ var prevTransition = ReactCurrentBatchConfig.transition;
3925
+ ReactCurrentBatchConfig.transition = {};
3926
+ var currentTransition = ReactCurrentBatchConfig.transition;
3927
+ {
3928
+ ReactCurrentBatchConfig.transition._updatedFibers = new Set;
3929
+ }
3930
+ try {
3931
+ scope();
3932
+ } finally {
3933
+ ReactCurrentBatchConfig.transition = prevTransition;
3934
+ {
3935
+ if (prevTransition === null && currentTransition._updatedFibers) {
3936
+ var updatedFibersCount = currentTransition._updatedFibers.size;
3937
+ if (updatedFibersCount > 10) {
3938
+ warn("Detected a large number of updates inside startTransition. " + "If this is due to a subscription please re-write it to use React provided hooks. " + "Otherwise concurrent mode guarantees are off the table.");
3939
+ }
3940
+ currentTransition._updatedFibers.clear();
3941
+ }
3942
+ }
3943
+ }
3944
+ }
3945
+ var didWarnAboutMessageChannel = false;
3946
+ var enqueueTaskImpl = null;
3947
+ function enqueueTask(task) {
3948
+ if (enqueueTaskImpl === null) {
3949
+ try {
3950
+ var requireString = ("require" + Math.random()).slice(0, 7);
3951
+ var nodeRequire = module && module[requireString];
3952
+ enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate;
3953
+ } catch (_err) {
3954
+ enqueueTaskImpl = function(callback) {
3955
+ {
3956
+ if (didWarnAboutMessageChannel === false) {
3957
+ didWarnAboutMessageChannel = true;
3958
+ if (typeof MessageChannel === "undefined") {
3959
+ error("This browser does not have a MessageChannel implementation, " + "so enqueuing tasks via await act(async () => ...) will fail. " + "Please file an issue at https://github.com/facebook/react/issues " + "if you encounter this warning.");
3960
+ }
3961
+ }
3962
+ }
3963
+ var channel = new MessageChannel;
3964
+ channel.port1.onmessage = callback;
3965
+ channel.port2.postMessage(undefined);
3966
+ };
3967
+ }
3968
+ }
3969
+ return enqueueTaskImpl(task);
3970
+ }
3971
+ var actScopeDepth = 0;
3972
+ var didWarnNoAwaitAct = false;
3973
+ function act(callback) {
3974
+ {
3975
+ var prevActScopeDepth = actScopeDepth;
3976
+ actScopeDepth++;
3977
+ if (ReactCurrentActQueue.current === null) {
3978
+ ReactCurrentActQueue.current = [];
3979
+ }
3980
+ var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
3981
+ var result;
3982
+ try {
3983
+ ReactCurrentActQueue.isBatchingLegacy = true;
3984
+ result = callback();
3985
+ if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
3986
+ var queue = ReactCurrentActQueue.current;
3987
+ if (queue !== null) {
3988
+ ReactCurrentActQueue.didScheduleLegacyUpdate = false;
3989
+ flushActQueue(queue);
3990
+ }
3991
+ }
3992
+ } catch (error2) {
3993
+ popActScope(prevActScopeDepth);
3994
+ throw error2;
3995
+ } finally {
3996
+ ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
3997
+ }
3998
+ if (result !== null && typeof result === "object" && typeof result.then === "function") {
3999
+ var thenableResult = result;
4000
+ var wasAwaited = false;
4001
+ var thenable = {
4002
+ then: function(resolve, reject) {
4003
+ wasAwaited = true;
4004
+ thenableResult.then(function(returnValue2) {
4005
+ popActScope(prevActScopeDepth);
4006
+ if (actScopeDepth === 0) {
4007
+ recursivelyFlushAsyncActWork(returnValue2, resolve, reject);
4008
+ } else {
4009
+ resolve(returnValue2);
4010
+ }
4011
+ }, function(error2) {
4012
+ popActScope(prevActScopeDepth);
4013
+ reject(error2);
4014
+ });
4015
+ }
4016
+ };
4017
+ {
4018
+ if (!didWarnNoAwaitAct && typeof Promise !== "undefined") {
4019
+ Promise.resolve().then(function() {}).then(function() {
4020
+ if (!wasAwaited) {
4021
+ didWarnNoAwaitAct = true;
4022
+ error("You called act(async () => ...) without await. " + "This could lead to unexpected testing behaviour, " + "interleaving multiple act calls and mixing their " + "scopes. " + "You should - await act(async () => ...);");
4023
+ }
4024
+ });
4025
+ }
4026
+ }
4027
+ return thenable;
4028
+ } else {
4029
+ var returnValue = result;
4030
+ popActScope(prevActScopeDepth);
4031
+ if (actScopeDepth === 0) {
4032
+ var _queue = ReactCurrentActQueue.current;
4033
+ if (_queue !== null) {
4034
+ flushActQueue(_queue);
4035
+ ReactCurrentActQueue.current = null;
4036
+ }
4037
+ var _thenable = {
4038
+ then: function(resolve, reject) {
4039
+ if (ReactCurrentActQueue.current === null) {
4040
+ ReactCurrentActQueue.current = [];
4041
+ recursivelyFlushAsyncActWork(returnValue, resolve, reject);
4042
+ } else {
4043
+ resolve(returnValue);
4044
+ }
4045
+ }
4046
+ };
4047
+ return _thenable;
4048
+ } else {
4049
+ var _thenable2 = {
4050
+ then: function(resolve, reject) {
4051
+ resolve(returnValue);
4052
+ }
4053
+ };
4054
+ return _thenable2;
4055
+ }
4056
+ }
4057
+ }
4058
+ }
4059
+ function popActScope(prevActScopeDepth) {
4060
+ {
4061
+ if (prevActScopeDepth !== actScopeDepth - 1) {
4062
+ error("You seem to have overlapping act() calls, this is not supported. " + "Be sure to await previous act() calls before making a new one. ");
4063
+ }
4064
+ actScopeDepth = prevActScopeDepth;
4065
+ }
4066
+ }
4067
+ function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
4068
+ {
4069
+ var queue = ReactCurrentActQueue.current;
4070
+ if (queue !== null) {
4071
+ try {
4072
+ flushActQueue(queue);
4073
+ enqueueTask(function() {
4074
+ if (queue.length === 0) {
4075
+ ReactCurrentActQueue.current = null;
4076
+ resolve(returnValue);
4077
+ } else {
4078
+ recursivelyFlushAsyncActWork(returnValue, resolve, reject);
4079
+ }
4080
+ });
4081
+ } catch (error2) {
4082
+ reject(error2);
4083
+ }
4084
+ } else {
4085
+ resolve(returnValue);
4086
+ }
4087
+ }
4088
+ }
4089
+ var isFlushing = false;
4090
+ function flushActQueue(queue) {
4091
+ {
4092
+ if (!isFlushing) {
4093
+ isFlushing = true;
4094
+ var i = 0;
4095
+ try {
4096
+ for (;i < queue.length; i++) {
4097
+ var callback = queue[i];
4098
+ do {
4099
+ callback = callback(true);
4100
+ } while (callback !== null);
4101
+ }
4102
+ queue.length = 0;
4103
+ } catch (error2) {
4104
+ queue = queue.slice(i + 1);
4105
+ throw error2;
4106
+ } finally {
4107
+ isFlushing = false;
4108
+ }
4109
+ }
4110
+ }
4111
+ }
4112
+ var createElement$1 = createElementWithValidation;
4113
+ var cloneElement$1 = cloneElementWithValidation;
4114
+ var createFactory = createFactoryWithValidation;
4115
+ var Children = {
4116
+ map: mapChildren,
4117
+ forEach: forEachChildren,
4118
+ count: countChildren,
4119
+ toArray,
4120
+ only: onlyChild
4121
+ };
4122
+ exports.Children = Children;
4123
+ exports.Component = Component;
4124
+ exports.Fragment = REACT_FRAGMENT_TYPE;
4125
+ exports.Profiler = REACT_PROFILER_TYPE;
4126
+ exports.PureComponent = PureComponent;
4127
+ exports.StrictMode = REACT_STRICT_MODE_TYPE;
4128
+ exports.Suspense = REACT_SUSPENSE_TYPE;
4129
+ exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
4130
+ exports.act = act;
4131
+ exports.cloneElement = cloneElement$1;
4132
+ exports.createContext = createContext;
4133
+ exports.createElement = createElement$1;
4134
+ exports.createFactory = createFactory;
4135
+ exports.createRef = createRef;
4136
+ exports.forwardRef = forwardRef;
4137
+ exports.isValidElement = isValidElement;
4138
+ exports.lazy = lazy;
4139
+ exports.memo = memo;
4140
+ exports.startTransition = startTransition;
4141
+ exports.unstable_act = act;
4142
+ exports.useCallback = useCallback;
4143
+ exports.useContext = useContext;
4144
+ exports.useDebugValue = useDebugValue;
4145
+ exports.useDeferredValue = useDeferredValue;
4146
+ exports.useEffect = useEffect;
4147
+ exports.useId = useId;
4148
+ exports.useImperativeHandle = useImperativeHandle;
4149
+ exports.useInsertionEffect = useInsertionEffect;
4150
+ exports.useLayoutEffect = useLayoutEffect;
4151
+ exports.useMemo = useMemo;
4152
+ exports.useReducer = useReducer;
4153
+ exports.useRef = useRef;
4154
+ exports.useState = useState;
4155
+ exports.useSyncExternalStore = useSyncExternalStore;
4156
+ exports.useTransition = useTransition;
4157
+ exports.version = ReactVersion;
4158
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
4159
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error);
4160
+ }
4161
+ })();
4162
+ }
4163
+ });
4164
+
4165
+ // ../../node_modules/react/index.js
4166
+ var require_react = __commonJS((exports, module) => {
4167
+ var react_development = __toESM(require_react_development(), 1);
4168
+ if (false) {} else {
4169
+ module.exports = react_development;
4170
+ }
4171
+ });
4172
+
4173
+ // src/build/block-build-worker.ts
4174
+ var esbuild = __toESM(require_main(), 1);
4175
+ var react = __toESM(require_react(), 1);
4176
+ import { parentPort, workerData } from "worker_threads";
4177
+ import * as path from "path";
4178
+ import * as fs from "fs";
4179
+ import { execSync } from "child_process";
4180
+ async function buildBlock() {
4181
+ const { block, outputDir, webpackConfigPath, scriptsPath, tempDir } = workerData;
4182
+ try {
4183
+ fs.mkdirSync(tempDir, { recursive: true });
4184
+ const entryPoint = await generateEntryPoint(block, tempDir);
4185
+ const blockOutputDir = path.join(outputDir, block.name);
4186
+ fs.mkdirSync(blockOutputDir, { recursive: true });
4187
+ let scriptPaths = [];
4188
+ if (block.scripts && block.scripts.length > 0 && scriptsPath) {
4189
+ scriptPaths = await buildBlockScripts(block.scripts, scriptsPath, outputDir);
4190
+ }
4191
+ await generateBlockJson(block, blockOutputDir, tempDir);
4192
+ await generateSSRVersion(block, blockOutputDir);
4193
+ await runWebpackBuild(entryPoint, blockOutputDir, webpackConfigPath);
4194
+ verifyBuildOutput(blockOutputDir);
4195
+ cleanupTempFiles(tempDir);
4196
+ return {
4197
+ success: true,
4198
+ blockName: block.name,
4199
+ scriptPaths: scriptPaths.length > 0 ? scriptPaths : undefined
4200
+ };
4201
+ } catch (error) {
4202
+ cleanupTempFiles(tempDir);
4203
+ return {
4204
+ success: false,
4205
+ blockName: block.name,
4206
+ error: error.message || String(error)
4207
+ };
4208
+ }
4209
+ }
4210
+ async function generateEntryPoint(block, tempDir) {
4211
+ const entryContent = `
4212
+ import React from 'react';
4213
+ import blockExport from '${block.filePath}';
4214
+
4215
+ const blockInstance = blockExport?.default || blockExport;
4216
+
4217
+ if (!blockInstance || typeof blockInstance.register !== 'function') {
4218
+ throw new Error('Block must export a valid block instance with register() method');
4219
+ }
4220
+
4221
+ if (document.readyState === 'loading') {
4222
+ document.addEventListener('DOMContentLoaded', () => {
4223
+ blockInstance.register();
4224
+ });
4225
+ } else {
4226
+ blockInstance.register();
4227
+ }
4228
+ `;
4229
+ const entryPath = path.join(tempDir, `${block.name}-entry.js`);
4230
+ fs.writeFileSync(entryPath, entryContent, "utf8");
4231
+ return entryPath;
4232
+ }
4233
+ async function buildBlockScripts(scripts, scriptsPath, outputDir) {
4234
+ const scriptsOutputDir = path.join(path.dirname(outputDir), "scripts");
4235
+ fs.mkdirSync(scriptsOutputDir, { recursive: true });
4236
+ const outputPaths = [];
4237
+ for (const script of scripts) {
4238
+ const scriptPath = path.resolve(scriptsPath, script);
4239
+ if (!fs.existsSync(scriptPath)) {
4240
+ continue;
4241
+ }
4242
+ const scriptName = path.basename(script);
4243
+ const outputPath = path.join(scriptsOutputDir, scriptName.replace(/\.ts$/, ".js"));
4244
+ await esbuild.build({
4245
+ entryPoints: [scriptPath],
4246
+ outfile: outputPath,
4247
+ bundle: true,
4248
+ minify: true,
4249
+ platform: "browser",
4250
+ target: "es2015",
4251
+ format: "iife",
4252
+ external: ["react", "react-dom", "@wordpress/*", "jquery"],
4253
+ define: { "process.env.NODE_ENV": '"production"' },
4254
+ logLevel: "warning"
4255
+ });
4256
+ outputPaths.push(outputPath);
4257
+ }
4258
+ return outputPaths;
4259
+ }
4260
+ async function generateSSRVersion(block, outputDir) {
4261
+ const ssrPath = path.join(outputDir, "ssr.js");
4262
+ await esbuild.build({
4263
+ entryPoints: [block.filePath],
4264
+ outfile: ssrPath,
4265
+ platform: "node",
4266
+ format: "cjs",
4267
+ target: "node16",
4268
+ bundle: true,
4269
+ jsx: "transform",
4270
+ external: [
4271
+ "react",
4272
+ "react-dom",
4273
+ "@wordpress/block-editor",
4274
+ "@wordpress/blocks",
4275
+ "@wordpress/element",
4276
+ "@wordpress/components"
4277
+ ],
4278
+ define: { SSR: "true" },
4279
+ treeShaking: true,
4280
+ write: true,
4281
+ logLevel: "warning",
4282
+ sourcemap: false,
4283
+ minify: false
4284
+ });
4285
+ }
4286
+ async function generateBlockJson(block, outputDir, tempDir) {
4287
+ try {
4288
+ const blockModule = await compileAndImport(block.filePath, tempDir);
4289
+ const blockInstance = blockModule.default || blockModule;
4290
+ if (blockInstance && typeof blockInstance.toBlockJson === "function") {
4291
+ const blockJson2 = blockInstance.toBlockJson();
4292
+ const blockJsonPath2 = path.join(outputDir, "block.json");
4293
+ fs.writeFileSync(blockJsonPath2, JSON.stringify(blockJson2, null, 2), "utf8");
4294
+ return;
4295
+ }
4296
+ } catch (error) {}
4297
+ const blockJson = parseBlockJsonFromSource(block);
4298
+ const blockJsonPath = path.join(outputDir, "block.json");
4299
+ fs.writeFileSync(blockJsonPath, JSON.stringify(blockJson, null, 2), "utf8");
4300
+ }
4301
+ async function compileAndImport(filePath, tempDir) {
4302
+ const tempFile = path.join(tempDir, `${path.basename(filePath, path.extname(filePath))}-compiled.js`);
4303
+ if (typeof global.React === "undefined") {
4304
+ global.React = react;
4305
+ }
4306
+ await esbuild.build({
4307
+ entryPoints: [filePath],
4308
+ outfile: tempFile,
4309
+ platform: "node",
4310
+ format: "cjs",
4311
+ target: "node16",
4312
+ bundle: true,
4313
+ jsx: "transform",
4314
+ external: [],
4315
+ write: true,
4316
+ logLevel: "error"
4317
+ });
4318
+ delete __require.cache[__require.resolve(tempFile)];
4319
+ return __require(tempFile);
4320
+ }
4321
+ function parseBlockJsonFromSource(block) {
4322
+ const content = fs.readFileSync(block.filePath, "utf8");
4323
+ const blockName = path.basename(block.filePath, ".tsx");
4324
+ const aliasMatch = content.match(/alias:\s*["']([^"']+)["']/);
4325
+ const nameMatch = content.match(/name:\s*["']([^"']+)["']/);
4326
+ const iconMatch = content.match(/icon:\s*["']([^"']+)["']/);
4327
+ const descMatch = content.match(/description:\s*["']([^"']+)["']/);
4328
+ const alias = aliasMatch?.[1] || blockName.toLowerCase().replace(/[^a-z0-9]/g, "-");
4329
+ return {
4330
+ $schema: "https://schemas.wp.org/trunk/block.json",
4331
+ apiVersion: 3,
4332
+ name: `custom/${alias}`,
4333
+ version: "1.0.0",
4334
+ title: nameMatch?.[1] || blockName,
4335
+ category: "common",
4336
+ icon: iconMatch?.[1] || "smiley",
4337
+ description: descMatch?.[1] || `Generated ${blockName} block`,
4338
+ example: {},
4339
+ attributes: {},
4340
+ supports: { html: false },
4341
+ textdomain: alias,
4342
+ editorScript: ["file:./index.js"]
4343
+ };
4344
+ }
4345
+ async function runWebpackBuild(entryPoint, outputDir, webpackConfigPath) {
4346
+ const webpackBinary = findWebpackBinary();
4347
+ const envString = `--env entry="${entryPoint}" --env output="${outputDir}"`;
4348
+ const command = `${webpackBinary} --config "${webpackConfigPath}" ${envString} --mode production`;
4349
+ execSync(command, {
4350
+ cwd: path.dirname(webpackConfigPath),
4351
+ encoding: "utf8",
4352
+ stdio: "pipe"
4353
+ });
4354
+ }
4355
+ function findWebpackBinary() {
4356
+ const possiblePaths = [
4357
+ path.join(process.cwd(), "packages", "block", "node_modules", ".bin", "webpack"),
4358
+ path.join(process.cwd(), "node_modules", ".bin", "webpack")
4359
+ ];
4360
+ for (const webpackPath of possiblePaths) {
4361
+ if (fs.existsSync(webpackPath)) {
4362
+ return webpackPath;
4363
+ }
4364
+ }
4365
+ return "npx webpack";
4366
+ }
4367
+ function verifyBuildOutput(outputDir) {
4368
+ const requiredFiles = ["block.json", "index.js", "ssr.js"];
4369
+ for (const file of requiredFiles) {
4370
+ const filePath = path.join(outputDir, file);
4371
+ if (!fs.existsSync(filePath)) {
4372
+ throw new Error(`Required build output file missing: ${file}`);
4373
+ }
4374
+ }
4375
+ }
4376
+ function cleanupTempFiles(tempDir) {
4377
+ try {
4378
+ if (fs.existsSync(tempDir)) {
4379
+ fs.rmSync(tempDir, { recursive: true, force: true });
4380
+ }
4381
+ } catch {}
4382
+ }
4383
+ buildBlock().then((result) => {
4384
+ parentPort?.postMessage(result);
4385
+ });