vite-plugin-html-pages 1.2.3 → 1.2.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.
package/dist/index.js CHANGED
@@ -1,3 +1,2536 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // node_modules/esbuild/lib/main.js
34
+ var require_main = __commonJS({
35
+ "node_modules/esbuild/lib/main.js"(exports, module) {
36
+ "use strict";
37
+ var __defProp2 = Object.defineProperty;
38
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
39
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
40
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
41
+ var __export = (target, all) => {
42
+ for (var name in all)
43
+ __defProp2(target, name, { get: all[name], enumerable: true });
44
+ };
45
+ var __copyProps2 = (to, from, except, desc) => {
46
+ if (from && typeof from === "object" || typeof from === "function") {
47
+ for (let key of __getOwnPropNames2(from))
48
+ if (!__hasOwnProp2.call(to, key) && key !== except)
49
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
50
+ }
51
+ return to;
52
+ };
53
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
54
+ var node_exports = {};
55
+ __export(node_exports, {
56
+ analyzeMetafile: () => analyzeMetafile,
57
+ analyzeMetafileSync: () => analyzeMetafileSync,
58
+ build: () => build2,
59
+ buildSync: () => buildSync,
60
+ context: () => context,
61
+ default: () => node_default,
62
+ formatMessages: () => formatMessages,
63
+ formatMessagesSync: () => formatMessagesSync,
64
+ initialize: () => initialize,
65
+ stop: () => stop,
66
+ transform: () => transform,
67
+ transformSync: () => transformSync,
68
+ version: () => version
69
+ });
70
+ module.exports = __toCommonJS(node_exports);
71
+ function encodePacket(packet) {
72
+ let visit = (value) => {
73
+ if (value === null) {
74
+ bb.write8(0);
75
+ } else if (typeof value === "boolean") {
76
+ bb.write8(1);
77
+ bb.write8(+value);
78
+ } else if (typeof value === "number") {
79
+ bb.write8(2);
80
+ bb.write32(value | 0);
81
+ } else if (typeof value === "string") {
82
+ bb.write8(3);
83
+ bb.write(encodeUTF8(value));
84
+ } else if (value instanceof Uint8Array) {
85
+ bb.write8(4);
86
+ bb.write(value);
87
+ } else if (value instanceof Array) {
88
+ bb.write8(5);
89
+ bb.write32(value.length);
90
+ for (let item of value) {
91
+ visit(item);
92
+ }
93
+ } else {
94
+ let keys = Object.keys(value);
95
+ bb.write8(6);
96
+ bb.write32(keys.length);
97
+ for (let key of keys) {
98
+ bb.write(encodeUTF8(key));
99
+ visit(value[key]);
100
+ }
101
+ }
102
+ };
103
+ let bb = new ByteBuffer();
104
+ bb.write32(0);
105
+ bb.write32(packet.id << 1 | +!packet.isRequest);
106
+ visit(packet.value);
107
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
108
+ return bb.buf.subarray(0, bb.len);
109
+ }
110
+ function decodePacket(bytes) {
111
+ let visit = () => {
112
+ switch (bb.read8()) {
113
+ case 0:
114
+ return null;
115
+ case 1:
116
+ return !!bb.read8();
117
+ case 2:
118
+ return bb.read32();
119
+ case 3:
120
+ return decodeUTF8(bb.read());
121
+ case 4:
122
+ return bb.read();
123
+ case 5: {
124
+ let count = bb.read32();
125
+ let value2 = [];
126
+ for (let i = 0; i < count; i++) {
127
+ value2.push(visit());
128
+ }
129
+ return value2;
130
+ }
131
+ case 6: {
132
+ let count = bb.read32();
133
+ let value2 = {};
134
+ for (let i = 0; i < count; i++) {
135
+ value2[decodeUTF8(bb.read())] = visit();
136
+ }
137
+ return value2;
138
+ }
139
+ default:
140
+ throw new Error("Invalid packet");
141
+ }
142
+ };
143
+ let bb = new ByteBuffer(bytes);
144
+ let id = bb.read32();
145
+ let isRequest = (id & 1) === 0;
146
+ id >>>= 1;
147
+ let value = visit();
148
+ if (bb.ptr !== bytes.length) {
149
+ throw new Error("Invalid packet");
150
+ }
151
+ return { id, isRequest, value };
152
+ }
153
+ var ByteBuffer = class {
154
+ constructor(buf = new Uint8Array(1024)) {
155
+ this.buf = buf;
156
+ this.len = 0;
157
+ this.ptr = 0;
158
+ }
159
+ _write(delta) {
160
+ if (this.len + delta > this.buf.length) {
161
+ let clone = new Uint8Array((this.len + delta) * 2);
162
+ clone.set(this.buf);
163
+ this.buf = clone;
164
+ }
165
+ this.len += delta;
166
+ return this.len - delta;
167
+ }
168
+ write8(value) {
169
+ let offset = this._write(1);
170
+ this.buf[offset] = value;
171
+ }
172
+ write32(value) {
173
+ let offset = this._write(4);
174
+ writeUInt32LE(this.buf, value, offset);
175
+ }
176
+ write(bytes) {
177
+ let offset = this._write(4 + bytes.length);
178
+ writeUInt32LE(this.buf, bytes.length, offset);
179
+ this.buf.set(bytes, offset + 4);
180
+ }
181
+ _read(delta) {
182
+ if (this.ptr + delta > this.buf.length) {
183
+ throw new Error("Invalid packet");
184
+ }
185
+ this.ptr += delta;
186
+ return this.ptr - delta;
187
+ }
188
+ read8() {
189
+ return this.buf[this._read(1)];
190
+ }
191
+ read32() {
192
+ return readUInt32LE(this.buf, this._read(4));
193
+ }
194
+ read() {
195
+ let length = this.read32();
196
+ let bytes = new Uint8Array(length);
197
+ let ptr = this._read(bytes.length);
198
+ bytes.set(this.buf.subarray(ptr, ptr + length));
199
+ return bytes;
200
+ }
201
+ };
202
+ var encodeUTF8;
203
+ var decodeUTF8;
204
+ var encodeInvariant;
205
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
206
+ let encoder = new TextEncoder();
207
+ let decoder = new TextDecoder();
208
+ encodeUTF8 = (text) => encoder.encode(text);
209
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
210
+ encodeInvariant = 'new TextEncoder().encode("")';
211
+ } else if (typeof Buffer !== "undefined") {
212
+ encodeUTF8 = (text) => Buffer.from(text);
213
+ decodeUTF8 = (bytes) => {
214
+ let { buffer, byteOffset, byteLength } = bytes;
215
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
216
+ };
217
+ encodeInvariant = 'Buffer.from("")';
218
+ } else {
219
+ throw new Error("No UTF-8 codec found");
220
+ }
221
+ if (!(encodeUTF8("") instanceof Uint8Array))
222
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
223
+
224
+ This indicates that your JavaScript environment is broken. You cannot use
225
+ esbuild in this environment because esbuild relies on this invariant. This
226
+ is not a problem with esbuild. You need to fix your environment instead.
227
+ `);
228
+ function readUInt32LE(buffer, offset) {
229
+ return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
230
+ }
231
+ function writeUInt32LE(buffer, value, offset) {
232
+ buffer[offset++] = value;
233
+ buffer[offset++] = value >> 8;
234
+ buffer[offset++] = value >> 16;
235
+ buffer[offset++] = value >> 24;
236
+ }
237
+ var fromCharCode = String.fromCharCode;
238
+ function throwSyntaxError(bytes, index, message) {
239
+ const c = bytes[index];
240
+ let line = 1;
241
+ let column = 0;
242
+ for (let i = 0; i < index; i++) {
243
+ if (bytes[i] === 10) {
244
+ line++;
245
+ column = 0;
246
+ } else {
247
+ column++;
248
+ }
249
+ }
250
+ throw new SyntaxError(
251
+ message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`
252
+ );
253
+ }
254
+ function JSON_parse(bytes) {
255
+ if (!(bytes instanceof Uint8Array)) {
256
+ throw new Error(`JSON input must be a Uint8Array`);
257
+ }
258
+ const propertyStack = [];
259
+ const objectStack = [];
260
+ const stateStack = [];
261
+ const length = bytes.length;
262
+ let property = null;
263
+ let state = 0;
264
+ let object;
265
+ let i = 0;
266
+ while (i < length) {
267
+ let c = bytes[i++];
268
+ if (c <= 32) {
269
+ continue;
270
+ }
271
+ let value;
272
+ if (state === 2 && property === null && c !== 34 && c !== 125) {
273
+ throwSyntaxError(bytes, --i);
274
+ }
275
+ switch (c) {
276
+ // True
277
+ case 116: {
278
+ if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) {
279
+ throwSyntaxError(bytes, --i);
280
+ }
281
+ value = true;
282
+ break;
283
+ }
284
+ // False
285
+ case 102: {
286
+ if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) {
287
+ throwSyntaxError(bytes, --i);
288
+ }
289
+ value = false;
290
+ break;
291
+ }
292
+ // Null
293
+ case 110: {
294
+ if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) {
295
+ throwSyntaxError(bytes, --i);
296
+ }
297
+ value = null;
298
+ break;
299
+ }
300
+ // Number begin
301
+ case 45:
302
+ case 46:
303
+ case 48:
304
+ case 49:
305
+ case 50:
306
+ case 51:
307
+ case 52:
308
+ case 53:
309
+ case 54:
310
+ case 55:
311
+ case 56:
312
+ case 57: {
313
+ let index = i;
314
+ value = fromCharCode(c);
315
+ c = bytes[i];
316
+ while (true) {
317
+ switch (c) {
318
+ case 43:
319
+ case 45:
320
+ case 46:
321
+ case 48:
322
+ case 49:
323
+ case 50:
324
+ case 51:
325
+ case 52:
326
+ case 53:
327
+ case 54:
328
+ case 55:
329
+ case 56:
330
+ case 57:
331
+ case 101:
332
+ case 69: {
333
+ value += fromCharCode(c);
334
+ c = bytes[++i];
335
+ continue;
336
+ }
337
+ }
338
+ break;
339
+ }
340
+ value = +value;
341
+ if (isNaN(value)) {
342
+ throwSyntaxError(bytes, --index, "Invalid number");
343
+ }
344
+ break;
345
+ }
346
+ // String begin
347
+ case 34: {
348
+ value = "";
349
+ while (true) {
350
+ if (i >= length) {
351
+ throwSyntaxError(bytes, length);
352
+ }
353
+ c = bytes[i++];
354
+ if (c === 34) {
355
+ break;
356
+ } else if (c === 92) {
357
+ switch (bytes[i++]) {
358
+ // Normal escape sequence
359
+ case 34:
360
+ value += '"';
361
+ break;
362
+ case 47:
363
+ value += "/";
364
+ break;
365
+ case 92:
366
+ value += "\\";
367
+ break;
368
+ case 98:
369
+ value += "\b";
370
+ break;
371
+ case 102:
372
+ value += "\f";
373
+ break;
374
+ case 110:
375
+ value += "\n";
376
+ break;
377
+ case 114:
378
+ value += "\r";
379
+ break;
380
+ case 116:
381
+ value += " ";
382
+ break;
383
+ // Unicode escape sequence
384
+ case 117: {
385
+ let code = 0;
386
+ for (let j = 0; j < 4; j++) {
387
+ c = bytes[i++];
388
+ code <<= 4;
389
+ if (c >= 48 && c <= 57) code |= c - 48;
390
+ else if (c >= 97 && c <= 102) code |= c + (10 - 97);
391
+ else if (c >= 65 && c <= 70) code |= c + (10 - 65);
392
+ else throwSyntaxError(bytes, --i);
393
+ }
394
+ value += fromCharCode(code);
395
+ break;
396
+ }
397
+ // Invalid escape sequence
398
+ default:
399
+ throwSyntaxError(bytes, --i);
400
+ break;
401
+ }
402
+ } else if (c <= 127) {
403
+ value += fromCharCode(c);
404
+ } else if ((c & 224) === 192) {
405
+ value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
406
+ } else if ((c & 240) === 224) {
407
+ value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
408
+ } else if ((c & 248) == 240) {
409
+ let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
410
+ if (codePoint > 65535) {
411
+ codePoint -= 65536;
412
+ value += fromCharCode(codePoint >> 10 & 1023 | 55296);
413
+ codePoint = 56320 | codePoint & 1023;
414
+ }
415
+ value += fromCharCode(codePoint);
416
+ }
417
+ }
418
+ value[0];
419
+ break;
420
+ }
421
+ // Array begin
422
+ case 91: {
423
+ value = [];
424
+ propertyStack.push(property);
425
+ objectStack.push(object);
426
+ stateStack.push(state);
427
+ property = null;
428
+ object = value;
429
+ state = 1;
430
+ continue;
431
+ }
432
+ // Object begin
433
+ case 123: {
434
+ value = {};
435
+ propertyStack.push(property);
436
+ objectStack.push(object);
437
+ stateStack.push(state);
438
+ property = null;
439
+ object = value;
440
+ state = 2;
441
+ continue;
442
+ }
443
+ // Array end
444
+ case 93: {
445
+ if (state !== 1) {
446
+ throwSyntaxError(bytes, --i);
447
+ }
448
+ value = object;
449
+ property = propertyStack.pop();
450
+ object = objectStack.pop();
451
+ state = stateStack.pop();
452
+ break;
453
+ }
454
+ // Object end
455
+ case 125: {
456
+ if (state !== 2) {
457
+ throwSyntaxError(bytes, --i);
458
+ }
459
+ value = object;
460
+ property = propertyStack.pop();
461
+ object = objectStack.pop();
462
+ state = stateStack.pop();
463
+ break;
464
+ }
465
+ default: {
466
+ throwSyntaxError(bytes, --i);
467
+ }
468
+ }
469
+ c = bytes[i];
470
+ while (c <= 32) {
471
+ c = bytes[++i];
472
+ }
473
+ switch (state) {
474
+ case 0: {
475
+ if (i === length) {
476
+ return value;
477
+ }
478
+ break;
479
+ }
480
+ case 1: {
481
+ object.push(value);
482
+ if (c === 44) {
483
+ i++;
484
+ continue;
485
+ }
486
+ if (c === 93) {
487
+ continue;
488
+ }
489
+ break;
490
+ }
491
+ case 2: {
492
+ if (property === null) {
493
+ property = value;
494
+ if (c === 58) {
495
+ i++;
496
+ continue;
497
+ }
498
+ } else {
499
+ object[property] = value;
500
+ property = null;
501
+ if (c === 44) {
502
+ i++;
503
+ continue;
504
+ }
505
+ if (c === 125) {
506
+ continue;
507
+ }
508
+ }
509
+ break;
510
+ }
511
+ }
512
+ break;
513
+ }
514
+ throwSyntaxError(bytes, i);
515
+ }
516
+ var quote = JSON.stringify;
517
+ var buildLogLevelDefault = "warning";
518
+ var transformLogLevelDefault = "silent";
519
+ function validateAndJoinStringArray(values, what) {
520
+ const toJoin = [];
521
+ for (const value of values) {
522
+ validateStringValue(value, what);
523
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
524
+ toJoin.push(value);
525
+ }
526
+ return toJoin.join(",");
527
+ }
528
+ var canBeAnything = () => null;
529
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
530
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
531
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
532
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
533
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
534
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
535
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
536
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
537
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
538
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
539
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
540
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
541
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
542
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
543
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
544
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
545
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
546
+ function getFlag(object, keys, key, mustBeFn) {
547
+ let value = object[key];
548
+ keys[key + ""] = true;
549
+ if (value === void 0) return void 0;
550
+ let mustBe = mustBeFn(value);
551
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
552
+ return value;
553
+ }
554
+ function checkForInvalidFlags(object, keys, where) {
555
+ for (let key in object) {
556
+ if (!(key in keys)) {
557
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
558
+ }
559
+ }
560
+ }
561
+ function validateInitializeOptions(options) {
562
+ let keys = /* @__PURE__ */ Object.create(null);
563
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
564
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
565
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
566
+ checkForInvalidFlags(options, keys, "in initialize() call");
567
+ return {
568
+ wasmURL,
569
+ wasmModule,
570
+ worker
571
+ };
572
+ }
573
+ function validateMangleCache(mangleCache) {
574
+ let validated;
575
+ if (mangleCache !== void 0) {
576
+ validated = /* @__PURE__ */ Object.create(null);
577
+ for (let key in mangleCache) {
578
+ let value = mangleCache[key];
579
+ if (typeof value === "string" || value === false) {
580
+ validated[key] = value;
581
+ } else {
582
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
583
+ }
584
+ }
585
+ }
586
+ return validated;
587
+ }
588
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
589
+ let color = getFlag(options, keys, "color", mustBeBoolean);
590
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
591
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
592
+ if (color !== void 0) flags.push(`--color=${color}`);
593
+ else if (isTTY2) flags.push(`--color=true`);
594
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
595
+ flags.push(`--log-limit=${logLimit || 0}`);
596
+ }
597
+ function validateStringValue(value, what, key) {
598
+ if (typeof value !== "string") {
599
+ throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
600
+ }
601
+ return value;
602
+ }
603
+ function pushCommonFlags(flags, options, keys) {
604
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
605
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
606
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
607
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
608
+ let format = getFlag(options, keys, "format", mustBeString);
609
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
610
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
611
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
612
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
613
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
614
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
615
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
616
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
617
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
618
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
619
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
620
+ let charset = getFlag(options, keys, "charset", mustBeString);
621
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
622
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
623
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
624
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
625
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
626
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
627
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
628
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
629
+ let define = getFlag(options, keys, "define", mustBeObject);
630
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
631
+ let supported = getFlag(options, keys, "supported", mustBeObject);
632
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
633
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
634
+ let platform = getFlag(options, keys, "platform", mustBeString);
635
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
636
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
637
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
638
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
639
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
640
+ if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
641
+ if (format) flags.push(`--format=${format}`);
642
+ if (globalName) flags.push(`--global-name=${globalName}`);
643
+ if (platform) flags.push(`--platform=${platform}`);
644
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
645
+ if (minify) flags.push("--minify");
646
+ if (minifySyntax) flags.push("--minify-syntax");
647
+ if (minifyWhitespace) flags.push("--minify-whitespace");
648
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
649
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
650
+ if (charset) flags.push(`--charset=${charset}`);
651
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
652
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
653
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
654
+ if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
655
+ if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
656
+ if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
657
+ if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
658
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
659
+ if (jsx) flags.push(`--jsx=${jsx}`);
660
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
661
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
662
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
663
+ if (jsxDev) flags.push(`--jsx-dev`);
664
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
665
+ if (define) {
666
+ for (let key in define) {
667
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
668
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
669
+ }
670
+ }
671
+ if (logOverride) {
672
+ for (let key in logOverride) {
673
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
674
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
675
+ }
676
+ }
677
+ if (supported) {
678
+ for (let key in supported) {
679
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
680
+ const value = supported[key];
681
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
682
+ flags.push(`--supported:${key}=${value}`);
683
+ }
684
+ }
685
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
686
+ if (keepNames) flags.push(`--keep-names`);
687
+ }
688
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
689
+ var _a2;
690
+ let flags = [];
691
+ let entries = [];
692
+ let keys = /* @__PURE__ */ Object.create(null);
693
+ let stdinContents = null;
694
+ let stdinResolveDir = null;
695
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
696
+ pushCommonFlags(flags, options, keys);
697
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
698
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
699
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
700
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
701
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
702
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
703
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
704
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
705
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
706
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
707
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
708
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
709
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
710
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
711
+ let packages = getFlag(options, keys, "packages", mustBeString);
712
+ let alias = getFlag(options, keys, "alias", mustBeObject);
713
+ let loader = getFlag(options, keys, "loader", mustBeObject);
714
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
715
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
716
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
717
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
718
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
719
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
720
+ let banner = getFlag(options, keys, "banner", mustBeObject);
721
+ let footer = getFlag(options, keys, "footer", mustBeObject);
722
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
723
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
724
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
725
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
726
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
727
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
728
+ keys.plugins = true;
729
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
730
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
731
+ if (bundle) flags.push("--bundle");
732
+ if (allowOverwrite) flags.push("--allow-overwrite");
733
+ if (splitting) flags.push("--splitting");
734
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
735
+ if (metafile) flags.push(`--metafile`);
736
+ if (outfile) flags.push(`--outfile=${outfile}`);
737
+ if (outdir) flags.push(`--outdir=${outdir}`);
738
+ if (outbase) flags.push(`--outbase=${outbase}`);
739
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
740
+ if (packages) flags.push(`--packages=${packages}`);
741
+ if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
742
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
743
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
744
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
745
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
746
+ if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
747
+ if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
748
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
749
+ if (alias) {
750
+ for (let old in alias) {
751
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
752
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
753
+ }
754
+ }
755
+ if (banner) {
756
+ for (let type in banner) {
757
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
758
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
759
+ }
760
+ }
761
+ if (footer) {
762
+ for (let type in footer) {
763
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
764
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
765
+ }
766
+ }
767
+ if (inject) for (let path32 of inject) flags.push(`--inject:${validateStringValue(path32, "inject")}`);
768
+ if (loader) {
769
+ for (let ext in loader) {
770
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
771
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
772
+ }
773
+ }
774
+ if (outExtension) {
775
+ for (let ext in outExtension) {
776
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
777
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
778
+ }
779
+ }
780
+ if (entryPoints) {
781
+ if (Array.isArray(entryPoints)) {
782
+ for (let i = 0, n = entryPoints.length; i < n; i++) {
783
+ let entryPoint = entryPoints[i];
784
+ if (typeof entryPoint === "object" && entryPoint !== null) {
785
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
786
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
787
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
788
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
789
+ if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
790
+ if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
791
+ entries.push([output, input]);
792
+ } else {
793
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
794
+ }
795
+ }
796
+ } else {
797
+ for (let key in entryPoints) {
798
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
799
+ }
800
+ }
801
+ }
802
+ if (stdin) {
803
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
804
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
805
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
806
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
807
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
808
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
809
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
810
+ if (loader2) flags.push(`--loader=${loader2}`);
811
+ if (resolveDir) stdinResolveDir = resolveDir;
812
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
813
+ else if (contents instanceof Uint8Array) stdinContents = contents;
814
+ }
815
+ let nodePaths = [];
816
+ if (nodePathsInput) {
817
+ for (let value of nodePathsInput) {
818
+ value += "";
819
+ nodePaths.push(value);
820
+ }
821
+ }
822
+ return {
823
+ entries,
824
+ flags,
825
+ write,
826
+ stdinContents,
827
+ stdinResolveDir,
828
+ absWorkingDir,
829
+ nodePaths,
830
+ mangleCache: validateMangleCache(mangleCache)
831
+ };
832
+ }
833
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
834
+ let flags = [];
835
+ let keys = /* @__PURE__ */ Object.create(null);
836
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
837
+ pushCommonFlags(flags, options, keys);
838
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
839
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
840
+ let loader = getFlag(options, keys, "loader", mustBeString);
841
+ let banner = getFlag(options, keys, "banner", mustBeString);
842
+ let footer = getFlag(options, keys, "footer", mustBeString);
843
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
844
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
845
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
846
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
847
+ if (loader) flags.push(`--loader=${loader}`);
848
+ if (banner) flags.push(`--banner=${banner}`);
849
+ if (footer) flags.push(`--footer=${footer}`);
850
+ return {
851
+ flags,
852
+ mangleCache: validateMangleCache(mangleCache)
853
+ };
854
+ }
855
+ function createChannel(streamIn) {
856
+ const requestCallbacksByKey = {};
857
+ const closeData = { didClose: false, reason: "" };
858
+ let responseCallbacks = {};
859
+ let nextRequestID = 0;
860
+ let nextBuildKey = 0;
861
+ let stdout = new Uint8Array(16 * 1024);
862
+ let stdoutUsed = 0;
863
+ let readFromStdout = (chunk) => {
864
+ let limit = stdoutUsed + chunk.length;
865
+ if (limit > stdout.length) {
866
+ let swap = new Uint8Array(limit * 2);
867
+ swap.set(stdout);
868
+ stdout = swap;
869
+ }
870
+ stdout.set(chunk, stdoutUsed);
871
+ stdoutUsed += chunk.length;
872
+ let offset = 0;
873
+ while (offset + 4 <= stdoutUsed) {
874
+ let length = readUInt32LE(stdout, offset);
875
+ if (offset + 4 + length > stdoutUsed) {
876
+ break;
877
+ }
878
+ offset += 4;
879
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
880
+ offset += length;
881
+ }
882
+ if (offset > 0) {
883
+ stdout.copyWithin(0, offset, stdoutUsed);
884
+ stdoutUsed -= offset;
885
+ }
886
+ };
887
+ let afterClose = (error) => {
888
+ closeData.didClose = true;
889
+ if (error) closeData.reason = ": " + (error.message || error);
890
+ const text = "The service was stopped" + closeData.reason;
891
+ for (let id in responseCallbacks) {
892
+ responseCallbacks[id](text, null);
893
+ }
894
+ responseCallbacks = {};
895
+ };
896
+ let sendRequest = (refs, value, callback) => {
897
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
898
+ let id = nextRequestID++;
899
+ responseCallbacks[id] = (error, response) => {
900
+ try {
901
+ callback(error, response);
902
+ } finally {
903
+ if (refs) refs.unref();
904
+ }
905
+ };
906
+ if (refs) refs.ref();
907
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
908
+ };
909
+ let sendResponse = (id, value) => {
910
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
911
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
912
+ };
913
+ let handleRequest = async (id, request) => {
914
+ try {
915
+ if (request.command === "ping") {
916
+ sendResponse(id, {});
917
+ return;
918
+ }
919
+ if (typeof request.key === "number") {
920
+ const requestCallbacks = requestCallbacksByKey[request.key];
921
+ if (!requestCallbacks) {
922
+ return;
923
+ }
924
+ const callback = requestCallbacks[request.command];
925
+ if (callback) {
926
+ await callback(id, request);
927
+ return;
928
+ }
929
+ }
930
+ throw new Error(`Invalid command: ` + request.command);
931
+ } catch (e) {
932
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
933
+ try {
934
+ sendResponse(id, { errors });
935
+ } catch {
936
+ }
937
+ }
938
+ };
939
+ let isFirstPacket = true;
940
+ let handleIncomingPacket = (bytes) => {
941
+ if (isFirstPacket) {
942
+ isFirstPacket = false;
943
+ let binaryVersion = String.fromCharCode(...bytes);
944
+ if (binaryVersion !== "0.27.4") {
945
+ throw new Error(`Cannot start service: Host version "${"0.27.4"}" does not match binary version ${quote(binaryVersion)}`);
946
+ }
947
+ return;
948
+ }
949
+ let packet = decodePacket(bytes);
950
+ if (packet.isRequest) {
951
+ handleRequest(packet.id, packet.value);
952
+ } else {
953
+ let callback = responseCallbacks[packet.id];
954
+ delete responseCallbacks[packet.id];
955
+ if (packet.value.error) callback(packet.value.error, {});
956
+ else callback(null, packet.value);
957
+ }
958
+ };
959
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
960
+ let refCount = 0;
961
+ const buildKey = nextBuildKey++;
962
+ const requestCallbacks = {};
963
+ const buildRefs = {
964
+ ref() {
965
+ if (++refCount === 1) {
966
+ if (refs) refs.ref();
967
+ }
968
+ },
969
+ unref() {
970
+ if (--refCount === 0) {
971
+ delete requestCallbacksByKey[buildKey];
972
+ if (refs) refs.unref();
973
+ }
974
+ }
975
+ };
976
+ requestCallbacksByKey[buildKey] = requestCallbacks;
977
+ buildRefs.ref();
978
+ buildOrContextImpl(
979
+ callName,
980
+ buildKey,
981
+ sendRequest,
982
+ sendResponse,
983
+ buildRefs,
984
+ streamIn,
985
+ requestCallbacks,
986
+ options,
987
+ isTTY2,
988
+ defaultWD2,
989
+ (err, res) => {
990
+ try {
991
+ callback(err, res);
992
+ } finally {
993
+ buildRefs.unref();
994
+ }
995
+ }
996
+ );
997
+ };
998
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs32, callback }) => {
999
+ const details = createObjectStash();
1000
+ let start = (inputPath) => {
1001
+ try {
1002
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
1003
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
1004
+ let {
1005
+ flags,
1006
+ mangleCache
1007
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1008
+ let request = {
1009
+ command: "transform",
1010
+ flags,
1011
+ inputFS: inputPath !== null,
1012
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1013
+ };
1014
+ if (mangleCache) request.mangleCache = mangleCache;
1015
+ sendRequest(refs, request, (error, response) => {
1016
+ if (error) return callback(new Error(error), null);
1017
+ let errors = replaceDetailsInMessages(response.errors, details);
1018
+ let warnings = replaceDetailsInMessages(response.warnings, details);
1019
+ let outstanding = 1;
1020
+ let next = () => {
1021
+ if (--outstanding === 0) {
1022
+ let result = {
1023
+ warnings,
1024
+ code: response.code,
1025
+ map: response.map,
1026
+ mangleCache: void 0,
1027
+ legalComments: void 0
1028
+ };
1029
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1030
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1031
+ callback(null, result);
1032
+ }
1033
+ };
1034
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1035
+ if (response.codeFS) {
1036
+ outstanding++;
1037
+ fs32.readFile(response.code, (err, contents) => {
1038
+ if (err !== null) {
1039
+ callback(err, null);
1040
+ } else {
1041
+ response.code = contents;
1042
+ next();
1043
+ }
1044
+ });
1045
+ }
1046
+ if (response.mapFS) {
1047
+ outstanding++;
1048
+ fs32.readFile(response.map, (err, contents) => {
1049
+ if (err !== null) {
1050
+ callback(err, null);
1051
+ } else {
1052
+ response.map = contents;
1053
+ next();
1054
+ }
1055
+ });
1056
+ }
1057
+ next();
1058
+ });
1059
+ } catch (e) {
1060
+ let flags = [];
1061
+ try {
1062
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1063
+ } catch {
1064
+ }
1065
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1066
+ sendRequest(refs, { command: "error", flags, error }, () => {
1067
+ error.detail = details.load(error.detail);
1068
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
1069
+ });
1070
+ }
1071
+ };
1072
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1073
+ let next = start;
1074
+ start = () => fs32.writeFile(input, next);
1075
+ }
1076
+ start(null);
1077
+ };
1078
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1079
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1080
+ let keys = {};
1081
+ let kind = getFlag(options, keys, "kind", mustBeString);
1082
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1083
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1084
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1085
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1086
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1087
+ let request = {
1088
+ command: "format-msgs",
1089
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1090
+ isWarning: kind === "warning"
1091
+ };
1092
+ if (color !== void 0) request.color = color;
1093
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1094
+ sendRequest(refs, request, (error, response) => {
1095
+ if (error) return callback(new Error(error), null);
1096
+ callback(null, response.messages);
1097
+ });
1098
+ };
1099
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1100
+ if (options === void 0) options = {};
1101
+ let keys = {};
1102
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1103
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1104
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1105
+ let request = {
1106
+ command: "analyze-metafile",
1107
+ metafile
1108
+ };
1109
+ if (color !== void 0) request.color = color;
1110
+ if (verbose !== void 0) request.verbose = verbose;
1111
+ sendRequest(refs, request, (error, response) => {
1112
+ if (error) return callback(new Error(error), null);
1113
+ callback(null, response.result);
1114
+ });
1115
+ };
1116
+ return {
1117
+ readFromStdout,
1118
+ afterClose,
1119
+ service: {
1120
+ buildOrContext,
1121
+ transform: transform2,
1122
+ formatMessages: formatMessages2,
1123
+ analyzeMetafile: analyzeMetafile2
1124
+ }
1125
+ };
1126
+ }
1127
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1128
+ const details = createObjectStash();
1129
+ const isContext = callName === "context";
1130
+ const handleError = (e, pluginName) => {
1131
+ const flags = [];
1132
+ try {
1133
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1134
+ } catch {
1135
+ }
1136
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1137
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
1138
+ message.detail = details.load(message.detail);
1139
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1140
+ });
1141
+ };
1142
+ let plugins;
1143
+ if (typeof options === "object") {
1144
+ const value = options.plugins;
1145
+ if (value !== void 0) {
1146
+ if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
1147
+ plugins = value;
1148
+ }
1149
+ }
1150
+ if (plugins && plugins.length > 0) {
1151
+ if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1152
+ handlePlugins(
1153
+ buildKey,
1154
+ sendRequest,
1155
+ sendResponse,
1156
+ refs,
1157
+ streamIn,
1158
+ requestCallbacks,
1159
+ options,
1160
+ plugins,
1161
+ details
1162
+ ).then(
1163
+ (result) => {
1164
+ if (!result.ok) return handleError(result.error, result.pluginName);
1165
+ try {
1166
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1167
+ } catch (e) {
1168
+ handleError(e, "");
1169
+ }
1170
+ },
1171
+ (e) => handleError(e, "")
1172
+ );
1173
+ return;
1174
+ }
1175
+ try {
1176
+ buildOrContextContinue(null, (result, done) => done([], []), () => {
1177
+ });
1178
+ } catch (e) {
1179
+ handleError(e, "");
1180
+ }
1181
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1182
+ const writeDefault = streamIn.hasFS;
1183
+ const {
1184
+ entries,
1185
+ flags,
1186
+ write,
1187
+ stdinContents,
1188
+ stdinResolveDir,
1189
+ absWorkingDir,
1190
+ nodePaths,
1191
+ mangleCache
1192
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1193
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1194
+ const request = {
1195
+ command: "build",
1196
+ key: buildKey,
1197
+ entries,
1198
+ flags,
1199
+ write,
1200
+ stdinContents,
1201
+ stdinResolveDir,
1202
+ absWorkingDir: absWorkingDir || defaultWD2,
1203
+ nodePaths,
1204
+ context: isContext
1205
+ };
1206
+ if (requestPlugins) request.plugins = requestPlugins;
1207
+ if (mangleCache) request.mangleCache = mangleCache;
1208
+ const buildResponseToResult = (response, callback2) => {
1209
+ const result = {
1210
+ errors: replaceDetailsInMessages(response.errors, details),
1211
+ warnings: replaceDetailsInMessages(response.warnings, details),
1212
+ outputFiles: void 0,
1213
+ metafile: void 0,
1214
+ mangleCache: void 0
1215
+ };
1216
+ const originalErrors = result.errors.slice();
1217
+ const originalWarnings = result.warnings.slice();
1218
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1219
+ if (response.metafile) result.metafile = parseJSON(response.metafile);
1220
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
1221
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1222
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1223
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1224
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1225
+ return callback2(error, null, onEndErrors, onEndWarnings);
1226
+ }
1227
+ callback2(null, result, onEndErrors, onEndWarnings);
1228
+ });
1229
+ };
1230
+ let latestResultPromise;
1231
+ let provideLatestResult;
1232
+ if (isContext)
1233
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1234
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1235
+ const response = {
1236
+ errors: onEndErrors,
1237
+ warnings: onEndWarnings
1238
+ };
1239
+ if (provideLatestResult) provideLatestResult(err, result);
1240
+ latestResultPromise = void 0;
1241
+ provideLatestResult = void 0;
1242
+ sendResponse(id, response);
1243
+ resolve();
1244
+ });
1245
+ });
1246
+ sendRequest(refs, request, (error, response) => {
1247
+ if (error) return callback(new Error(error), null);
1248
+ if (!isContext) {
1249
+ return buildResponseToResult(response, (err, res) => {
1250
+ scheduleOnDisposeCallbacks();
1251
+ return callback(err, res);
1252
+ });
1253
+ }
1254
+ if (response.errors.length > 0) {
1255
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1256
+ }
1257
+ let didDispose = false;
1258
+ const result = {
1259
+ rebuild: () => {
1260
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1261
+ let settlePromise;
1262
+ provideLatestResult = (err, result2) => {
1263
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1264
+ };
1265
+ const triggerAnotherBuild = () => {
1266
+ const request2 = {
1267
+ command: "rebuild",
1268
+ key: buildKey
1269
+ };
1270
+ sendRequest(refs, request2, (error2, response2) => {
1271
+ if (error2) {
1272
+ reject(new Error(error2));
1273
+ } else if (settlePromise) {
1274
+ settlePromise();
1275
+ } else {
1276
+ triggerAnotherBuild();
1277
+ }
1278
+ });
1279
+ };
1280
+ triggerAnotherBuild();
1281
+ });
1282
+ return latestResultPromise;
1283
+ },
1284
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1285
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1286
+ const keys = {};
1287
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1288
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1289
+ const request2 = {
1290
+ command: "watch",
1291
+ key: buildKey
1292
+ };
1293
+ if (delay) request2.delay = delay;
1294
+ sendRequest(refs, request2, (error2) => {
1295
+ if (error2) reject(new Error(error2));
1296
+ else resolve(void 0);
1297
+ });
1298
+ }),
1299
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1300
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1301
+ const keys = {};
1302
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1303
+ const host = getFlag(options2, keys, "host", mustBeString);
1304
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1305
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1306
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1307
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1308
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1309
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1310
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1311
+ const request2 = {
1312
+ command: "serve",
1313
+ key: buildKey,
1314
+ onRequest: !!onRequest
1315
+ };
1316
+ if (port !== void 0) request2.port = port;
1317
+ if (host !== void 0) request2.host = host;
1318
+ if (servedir !== void 0) request2.servedir = servedir;
1319
+ if (keyfile !== void 0) request2.keyfile = keyfile;
1320
+ if (certfile !== void 0) request2.certfile = certfile;
1321
+ if (fallback !== void 0) request2.fallback = fallback;
1322
+ if (cors) {
1323
+ const corsKeys = {};
1324
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1325
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1326
+ if (Array.isArray(origin)) request2.corsOrigin = origin;
1327
+ else if (origin !== void 0) request2.corsOrigin = [origin];
1328
+ }
1329
+ sendRequest(refs, request2, (error2, response2) => {
1330
+ if (error2) return reject(new Error(error2));
1331
+ if (onRequest) {
1332
+ requestCallbacks["serve-request"] = (id, request3) => {
1333
+ onRequest(request3.args);
1334
+ sendResponse(id, {});
1335
+ };
1336
+ }
1337
+ resolve(response2);
1338
+ });
1339
+ }),
1340
+ cancel: () => new Promise((resolve) => {
1341
+ if (didDispose) return resolve();
1342
+ const request2 = {
1343
+ command: "cancel",
1344
+ key: buildKey
1345
+ };
1346
+ sendRequest(refs, request2, () => {
1347
+ resolve();
1348
+ });
1349
+ }),
1350
+ dispose: () => new Promise((resolve) => {
1351
+ if (didDispose) return resolve();
1352
+ didDispose = true;
1353
+ const request2 = {
1354
+ command: "dispose",
1355
+ key: buildKey
1356
+ };
1357
+ sendRequest(refs, request2, () => {
1358
+ resolve();
1359
+ scheduleOnDisposeCallbacks();
1360
+ refs.unref();
1361
+ });
1362
+ })
1363
+ };
1364
+ refs.ref();
1365
+ callback(null, result);
1366
+ });
1367
+ }
1368
+ }
1369
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1370
+ let onStartCallbacks = [];
1371
+ let onEndCallbacks = [];
1372
+ let onResolveCallbacks = {};
1373
+ let onLoadCallbacks = {};
1374
+ let onDisposeCallbacks = [];
1375
+ let nextCallbackID = 0;
1376
+ let i = 0;
1377
+ let requestPlugins = [];
1378
+ let isSetupDone = false;
1379
+ plugins = [...plugins];
1380
+ for (let item of plugins) {
1381
+ let keys = {};
1382
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1383
+ const name = getFlag(item, keys, "name", mustBeString);
1384
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1385
+ try {
1386
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1387
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1388
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1389
+ let plugin = {
1390
+ name,
1391
+ onStart: false,
1392
+ onEnd: false,
1393
+ onResolve: [],
1394
+ onLoad: []
1395
+ };
1396
+ i++;
1397
+ let resolve = (path32, options = {}) => {
1398
+ if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
1399
+ if (typeof path32 !== "string") throw new Error(`The path to resolve must be a string`);
1400
+ let keys2 = /* @__PURE__ */ Object.create(null);
1401
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1402
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1403
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1404
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1405
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1406
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1407
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1408
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1409
+ return new Promise((resolve2, reject) => {
1410
+ const request = {
1411
+ command: "resolve",
1412
+ path: path32,
1413
+ key: buildKey,
1414
+ pluginName: name
1415
+ };
1416
+ if (pluginName != null) request.pluginName = pluginName;
1417
+ if (importer != null) request.importer = importer;
1418
+ if (namespace != null) request.namespace = namespace;
1419
+ if (resolveDir != null) request.resolveDir = resolveDir;
1420
+ if (kind != null) request.kind = kind;
1421
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
1422
+ if (pluginData != null) request.pluginData = details.store(pluginData);
1423
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1424
+ sendRequest(refs, request, (error, response) => {
1425
+ if (error !== null) reject(new Error(error));
1426
+ else resolve2({
1427
+ errors: replaceDetailsInMessages(response.errors, details),
1428
+ warnings: replaceDetailsInMessages(response.warnings, details),
1429
+ path: response.path,
1430
+ external: response.external,
1431
+ sideEffects: response.sideEffects,
1432
+ namespace: response.namespace,
1433
+ suffix: response.suffix,
1434
+ pluginData: details.load(response.pluginData)
1435
+ });
1436
+ });
1437
+ });
1438
+ };
1439
+ let promise = setup({
1440
+ initialOptions,
1441
+ resolve,
1442
+ onStart(callback) {
1443
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1444
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1445
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1446
+ plugin.onStart = true;
1447
+ },
1448
+ onEnd(callback) {
1449
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1450
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1451
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1452
+ plugin.onEnd = true;
1453
+ },
1454
+ onResolve(options, callback) {
1455
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1456
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1457
+ let keys2 = {};
1458
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1459
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1460
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1461
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1462
+ let id = nextCallbackID++;
1463
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1464
+ plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1465
+ },
1466
+ onLoad(options, callback) {
1467
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1468
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1469
+ let keys2 = {};
1470
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1471
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1472
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1473
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1474
+ let id = nextCallbackID++;
1475
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1476
+ plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1477
+ },
1478
+ onDispose(callback) {
1479
+ onDisposeCallbacks.push(callback);
1480
+ },
1481
+ esbuild: streamIn.esbuild
1482
+ });
1483
+ if (promise) await promise;
1484
+ requestPlugins.push(plugin);
1485
+ } catch (e) {
1486
+ return { ok: false, error: e, pluginName: name };
1487
+ }
1488
+ }
1489
+ requestCallbacks["on-start"] = async (id, request) => {
1490
+ details.clear();
1491
+ let response = { errors: [], warnings: [] };
1492
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1493
+ try {
1494
+ let result = await callback();
1495
+ if (result != null) {
1496
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1497
+ let keys = {};
1498
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1499
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1500
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1501
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1502
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1503
+ }
1504
+ } catch (e) {
1505
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1506
+ }
1507
+ }));
1508
+ sendResponse(id, response);
1509
+ };
1510
+ requestCallbacks["on-resolve"] = async (id, request) => {
1511
+ let response = {}, name = "", callback, note;
1512
+ for (let id2 of request.ids) {
1513
+ try {
1514
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1515
+ let result = await callback({
1516
+ path: request.path,
1517
+ importer: request.importer,
1518
+ namespace: request.namespace,
1519
+ resolveDir: request.resolveDir,
1520
+ kind: request.kind,
1521
+ pluginData: details.load(request.pluginData),
1522
+ with: request.with
1523
+ });
1524
+ if (result != null) {
1525
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1526
+ let keys = {};
1527
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1528
+ let path32 = getFlag(result, keys, "path", mustBeString);
1529
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1530
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1531
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1532
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1533
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1534
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1535
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1536
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1537
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1538
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1539
+ response.id = id2;
1540
+ if (pluginName != null) response.pluginName = pluginName;
1541
+ if (path32 != null) response.path = path32;
1542
+ if (namespace != null) response.namespace = namespace;
1543
+ if (suffix != null) response.suffix = suffix;
1544
+ if (external != null) response.external = external;
1545
+ if (sideEffects != null) response.sideEffects = sideEffects;
1546
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1547
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1548
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1549
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1550
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1551
+ break;
1552
+ }
1553
+ } catch (e) {
1554
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1555
+ break;
1556
+ }
1557
+ }
1558
+ sendResponse(id, response);
1559
+ };
1560
+ requestCallbacks["on-load"] = async (id, request) => {
1561
+ let response = {}, name = "", callback, note;
1562
+ for (let id2 of request.ids) {
1563
+ try {
1564
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1565
+ let result = await callback({
1566
+ path: request.path,
1567
+ namespace: request.namespace,
1568
+ suffix: request.suffix,
1569
+ pluginData: details.load(request.pluginData),
1570
+ with: request.with
1571
+ });
1572
+ if (result != null) {
1573
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1574
+ let keys = {};
1575
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1576
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1577
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1578
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1579
+ let loader = getFlag(result, keys, "loader", mustBeString);
1580
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1581
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1582
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1583
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1584
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1585
+ response.id = id2;
1586
+ if (pluginName != null) response.pluginName = pluginName;
1587
+ if (contents instanceof Uint8Array) response.contents = contents;
1588
+ else if (contents != null) response.contents = encodeUTF8(contents);
1589
+ if (resolveDir != null) response.resolveDir = resolveDir;
1590
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1591
+ if (loader != null) response.loader = loader;
1592
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1593
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1594
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1595
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1596
+ break;
1597
+ }
1598
+ } catch (e) {
1599
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1600
+ break;
1601
+ }
1602
+ }
1603
+ sendResponse(id, response);
1604
+ };
1605
+ let runOnEndCallbacks = (result, done) => done([], []);
1606
+ if (onEndCallbacks.length > 0) {
1607
+ runOnEndCallbacks = (result, done) => {
1608
+ (async () => {
1609
+ const onEndErrors = [];
1610
+ const onEndWarnings = [];
1611
+ for (const { name, callback, note } of onEndCallbacks) {
1612
+ let newErrors;
1613
+ let newWarnings;
1614
+ try {
1615
+ const value = await callback(result);
1616
+ if (value != null) {
1617
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1618
+ let keys = {};
1619
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1620
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1621
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1622
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1623
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1624
+ }
1625
+ } catch (e) {
1626
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1627
+ }
1628
+ if (newErrors) {
1629
+ onEndErrors.push(...newErrors);
1630
+ try {
1631
+ result.errors.push(...newErrors);
1632
+ } catch {
1633
+ }
1634
+ }
1635
+ if (newWarnings) {
1636
+ onEndWarnings.push(...newWarnings);
1637
+ try {
1638
+ result.warnings.push(...newWarnings);
1639
+ } catch {
1640
+ }
1641
+ }
1642
+ }
1643
+ done(onEndErrors, onEndWarnings);
1644
+ })();
1645
+ };
1646
+ }
1647
+ let scheduleOnDisposeCallbacks = () => {
1648
+ for (const cb of onDisposeCallbacks) {
1649
+ setTimeout(() => cb(), 0);
1650
+ }
1651
+ };
1652
+ isSetupDone = true;
1653
+ return {
1654
+ ok: true,
1655
+ requestPlugins,
1656
+ runOnEndCallbacks,
1657
+ scheduleOnDisposeCallbacks
1658
+ };
1659
+ };
1660
+ function createObjectStash() {
1661
+ const map = /* @__PURE__ */ new Map();
1662
+ let nextID = 0;
1663
+ return {
1664
+ clear() {
1665
+ map.clear();
1666
+ },
1667
+ load(id) {
1668
+ return map.get(id);
1669
+ },
1670
+ store(value) {
1671
+ if (value === void 0) return -1;
1672
+ const id = nextID++;
1673
+ map.set(id, value);
1674
+ return id;
1675
+ }
1676
+ };
1677
+ }
1678
+ function extractCallerV8(e, streamIn, ident) {
1679
+ let note;
1680
+ let tried = false;
1681
+ return () => {
1682
+ if (tried) return note;
1683
+ tried = true;
1684
+ try {
1685
+ let lines = (e.stack + "").split("\n");
1686
+ lines.splice(1, 1);
1687
+ let location = parseStackLinesV8(streamIn, lines, ident);
1688
+ if (location) {
1689
+ note = { text: e.message, location };
1690
+ return note;
1691
+ }
1692
+ } catch {
1693
+ }
1694
+ };
1695
+ }
1696
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1697
+ let text = "Internal error";
1698
+ let location = null;
1699
+ try {
1700
+ text = (e && e.message || e) + "";
1701
+ } catch {
1702
+ }
1703
+ try {
1704
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1705
+ } catch {
1706
+ }
1707
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1708
+ }
1709
+ function parseStackLinesV8(streamIn, lines, ident) {
1710
+ let at = " at ";
1711
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1712
+ for (let i = 1; i < lines.length; i++) {
1713
+ let line = lines[i];
1714
+ if (!line.startsWith(at)) continue;
1715
+ line = line.slice(at.length);
1716
+ while (true) {
1717
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1718
+ if (match) {
1719
+ line = match[1];
1720
+ continue;
1721
+ }
1722
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1723
+ if (match) {
1724
+ line = match[1];
1725
+ continue;
1726
+ }
1727
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1728
+ if (match) {
1729
+ let contents;
1730
+ try {
1731
+ contents = streamIn.readFileSync(match[1], "utf8");
1732
+ } catch {
1733
+ break;
1734
+ }
1735
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1736
+ let column = +match[3] - 1;
1737
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1738
+ return {
1739
+ file: match[1],
1740
+ namespace: "file",
1741
+ line: +match[2],
1742
+ column: encodeUTF8(lineText.slice(0, column)).length,
1743
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1744
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1745
+ suggestion: ""
1746
+ };
1747
+ }
1748
+ break;
1749
+ }
1750
+ }
1751
+ }
1752
+ return null;
1753
+ }
1754
+ function failureErrorWithLog(text, errors, warnings) {
1755
+ let limit = 5;
1756
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1757
+ if (i === limit) return "\n...";
1758
+ if (!e.location) return `
1759
+ error: ${e.text}`;
1760
+ let { file, line, column } = e.location;
1761
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1762
+ return `
1763
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1764
+ }).join("");
1765
+ let error = new Error(text);
1766
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1767
+ Object.defineProperty(error, key, {
1768
+ configurable: true,
1769
+ enumerable: true,
1770
+ get: () => value,
1771
+ set: (value2) => Object.defineProperty(error, key, {
1772
+ configurable: true,
1773
+ enumerable: true,
1774
+ value: value2
1775
+ })
1776
+ });
1777
+ }
1778
+ return error;
1779
+ }
1780
+ function replaceDetailsInMessages(messages, stash) {
1781
+ for (const message of messages) {
1782
+ message.detail = stash.load(message.detail);
1783
+ }
1784
+ return messages;
1785
+ }
1786
+ function sanitizeLocation(location, where, terminalWidth) {
1787
+ if (location == null) return null;
1788
+ let keys = {};
1789
+ let file = getFlag(location, keys, "file", mustBeString);
1790
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1791
+ let line = getFlag(location, keys, "line", mustBeInteger);
1792
+ let column = getFlag(location, keys, "column", mustBeInteger);
1793
+ let length = getFlag(location, keys, "length", mustBeInteger);
1794
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1795
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1796
+ checkForInvalidFlags(location, keys, where);
1797
+ if (lineText) {
1798
+ const relevantASCII = lineText.slice(
1799
+ 0,
1800
+ (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
1801
+ );
1802
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1803
+ lineText = relevantASCII;
1804
+ }
1805
+ }
1806
+ return {
1807
+ file: file || "",
1808
+ namespace: namespace || "",
1809
+ line: line || 0,
1810
+ column: column || 0,
1811
+ length: length || 0,
1812
+ lineText: lineText || "",
1813
+ suggestion: suggestion || ""
1814
+ };
1815
+ }
1816
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1817
+ let messagesClone = [];
1818
+ let index = 0;
1819
+ for (const message of messages) {
1820
+ let keys = {};
1821
+ let id = getFlag(message, keys, "id", mustBeString);
1822
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1823
+ let text = getFlag(message, keys, "text", mustBeString);
1824
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1825
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1826
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1827
+ let where = `in element ${index} of "${property}"`;
1828
+ checkForInvalidFlags(message, keys, where);
1829
+ let notesClone = [];
1830
+ if (notes) {
1831
+ for (const note of notes) {
1832
+ let noteKeys = {};
1833
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1834
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1835
+ checkForInvalidFlags(note, noteKeys, where);
1836
+ notesClone.push({
1837
+ text: noteText || "",
1838
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1839
+ });
1840
+ }
1841
+ }
1842
+ messagesClone.push({
1843
+ id: id || "",
1844
+ pluginName: pluginName || fallbackPluginName,
1845
+ text: text || "",
1846
+ location: sanitizeLocation(location, where, terminalWidth),
1847
+ notes: notesClone,
1848
+ detail: stash ? stash.store(detail) : -1
1849
+ });
1850
+ index++;
1851
+ }
1852
+ return messagesClone;
1853
+ }
1854
+ function sanitizeStringArray(values, property) {
1855
+ const result = [];
1856
+ for (const value of values) {
1857
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1858
+ result.push(value);
1859
+ }
1860
+ return result;
1861
+ }
1862
+ function sanitizeStringMap(map, property) {
1863
+ const result = /* @__PURE__ */ Object.create(null);
1864
+ for (const key in map) {
1865
+ const value = map[key];
1866
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1867
+ result[key] = value;
1868
+ }
1869
+ return result;
1870
+ }
1871
+ function convertOutputFiles({ path: path32, contents, hash }) {
1872
+ let text = null;
1873
+ return {
1874
+ path: path32,
1875
+ contents,
1876
+ hash,
1877
+ get text() {
1878
+ const binary = this.contents;
1879
+ if (text === null || binary !== contents) {
1880
+ contents = binary;
1881
+ text = decodeUTF8(binary);
1882
+ }
1883
+ return text;
1884
+ }
1885
+ };
1886
+ }
1887
+ function jsRegExpToGoRegExp(regexp) {
1888
+ let result = regexp.source;
1889
+ if (regexp.flags) result = `(?${regexp.flags})${result}`;
1890
+ return result;
1891
+ }
1892
+ function parseJSON(bytes) {
1893
+ let text;
1894
+ try {
1895
+ text = decodeUTF8(bytes);
1896
+ } catch {
1897
+ return JSON_parse(bytes);
1898
+ }
1899
+ return JSON.parse(text);
1900
+ }
1901
+ var fs5 = __require("fs");
1902
+ var os = __require("os");
1903
+ var path8 = __require("path");
1904
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1905
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1906
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1907
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1908
+ var knownWindowsPackages = {
1909
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1910
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1911
+ "win32 x64 LE": "@esbuild/win32-x64"
1912
+ };
1913
+ var knownUnixlikePackages = {
1914
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1915
+ "android arm64 LE": "@esbuild/android-arm64",
1916
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1917
+ "darwin x64 LE": "@esbuild/darwin-x64",
1918
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1919
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1920
+ "linux arm LE": "@esbuild/linux-arm",
1921
+ "linux arm64 LE": "@esbuild/linux-arm64",
1922
+ "linux ia32 LE": "@esbuild/linux-ia32",
1923
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1924
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1925
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1926
+ "linux s390x BE": "@esbuild/linux-s390x",
1927
+ "linux x64 LE": "@esbuild/linux-x64",
1928
+ "linux loong64 LE": "@esbuild/linux-loong64",
1929
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1930
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1931
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1932
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1933
+ "sunos x64 LE": "@esbuild/sunos-x64"
1934
+ };
1935
+ var knownWebAssemblyFallbackPackages = {
1936
+ "android arm LE": "@esbuild/android-arm",
1937
+ "android x64 LE": "@esbuild/android-x64",
1938
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
1939
+ };
1940
+ function pkgAndSubpathForCurrentPlatform() {
1941
+ let pkg;
1942
+ let subpath;
1943
+ let isWASM = false;
1944
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1945
+ if (platformKey in knownWindowsPackages) {
1946
+ pkg = knownWindowsPackages[platformKey];
1947
+ subpath = "esbuild.exe";
1948
+ } else if (platformKey in knownUnixlikePackages) {
1949
+ pkg = knownUnixlikePackages[platformKey];
1950
+ subpath = "bin/esbuild";
1951
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1952
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1953
+ subpath = "bin/esbuild";
1954
+ isWASM = true;
1955
+ } else {
1956
+ throw new Error(`Unsupported platform: ${platformKey}`);
1957
+ }
1958
+ return { pkg, subpath, isWASM };
1959
+ }
1960
+ function pkgForSomeOtherPlatform() {
1961
+ const libMainJS = __require.resolve("esbuild");
1962
+ const nodeModulesDirectory = path8.dirname(path8.dirname(path8.dirname(libMainJS)));
1963
+ if (path8.basename(nodeModulesDirectory) === "node_modules") {
1964
+ for (const unixKey in knownUnixlikePackages) {
1965
+ try {
1966
+ const pkg = knownUnixlikePackages[unixKey];
1967
+ if (fs5.existsSync(path8.join(nodeModulesDirectory, pkg))) return pkg;
1968
+ } catch {
1969
+ }
1970
+ }
1971
+ for (const windowsKey in knownWindowsPackages) {
1972
+ try {
1973
+ const pkg = knownWindowsPackages[windowsKey];
1974
+ if (fs5.existsSync(path8.join(nodeModulesDirectory, pkg))) return pkg;
1975
+ } catch {
1976
+ }
1977
+ }
1978
+ }
1979
+ return null;
1980
+ }
1981
+ function downloadedBinPath(pkg, subpath) {
1982
+ const esbuildLibDir = path8.dirname(__require.resolve("esbuild"));
1983
+ return path8.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path8.basename(subpath)}`);
1984
+ }
1985
+ function generateBinPath() {
1986
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1987
+ if (!fs5.existsSync(ESBUILD_BINARY_PATH)) {
1988
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1989
+ } else {
1990
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1991
+ }
1992
+ }
1993
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1994
+ let binPath;
1995
+ try {
1996
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1997
+ } catch (e) {
1998
+ binPath = downloadedBinPath(pkg, subpath);
1999
+ if (!fs5.existsSync(binPath)) {
2000
+ try {
2001
+ __require.resolve(pkg);
2002
+ } catch {
2003
+ const otherPkg = pkgForSomeOtherPlatform();
2004
+ if (otherPkg) {
2005
+ let suggestions = `
2006
+ Specifically the "${otherPkg}" package is present but this platform
2007
+ needs the "${pkg}" package instead. People often get into this
2008
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
2009
+ into a Docker image that runs Linux, or by copying "node_modules" between
2010
+ Windows and WSL environments.
2011
+
2012
+ If you are installing with npm, you can try not copying the "node_modules"
2013
+ directory when you copy the files over, and running "npm ci" or "npm install"
2014
+ on the destination platform after the copy. Or you could consider using yarn
2015
+ instead of npm which has built-in support for installing a package on multiple
2016
+ platforms simultaneously.
2017
+
2018
+ If you are installing with yarn, you can try listing both this platform and the
2019
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2020
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2021
+ Keep in mind that this means multiple copies of esbuild will be present.
2022
+ `;
2023
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
2024
+ suggestions = `
2025
+ Specifically the "${otherPkg}" package is present but this platform
2026
+ needs the "${pkg}" package instead. People often get into this
2027
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
2028
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2029
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2030
+
2031
+ If you are installing with npm, you can try ensuring that both npm and node are
2032
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2033
+ changing how you installed npm and/or node. For example, installing node with
2034
+ the universal installer here should work: https://nodejs.org/en/download/. Or
2035
+ you could consider using yarn instead of npm which has built-in support for
2036
+ installing a package on multiple platforms simultaneously.
2037
+
2038
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
2039
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2040
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2041
+ Keep in mind that this means multiple copies of esbuild will be present.
2042
+ `;
2043
+ }
2044
+ throw new Error(`
2045
+ You installed esbuild for another platform than the one you're currently using.
2046
+ This won't work because esbuild is written with native code and needs to
2047
+ install a platform-specific binary executable.
2048
+ ${suggestions}
2049
+ Another alternative is to use the "esbuild-wasm" package instead, which works
2050
+ the same way on all platforms. But it comes with a heavy performance cost and
2051
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
2052
+ want to do that.
2053
+ `);
2054
+ }
2055
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2056
+
2057
+ If you are installing esbuild with npm, make sure that you don't specify the
2058
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2059
+ of "package.json" is used by esbuild to install the correct binary executable
2060
+ for your current platform.`);
2061
+ }
2062
+ throw e;
2063
+ }
2064
+ }
2065
+ if (/\.zip\//.test(binPath)) {
2066
+ let pnpapi;
2067
+ try {
2068
+ pnpapi = __require("pnpapi");
2069
+ } catch (e) {
2070
+ }
2071
+ if (pnpapi) {
2072
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2073
+ const binTargetPath = path8.join(
2074
+ root,
2075
+ "node_modules",
2076
+ ".cache",
2077
+ "esbuild",
2078
+ `pnpapi-${pkg.replace("/", "-")}-${"0.27.4"}-${path8.basename(subpath)}`
2079
+ );
2080
+ if (!fs5.existsSync(binTargetPath)) {
2081
+ fs5.mkdirSync(path8.dirname(binTargetPath), { recursive: true });
2082
+ fs5.copyFileSync(binPath, binTargetPath);
2083
+ fs5.chmodSync(binTargetPath, 493);
2084
+ }
2085
+ return { binPath: binTargetPath, isWASM };
2086
+ }
2087
+ }
2088
+ return { binPath, isWASM };
2089
+ }
2090
+ var child_process = __require("child_process");
2091
+ var crypto = __require("crypto");
2092
+ var path22 = __require("path");
2093
+ var fs22 = __require("fs");
2094
+ var os2 = __require("os");
2095
+ var tty = __require("tty");
2096
+ var worker_threads;
2097
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2098
+ try {
2099
+ worker_threads = __require("worker_threads");
2100
+ } catch {
2101
+ }
2102
+ let [major, minor] = process.versions.node.split(".");
2103
+ if (
2104
+ // <v12.17.0 does not work
2105
+ +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
2106
+ ) {
2107
+ worker_threads = void 0;
2108
+ }
2109
+ }
2110
+ var _a;
2111
+ var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.4";
2112
+ var esbuildCommandAndArgs = () => {
2113
+ if ((!ESBUILD_BINARY_PATH || false) && (path22.basename(__filename) !== "main.js" || path22.basename(__dirname) !== "lib")) {
2114
+ throw new Error(
2115
+ `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
2116
+
2117
+ 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.`
2118
+ );
2119
+ }
2120
+ if (false) {
2121
+ return ["node", [path22.join(__dirname, "..", "bin", "esbuild")]];
2122
+ } else {
2123
+ const { binPath, isWASM } = generateBinPath();
2124
+ if (isWASM) {
2125
+ return ["node", [binPath]];
2126
+ } else {
2127
+ return [binPath, []];
2128
+ }
2129
+ }
2130
+ };
2131
+ var isTTY = () => tty.isatty(2);
2132
+ var fsSync = {
2133
+ readFile(tempFile, callback) {
2134
+ try {
2135
+ let contents = fs22.readFileSync(tempFile, "utf8");
2136
+ try {
2137
+ fs22.unlinkSync(tempFile);
2138
+ } catch {
2139
+ }
2140
+ callback(null, contents);
2141
+ } catch (err) {
2142
+ callback(err, null);
2143
+ }
2144
+ },
2145
+ writeFile(contents, callback) {
2146
+ try {
2147
+ let tempFile = randomFileName();
2148
+ fs22.writeFileSync(tempFile, contents);
2149
+ callback(tempFile);
2150
+ } catch {
2151
+ callback(null);
2152
+ }
2153
+ }
2154
+ };
2155
+ var fsAsync = {
2156
+ readFile(tempFile, callback) {
2157
+ try {
2158
+ fs22.readFile(tempFile, "utf8", (err, contents) => {
2159
+ try {
2160
+ fs22.unlink(tempFile, () => callback(err, contents));
2161
+ } catch {
2162
+ callback(err, contents);
2163
+ }
2164
+ });
2165
+ } catch (err) {
2166
+ callback(err, null);
2167
+ }
2168
+ },
2169
+ writeFile(contents, callback) {
2170
+ try {
2171
+ let tempFile = randomFileName();
2172
+ fs22.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2173
+ } catch {
2174
+ callback(null);
2175
+ }
2176
+ }
2177
+ };
2178
+ var version = "0.27.4";
2179
+ var build2 = (options) => ensureServiceIsRunning().build(options);
2180
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2181
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2182
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2183
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2184
+ var buildSync = (options) => {
2185
+ if (worker_threads && !isInternalWorkerThread) {
2186
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2187
+ return workerThreadService.buildSync(options);
2188
+ }
2189
+ let result;
2190
+ runServiceSync((service) => service.buildOrContext({
2191
+ callName: "buildSync",
2192
+ refs: null,
2193
+ options,
2194
+ isTTY: isTTY(),
2195
+ defaultWD,
2196
+ callback: (err, res) => {
2197
+ if (err) throw err;
2198
+ result = res;
2199
+ }
2200
+ }));
2201
+ return result;
2202
+ };
2203
+ var transformSync = (input, options) => {
2204
+ if (worker_threads && !isInternalWorkerThread) {
2205
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2206
+ return workerThreadService.transformSync(input, options);
2207
+ }
2208
+ let result;
2209
+ runServiceSync((service) => service.transform({
2210
+ callName: "transformSync",
2211
+ refs: null,
2212
+ input,
2213
+ options: options || {},
2214
+ isTTY: isTTY(),
2215
+ fs: fsSync,
2216
+ callback: (err, res) => {
2217
+ if (err) throw err;
2218
+ result = res;
2219
+ }
2220
+ }));
2221
+ return result;
2222
+ };
2223
+ var formatMessagesSync = (messages, options) => {
2224
+ if (worker_threads && !isInternalWorkerThread) {
2225
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2226
+ return workerThreadService.formatMessagesSync(messages, options);
2227
+ }
2228
+ let result;
2229
+ runServiceSync((service) => service.formatMessages({
2230
+ callName: "formatMessagesSync",
2231
+ refs: null,
2232
+ messages,
2233
+ options,
2234
+ callback: (err, res) => {
2235
+ if (err) throw err;
2236
+ result = res;
2237
+ }
2238
+ }));
2239
+ return result;
2240
+ };
2241
+ var analyzeMetafileSync = (metafile, options) => {
2242
+ if (worker_threads && !isInternalWorkerThread) {
2243
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2244
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2245
+ }
2246
+ let result;
2247
+ runServiceSync((service) => service.analyzeMetafile({
2248
+ callName: "analyzeMetafileSync",
2249
+ refs: null,
2250
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2251
+ options,
2252
+ callback: (err, res) => {
2253
+ if (err) throw err;
2254
+ result = res;
2255
+ }
2256
+ }));
2257
+ return result;
2258
+ };
2259
+ var stop = () => {
2260
+ if (stopService) stopService();
2261
+ if (workerThreadService) workerThreadService.stop();
2262
+ return Promise.resolve();
2263
+ };
2264
+ var initializeWasCalled = false;
2265
+ var initialize = (options) => {
2266
+ options = validateInitializeOptions(options || {});
2267
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2268
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2269
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2270
+ if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
2271
+ ensureServiceIsRunning();
2272
+ initializeWasCalled = true;
2273
+ return Promise.resolve();
2274
+ };
2275
+ var defaultWD = process.cwd();
2276
+ var longLivedService;
2277
+ var stopService;
2278
+ var ensureServiceIsRunning = () => {
2279
+ if (longLivedService) return longLivedService;
2280
+ let [command, args] = esbuildCommandAndArgs();
2281
+ let child = child_process.spawn(command, args.concat(`--service=${"0.27.4"}`, "--ping"), {
2282
+ windowsHide: true,
2283
+ stdio: ["pipe", "pipe", "inherit"],
2284
+ cwd: defaultWD
2285
+ });
2286
+ let { readFromStdout, afterClose, service } = createChannel({
2287
+ writeToStdin(bytes) {
2288
+ child.stdin.write(bytes, (err) => {
2289
+ if (err) afterClose(err);
2290
+ });
2291
+ },
2292
+ readFileSync: fs22.readFileSync,
2293
+ isSync: false,
2294
+ hasFS: true,
2295
+ esbuild: node_exports
2296
+ });
2297
+ child.stdin.on("error", afterClose);
2298
+ child.on("error", afterClose);
2299
+ const stdin = child.stdin;
2300
+ const stdout = child.stdout;
2301
+ stdout.on("data", readFromStdout);
2302
+ stdout.on("end", afterClose);
2303
+ stopService = () => {
2304
+ stdin.destroy();
2305
+ stdout.destroy();
2306
+ child.kill();
2307
+ initializeWasCalled = false;
2308
+ longLivedService = void 0;
2309
+ stopService = void 0;
2310
+ };
2311
+ let refCount = 0;
2312
+ child.unref();
2313
+ if (stdin.unref) {
2314
+ stdin.unref();
2315
+ }
2316
+ if (stdout.unref) {
2317
+ stdout.unref();
2318
+ }
2319
+ const refs = {
2320
+ ref() {
2321
+ if (++refCount === 1) child.ref();
2322
+ },
2323
+ unref() {
2324
+ if (--refCount === 0) child.unref();
2325
+ }
2326
+ };
2327
+ longLivedService = {
2328
+ build: (options) => new Promise((resolve, reject) => {
2329
+ service.buildOrContext({
2330
+ callName: "build",
2331
+ refs,
2332
+ options,
2333
+ isTTY: isTTY(),
2334
+ defaultWD,
2335
+ callback: (err, res) => err ? reject(err) : resolve(res)
2336
+ });
2337
+ }),
2338
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2339
+ callName: "context",
2340
+ refs,
2341
+ options,
2342
+ isTTY: isTTY(),
2343
+ defaultWD,
2344
+ callback: (err, res) => err ? reject(err) : resolve(res)
2345
+ })),
2346
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2347
+ callName: "transform",
2348
+ refs,
2349
+ input,
2350
+ options: options || {},
2351
+ isTTY: isTTY(),
2352
+ fs: fsAsync,
2353
+ callback: (err, res) => err ? reject(err) : resolve(res)
2354
+ })),
2355
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2356
+ callName: "formatMessages",
2357
+ refs,
2358
+ messages,
2359
+ options,
2360
+ callback: (err, res) => err ? reject(err) : resolve(res)
2361
+ })),
2362
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2363
+ callName: "analyzeMetafile",
2364
+ refs,
2365
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2366
+ options,
2367
+ callback: (err, res) => err ? reject(err) : resolve(res)
2368
+ }))
2369
+ };
2370
+ return longLivedService;
2371
+ };
2372
+ var runServiceSync = (callback) => {
2373
+ let [command, args] = esbuildCommandAndArgs();
2374
+ let stdin = new Uint8Array();
2375
+ let { readFromStdout, afterClose, service } = createChannel({
2376
+ writeToStdin(bytes) {
2377
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
2378
+ stdin = bytes;
2379
+ },
2380
+ isSync: true,
2381
+ hasFS: true,
2382
+ esbuild: node_exports
2383
+ });
2384
+ callback(service);
2385
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.27.4"}`), {
2386
+ cwd: defaultWD,
2387
+ windowsHide: true,
2388
+ input: stdin,
2389
+ // We don't know how large the output could be. If it's too large, the
2390
+ // command will fail with ENOBUFS. Reserve 16mb for now since that feels
2391
+ // like it should be enough. Also allow overriding this with an environment
2392
+ // variable.
2393
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2394
+ });
2395
+ readFromStdout(stdout);
2396
+ afterClose(null);
2397
+ };
2398
+ var randomFileName = () => {
2399
+ return path22.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2400
+ };
2401
+ var workerThreadService = null;
2402
+ var startWorkerThreadService = (worker_threads2) => {
2403
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2404
+ let worker = new worker_threads2.Worker(__filename, {
2405
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.27.4" },
2406
+ transferList: [workerPort],
2407
+ // From node's documentation: https://nodejs.org/api/worker_threads.html
2408
+ //
2409
+ // Take care when launching worker threads from preload scripts (scripts loaded
2410
+ // and run using the `-r` command line flag). Unless the `execArgv` option is
2411
+ // explicitly set, new Worker threads automatically inherit the command line flags
2412
+ // from the running process and will preload the same preload scripts as the main
2413
+ // thread. If the preload script unconditionally launches a worker thread, every
2414
+ // thread spawned will spawn another until the application crashes.
2415
+ //
2416
+ execArgv: []
2417
+ });
2418
+ let nextID = 0;
2419
+ let fakeBuildError = (text) => {
2420
+ let error = new Error(`Build failed with 1 error:
2421
+ error: ${text}`);
2422
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
2423
+ error.errors = errors;
2424
+ error.warnings = [];
2425
+ return error;
2426
+ };
2427
+ let validateBuildSyncOptions = (options) => {
2428
+ if (!options) return;
2429
+ let plugins = options.plugins;
2430
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2431
+ };
2432
+ let applyProperties = (object, properties) => {
2433
+ for (let key in properties) {
2434
+ object[key] = properties[key];
2435
+ }
2436
+ };
2437
+ let runCallSync = (command, args) => {
2438
+ let id = nextID++;
2439
+ let sharedBuffer = new SharedArrayBuffer(8);
2440
+ let sharedBufferView = new Int32Array(sharedBuffer);
2441
+ let msg = { sharedBuffer, id, command, args };
2442
+ worker.postMessage(msg);
2443
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2444
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2445
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2446
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2447
+ if (reject) {
2448
+ applyProperties(reject, properties);
2449
+ throw reject;
2450
+ }
2451
+ return resolve;
2452
+ };
2453
+ worker.unref();
2454
+ return {
2455
+ buildSync(options) {
2456
+ validateBuildSyncOptions(options);
2457
+ return runCallSync("build", [options]);
2458
+ },
2459
+ transformSync(input, options) {
2460
+ return runCallSync("transform", [input, options]);
2461
+ },
2462
+ formatMessagesSync(messages, options) {
2463
+ return runCallSync("formatMessages", [messages, options]);
2464
+ },
2465
+ analyzeMetafileSync(metafile, options) {
2466
+ return runCallSync("analyzeMetafile", [metafile, options]);
2467
+ },
2468
+ stop() {
2469
+ worker.terminate();
2470
+ workerThreadService = null;
2471
+ }
2472
+ };
2473
+ };
2474
+ var startSyncServiceWorker = () => {
2475
+ let workerPort = worker_threads.workerData.workerPort;
2476
+ let parentPort = worker_threads.parentPort;
2477
+ let extractProperties = (object) => {
2478
+ let properties = {};
2479
+ if (object && typeof object === "object") {
2480
+ for (let key in object) {
2481
+ properties[key] = object[key];
2482
+ }
2483
+ }
2484
+ return properties;
2485
+ };
2486
+ try {
2487
+ let service = ensureServiceIsRunning();
2488
+ defaultWD = worker_threads.workerData.defaultWD;
2489
+ parentPort.on("message", (msg) => {
2490
+ (async () => {
2491
+ let { sharedBuffer, id, command, args } = msg;
2492
+ let sharedBufferView = new Int32Array(sharedBuffer);
2493
+ try {
2494
+ switch (command) {
2495
+ case "build":
2496
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2497
+ break;
2498
+ case "transform":
2499
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2500
+ break;
2501
+ case "formatMessages":
2502
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2503
+ break;
2504
+ case "analyzeMetafile":
2505
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2506
+ break;
2507
+ default:
2508
+ throw new Error(`Invalid command: ${command}`);
2509
+ }
2510
+ } catch (reject) {
2511
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2512
+ }
2513
+ Atomics.add(sharedBufferView, 0, 1);
2514
+ Atomics.notify(sharedBufferView, 0, Infinity);
2515
+ })();
2516
+ });
2517
+ } catch (reject) {
2518
+ parentPort.on("message", (msg) => {
2519
+ let { sharedBuffer, id } = msg;
2520
+ let sharedBufferView = new Int32Array(sharedBuffer);
2521
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2522
+ Atomics.add(sharedBufferView, 0, 1);
2523
+ Atomics.notify(sharedBufferView, 0, Infinity);
2524
+ });
2525
+ }
2526
+ };
2527
+ if (isInternalWorkerThread) {
2528
+ startSyncServiceWorker();
2529
+ }
2530
+ var node_default = node_exports;
2531
+ }
2532
+ });
2533
+
1
2534
  // src/plugin.ts
2
2535
  import pLimit from "p-limit";
3
2536
 
@@ -126,13 +2659,13 @@ function buildDefaultIncludeGlobs(pagesDir, pageExtensions) {
126
2659
  }
127
2660
  async function discoverEntryPages(root, options) {
128
2661
  const fgModule = await import("fast-glob");
129
- const fg = fgModule.default ?? fgModule;
2662
+ const fg2 = fgModule.default ?? fgModule;
130
2663
  const pagesDir = options.pagesDir ?? "src";
131
2664
  const pageExtensions = options.pageExtensions?.length ? options.pageExtensions : [".ht.js", ".html.js", ".ht.ts", ".html.ts"];
132
2665
  const include = Array.isArray(options.include) ? options.include : options.include ? [options.include] : buildDefaultIncludeGlobs(pagesDir, pageExtensions);
133
2666
  const exclude = Array.isArray(options.exclude) ? options.exclude : options.exclude ? [options.exclude] : [];
134
2667
  const pagesRoot = normalizeFsPath(path2.join(root, pagesDir));
135
- const files = await fg.glob(include, {
2668
+ const files = await fg2.glob(include, {
136
2669
  cwd: root,
137
2670
  ignore: exclude,
138
2671
  absolute: true
@@ -368,147 +2901,100 @@ async function buildPageIndex(args) {
368
2901
  return pages;
369
2902
  }
370
2903
 
371
- // src/assets.ts
372
- import fs2 from "fs";
2904
+ // src/static-assets.ts
2905
+ var esbuild = __toESM(require_main(), 1);
2906
+ import fs2 from "fs/promises";
373
2907
  import path5 from "path";
374
- var EXTERNAL_URL_RE = /^(?:[a-z]+:)?\/\//i;
375
- function isLocalAssetUrl(url) {
376
- return !!url && !url.startsWith("data:") && !url.startsWith("mailto:") && !url.startsWith("tel:") && !url.startsWith("#") && !EXTERNAL_URL_RE.test(url);
2908
+ import fg from "fast-glob";
2909
+ function normalizeSlashes(value) {
2910
+ return value.replace(/\\/g, "/");
377
2911
  }
378
- function stripQueryAndHash(url) {
379
- return url.split("#")[0].split("?")[0];
2912
+ function hasAnySuffix(value, suffixes) {
2913
+ return suffixes.some((suffix) => value.endsWith(suffix));
380
2914
  }
381
- function extractHtmlAssets(html) {
382
- const assets = [];
383
- for (const match of html.matchAll(
384
- /<link\b[^>]*\brel=["']stylesheet["'][^>]*\bhref=["']([^"']+)["'][^>]*>/gi
385
- )) {
386
- assets.push({ kind: "css", url: match[1] });
387
- }
388
- for (const match of html.matchAll(
389
- /<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*>/gi
390
- )) {
391
- assets.push({ kind: "js", url: match[1] });
392
- }
393
- return dedupeExtractedAssets(assets);
2915
+ function shouldIgnoreFile(rel) {
2916
+ return rel.endsWith(".d.ts") || rel.endsWith(".map") || rel.endsWith(".tsbuildinfo") || rel.startsWith(".") || rel.includes("/.");
394
2917
  }
395
- function dedupeExtractedAssets(assets) {
396
- const seen = /* @__PURE__ */ new Set();
397
- const out = [];
398
- for (const asset of assets) {
399
- const key = `${asset.kind}:${asset.url}`;
400
- if (seen.has(key)) continue;
401
- seen.add(key);
402
- out.push(asset);
403
- }
404
- return out;
2918
+ function isProcessableAsset(rel) {
2919
+ return rel.endsWith(".js") || rel.endsWith(".mjs") || rel.endsWith(".ts") || rel.endsWith(".css");
405
2920
  }
406
- function resolveLocalAssetPath(args) {
407
- const { root, pagesDir, pageDir, url } = args;
408
- if (!isLocalAssetUrl(url)) return null;
409
- const cleanUrl = stripQueryAndHash(url);
410
- let abs;
411
- if (cleanUrl.startsWith("/")) {
412
- abs = path5.join(root, pagesDir, cleanUrl.slice(1));
413
- } else if (cleanUrl.startsWith(`${pagesDir}/`)) {
414
- abs = path5.join(root, cleanUrl);
415
- } else {
416
- const baseDir = pageDir ?? path5.join(root, pagesDir);
417
- abs = path5.resolve(baseDir, cleanUrl);
2921
+ function toOutputFileName(relativePathFromSrc) {
2922
+ if (relativePathFromSrc.endsWith(".ts")) {
2923
+ return relativePathFromSrc.slice(0, -3) + ".js";
418
2924
  }
419
- return fs2.existsSync(abs) ? abs : null;
420
- }
421
- function emitHtmlAsset(args) {
422
- const { ctx, kind, absolutePath } = args;
423
- if (kind === "css" || kind === "js") {
424
- return ctx.emitFile({
425
- type: "chunk",
426
- id: absolutePath,
427
- name: path5.basename(absolutePath, path5.extname(absolutePath))
2925
+ return relativePathFromSrc;
2926
+ }
2927
+ async function collectStaticAssets(args) {
2928
+ const { root, pagesDir, pageExtensions } = args;
2929
+ const srcDir = path5.join(root, pagesDir);
2930
+ const entries = await fg("**/*", {
2931
+ cwd: srcDir,
2932
+ onlyFiles: true,
2933
+ dot: false,
2934
+ absolute: false
2935
+ });
2936
+ const assets = [];
2937
+ for (const entry of entries) {
2938
+ const rel = normalizeSlashes(entry);
2939
+ if (shouldIgnoreFile(rel)) continue;
2940
+ if (hasAnySuffix(rel, pageExtensions)) continue;
2941
+ const absolutePath = path5.join(srcDir, rel);
2942
+ assets.push({
2943
+ absolutePath,
2944
+ relativePathFromSrc: rel,
2945
+ outputFileName: normalizeSlashes(toOutputFileName(rel)),
2946
+ kind: isProcessableAsset(rel) ? "process" : "copy"
428
2947
  });
429
2948
  }
430
- throw new Error(`[vite-plugin-html-pages] Unsupported asset kind: ${kind}`);
431
- }
432
- function replaceAllLiteral(input, search, replacement) {
433
- return input.split(search).join(replacement);
434
- }
435
- function rewriteHtmlAssetUrls(html, replacements) {
436
- let out = html;
437
- for (const [originalUrl, builtUrl] of replacements) {
438
- out = replaceAllLiteral(
439
- out,
440
- `href="${originalUrl}"`,
441
- `href="${builtUrl}"`
442
- );
443
- out = replaceAllLiteral(
444
- out,
445
- `href='${originalUrl}'`,
446
- `href='${builtUrl}'`
447
- );
448
- out = replaceAllLiteral(
449
- out,
450
- `src="${originalUrl}"`,
451
- `src="${builtUrl}"`
452
- );
453
- out = replaceAllLiteral(
454
- out,
455
- `src='${originalUrl}'`,
456
- `src='${builtUrl}'`
457
- );
458
- }
459
- return out;
2949
+ return assets;
460
2950
  }
461
- async function collectHtmlAssetRefs(args) {
462
- const { ctx, root, pagesDir, htmlByPageKey } = args;
463
- const refs = /* @__PURE__ */ new Map();
464
- for (const { html, pageDir } of htmlByPageKey.values()) {
465
- const assets = extractHtmlAssets(html);
466
- for (const asset of assets) {
467
- const abs = resolveLocalAssetPath({
468
- root,
469
- pagesDir,
470
- pageDir,
471
- url: asset.url
472
- });
473
- if (!abs) continue;
474
- const key = `${asset.kind}:${asset.url}`;
475
- if (refs.has(key)) continue;
476
- const refId = emitHtmlAsset({
477
- ctx,
478
- kind: asset.kind,
479
- absolutePath: abs
480
- });
481
- refs.set(key, {
482
- kind: asset.kind,
483
- originalUrl: asset.url,
484
- absolutePath: abs,
485
- refId
486
- });
487
- }
2951
+ async function copyStaticAssetSource(asset) {
2952
+ return fs2.readFile(asset.absolutePath);
2953
+ }
2954
+ async function buildProcessedStaticAssets(args) {
2955
+ const { root, pagesDir, assets, minify = true, sourcemap = false } = args;
2956
+ const processable = assets.filter((a) => a.kind === "process");
2957
+ const out = /* @__PURE__ */ new Map();
2958
+ if (processable.length === 0) {
2959
+ return out;
488
2960
  }
489
- return refs;
490
- }
491
- function buildHtmlAssetReplacementMap(args) {
492
- const { ctx, refs, bundle } = args;
493
- const replacements = /* @__PURE__ */ new Map();
494
- for (const ref of refs.values()) {
495
- if (ref.kind === "js") {
496
- const fileName = ctx.getFileName(ref.refId);
497
- replacements.set(ref.originalUrl, `/${fileName}`);
498
- continue;
499
- }
500
- if (ref.kind === "css") {
501
- const jsEntryFile = ctx.getFileName(ref.refId);
502
- const jsChunk = bundle[jsEntryFile];
503
- if (jsChunk && jsChunk.type === "chunk" && "viteMetadata" in jsChunk && jsChunk.viteMetadata?.importedCss && jsChunk.viteMetadata.importedCss.size > 0) {
504
- const cssFile = [...jsChunk.viteMetadata.importedCss][0];
505
- replacements.set(ref.originalUrl, `/${cssFile}`);
506
- continue;
507
- }
508
- replacements.set(ref.originalUrl, `/${jsEntryFile}`);
2961
+ const srcDir = path5.join(root, pagesDir);
2962
+ const distDir = path5.join(root, "dist");
2963
+ const result = await esbuild.build({
2964
+ entryPoints: processable.map((a) => a.absolutePath),
2965
+ absWorkingDir: root,
2966
+ outbase: srcDir,
2967
+ outdir: distDir,
2968
+ bundle: true,
2969
+ splitting: true,
2970
+ treeShaking: true,
2971
+ minify,
2972
+ sourcemap,
2973
+ format: "esm",
2974
+ target: "es2020",
2975
+ platform: "browser",
2976
+ write: false,
2977
+ entryNames: "[dir]/[name]",
2978
+ assetNames: "[dir]/[name]",
2979
+ loader: {
2980
+ ".css": "css",
2981
+ ".png": "file",
2982
+ ".jpg": "file",
2983
+ ".jpeg": "file",
2984
+ ".gif": "file",
2985
+ ".svg": "file",
2986
+ ".webp": "file",
2987
+ ".woff": "file",
2988
+ ".woff2": "file",
2989
+ ".ttf": "file",
2990
+ ".otf": "file"
509
2991
  }
2992
+ });
2993
+ for (const file of result.outputFiles) {
2994
+ const rel = normalizeSlashes(path5.relative(distDir, file.path));
2995
+ out.set(rel, file.text ?? file.contents);
510
2996
  }
511
- return replacements;
2997
+ return out;
512
2998
  }
513
2999
 
514
3000
  // src/plugin.ts
@@ -539,9 +3025,9 @@ function htPages(options = {}) {
539
3025
  let root = process.cwd();
540
3026
  let server = null;
541
3027
  let devPages = [];
542
- let htmlAssetRefs = /* @__PURE__ */ new Map();
543
3028
  const cleanUrls = options.cleanUrls ?? true;
544
3029
  const pagesDir = options.pagesDir ?? "src";
3030
+ const pageExtensions = options.pageExtensions?.length ? options.pageExtensions : [".ht.js", ".html.js", ".ht.ts", ".html.ts"];
545
3031
  function logDebug(enabled, ...args) {
546
3032
  if (!enabled) return;
547
3033
  console.log(`[${PLUGIN_NAME}]`, ...args);
@@ -630,38 +3116,21 @@ function htPages(options = {}) {
630
3116
  for (const entry of entries) {
631
3117
  this.addWatchFile(entry.entryPath);
632
3118
  }
633
- if (server) {
634
- return;
635
- }
636
- htmlAssetRefs.clear();
637
- const { modulesByEntry, pages } = await buildPagesPipeline();
638
- const htmlByPageKey = /* @__PURE__ */ new Map();
639
- for (const page of pages) {
640
- const mod = modulesByEntry.get(page.entryPath);
641
- if (!mod) {
642
- throw new Error(
643
- `[${PLUGIN_NAME}] Missing module for page entry: ${page.entryPath}`
644
- );
645
- }
646
- const html = await renderPage(page, mod, false);
647
- htmlByPageKey.set(page.entryPath, {
648
- html,
649
- pageDir: path6.dirname(page.absolutePath)
650
- });
651
- }
652
- htmlAssetRefs = await collectHtmlAssetRefs({
653
- ctx: this,
3119
+ const staticAssets = await collectStaticAssets({
654
3120
  root,
655
3121
  pagesDir,
656
- htmlByPageKey
3122
+ pageExtensions
657
3123
  });
3124
+ for (const asset of staticAssets) {
3125
+ this.addWatchFile(asset.absolutePath);
3126
+ }
658
3127
  logDebug(
659
3128
  options.debug,
660
- "collected html assets",
661
- [...htmlAssetRefs.values()].map((ref) => ({
662
- kind: ref.kind,
663
- originalUrl: ref.originalUrl,
664
- absolutePath: ref.absolutePath
3129
+ "static assets",
3130
+ staticAssets.map((asset) => ({
3131
+ kind: asset.kind,
3132
+ input: asset.relativePathFromSrc,
3133
+ output: asset.outputFileName
665
3134
  }))
666
3135
  );
667
3136
  },
@@ -690,23 +3159,50 @@ function htPages(options = {}) {
690
3159
  async generateBundle(_, bundle) {
691
3160
  try {
692
3161
  const { modulesByEntry, pages } = await buildPagesPipeline();
693
- const assetReplacements = buildHtmlAssetReplacementMap({
694
- ctx: this,
695
- refs: htmlAssetRefs,
696
- bundle
3162
+ const staticAssets = await collectStaticAssets({
3163
+ root,
3164
+ pagesDir,
3165
+ pageExtensions
697
3166
  });
698
3167
  logDebug(
699
3168
  options.debug,
700
- "asset replacements",
701
- [...assetReplacements.entries()]
3169
+ "emitting pages",
3170
+ pages.map((p) => p.fileName)
702
3171
  );
703
3172
  logDebug(
704
3173
  options.debug,
705
- "emitting pages",
706
- pages.map((p) => p.fileName)
3174
+ "emitting static assets",
3175
+ staticAssets.map((asset) => ({
3176
+ kind: asset.kind,
3177
+ input: asset.relativePathFromSrc,
3178
+ output: asset.outputFileName
3179
+ }))
707
3180
  );
708
3181
  const limit = pLimit(options.renderConcurrency ?? 8);
709
3182
  const batchSize = options.renderBatchSize ?? Math.max(options.renderConcurrency ?? 8, 32);
3183
+ const processedOutputs = await buildProcessedStaticAssets({
3184
+ root,
3185
+ pagesDir,
3186
+ assets: staticAssets,
3187
+ minify: true,
3188
+ sourcemap: false
3189
+ });
3190
+ for (const [fileName, source] of processedOutputs) {
3191
+ this.emitFile({
3192
+ type: "asset",
3193
+ fileName,
3194
+ source
3195
+ });
3196
+ }
3197
+ for (const asset of staticAssets) {
3198
+ if (asset.kind !== "copy") continue;
3199
+ const source = await copyStaticAssetSource(asset);
3200
+ this.emitFile({
3201
+ type: "asset",
3202
+ fileName: asset.outputFileName,
3203
+ source
3204
+ });
3205
+ }
710
3206
  for (const batch of chunkArray(pages, batchSize)) {
711
3207
  await Promise.all(
712
3208
  batch.map(
@@ -717,8 +3213,7 @@ function htPages(options = {}) {
717
3213
  `[${PLUGIN_NAME}] Missing module for page entry: ${page.entryPath}`
718
3214
  );
719
3215
  }
720
- let html = await renderPage(page, mod, false);
721
- html = rewriteHtmlAssetUrls(html, assetReplacements);
3216
+ const html = await renderPage(page, mod, false);
722
3217
  this.emitFile({
723
3218
  type: "asset",
724
3219
  fileName: options.mapOutputPath?.(page) ?? page.fileName,
@@ -736,8 +3231,7 @@ function htPages(options = {}) {
736
3231
  `[${PLUGIN_NAME}] Missing module for 404 page entry: ${notFoundPage.entryPath}`
737
3232
  );
738
3233
  }
739
- let html = await renderPage(notFoundPage, mod, false);
740
- html = rewriteHtmlAssetUrls(html, assetReplacements);
3234
+ const html = await renderPage(notFoundPage, mod, false);
741
3235
  this.emitFile({
742
3236
  type: "asset",
743
3237
  fileName: "404.html",
@@ -813,22 +3307,23 @@ ${sitemapRoutes.map((route) => ` <url><loc>${sitemapBase}${route}</loc></url>`)
813
3307
  });
814
3308
  logDebug(options.debug, "generated sitemap.xml");
815
3309
  }
816
- if (options.rss?.site) {
817
- const routePrefix = options.rss.routePrefix ?? "/blog";
3310
+ const rss = options.rss;
3311
+ if (rss?.site) {
3312
+ const routePrefix = rss.routePrefix ?? "/blog";
818
3313
  const rssItems = pages.filter((page) => page.routePath.startsWith(routePrefix)).map((page) => {
819
- const url = `${options.rss.site}${page.routePath}`;
3314
+ const url = `${rss.site}${page.routePath}`;
820
3315
  return ` <item>
821
3316
  <title>${page.routePath}</title>
822
3317
  <link>${url}</link>
823
3318
  <guid>${url}</guid>
824
3319
  </item>`;
825
3320
  }).join("\n");
826
- const rss = `<?xml version="1.0" encoding="UTF-8"?>
3321
+ const rssXml = `<?xml version="1.0" encoding="UTF-8"?>
827
3322
  <rss version="2.0">
828
3323
  <channel>
829
- <title>${options.rss.title ?? PLUGIN_NAME}</title>
830
- <link>${options.rss.site}</link>
831
- <description>${options.rss.description ?? "RSS feed"}</description>
3324
+ <title>${rss.title ?? PLUGIN_NAME}</title>
3325
+ <link>${rss.site}</link>
3326
+ <description>${rss.description ?? "RSS feed"}</description>
832
3327
  ${rssItems}
833
3328
  </channel>
834
3329
  </rss>
@@ -836,7 +3331,7 @@ ${rssItems}
836
3331
  this.emitFile({
837
3332
  type: "asset",
838
3333
  fileName: "rss.xml",
839
- source: rss
3334
+ source: rssXml
840
3335
  });
841
3336
  logDebug(options.debug, "generated rss.xml");
842
3337
  }