@vertz/cli 0.2.0

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/vertz.js ADDED
@@ -0,0 +1,3624 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // ../../node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib/main.js
23
+ var require_main = __commonJS((exports, module) => {
24
+ var __dirname = "/home/runner/work/vertz/vertz/node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib", __filename = "/home/runner/work/vertz/vertz/node_modules/.bun/esbuild@0.27.3/node_modules/esbuild/lib/main.js";
25
+ var __defProp2 = Object.defineProperty;
26
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
27
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
28
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
29
+ var __export = (target, all) => {
30
+ for (var name in all)
31
+ __defProp2(target, name, { get: all[name], enumerable: true });
32
+ };
33
+ var __copyProps = (to, from, except, desc) => {
34
+ if (from && typeof from === "object" || typeof from === "function") {
35
+ for (let key of __getOwnPropNames2(from))
36
+ if (!__hasOwnProp2.call(to, key) && key !== except)
37
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
38
+ }
39
+ return to;
40
+ };
41
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
42
+ var node_exports = {};
43
+ __export(node_exports, {
44
+ analyzeMetafile: () => analyzeMetafile,
45
+ analyzeMetafileSync: () => analyzeMetafileSync,
46
+ build: () => build,
47
+ buildSync: () => buildSync,
48
+ context: () => context,
49
+ default: () => node_default,
50
+ formatMessages: () => formatMessages,
51
+ formatMessagesSync: () => formatMessagesSync,
52
+ initialize: () => initialize,
53
+ stop: () => stop,
54
+ transform: () => transform,
55
+ transformSync: () => transformSync,
56
+ version: () => version
57
+ });
58
+ module.exports = __toCommonJS(node_exports);
59
+ function encodePacket(packet) {
60
+ let visit = (value) => {
61
+ if (value === null) {
62
+ bb.write8(0);
63
+ } else if (typeof value === "boolean") {
64
+ bb.write8(1);
65
+ bb.write8(+value);
66
+ } else if (typeof value === "number") {
67
+ bb.write8(2);
68
+ bb.write32(value | 0);
69
+ } else if (typeof value === "string") {
70
+ bb.write8(3);
71
+ bb.write(encodeUTF8(value));
72
+ } else if (value instanceof Uint8Array) {
73
+ bb.write8(4);
74
+ bb.write(value);
75
+ } else if (value instanceof Array) {
76
+ bb.write8(5);
77
+ bb.write32(value.length);
78
+ for (let item of value) {
79
+ visit(item);
80
+ }
81
+ } else {
82
+ let keys = Object.keys(value);
83
+ bb.write8(6);
84
+ bb.write32(keys.length);
85
+ for (let key of keys) {
86
+ bb.write(encodeUTF8(key));
87
+ visit(value[key]);
88
+ }
89
+ }
90
+ };
91
+ let bb = new ByteBuffer;
92
+ bb.write32(0);
93
+ bb.write32(packet.id << 1 | +!packet.isRequest);
94
+ visit(packet.value);
95
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
96
+ return bb.buf.subarray(0, bb.len);
97
+ }
98
+ function decodePacket(bytes) {
99
+ let visit = () => {
100
+ switch (bb.read8()) {
101
+ case 0:
102
+ return null;
103
+ case 1:
104
+ return !!bb.read8();
105
+ case 2:
106
+ return bb.read32();
107
+ case 3:
108
+ return decodeUTF8(bb.read());
109
+ case 4:
110
+ return bb.read();
111
+ case 5: {
112
+ let count = bb.read32();
113
+ let value2 = [];
114
+ for (let i = 0;i < count; i++) {
115
+ value2.push(visit());
116
+ }
117
+ return value2;
118
+ }
119
+ case 6: {
120
+ let count = bb.read32();
121
+ let value2 = {};
122
+ for (let i = 0;i < count; i++) {
123
+ value2[decodeUTF8(bb.read())] = visit();
124
+ }
125
+ return value2;
126
+ }
127
+ default:
128
+ throw new Error("Invalid packet");
129
+ }
130
+ };
131
+ let bb = new ByteBuffer(bytes);
132
+ let id = bb.read32();
133
+ let isRequest = (id & 1) === 0;
134
+ id >>>= 1;
135
+ let value = visit();
136
+ if (bb.ptr !== bytes.length) {
137
+ throw new Error("Invalid packet");
138
+ }
139
+ return { id, isRequest, value };
140
+ }
141
+ var ByteBuffer = class {
142
+ constructor(buf = new Uint8Array(1024)) {
143
+ this.buf = buf;
144
+ this.len = 0;
145
+ this.ptr = 0;
146
+ }
147
+ _write(delta) {
148
+ if (this.len + delta > this.buf.length) {
149
+ let clone = new Uint8Array((this.len + delta) * 2);
150
+ clone.set(this.buf);
151
+ this.buf = clone;
152
+ }
153
+ this.len += delta;
154
+ return this.len - delta;
155
+ }
156
+ write8(value) {
157
+ let offset = this._write(1);
158
+ this.buf[offset] = value;
159
+ }
160
+ write32(value) {
161
+ let offset = this._write(4);
162
+ writeUInt32LE(this.buf, value, offset);
163
+ }
164
+ write(bytes) {
165
+ let offset = this._write(4 + bytes.length);
166
+ writeUInt32LE(this.buf, bytes.length, offset);
167
+ this.buf.set(bytes, offset + 4);
168
+ }
169
+ _read(delta) {
170
+ if (this.ptr + delta > this.buf.length) {
171
+ throw new Error("Invalid packet");
172
+ }
173
+ this.ptr += delta;
174
+ return this.ptr - delta;
175
+ }
176
+ read8() {
177
+ return this.buf[this._read(1)];
178
+ }
179
+ read32() {
180
+ return readUInt32LE(this.buf, this._read(4));
181
+ }
182
+ read() {
183
+ let length = this.read32();
184
+ let bytes = new Uint8Array(length);
185
+ let ptr = this._read(bytes.length);
186
+ bytes.set(this.buf.subarray(ptr, ptr + length));
187
+ return bytes;
188
+ }
189
+ };
190
+ var encodeUTF8;
191
+ var decodeUTF8;
192
+ var encodeInvariant;
193
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
194
+ let encoder = new TextEncoder;
195
+ let decoder = new TextDecoder;
196
+ encodeUTF8 = (text) => encoder.encode(text);
197
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
198
+ encodeInvariant = 'new TextEncoder().encode("")';
199
+ } else if (typeof Buffer !== "undefined") {
200
+ encodeUTF8 = (text) => Buffer.from(text);
201
+ decodeUTF8 = (bytes) => {
202
+ let { buffer, byteOffset, byteLength } = bytes;
203
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
204
+ };
205
+ encodeInvariant = 'Buffer.from("")';
206
+ } else {
207
+ throw new Error("No UTF-8 codec found");
208
+ }
209
+ if (!(encodeUTF8("") instanceof Uint8Array))
210
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
211
+
212
+ This indicates that your JavaScript environment is broken. You cannot use
213
+ esbuild in this environment because esbuild relies on this invariant. This
214
+ is not a problem with esbuild. You need to fix your environment instead.
215
+ `);
216
+ function readUInt32LE(buffer, offset) {
217
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
218
+ }
219
+ function writeUInt32LE(buffer, value, offset) {
220
+ buffer[offset++] = value;
221
+ buffer[offset++] = value >> 8;
222
+ buffer[offset++] = value >> 16;
223
+ buffer[offset++] = value >> 24;
224
+ }
225
+ var quote = JSON.stringify;
226
+ var buildLogLevelDefault = "warning";
227
+ var transformLogLevelDefault = "silent";
228
+ function validateAndJoinStringArray(values, what) {
229
+ const toJoin = [];
230
+ for (const value of values) {
231
+ validateStringValue(value, what);
232
+ if (value.indexOf(",") >= 0)
233
+ throw new Error(`Invalid ${what}: ${value}`);
234
+ toJoin.push(value);
235
+ }
236
+ return toJoin.join(",");
237
+ }
238
+ var canBeAnything = () => null;
239
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
240
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
241
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
242
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
243
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
244
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
245
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
246
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
247
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
248
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
249
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
250
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
251
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
252
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
253
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
254
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
255
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
256
+ function getFlag(object, keys, key, mustBeFn) {
257
+ let value = object[key];
258
+ keys[key + ""] = true;
259
+ if (value === undefined)
260
+ return;
261
+ let mustBe = mustBeFn(value);
262
+ if (mustBe !== null)
263
+ throw new Error(`${quote(key)} must be ${mustBe}`);
264
+ return value;
265
+ }
266
+ function checkForInvalidFlags(object, keys, where) {
267
+ for (let key in object) {
268
+ if (!(key in keys)) {
269
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
270
+ }
271
+ }
272
+ }
273
+ function validateInitializeOptions(options) {
274
+ let keys = /* @__PURE__ */ Object.create(null);
275
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
276
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
277
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
278
+ checkForInvalidFlags(options, keys, "in initialize() call");
279
+ return {
280
+ wasmURL,
281
+ wasmModule,
282
+ worker
283
+ };
284
+ }
285
+ function validateMangleCache(mangleCache) {
286
+ let validated;
287
+ if (mangleCache !== undefined) {
288
+ validated = /* @__PURE__ */ Object.create(null);
289
+ for (let key in mangleCache) {
290
+ let value = mangleCache[key];
291
+ if (typeof value === "string" || value === false) {
292
+ validated[key] = value;
293
+ } else {
294
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
295
+ }
296
+ }
297
+ }
298
+ return validated;
299
+ }
300
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
301
+ let color = getFlag(options, keys, "color", mustBeBoolean);
302
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
303
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
304
+ if (color !== undefined)
305
+ flags.push(`--color=${color}`);
306
+ else if (isTTY2)
307
+ flags.push(`--color=true`);
308
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
309
+ flags.push(`--log-limit=${logLimit || 0}`);
310
+ }
311
+ function validateStringValue(value, what, key) {
312
+ if (typeof value !== "string") {
313
+ throw new Error(`Expected value for ${what}${key !== undefined ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
314
+ }
315
+ return value;
316
+ }
317
+ function pushCommonFlags(flags, options, keys) {
318
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
319
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
320
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
321
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
322
+ let format = getFlag(options, keys, "format", mustBeString);
323
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
324
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
325
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
326
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
327
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
328
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
329
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
330
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
331
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
332
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
333
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
334
+ let charset = getFlag(options, keys, "charset", mustBeString);
335
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
336
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
337
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
338
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
339
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
340
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
341
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
342
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
343
+ let define = getFlag(options, keys, "define", mustBeObject);
344
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
345
+ let supported = getFlag(options, keys, "supported", mustBeObject);
346
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
347
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
348
+ let platform = getFlag(options, keys, "platform", mustBeString);
349
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
350
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
351
+ if (legalComments)
352
+ flags.push(`--legal-comments=${legalComments}`);
353
+ if (sourceRoot !== undefined)
354
+ flags.push(`--source-root=${sourceRoot}`);
355
+ if (sourcesContent !== undefined)
356
+ flags.push(`--sources-content=${sourcesContent}`);
357
+ if (target)
358
+ flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
359
+ if (format)
360
+ flags.push(`--format=${format}`);
361
+ if (globalName)
362
+ flags.push(`--global-name=${globalName}`);
363
+ if (platform)
364
+ flags.push(`--platform=${platform}`);
365
+ if (tsconfigRaw)
366
+ flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
367
+ if (minify)
368
+ flags.push("--minify");
369
+ if (minifySyntax)
370
+ flags.push("--minify-syntax");
371
+ if (minifyWhitespace)
372
+ flags.push("--minify-whitespace");
373
+ if (minifyIdentifiers)
374
+ flags.push("--minify-identifiers");
375
+ if (lineLimit)
376
+ flags.push(`--line-limit=${lineLimit}`);
377
+ if (charset)
378
+ flags.push(`--charset=${charset}`);
379
+ if (treeShaking !== undefined)
380
+ flags.push(`--tree-shaking=${treeShaking}`);
381
+ if (ignoreAnnotations)
382
+ flags.push(`--ignore-annotations`);
383
+ if (drop)
384
+ for (let what of drop)
385
+ flags.push(`--drop:${validateStringValue(what, "drop")}`);
386
+ if (dropLabels)
387
+ flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
388
+ if (absPaths)
389
+ flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
390
+ if (mangleProps)
391
+ flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
392
+ if (reserveProps)
393
+ flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
394
+ if (mangleQuoted !== undefined)
395
+ flags.push(`--mangle-quoted=${mangleQuoted}`);
396
+ if (jsx)
397
+ flags.push(`--jsx=${jsx}`);
398
+ if (jsxFactory)
399
+ flags.push(`--jsx-factory=${jsxFactory}`);
400
+ if (jsxFragment)
401
+ flags.push(`--jsx-fragment=${jsxFragment}`);
402
+ if (jsxImportSource)
403
+ flags.push(`--jsx-import-source=${jsxImportSource}`);
404
+ if (jsxDev)
405
+ flags.push(`--jsx-dev`);
406
+ if (jsxSideEffects)
407
+ flags.push(`--jsx-side-effects`);
408
+ if (define) {
409
+ for (let key in define) {
410
+ if (key.indexOf("=") >= 0)
411
+ throw new Error(`Invalid define: ${key}`);
412
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
413
+ }
414
+ }
415
+ if (logOverride) {
416
+ for (let key in logOverride) {
417
+ if (key.indexOf("=") >= 0)
418
+ throw new Error(`Invalid log override: ${key}`);
419
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
420
+ }
421
+ }
422
+ if (supported) {
423
+ for (let key in supported) {
424
+ if (key.indexOf("=") >= 0)
425
+ throw new Error(`Invalid supported: ${key}`);
426
+ const value = supported[key];
427
+ if (typeof value !== "boolean")
428
+ throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
429
+ flags.push(`--supported:${key}=${value}`);
430
+ }
431
+ }
432
+ if (pure)
433
+ for (let fn of pure)
434
+ flags.push(`--pure:${validateStringValue(fn, "pure")}`);
435
+ if (keepNames)
436
+ flags.push(`--keep-names`);
437
+ }
438
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
439
+ var _a2;
440
+ let flags = [];
441
+ let entries = [];
442
+ let keys = /* @__PURE__ */ Object.create(null);
443
+ let stdinContents = null;
444
+ let stdinResolveDir = null;
445
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
446
+ pushCommonFlags(flags, options, keys);
447
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
448
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
449
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
450
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
451
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
452
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
453
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
454
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
455
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
456
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
457
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
458
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
459
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
460
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
461
+ let packages = getFlag(options, keys, "packages", mustBeString);
462
+ let alias = getFlag(options, keys, "alias", mustBeObject);
463
+ let loader = getFlag(options, keys, "loader", mustBeObject);
464
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
465
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
466
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
467
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
468
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
469
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
470
+ let banner = getFlag(options, keys, "banner", mustBeObject);
471
+ let footer = getFlag(options, keys, "footer", mustBeObject);
472
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
473
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
474
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
475
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
476
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
477
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
478
+ keys.plugins = true;
479
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
480
+ if (sourcemap)
481
+ flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
482
+ if (bundle)
483
+ flags.push("--bundle");
484
+ if (allowOverwrite)
485
+ flags.push("--allow-overwrite");
486
+ if (splitting)
487
+ flags.push("--splitting");
488
+ if (preserveSymlinks)
489
+ flags.push("--preserve-symlinks");
490
+ if (metafile)
491
+ flags.push(`--metafile`);
492
+ if (outfile)
493
+ flags.push(`--outfile=${outfile}`);
494
+ if (outdir)
495
+ flags.push(`--outdir=${outdir}`);
496
+ if (outbase)
497
+ flags.push(`--outbase=${outbase}`);
498
+ if (tsconfig)
499
+ flags.push(`--tsconfig=${tsconfig}`);
500
+ if (packages)
501
+ flags.push(`--packages=${packages}`);
502
+ if (resolveExtensions)
503
+ flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
504
+ if (publicPath)
505
+ flags.push(`--public-path=${publicPath}`);
506
+ if (entryNames)
507
+ flags.push(`--entry-names=${entryNames}`);
508
+ if (chunkNames)
509
+ flags.push(`--chunk-names=${chunkNames}`);
510
+ if (assetNames)
511
+ flags.push(`--asset-names=${assetNames}`);
512
+ if (mainFields)
513
+ flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
514
+ if (conditions)
515
+ flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
516
+ if (external)
517
+ for (let name of external)
518
+ flags.push(`--external:${validateStringValue(name, "external")}`);
519
+ if (alias) {
520
+ for (let old in alias) {
521
+ if (old.indexOf("=") >= 0)
522
+ throw new Error(`Invalid package name in alias: ${old}`);
523
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
524
+ }
525
+ }
526
+ if (banner) {
527
+ for (let type in banner) {
528
+ if (type.indexOf("=") >= 0)
529
+ throw new Error(`Invalid banner file type: ${type}`);
530
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
531
+ }
532
+ }
533
+ if (footer) {
534
+ for (let type in footer) {
535
+ if (type.indexOf("=") >= 0)
536
+ throw new Error(`Invalid footer file type: ${type}`);
537
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
538
+ }
539
+ }
540
+ if (inject)
541
+ for (let path3 of inject)
542
+ flags.push(`--inject:${validateStringValue(path3, "inject")}`);
543
+ if (loader) {
544
+ for (let ext in loader) {
545
+ if (ext.indexOf("=") >= 0)
546
+ throw new Error(`Invalid loader extension: ${ext}`);
547
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
548
+ }
549
+ }
550
+ if (outExtension) {
551
+ for (let ext in outExtension) {
552
+ if (ext.indexOf("=") >= 0)
553
+ throw new Error(`Invalid out extension: ${ext}`);
554
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
555
+ }
556
+ }
557
+ if (entryPoints) {
558
+ if (Array.isArray(entryPoints)) {
559
+ for (let i = 0, n = entryPoints.length;i < n; i++) {
560
+ let entryPoint = entryPoints[i];
561
+ if (typeof entryPoint === "object" && entryPoint !== null) {
562
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
563
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
564
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
565
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
566
+ if (input === undefined)
567
+ throw new Error('Missing property "in" for entry point at index ' + i);
568
+ if (output === undefined)
569
+ throw new Error('Missing property "out" for entry point at index ' + i);
570
+ entries.push([output, input]);
571
+ } else {
572
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
573
+ }
574
+ }
575
+ } else {
576
+ for (let key in entryPoints) {
577
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
578
+ }
579
+ }
580
+ }
581
+ if (stdin) {
582
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
583
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
584
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
585
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
586
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
587
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
588
+ if (sourcefile)
589
+ flags.push(`--sourcefile=${sourcefile}`);
590
+ if (loader2)
591
+ flags.push(`--loader=${loader2}`);
592
+ if (resolveDir)
593
+ stdinResolveDir = resolveDir;
594
+ if (typeof contents === "string")
595
+ stdinContents = encodeUTF8(contents);
596
+ else if (contents instanceof Uint8Array)
597
+ stdinContents = contents;
598
+ }
599
+ let nodePaths = [];
600
+ if (nodePathsInput) {
601
+ for (let value of nodePathsInput) {
602
+ value += "";
603
+ nodePaths.push(value);
604
+ }
605
+ }
606
+ return {
607
+ entries,
608
+ flags,
609
+ write,
610
+ stdinContents,
611
+ stdinResolveDir,
612
+ absWorkingDir,
613
+ nodePaths,
614
+ mangleCache: validateMangleCache(mangleCache)
615
+ };
616
+ }
617
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
618
+ let flags = [];
619
+ let keys = /* @__PURE__ */ Object.create(null);
620
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
621
+ pushCommonFlags(flags, options, keys);
622
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
623
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
624
+ let loader = getFlag(options, keys, "loader", mustBeString);
625
+ let banner = getFlag(options, keys, "banner", mustBeString);
626
+ let footer = getFlag(options, keys, "footer", mustBeString);
627
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
628
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
629
+ if (sourcemap)
630
+ flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
631
+ if (sourcefile)
632
+ flags.push(`--sourcefile=${sourcefile}`);
633
+ if (loader)
634
+ flags.push(`--loader=${loader}`);
635
+ if (banner)
636
+ flags.push(`--banner=${banner}`);
637
+ if (footer)
638
+ flags.push(`--footer=${footer}`);
639
+ return {
640
+ flags,
641
+ mangleCache: validateMangleCache(mangleCache)
642
+ };
643
+ }
644
+ function createChannel(streamIn) {
645
+ const requestCallbacksByKey = {};
646
+ const closeData = { didClose: false, reason: "" };
647
+ let responseCallbacks = {};
648
+ let nextRequestID = 0;
649
+ let nextBuildKey = 0;
650
+ let stdout = new Uint8Array(16 * 1024);
651
+ let stdoutUsed = 0;
652
+ let readFromStdout = (chunk) => {
653
+ let limit = stdoutUsed + chunk.length;
654
+ if (limit > stdout.length) {
655
+ let swap = new Uint8Array(limit * 2);
656
+ swap.set(stdout);
657
+ stdout = swap;
658
+ }
659
+ stdout.set(chunk, stdoutUsed);
660
+ stdoutUsed += chunk.length;
661
+ let offset = 0;
662
+ while (offset + 4 <= stdoutUsed) {
663
+ let length = readUInt32LE(stdout, offset);
664
+ if (offset + 4 + length > stdoutUsed) {
665
+ break;
666
+ }
667
+ offset += 4;
668
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
669
+ offset += length;
670
+ }
671
+ if (offset > 0) {
672
+ stdout.copyWithin(0, offset, stdoutUsed);
673
+ stdoutUsed -= offset;
674
+ }
675
+ };
676
+ let afterClose = (error) => {
677
+ closeData.didClose = true;
678
+ if (error)
679
+ closeData.reason = ": " + (error.message || error);
680
+ const text = "The service was stopped" + closeData.reason;
681
+ for (let id in responseCallbacks) {
682
+ responseCallbacks[id](text, null);
683
+ }
684
+ responseCallbacks = {};
685
+ };
686
+ let sendRequest = (refs, value, callback) => {
687
+ if (closeData.didClose)
688
+ return callback("The service is no longer running" + closeData.reason, null);
689
+ let id = nextRequestID++;
690
+ responseCallbacks[id] = (error, response) => {
691
+ try {
692
+ callback(error, response);
693
+ } finally {
694
+ if (refs)
695
+ refs.unref();
696
+ }
697
+ };
698
+ if (refs)
699
+ refs.ref();
700
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
701
+ };
702
+ let sendResponse = (id, value) => {
703
+ if (closeData.didClose)
704
+ throw new Error("The service is no longer running" + closeData.reason);
705
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
706
+ };
707
+ let handleRequest = async (id, request) => {
708
+ try {
709
+ if (request.command === "ping") {
710
+ sendResponse(id, {});
711
+ return;
712
+ }
713
+ if (typeof request.key === "number") {
714
+ const requestCallbacks = requestCallbacksByKey[request.key];
715
+ if (!requestCallbacks) {
716
+ return;
717
+ }
718
+ const callback = requestCallbacks[request.command];
719
+ if (callback) {
720
+ await callback(id, request);
721
+ return;
722
+ }
723
+ }
724
+ throw new Error(`Invalid command: ` + request.command);
725
+ } catch (e) {
726
+ const errors = [extractErrorMessageV8(e, streamIn, null, undefined, "")];
727
+ try {
728
+ sendResponse(id, { errors });
729
+ } catch {}
730
+ }
731
+ };
732
+ let isFirstPacket = true;
733
+ let handleIncomingPacket = (bytes) => {
734
+ if (isFirstPacket) {
735
+ isFirstPacket = false;
736
+ let binaryVersion = String.fromCharCode(...bytes);
737
+ if (binaryVersion !== "0.27.3") {
738
+ throw new Error(`Cannot start service: Host version "${"0.27.3"}" does not match binary version ${quote(binaryVersion)}`);
739
+ }
740
+ return;
741
+ }
742
+ let packet = decodePacket(bytes);
743
+ if (packet.isRequest) {
744
+ handleRequest(packet.id, packet.value);
745
+ } else {
746
+ let callback = responseCallbacks[packet.id];
747
+ delete responseCallbacks[packet.id];
748
+ if (packet.value.error)
749
+ callback(packet.value.error, {});
750
+ else
751
+ callback(null, packet.value);
752
+ }
753
+ };
754
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
755
+ let refCount = 0;
756
+ const buildKey = nextBuildKey++;
757
+ const requestCallbacks = {};
758
+ const buildRefs = {
759
+ ref() {
760
+ if (++refCount === 1) {
761
+ if (refs)
762
+ refs.ref();
763
+ }
764
+ },
765
+ unref() {
766
+ if (--refCount === 0) {
767
+ delete requestCallbacksByKey[buildKey];
768
+ if (refs)
769
+ refs.unref();
770
+ }
771
+ }
772
+ };
773
+ requestCallbacksByKey[buildKey] = requestCallbacks;
774
+ buildRefs.ref();
775
+ buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
776
+ try {
777
+ callback(err, res);
778
+ } finally {
779
+ buildRefs.unref();
780
+ }
781
+ });
782
+ };
783
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
784
+ const details = createObjectStash();
785
+ let start = (inputPath) => {
786
+ try {
787
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
788
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
789
+ let {
790
+ flags,
791
+ mangleCache
792
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
793
+ let request = {
794
+ command: "transform",
795
+ flags,
796
+ inputFS: inputPath !== null,
797
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
798
+ };
799
+ if (mangleCache)
800
+ request.mangleCache = mangleCache;
801
+ sendRequest(refs, request, (error, response) => {
802
+ if (error)
803
+ return callback(new Error(error), null);
804
+ let errors = replaceDetailsInMessages(response.errors, details);
805
+ let warnings = replaceDetailsInMessages(response.warnings, details);
806
+ let outstanding = 1;
807
+ let next = () => {
808
+ if (--outstanding === 0) {
809
+ let result = {
810
+ warnings,
811
+ code: response.code,
812
+ map: response.map,
813
+ mangleCache: undefined,
814
+ legalComments: undefined
815
+ };
816
+ if ("legalComments" in response)
817
+ result.legalComments = response == null ? undefined : response.legalComments;
818
+ if (response.mangleCache)
819
+ result.mangleCache = response == null ? undefined : response.mangleCache;
820
+ callback(null, result);
821
+ }
822
+ };
823
+ if (errors.length > 0)
824
+ return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
825
+ if (response.codeFS) {
826
+ outstanding++;
827
+ fs3.readFile(response.code, (err, contents) => {
828
+ if (err !== null) {
829
+ callback(err, null);
830
+ } else {
831
+ response.code = contents;
832
+ next();
833
+ }
834
+ });
835
+ }
836
+ if (response.mapFS) {
837
+ outstanding++;
838
+ fs3.readFile(response.map, (err, contents) => {
839
+ if (err !== null) {
840
+ callback(err, null);
841
+ } else {
842
+ response.map = contents;
843
+ next();
844
+ }
845
+ });
846
+ }
847
+ next();
848
+ });
849
+ } catch (e) {
850
+ let flags = [];
851
+ try {
852
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
853
+ } catch {}
854
+ const error = extractErrorMessageV8(e, streamIn, details, undefined, "");
855
+ sendRequest(refs, { command: "error", flags, error }, () => {
856
+ error.detail = details.load(error.detail);
857
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
858
+ });
859
+ }
860
+ };
861
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
862
+ let next = start;
863
+ start = () => fs3.writeFile(input, next);
864
+ }
865
+ start(null);
866
+ };
867
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
868
+ if (!options)
869
+ throw new Error(`Missing second argument in ${callName}() call`);
870
+ let keys = {};
871
+ let kind = getFlag(options, keys, "kind", mustBeString);
872
+ let color = getFlag(options, keys, "color", mustBeBoolean);
873
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
874
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
875
+ if (kind === undefined)
876
+ throw new Error(`Missing "kind" in ${callName}() call`);
877
+ if (kind !== "error" && kind !== "warning")
878
+ throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
879
+ let request = {
880
+ command: "format-msgs",
881
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
882
+ isWarning: kind === "warning"
883
+ };
884
+ if (color !== undefined)
885
+ request.color = color;
886
+ if (terminalWidth !== undefined)
887
+ request.terminalWidth = terminalWidth;
888
+ sendRequest(refs, request, (error, response) => {
889
+ if (error)
890
+ return callback(new Error(error), null);
891
+ callback(null, response.messages);
892
+ });
893
+ };
894
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
895
+ if (options === undefined)
896
+ options = {};
897
+ let keys = {};
898
+ let color = getFlag(options, keys, "color", mustBeBoolean);
899
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
900
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
901
+ let request = {
902
+ command: "analyze-metafile",
903
+ metafile
904
+ };
905
+ if (color !== undefined)
906
+ request.color = color;
907
+ if (verbose !== undefined)
908
+ request.verbose = verbose;
909
+ sendRequest(refs, request, (error, response) => {
910
+ if (error)
911
+ return callback(new Error(error), null);
912
+ callback(null, response.result);
913
+ });
914
+ };
915
+ return {
916
+ readFromStdout,
917
+ afterClose,
918
+ service: {
919
+ buildOrContext,
920
+ transform: transform2,
921
+ formatMessages: formatMessages2,
922
+ analyzeMetafile: analyzeMetafile2
923
+ }
924
+ };
925
+ }
926
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
927
+ const details = createObjectStash();
928
+ const isContext = callName === "context";
929
+ const handleError = (e, pluginName) => {
930
+ const flags = [];
931
+ try {
932
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
933
+ } catch {}
934
+ const message = extractErrorMessageV8(e, streamIn, details, undefined, pluginName);
935
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
936
+ message.detail = details.load(message.detail);
937
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
938
+ });
939
+ };
940
+ let plugins;
941
+ if (typeof options === "object") {
942
+ const value = options.plugins;
943
+ if (value !== undefined) {
944
+ if (!Array.isArray(value))
945
+ return handleError(new Error(`"plugins" must be an array`), "");
946
+ plugins = value;
947
+ }
948
+ }
949
+ if (plugins && plugins.length > 0) {
950
+ if (streamIn.isSync)
951
+ return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
952
+ handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
953
+ if (!result.ok)
954
+ return handleError(result.error, result.pluginName);
955
+ try {
956
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
957
+ } catch (e) {
958
+ handleError(e, "");
959
+ }
960
+ }, (e) => handleError(e, ""));
961
+ return;
962
+ }
963
+ try {
964
+ buildOrContextContinue(null, (result, done) => done([], []), () => {});
965
+ } catch (e) {
966
+ handleError(e, "");
967
+ }
968
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
969
+ const writeDefault = streamIn.hasFS;
970
+ const {
971
+ entries,
972
+ flags,
973
+ write,
974
+ stdinContents,
975
+ stdinResolveDir,
976
+ absWorkingDir,
977
+ nodePaths,
978
+ mangleCache
979
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
980
+ if (write && !streamIn.hasFS)
981
+ throw new Error(`The "write" option is unavailable in this environment`);
982
+ const request = {
983
+ command: "build",
984
+ key: buildKey,
985
+ entries,
986
+ flags,
987
+ write,
988
+ stdinContents,
989
+ stdinResolveDir,
990
+ absWorkingDir: absWorkingDir || defaultWD2,
991
+ nodePaths,
992
+ context: isContext
993
+ };
994
+ if (requestPlugins)
995
+ request.plugins = requestPlugins;
996
+ if (mangleCache)
997
+ request.mangleCache = mangleCache;
998
+ const buildResponseToResult = (response, callback2) => {
999
+ const result = {
1000
+ errors: replaceDetailsInMessages(response.errors, details),
1001
+ warnings: replaceDetailsInMessages(response.warnings, details),
1002
+ outputFiles: undefined,
1003
+ metafile: undefined,
1004
+ mangleCache: undefined
1005
+ };
1006
+ const originalErrors = result.errors.slice();
1007
+ const originalWarnings = result.warnings.slice();
1008
+ if (response.outputFiles)
1009
+ result.outputFiles = response.outputFiles.map(convertOutputFiles);
1010
+ if (response.metafile)
1011
+ result.metafile = JSON.parse(response.metafile);
1012
+ if (response.mangleCache)
1013
+ result.mangleCache = response.mangleCache;
1014
+ if (response.writeToStdout !== undefined)
1015
+ console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1016
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1017
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1018
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1019
+ return callback2(error, null, onEndErrors, onEndWarnings);
1020
+ }
1021
+ callback2(null, result, onEndErrors, onEndWarnings);
1022
+ });
1023
+ };
1024
+ let latestResultPromise;
1025
+ let provideLatestResult;
1026
+ if (isContext)
1027
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve2) => {
1028
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1029
+ const response = {
1030
+ errors: onEndErrors,
1031
+ warnings: onEndWarnings
1032
+ };
1033
+ if (provideLatestResult)
1034
+ provideLatestResult(err, result);
1035
+ latestResultPromise = undefined;
1036
+ provideLatestResult = undefined;
1037
+ sendResponse(id, response);
1038
+ resolve2();
1039
+ });
1040
+ });
1041
+ sendRequest(refs, request, (error, response) => {
1042
+ if (error)
1043
+ return callback(new Error(error), null);
1044
+ if (!isContext) {
1045
+ return buildResponseToResult(response, (err, res) => {
1046
+ scheduleOnDisposeCallbacks();
1047
+ return callback(err, res);
1048
+ });
1049
+ }
1050
+ if (response.errors.length > 0) {
1051
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1052
+ }
1053
+ let didDispose = false;
1054
+ const result = {
1055
+ rebuild: () => {
1056
+ if (!latestResultPromise)
1057
+ latestResultPromise = new Promise((resolve2, reject) => {
1058
+ let settlePromise;
1059
+ provideLatestResult = (err, result2) => {
1060
+ if (!settlePromise)
1061
+ settlePromise = () => err ? reject(err) : resolve2(result2);
1062
+ };
1063
+ const triggerAnotherBuild = () => {
1064
+ const request2 = {
1065
+ command: "rebuild",
1066
+ key: buildKey
1067
+ };
1068
+ sendRequest(refs, request2, (error2, response2) => {
1069
+ if (error2) {
1070
+ reject(new Error(error2));
1071
+ } else if (settlePromise) {
1072
+ settlePromise();
1073
+ } else {
1074
+ triggerAnotherBuild();
1075
+ }
1076
+ });
1077
+ };
1078
+ triggerAnotherBuild();
1079
+ });
1080
+ return latestResultPromise;
1081
+ },
1082
+ watch: (options2 = {}) => new Promise((resolve2, reject) => {
1083
+ if (!streamIn.hasFS)
1084
+ throw new Error(`Cannot use the "watch" API in this environment`);
1085
+ const keys = {};
1086
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1087
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1088
+ const request2 = {
1089
+ command: "watch",
1090
+ key: buildKey
1091
+ };
1092
+ if (delay)
1093
+ request2.delay = delay;
1094
+ sendRequest(refs, request2, (error2) => {
1095
+ if (error2)
1096
+ reject(new Error(error2));
1097
+ else
1098
+ resolve2(undefined);
1099
+ });
1100
+ }),
1101
+ serve: (options2 = {}) => new Promise((resolve2, reject) => {
1102
+ if (!streamIn.hasFS)
1103
+ throw new Error(`Cannot use the "serve" API in this environment`);
1104
+ const keys = {};
1105
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1106
+ const host = getFlag(options2, keys, "host", mustBeString);
1107
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1108
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1109
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1110
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1111
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1112
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1113
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1114
+ const request2 = {
1115
+ command: "serve",
1116
+ key: buildKey,
1117
+ onRequest: !!onRequest
1118
+ };
1119
+ if (port !== undefined)
1120
+ request2.port = port;
1121
+ if (host !== undefined)
1122
+ request2.host = host;
1123
+ if (servedir !== undefined)
1124
+ request2.servedir = servedir;
1125
+ if (keyfile !== undefined)
1126
+ request2.keyfile = keyfile;
1127
+ if (certfile !== undefined)
1128
+ request2.certfile = certfile;
1129
+ if (fallback !== undefined)
1130
+ request2.fallback = fallback;
1131
+ if (cors) {
1132
+ const corsKeys = {};
1133
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1134
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1135
+ if (Array.isArray(origin))
1136
+ request2.corsOrigin = origin;
1137
+ else if (origin !== undefined)
1138
+ request2.corsOrigin = [origin];
1139
+ }
1140
+ sendRequest(refs, request2, (error2, response2) => {
1141
+ if (error2)
1142
+ return reject(new Error(error2));
1143
+ if (onRequest) {
1144
+ requestCallbacks["serve-request"] = (id, request3) => {
1145
+ onRequest(request3.args);
1146
+ sendResponse(id, {});
1147
+ };
1148
+ }
1149
+ resolve2(response2);
1150
+ });
1151
+ }),
1152
+ cancel: () => new Promise((resolve2) => {
1153
+ if (didDispose)
1154
+ return resolve2();
1155
+ const request2 = {
1156
+ command: "cancel",
1157
+ key: buildKey
1158
+ };
1159
+ sendRequest(refs, request2, () => {
1160
+ resolve2();
1161
+ });
1162
+ }),
1163
+ dispose: () => new Promise((resolve2) => {
1164
+ if (didDispose)
1165
+ return resolve2();
1166
+ didDispose = true;
1167
+ const request2 = {
1168
+ command: "dispose",
1169
+ key: buildKey
1170
+ };
1171
+ sendRequest(refs, request2, () => {
1172
+ resolve2();
1173
+ scheduleOnDisposeCallbacks();
1174
+ refs.unref();
1175
+ });
1176
+ })
1177
+ };
1178
+ refs.ref();
1179
+ callback(null, result);
1180
+ });
1181
+ }
1182
+ }
1183
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1184
+ let onStartCallbacks = [];
1185
+ let onEndCallbacks = [];
1186
+ let onResolveCallbacks = {};
1187
+ let onLoadCallbacks = {};
1188
+ let onDisposeCallbacks = [];
1189
+ let nextCallbackID = 0;
1190
+ let i = 0;
1191
+ let requestPlugins = [];
1192
+ let isSetupDone = false;
1193
+ plugins = [...plugins];
1194
+ for (let item of plugins) {
1195
+ let keys = {};
1196
+ if (typeof item !== "object")
1197
+ throw new Error(`Plugin at index ${i} must be an object`);
1198
+ const name = getFlag(item, keys, "name", mustBeString);
1199
+ if (typeof name !== "string" || name === "")
1200
+ throw new Error(`Plugin at index ${i} is missing a name`);
1201
+ try {
1202
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1203
+ if (typeof setup !== "function")
1204
+ throw new Error(`Plugin is missing a setup function`);
1205
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1206
+ let plugin = {
1207
+ name,
1208
+ onStart: false,
1209
+ onEnd: false,
1210
+ onResolve: [],
1211
+ onLoad: []
1212
+ };
1213
+ i++;
1214
+ let resolve2 = (path3, options = {}) => {
1215
+ if (!isSetupDone)
1216
+ throw new Error('Cannot call "resolve" before plugin setup has completed');
1217
+ if (typeof path3 !== "string")
1218
+ throw new Error(`The path to resolve must be a string`);
1219
+ let keys2 = /* @__PURE__ */ Object.create(null);
1220
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1221
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1222
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1223
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1224
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1225
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1226
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1227
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1228
+ return new Promise((resolve22, reject) => {
1229
+ const request = {
1230
+ command: "resolve",
1231
+ path: path3,
1232
+ key: buildKey,
1233
+ pluginName: name
1234
+ };
1235
+ if (pluginName != null)
1236
+ request.pluginName = pluginName;
1237
+ if (importer != null)
1238
+ request.importer = importer;
1239
+ if (namespace != null)
1240
+ request.namespace = namespace;
1241
+ if (resolveDir != null)
1242
+ request.resolveDir = resolveDir;
1243
+ if (kind != null)
1244
+ request.kind = kind;
1245
+ else
1246
+ throw new Error(`Must specify "kind" when calling "resolve"`);
1247
+ if (pluginData != null)
1248
+ request.pluginData = details.store(pluginData);
1249
+ if (importAttributes != null)
1250
+ request.with = sanitizeStringMap(importAttributes, "with");
1251
+ sendRequest(refs, request, (error, response) => {
1252
+ if (error !== null)
1253
+ reject(new Error(error));
1254
+ else
1255
+ resolve22({
1256
+ errors: replaceDetailsInMessages(response.errors, details),
1257
+ warnings: replaceDetailsInMessages(response.warnings, details),
1258
+ path: response.path,
1259
+ external: response.external,
1260
+ sideEffects: response.sideEffects,
1261
+ namespace: response.namespace,
1262
+ suffix: response.suffix,
1263
+ pluginData: details.load(response.pluginData)
1264
+ });
1265
+ });
1266
+ });
1267
+ };
1268
+ let promise = setup({
1269
+ initialOptions,
1270
+ resolve: resolve2,
1271
+ onStart(callback) {
1272
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1273
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1274
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1275
+ plugin.onStart = true;
1276
+ },
1277
+ onEnd(callback) {
1278
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1279
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1280
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1281
+ plugin.onEnd = true;
1282
+ },
1283
+ onResolve(options, callback) {
1284
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1285
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1286
+ let keys2 = {};
1287
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1288
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1289
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1290
+ if (filter == null)
1291
+ throw new Error(`onResolve() call is missing a filter`);
1292
+ let id = nextCallbackID++;
1293
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1294
+ plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1295
+ },
1296
+ onLoad(options, callback) {
1297
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1298
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1299
+ let keys2 = {};
1300
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1301
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1302
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1303
+ if (filter == null)
1304
+ throw new Error(`onLoad() call is missing a filter`);
1305
+ let id = nextCallbackID++;
1306
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1307
+ plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" });
1308
+ },
1309
+ onDispose(callback) {
1310
+ onDisposeCallbacks.push(callback);
1311
+ },
1312
+ esbuild: streamIn.esbuild
1313
+ });
1314
+ if (promise)
1315
+ await promise;
1316
+ requestPlugins.push(plugin);
1317
+ } catch (e) {
1318
+ return { ok: false, error: e, pluginName: name };
1319
+ }
1320
+ }
1321
+ requestCallbacks["on-start"] = async (id, request) => {
1322
+ details.clear();
1323
+ let response = { errors: [], warnings: [] };
1324
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1325
+ try {
1326
+ let result = await callback();
1327
+ if (result != null) {
1328
+ if (typeof result !== "object")
1329
+ throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1330
+ let keys = {};
1331
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1332
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1333
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1334
+ if (errors != null)
1335
+ response.errors.push(...sanitizeMessages(errors, "errors", details, name, undefined));
1336
+ if (warnings != null)
1337
+ response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, undefined));
1338
+ }
1339
+ } catch (e) {
1340
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1341
+ }
1342
+ }));
1343
+ sendResponse(id, response);
1344
+ };
1345
+ requestCallbacks["on-resolve"] = async (id, request) => {
1346
+ let response = {}, name = "", callback, note;
1347
+ for (let id2 of request.ids) {
1348
+ try {
1349
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1350
+ let result = await callback({
1351
+ path: request.path,
1352
+ importer: request.importer,
1353
+ namespace: request.namespace,
1354
+ resolveDir: request.resolveDir,
1355
+ kind: request.kind,
1356
+ pluginData: details.load(request.pluginData),
1357
+ with: request.with
1358
+ });
1359
+ if (result != null) {
1360
+ if (typeof result !== "object")
1361
+ throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1362
+ let keys = {};
1363
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1364
+ let path3 = getFlag(result, keys, "path", mustBeString);
1365
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1366
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1367
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1368
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1369
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1370
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1371
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1372
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1373
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1374
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1375
+ response.id = id2;
1376
+ if (pluginName != null)
1377
+ response.pluginName = pluginName;
1378
+ if (path3 != null)
1379
+ response.path = path3;
1380
+ if (namespace != null)
1381
+ response.namespace = namespace;
1382
+ if (suffix != null)
1383
+ response.suffix = suffix;
1384
+ if (external != null)
1385
+ response.external = external;
1386
+ if (sideEffects != null)
1387
+ response.sideEffects = sideEffects;
1388
+ if (pluginData != null)
1389
+ response.pluginData = details.store(pluginData);
1390
+ if (errors != null)
1391
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1392
+ if (warnings != null)
1393
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1394
+ if (watchFiles != null)
1395
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1396
+ if (watchDirs != null)
1397
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1398
+ break;
1399
+ }
1400
+ } catch (e) {
1401
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1402
+ break;
1403
+ }
1404
+ }
1405
+ sendResponse(id, response);
1406
+ };
1407
+ requestCallbacks["on-load"] = async (id, request) => {
1408
+ let response = {}, name = "", callback, note;
1409
+ for (let id2 of request.ids) {
1410
+ try {
1411
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1412
+ let result = await callback({
1413
+ path: request.path,
1414
+ namespace: request.namespace,
1415
+ suffix: request.suffix,
1416
+ pluginData: details.load(request.pluginData),
1417
+ with: request.with
1418
+ });
1419
+ if (result != null) {
1420
+ if (typeof result !== "object")
1421
+ throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1422
+ let keys = {};
1423
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1424
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1425
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1426
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1427
+ let loader = getFlag(result, keys, "loader", mustBeString);
1428
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1429
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1430
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1431
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1432
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1433
+ response.id = id2;
1434
+ if (pluginName != null)
1435
+ response.pluginName = pluginName;
1436
+ if (contents instanceof Uint8Array)
1437
+ response.contents = contents;
1438
+ else if (contents != null)
1439
+ response.contents = encodeUTF8(contents);
1440
+ if (resolveDir != null)
1441
+ response.resolveDir = resolveDir;
1442
+ if (pluginData != null)
1443
+ response.pluginData = details.store(pluginData);
1444
+ if (loader != null)
1445
+ response.loader = loader;
1446
+ if (errors != null)
1447
+ response.errors = sanitizeMessages(errors, "errors", details, name, undefined);
1448
+ if (warnings != null)
1449
+ response.warnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1450
+ if (watchFiles != null)
1451
+ response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1452
+ if (watchDirs != null)
1453
+ response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1454
+ break;
1455
+ }
1456
+ } catch (e) {
1457
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1458
+ break;
1459
+ }
1460
+ }
1461
+ sendResponse(id, response);
1462
+ };
1463
+ let runOnEndCallbacks = (result, done) => done([], []);
1464
+ if (onEndCallbacks.length > 0) {
1465
+ runOnEndCallbacks = (result, done) => {
1466
+ (async () => {
1467
+ const onEndErrors = [];
1468
+ const onEndWarnings = [];
1469
+ for (const { name, callback, note } of onEndCallbacks) {
1470
+ let newErrors;
1471
+ let newWarnings;
1472
+ try {
1473
+ const value = await callback(result);
1474
+ if (value != null) {
1475
+ if (typeof value !== "object")
1476
+ throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1477
+ let keys = {};
1478
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1479
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1480
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1481
+ if (errors != null)
1482
+ newErrors = sanitizeMessages(errors, "errors", details, name, undefined);
1483
+ if (warnings != null)
1484
+ newWarnings = sanitizeMessages(warnings, "warnings", details, name, undefined);
1485
+ }
1486
+ } catch (e) {
1487
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1488
+ }
1489
+ if (newErrors) {
1490
+ onEndErrors.push(...newErrors);
1491
+ try {
1492
+ result.errors.push(...newErrors);
1493
+ } catch {}
1494
+ }
1495
+ if (newWarnings) {
1496
+ onEndWarnings.push(...newWarnings);
1497
+ try {
1498
+ result.warnings.push(...newWarnings);
1499
+ } catch {}
1500
+ }
1501
+ }
1502
+ done(onEndErrors, onEndWarnings);
1503
+ })();
1504
+ };
1505
+ }
1506
+ let scheduleOnDisposeCallbacks = () => {
1507
+ for (const cb of onDisposeCallbacks) {
1508
+ setTimeout(() => cb(), 0);
1509
+ }
1510
+ };
1511
+ isSetupDone = true;
1512
+ return {
1513
+ ok: true,
1514
+ requestPlugins,
1515
+ runOnEndCallbacks,
1516
+ scheduleOnDisposeCallbacks
1517
+ };
1518
+ };
1519
+ function createObjectStash() {
1520
+ const map = /* @__PURE__ */ new Map;
1521
+ let nextID = 0;
1522
+ return {
1523
+ clear() {
1524
+ map.clear();
1525
+ },
1526
+ load(id) {
1527
+ return map.get(id);
1528
+ },
1529
+ store(value) {
1530
+ if (value === undefined)
1531
+ return -1;
1532
+ const id = nextID++;
1533
+ map.set(id, value);
1534
+ return id;
1535
+ }
1536
+ };
1537
+ }
1538
+ function extractCallerV8(e, streamIn, ident) {
1539
+ let note;
1540
+ let tried = false;
1541
+ return () => {
1542
+ if (tried)
1543
+ return note;
1544
+ tried = true;
1545
+ try {
1546
+ let lines = (e.stack + "").split(`
1547
+ `);
1548
+ lines.splice(1, 1);
1549
+ let location = parseStackLinesV8(streamIn, lines, ident);
1550
+ if (location) {
1551
+ note = { text: e.message, location };
1552
+ return note;
1553
+ }
1554
+ } catch {}
1555
+ };
1556
+ }
1557
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1558
+ let text = "Internal error";
1559
+ let location = null;
1560
+ try {
1561
+ text = (e && e.message || e) + "";
1562
+ } catch {}
1563
+ try {
1564
+ location = parseStackLinesV8(streamIn, (e.stack + "").split(`
1565
+ `), "");
1566
+ } catch {}
1567
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1568
+ }
1569
+ function parseStackLinesV8(streamIn, lines, ident) {
1570
+ let at = " at ";
1571
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1572
+ for (let i = 1;i < lines.length; i++) {
1573
+ let line = lines[i];
1574
+ if (!line.startsWith(at))
1575
+ continue;
1576
+ line = line.slice(at.length);
1577
+ while (true) {
1578
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1579
+ if (match) {
1580
+ line = match[1];
1581
+ continue;
1582
+ }
1583
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1584
+ if (match) {
1585
+ line = match[1];
1586
+ continue;
1587
+ }
1588
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1589
+ if (match) {
1590
+ let contents;
1591
+ try {
1592
+ contents = streamIn.readFileSync(match[1], "utf8");
1593
+ } catch {
1594
+ break;
1595
+ }
1596
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1597
+ let column = +match[3] - 1;
1598
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1599
+ return {
1600
+ file: match[1],
1601
+ namespace: "file",
1602
+ line: +match[2],
1603
+ column: encodeUTF8(lineText.slice(0, column)).length,
1604
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1605
+ lineText: lineText + `
1606
+ ` + lines.slice(1).join(`
1607
+ `),
1608
+ suggestion: ""
1609
+ };
1610
+ }
1611
+ break;
1612
+ }
1613
+ }
1614
+ }
1615
+ return null;
1616
+ }
1617
+ function failureErrorWithLog(text, errors, warnings) {
1618
+ let limit = 5;
1619
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1620
+ if (i === limit)
1621
+ return `
1622
+ ...`;
1623
+ if (!e.location)
1624
+ return `
1625
+ error: ${e.text}`;
1626
+ let { file, line, column } = e.location;
1627
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1628
+ return `
1629
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1630
+ }).join("");
1631
+ let error = new Error(text);
1632
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1633
+ Object.defineProperty(error, key, {
1634
+ configurable: true,
1635
+ enumerable: true,
1636
+ get: () => value,
1637
+ set: (value2) => Object.defineProperty(error, key, {
1638
+ configurable: true,
1639
+ enumerable: true,
1640
+ value: value2
1641
+ })
1642
+ });
1643
+ }
1644
+ return error;
1645
+ }
1646
+ function replaceDetailsInMessages(messages, stash) {
1647
+ for (const message of messages) {
1648
+ message.detail = stash.load(message.detail);
1649
+ }
1650
+ return messages;
1651
+ }
1652
+ function sanitizeLocation(location, where, terminalWidth) {
1653
+ if (location == null)
1654
+ return null;
1655
+ let keys = {};
1656
+ let file = getFlag(location, keys, "file", mustBeString);
1657
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1658
+ let line = getFlag(location, keys, "line", mustBeInteger);
1659
+ let column = getFlag(location, keys, "column", mustBeInteger);
1660
+ let length = getFlag(location, keys, "length", mustBeInteger);
1661
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1662
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1663
+ checkForInvalidFlags(location, keys, where);
1664
+ if (lineText) {
1665
+ const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1666
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1667
+ lineText = relevantASCII;
1668
+ }
1669
+ }
1670
+ return {
1671
+ file: file || "",
1672
+ namespace: namespace || "",
1673
+ line: line || 0,
1674
+ column: column || 0,
1675
+ length: length || 0,
1676
+ lineText: lineText || "",
1677
+ suggestion: suggestion || ""
1678
+ };
1679
+ }
1680
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1681
+ let messagesClone = [];
1682
+ let index = 0;
1683
+ for (const message of messages) {
1684
+ let keys = {};
1685
+ let id = getFlag(message, keys, "id", mustBeString);
1686
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1687
+ let text = getFlag(message, keys, "text", mustBeString);
1688
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1689
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1690
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1691
+ let where = `in element ${index} of "${property}"`;
1692
+ checkForInvalidFlags(message, keys, where);
1693
+ let notesClone = [];
1694
+ if (notes) {
1695
+ for (const note of notes) {
1696
+ let noteKeys = {};
1697
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1698
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1699
+ checkForInvalidFlags(note, noteKeys, where);
1700
+ notesClone.push({
1701
+ text: noteText || "",
1702
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1703
+ });
1704
+ }
1705
+ }
1706
+ messagesClone.push({
1707
+ id: id || "",
1708
+ pluginName: pluginName || fallbackPluginName,
1709
+ text: text || "",
1710
+ location: sanitizeLocation(location, where, terminalWidth),
1711
+ notes: notesClone,
1712
+ detail: stash ? stash.store(detail) : -1
1713
+ });
1714
+ index++;
1715
+ }
1716
+ return messagesClone;
1717
+ }
1718
+ function sanitizeStringArray(values, property) {
1719
+ const result = [];
1720
+ for (const value of values) {
1721
+ if (typeof value !== "string")
1722
+ throw new Error(`${quote(property)} must be an array of strings`);
1723
+ result.push(value);
1724
+ }
1725
+ return result;
1726
+ }
1727
+ function sanitizeStringMap(map, property) {
1728
+ const result = /* @__PURE__ */ Object.create(null);
1729
+ for (const key in map) {
1730
+ const value = map[key];
1731
+ if (typeof value !== "string")
1732
+ throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1733
+ result[key] = value;
1734
+ }
1735
+ return result;
1736
+ }
1737
+ function convertOutputFiles({ path: path3, contents, hash }) {
1738
+ let text = null;
1739
+ return {
1740
+ path: path3,
1741
+ contents,
1742
+ hash,
1743
+ get text() {
1744
+ const binary = this.contents;
1745
+ if (text === null || binary !== contents) {
1746
+ contents = binary;
1747
+ text = decodeUTF8(binary);
1748
+ }
1749
+ return text;
1750
+ }
1751
+ };
1752
+ }
1753
+ function jsRegExpToGoRegExp(regexp) {
1754
+ let result = regexp.source;
1755
+ if (regexp.flags)
1756
+ result = `(?${regexp.flags})${result}`;
1757
+ return result;
1758
+ }
1759
+ var fs = __require("fs");
1760
+ var os = __require("os");
1761
+ var path = __require("path");
1762
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1763
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1764
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1765
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1766
+ var knownWindowsPackages = {
1767
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1768
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1769
+ "win32 x64 LE": "@esbuild/win32-x64"
1770
+ };
1771
+ var knownUnixlikePackages = {
1772
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1773
+ "android arm64 LE": "@esbuild/android-arm64",
1774
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1775
+ "darwin x64 LE": "@esbuild/darwin-x64",
1776
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1777
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1778
+ "linux arm LE": "@esbuild/linux-arm",
1779
+ "linux arm64 LE": "@esbuild/linux-arm64",
1780
+ "linux ia32 LE": "@esbuild/linux-ia32",
1781
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1782
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1783
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1784
+ "linux s390x BE": "@esbuild/linux-s390x",
1785
+ "linux x64 LE": "@esbuild/linux-x64",
1786
+ "linux loong64 LE": "@esbuild/linux-loong64",
1787
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
1788
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1789
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
1790
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1791
+ "sunos x64 LE": "@esbuild/sunos-x64"
1792
+ };
1793
+ var knownWebAssemblyFallbackPackages = {
1794
+ "android arm LE": "@esbuild/android-arm",
1795
+ "android x64 LE": "@esbuild/android-x64",
1796
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
1797
+ };
1798
+ function pkgAndSubpathForCurrentPlatform() {
1799
+ let pkg;
1800
+ let subpath;
1801
+ let isWASM = false;
1802
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
1803
+ if (platformKey in knownWindowsPackages) {
1804
+ pkg = knownWindowsPackages[platformKey];
1805
+ subpath = "esbuild.exe";
1806
+ } else if (platformKey in knownUnixlikePackages) {
1807
+ pkg = knownUnixlikePackages[platformKey];
1808
+ subpath = "bin/esbuild";
1809
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1810
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1811
+ subpath = "bin/esbuild";
1812
+ isWASM = true;
1813
+ } else {
1814
+ throw new Error(`Unsupported platform: ${platformKey}`);
1815
+ }
1816
+ return { pkg, subpath, isWASM };
1817
+ }
1818
+ function pkgForSomeOtherPlatform() {
1819
+ const libMainJS = __require.resolve("esbuild");
1820
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
1821
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
1822
+ for (const unixKey in knownUnixlikePackages) {
1823
+ try {
1824
+ const pkg = knownUnixlikePackages[unixKey];
1825
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1826
+ return pkg;
1827
+ } catch {}
1828
+ }
1829
+ for (const windowsKey in knownWindowsPackages) {
1830
+ try {
1831
+ const pkg = knownWindowsPackages[windowsKey];
1832
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg)))
1833
+ return pkg;
1834
+ } catch {}
1835
+ }
1836
+ }
1837
+ return null;
1838
+ }
1839
+ function downloadedBinPath(pkg, subpath) {
1840
+ const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
1841
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
1842
+ }
1843
+ function generateBinPath() {
1844
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1845
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
1846
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1847
+ } else {
1848
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1849
+ }
1850
+ }
1851
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1852
+ let binPath;
1853
+ try {
1854
+ binPath = __require.resolve(`${pkg}/${subpath}`);
1855
+ } catch (e) {
1856
+ binPath = downloadedBinPath(pkg, subpath);
1857
+ if (!fs.existsSync(binPath)) {
1858
+ try {
1859
+ __require.resolve(pkg);
1860
+ } catch {
1861
+ const otherPkg = pkgForSomeOtherPlatform();
1862
+ if (otherPkg) {
1863
+ let suggestions = `
1864
+ Specifically the "${otherPkg}" package is present but this platform
1865
+ needs the "${pkg}" package instead. People often get into this
1866
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
1867
+ into a Docker image that runs Linux, or by copying "node_modules" between
1868
+ Windows and WSL environments.
1869
+
1870
+ If you are installing with npm, you can try not copying the "node_modules"
1871
+ directory when you copy the files over, and running "npm ci" or "npm install"
1872
+ on the destination platform after the copy. Or you could consider using yarn
1873
+ instead of npm which has built-in support for installing a package on multiple
1874
+ platforms simultaneously.
1875
+
1876
+ If you are installing with yarn, you can try listing both this platform and the
1877
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1878
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1879
+ Keep in mind that this means multiple copies of esbuild will be present.
1880
+ `;
1881
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
1882
+ suggestions = `
1883
+ Specifically the "${otherPkg}" package is present but this platform
1884
+ needs the "${pkg}" package instead. People often get into this
1885
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
1886
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
1887
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
1888
+
1889
+ If you are installing with npm, you can try ensuring that both npm and node are
1890
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1891
+ changing how you installed npm and/or node. For example, installing node with
1892
+ the universal installer here should work: https://nodejs.org/en/download/. Or
1893
+ you could consider using yarn instead of npm which has built-in support for
1894
+ installing a package on multiple platforms simultaneously.
1895
+
1896
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
1897
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1898
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1899
+ Keep in mind that this means multiple copies of esbuild will be present.
1900
+ `;
1901
+ }
1902
+ throw new Error(`
1903
+ You installed esbuild for another platform than the one you're currently using.
1904
+ This won't work because esbuild is written with native code and needs to
1905
+ install a platform-specific binary executable.
1906
+ ${suggestions}
1907
+ Another alternative is to use the "esbuild-wasm" package instead, which works
1908
+ the same way on all platforms. But it comes with a heavy performance cost and
1909
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
1910
+ want to do that.
1911
+ `);
1912
+ }
1913
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1914
+
1915
+ If you are installing esbuild with npm, make sure that you don't specify the
1916
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1917
+ of "package.json" is used by esbuild to install the correct binary executable
1918
+ for your current platform.`);
1919
+ }
1920
+ throw e;
1921
+ }
1922
+ }
1923
+ if (/\.zip\//.test(binPath)) {
1924
+ let pnpapi;
1925
+ try {
1926
+ pnpapi = (()=>{throw new Error("Cannot require module "+"pnpapi");})();
1927
+ } catch (e) {}
1928
+ if (pnpapi) {
1929
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1930
+ const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.27.3"}-${path.basename(subpath)}`);
1931
+ if (!fs.existsSync(binTargetPath)) {
1932
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
1933
+ fs.copyFileSync(binPath, binTargetPath);
1934
+ fs.chmodSync(binTargetPath, 493);
1935
+ }
1936
+ return { binPath: binTargetPath, isWASM };
1937
+ }
1938
+ }
1939
+ return { binPath, isWASM };
1940
+ }
1941
+ var child_process = __require("child_process");
1942
+ var crypto = __require("crypto");
1943
+ var path2 = __require("path");
1944
+ var fs2 = __require("fs");
1945
+ var os2 = __require("os");
1946
+ var tty = __require("tty");
1947
+ var worker_threads;
1948
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1949
+ try {
1950
+ worker_threads = __require("worker_threads");
1951
+ } catch {}
1952
+ let [major, minor] = process.versions.node.split(".");
1953
+ if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) {
1954
+ worker_threads = undefined;
1955
+ }
1956
+ }
1957
+ var _a;
1958
+ var isInternalWorkerThread = ((_a = worker_threads == null ? undefined : worker_threads.workerData) == null ? undefined : _a.esbuildVersion) === "0.27.3";
1959
+ var esbuildCommandAndArgs = () => {
1960
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) {
1961
+ throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
1962
+
1963
+ 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.`);
1964
+ }
1965
+ if (false) {} else {
1966
+ const { binPath, isWASM } = generateBinPath();
1967
+ if (isWASM) {
1968
+ return ["node", [binPath]];
1969
+ } else {
1970
+ return [binPath, []];
1971
+ }
1972
+ }
1973
+ };
1974
+ var isTTY = () => tty.isatty(2);
1975
+ var fsSync = {
1976
+ readFile(tempFile, callback) {
1977
+ try {
1978
+ let contents = fs2.readFileSync(tempFile, "utf8");
1979
+ try {
1980
+ fs2.unlinkSync(tempFile);
1981
+ } catch {}
1982
+ callback(null, contents);
1983
+ } catch (err) {
1984
+ callback(err, null);
1985
+ }
1986
+ },
1987
+ writeFile(contents, callback) {
1988
+ try {
1989
+ let tempFile = randomFileName();
1990
+ fs2.writeFileSync(tempFile, contents);
1991
+ callback(tempFile);
1992
+ } catch {
1993
+ callback(null);
1994
+ }
1995
+ }
1996
+ };
1997
+ var fsAsync = {
1998
+ readFile(tempFile, callback) {
1999
+ try {
2000
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
2001
+ try {
2002
+ fs2.unlink(tempFile, () => callback(err, contents));
2003
+ } catch {
2004
+ callback(err, contents);
2005
+ }
2006
+ });
2007
+ } catch (err) {
2008
+ callback(err, null);
2009
+ }
2010
+ },
2011
+ writeFile(contents, callback) {
2012
+ try {
2013
+ let tempFile = randomFileName();
2014
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2015
+ } catch {
2016
+ callback(null);
2017
+ }
2018
+ }
2019
+ };
2020
+ var version = "0.27.3";
2021
+ var build = (options) => ensureServiceIsRunning().build(options);
2022
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2023
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2024
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2025
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2026
+ var buildSync = (options) => {
2027
+ if (worker_threads && !isInternalWorkerThread) {
2028
+ if (!workerThreadService)
2029
+ workerThreadService = startWorkerThreadService(worker_threads);
2030
+ return workerThreadService.buildSync(options);
2031
+ }
2032
+ let result;
2033
+ runServiceSync((service) => service.buildOrContext({
2034
+ callName: "buildSync",
2035
+ refs: null,
2036
+ options,
2037
+ isTTY: isTTY(),
2038
+ defaultWD,
2039
+ callback: (err, res) => {
2040
+ if (err)
2041
+ throw err;
2042
+ result = res;
2043
+ }
2044
+ }));
2045
+ return result;
2046
+ };
2047
+ var transformSync = (input, options) => {
2048
+ if (worker_threads && !isInternalWorkerThread) {
2049
+ if (!workerThreadService)
2050
+ workerThreadService = startWorkerThreadService(worker_threads);
2051
+ return workerThreadService.transformSync(input, options);
2052
+ }
2053
+ let result;
2054
+ runServiceSync((service) => service.transform({
2055
+ callName: "transformSync",
2056
+ refs: null,
2057
+ input,
2058
+ options: options || {},
2059
+ isTTY: isTTY(),
2060
+ fs: fsSync,
2061
+ callback: (err, res) => {
2062
+ if (err)
2063
+ throw err;
2064
+ result = res;
2065
+ }
2066
+ }));
2067
+ return result;
2068
+ };
2069
+ var formatMessagesSync = (messages, options) => {
2070
+ if (worker_threads && !isInternalWorkerThread) {
2071
+ if (!workerThreadService)
2072
+ workerThreadService = startWorkerThreadService(worker_threads);
2073
+ return workerThreadService.formatMessagesSync(messages, options);
2074
+ }
2075
+ let result;
2076
+ runServiceSync((service) => service.formatMessages({
2077
+ callName: "formatMessagesSync",
2078
+ refs: null,
2079
+ messages,
2080
+ options,
2081
+ callback: (err, res) => {
2082
+ if (err)
2083
+ throw err;
2084
+ result = res;
2085
+ }
2086
+ }));
2087
+ return result;
2088
+ };
2089
+ var analyzeMetafileSync = (metafile, options) => {
2090
+ if (worker_threads && !isInternalWorkerThread) {
2091
+ if (!workerThreadService)
2092
+ workerThreadService = startWorkerThreadService(worker_threads);
2093
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2094
+ }
2095
+ let result;
2096
+ runServiceSync((service) => service.analyzeMetafile({
2097
+ callName: "analyzeMetafileSync",
2098
+ refs: null,
2099
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2100
+ options,
2101
+ callback: (err, res) => {
2102
+ if (err)
2103
+ throw err;
2104
+ result = res;
2105
+ }
2106
+ }));
2107
+ return result;
2108
+ };
2109
+ var stop = () => {
2110
+ if (stopService)
2111
+ stopService();
2112
+ if (workerThreadService)
2113
+ workerThreadService.stop();
2114
+ return Promise.resolve();
2115
+ };
2116
+ var initializeWasCalled = false;
2117
+ var initialize = (options) => {
2118
+ options = validateInitializeOptions(options || {});
2119
+ if (options.wasmURL)
2120
+ throw new Error(`The "wasmURL" option only works in the browser`);
2121
+ if (options.wasmModule)
2122
+ throw new Error(`The "wasmModule" option only works in the browser`);
2123
+ if (options.worker)
2124
+ throw new Error(`The "worker" option only works in the browser`);
2125
+ if (initializeWasCalled)
2126
+ throw new Error('Cannot call "initialize" more than once');
2127
+ ensureServiceIsRunning();
2128
+ initializeWasCalled = true;
2129
+ return Promise.resolve();
2130
+ };
2131
+ var defaultWD = process.cwd();
2132
+ var longLivedService;
2133
+ var stopService;
2134
+ var ensureServiceIsRunning = () => {
2135
+ if (longLivedService)
2136
+ return longLivedService;
2137
+ let [command, args] = esbuildCommandAndArgs();
2138
+ let child = child_process.spawn(command, args.concat(`--service=${"0.27.3"}`, "--ping"), {
2139
+ windowsHide: true,
2140
+ stdio: ["pipe", "pipe", "inherit"],
2141
+ cwd: defaultWD
2142
+ });
2143
+ let { readFromStdout, afterClose, service } = createChannel({
2144
+ writeToStdin(bytes) {
2145
+ child.stdin.write(bytes, (err) => {
2146
+ if (err)
2147
+ afterClose(err);
2148
+ });
2149
+ },
2150
+ readFileSync: fs2.readFileSync,
2151
+ isSync: false,
2152
+ hasFS: true,
2153
+ esbuild: node_exports
2154
+ });
2155
+ child.stdin.on("error", afterClose);
2156
+ child.on("error", afterClose);
2157
+ const stdin = child.stdin;
2158
+ const stdout = child.stdout;
2159
+ stdout.on("data", readFromStdout);
2160
+ stdout.on("end", afterClose);
2161
+ stopService = () => {
2162
+ stdin.destroy();
2163
+ stdout.destroy();
2164
+ child.kill();
2165
+ initializeWasCalled = false;
2166
+ longLivedService = undefined;
2167
+ stopService = undefined;
2168
+ };
2169
+ let refCount = 0;
2170
+ child.unref();
2171
+ if (stdin.unref) {
2172
+ stdin.unref();
2173
+ }
2174
+ if (stdout.unref) {
2175
+ stdout.unref();
2176
+ }
2177
+ const refs = {
2178
+ ref() {
2179
+ if (++refCount === 1)
2180
+ child.ref();
2181
+ },
2182
+ unref() {
2183
+ if (--refCount === 0)
2184
+ child.unref();
2185
+ }
2186
+ };
2187
+ longLivedService = {
2188
+ build: (options) => new Promise((resolve2, reject) => {
2189
+ service.buildOrContext({
2190
+ callName: "build",
2191
+ refs,
2192
+ options,
2193
+ isTTY: isTTY(),
2194
+ defaultWD,
2195
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2196
+ });
2197
+ }),
2198
+ context: (options) => new Promise((resolve2, reject) => service.buildOrContext({
2199
+ callName: "context",
2200
+ refs,
2201
+ options,
2202
+ isTTY: isTTY(),
2203
+ defaultWD,
2204
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2205
+ })),
2206
+ transform: (input, options) => new Promise((resolve2, reject) => service.transform({
2207
+ callName: "transform",
2208
+ refs,
2209
+ input,
2210
+ options: options || {},
2211
+ isTTY: isTTY(),
2212
+ fs: fsAsync,
2213
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2214
+ })),
2215
+ formatMessages: (messages, options) => new Promise((resolve2, reject) => service.formatMessages({
2216
+ callName: "formatMessages",
2217
+ refs,
2218
+ messages,
2219
+ options,
2220
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2221
+ })),
2222
+ analyzeMetafile: (metafile, options) => new Promise((resolve2, reject) => service.analyzeMetafile({
2223
+ callName: "analyzeMetafile",
2224
+ refs,
2225
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2226
+ options,
2227
+ callback: (err, res) => err ? reject(err) : resolve2(res)
2228
+ }))
2229
+ };
2230
+ return longLivedService;
2231
+ };
2232
+ var runServiceSync = (callback) => {
2233
+ let [command, args] = esbuildCommandAndArgs();
2234
+ let stdin = new Uint8Array;
2235
+ let { readFromStdout, afterClose, service } = createChannel({
2236
+ writeToStdin(bytes) {
2237
+ if (stdin.length !== 0)
2238
+ throw new Error("Must run at most one command");
2239
+ stdin = bytes;
2240
+ },
2241
+ isSync: true,
2242
+ hasFS: true,
2243
+ esbuild: node_exports
2244
+ });
2245
+ callback(service);
2246
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.27.3"}`), {
2247
+ cwd: defaultWD,
2248
+ windowsHide: true,
2249
+ input: stdin,
2250
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2251
+ });
2252
+ readFromStdout(stdout);
2253
+ afterClose(null);
2254
+ };
2255
+ var randomFileName = () => {
2256
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2257
+ };
2258
+ var workerThreadService = null;
2259
+ var startWorkerThreadService = (worker_threads2) => {
2260
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel;
2261
+ let worker = new worker_threads2.Worker(__filename, {
2262
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.27.3" },
2263
+ transferList: [workerPort],
2264
+ execArgv: []
2265
+ });
2266
+ let nextID = 0;
2267
+ let fakeBuildError = (text) => {
2268
+ let error = new Error(`Build failed with 1 error:
2269
+ error: ${text}`);
2270
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: undefined }];
2271
+ error.errors = errors;
2272
+ error.warnings = [];
2273
+ return error;
2274
+ };
2275
+ let validateBuildSyncOptions = (options) => {
2276
+ if (!options)
2277
+ return;
2278
+ let plugins = options.plugins;
2279
+ if (plugins && plugins.length > 0)
2280
+ throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2281
+ };
2282
+ let applyProperties = (object, properties) => {
2283
+ for (let key in properties) {
2284
+ object[key] = properties[key];
2285
+ }
2286
+ };
2287
+ let runCallSync = (command, args) => {
2288
+ let id = nextID++;
2289
+ let sharedBuffer = new SharedArrayBuffer(8);
2290
+ let sharedBufferView = new Int32Array(sharedBuffer);
2291
+ let msg = { sharedBuffer, id, command, args };
2292
+ worker.postMessage(msg);
2293
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2294
+ if (status !== "ok" && status !== "not-equal")
2295
+ throw new Error("Internal error: Atomics.wait() failed: " + status);
2296
+ let { message: { id: id2, resolve: resolve2, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2297
+ if (id !== id2)
2298
+ throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2299
+ if (reject) {
2300
+ applyProperties(reject, properties);
2301
+ throw reject;
2302
+ }
2303
+ return resolve2;
2304
+ };
2305
+ worker.unref();
2306
+ return {
2307
+ buildSync(options) {
2308
+ validateBuildSyncOptions(options);
2309
+ return runCallSync("build", [options]);
2310
+ },
2311
+ transformSync(input, options) {
2312
+ return runCallSync("transform", [input, options]);
2313
+ },
2314
+ formatMessagesSync(messages, options) {
2315
+ return runCallSync("formatMessages", [messages, options]);
2316
+ },
2317
+ analyzeMetafileSync(metafile, options) {
2318
+ return runCallSync("analyzeMetafile", [metafile, options]);
2319
+ },
2320
+ stop() {
2321
+ worker.terminate();
2322
+ workerThreadService = null;
2323
+ }
2324
+ };
2325
+ };
2326
+ var startSyncServiceWorker = () => {
2327
+ let workerPort = worker_threads.workerData.workerPort;
2328
+ let parentPort = worker_threads.parentPort;
2329
+ let extractProperties = (object) => {
2330
+ let properties = {};
2331
+ if (object && typeof object === "object") {
2332
+ for (let key in object) {
2333
+ properties[key] = object[key];
2334
+ }
2335
+ }
2336
+ return properties;
2337
+ };
2338
+ try {
2339
+ let service = ensureServiceIsRunning();
2340
+ defaultWD = worker_threads.workerData.defaultWD;
2341
+ parentPort.on("message", (msg) => {
2342
+ (async () => {
2343
+ let { sharedBuffer, id, command, args } = msg;
2344
+ let sharedBufferView = new Int32Array(sharedBuffer);
2345
+ try {
2346
+ switch (command) {
2347
+ case "build":
2348
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2349
+ break;
2350
+ case "transform":
2351
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2352
+ break;
2353
+ case "formatMessages":
2354
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2355
+ break;
2356
+ case "analyzeMetafile":
2357
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2358
+ break;
2359
+ default:
2360
+ throw new Error(`Invalid command: ${command}`);
2361
+ }
2362
+ } catch (reject) {
2363
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2364
+ }
2365
+ Atomics.add(sharedBufferView, 0, 1);
2366
+ Atomics.notify(sharedBufferView, 0, Infinity);
2367
+ })();
2368
+ });
2369
+ } catch (reject) {
2370
+ parentPort.on("message", (msg) => {
2371
+ let { sharedBuffer, id } = msg;
2372
+ let sharedBufferView = new Int32Array(sharedBuffer);
2373
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2374
+ Atomics.add(sharedBufferView, 0, 1);
2375
+ Atomics.notify(sharedBufferView, 0, Infinity);
2376
+ });
2377
+ }
2378
+ };
2379
+ if (isInternalWorkerThread) {
2380
+ startSyncServiceWorker();
2381
+ }
2382
+ var node_default = node_exports;
2383
+ });
2384
+
2385
+ // src/cli.ts
2386
+ import { Command } from "commander";
2387
+
2388
+ // src/generators/naming.ts
2389
+ function toKebabCase(name) {
2390
+ return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase();
2391
+ }
2392
+ function toPascalCase(name) {
2393
+ return name.split(/[-_\s]+/).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
2394
+ }
2395
+
2396
+ // src/generators/module.ts
2397
+ function generateModule(name, sourceDir) {
2398
+ const kebab = toKebabCase(name);
2399
+ const pascal = toPascalCase(kebab);
2400
+ const dir = `${sourceDir}/modules/${kebab}`;
2401
+ const moduleDefContent = `import { createModuleDef } from '@vertz/server';
2402
+
2403
+ export const ${pascal}ModuleDef = createModuleDef('${kebab}');
2404
+ `;
2405
+ const moduleContent = `import { createModule } from '@vertz/server';
2406
+ import { ${pascal}ModuleDef } from './${kebab}.module-def';
2407
+
2408
+ export const ${pascal}Module = createModule(${pascal}ModuleDef, (m) => {
2409
+ return m;
2410
+ });
2411
+ `;
2412
+ return [
2413
+ { path: `${dir}/${kebab}.module-def.ts`, content: moduleDefContent },
2414
+ { path: `${dir}/${kebab}.module.ts`, content: moduleContent }
2415
+ ];
2416
+ }
2417
+
2418
+ // src/generators/router.ts
2419
+ function generateRouter(name, moduleName, sourceDir) {
2420
+ const kebab = toKebabCase(name);
2421
+ const pascal = toPascalCase(kebab);
2422
+ const moduleKebab = toKebabCase(moduleName);
2423
+ const content = `import { createRouter } from '@vertz/server';
2424
+ import { ${pascal}ModuleDef } from './${moduleKebab}.module-def';
2425
+
2426
+ export const ${kebab}Router = createRouter(${pascal}ModuleDef, '/${kebab}', (r) => {
2427
+ return r;
2428
+ });
2429
+ `;
2430
+ return [
2431
+ {
2432
+ path: `${sourceDir}/modules/${moduleKebab}/${kebab}.router.ts`,
2433
+ content
2434
+ }
2435
+ ];
2436
+ }
2437
+
2438
+ // src/generators/schema.ts
2439
+ function generateSchema(name, moduleName, sourceDir) {
2440
+ const kebab = toKebabCase(name);
2441
+ const pascal = toPascalCase(kebab);
2442
+ const moduleKebab = toKebabCase(moduleName);
2443
+ const content = `import { createSchema } from '@vertz/server';
2444
+ import { z } from '@vertz/schema';
2445
+
2446
+ export const ${pascal}Schema = createSchema('${pascal}', z.object({
2447
+ // Add your schema fields here
2448
+ }));
2449
+ `;
2450
+ return [
2451
+ {
2452
+ path: `${sourceDir}/modules/${moduleKebab}/schemas/${kebab}.schema.ts`,
2453
+ content
2454
+ }
2455
+ ];
2456
+ }
2457
+
2458
+ // src/generators/service.ts
2459
+ function generateService(name, moduleName, sourceDir) {
2460
+ const kebab = toKebabCase(name);
2461
+ const pascal = toPascalCase(kebab);
2462
+ const moduleKebab = toKebabCase(moduleName);
2463
+ const content = `export function create${pascal}Service() {
2464
+ return {};
2465
+ }
2466
+ `;
2467
+ return [
2468
+ {
2469
+ path: `${sourceDir}/modules/${moduleKebab}/${kebab}.service.ts`,
2470
+ content
2471
+ }
2472
+ ];
2473
+ }
2474
+
2475
+ // src/commands/generate.ts
2476
+ var REQUIRES_MODULE = new Set(["service", "router", "schema"]);
2477
+ function generateAction(options) {
2478
+ const { type, name, module: moduleName, sourceDir } = options;
2479
+ if (REQUIRES_MODULE.has(type) && !moduleName) {
2480
+ return {
2481
+ success: false,
2482
+ files: [],
2483
+ error: `Generator "${type}" requires a --module option`
2484
+ };
2485
+ }
2486
+ const ensuredModuleName = moduleName;
2487
+ switch (type) {
2488
+ case "module":
2489
+ return { success: true, files: generateModule(name, sourceDir) };
2490
+ case "service":
2491
+ return { success: true, files: generateService(name, ensuredModuleName, sourceDir) };
2492
+ case "router":
2493
+ return { success: true, files: generateRouter(name, ensuredModuleName, sourceDir) };
2494
+ case "schema":
2495
+ return { success: true, files: generateSchema(name, ensuredModuleName, sourceDir) };
2496
+ default:
2497
+ return {
2498
+ success: false,
2499
+ files: [],
2500
+ error: `Unknown generator type: "${type}"`
2501
+ };
2502
+ }
2503
+ }
2504
+
2505
+ // src/commands/domain-gen.ts
2506
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
2507
+ import { join } from "node:path";
2508
+ import { createHash } from "node:crypto";
2509
+ import { generateClient } from "@vertz/db";
2510
+ function findDomainFiles(cwd) {
2511
+ const domainsDir = join(cwd, "domains");
2512
+ if (!existsSync(domainsDir)) {
2513
+ return [];
2514
+ }
2515
+ const files = readdirSync(domainsDir);
2516
+ return files.filter((f) => f.endsWith(".domain.ts")).map((f) => join(domainsDir, f));
2517
+ }
2518
+ function computeDomainHash(files) {
2519
+ const hash = createHash("sha256");
2520
+ for (const file of files.sort()) {
2521
+ const content = readFileSync(file, "utf-8");
2522
+ hash.update(content);
2523
+ }
2524
+ return hash.digest("hex");
2525
+ }
2526
+ function shouldSkipGeneration(cwd, currentHash) {
2527
+ const hashFile = join(cwd, ".vertz", "generated", ".domain-hash");
2528
+ if (!existsSync(hashFile)) {
2529
+ return false;
2530
+ }
2531
+ try {
2532
+ const storedHash = readFileSync(hashFile, "utf-8").trim();
2533
+ return storedHash === currentHash;
2534
+ } catch {
2535
+ return false;
2536
+ }
2537
+ }
2538
+ function saveDomainHash(cwd, hash) {
2539
+ const dir = join(cwd, ".vertz", "generated");
2540
+ if (!existsSync(dir)) {
2541
+ mkdirSync(dir, { recursive: true });
2542
+ }
2543
+ writeFileSync(join(dir, ".domain-hash"), hash);
2544
+ }
2545
+ async function loadDomainDefinitions(cwd, files) {
2546
+ const { createJiti } = await import("jiti");
2547
+ const jitiImport = createJiti(cwd);
2548
+ const domains = [];
2549
+ for (const file of files) {
2550
+ try {
2551
+ const mod = jitiImport(file);
2552
+ const exports = mod.__esModule ? mod.default : mod;
2553
+ if (exports) {
2554
+ const domainExports = Array.isArray(exports) ? exports : [exports];
2555
+ for (const exp of domainExports) {
2556
+ if (exp && exp.name && exp.fields) {
2557
+ domains.push(exp);
2558
+ }
2559
+ }
2560
+ }
2561
+ } catch (err) {
2562
+ console.warn(`Warning: Failed to load domain file ${file}:`, err);
2563
+ }
2564
+ }
2565
+ return domains;
2566
+ }
2567
+ async function generateDomainAction(options) {
2568
+ const cwd = process.cwd();
2569
+ const dryRun = options.dryRun || false;
2570
+ const domainFiles = findDomainFiles(cwd);
2571
+ if (domainFiles.length === 0) {
2572
+ console.log("No domain files found in domains/ directory");
2573
+ return;
2574
+ }
2575
+ console.log(`Found ${domainFiles.length} domain file(s)`);
2576
+ const domainHash = computeDomainHash(domainFiles);
2577
+ if (shouldSkipGeneration(cwd, domainHash)) {
2578
+ console.log("Skipping generation - domains unchanged");
2579
+ return;
2580
+ }
2581
+ console.log("Generating DB client...");
2582
+ const domains = await loadDomainDefinitions(cwd, domainFiles);
2583
+ if (domains.length === 0) {
2584
+ console.log("No valid domain definitions found");
2585
+ return;
2586
+ }
2587
+ const clientCode = generateClient(domains);
2588
+ const outputDir = join(cwd, ".vertz", "generated");
2589
+ const outputFile = join(outputDir, "db-client.ts");
2590
+ if (dryRun) {
2591
+ console.log("Dry run - would write to:", outputFile);
2592
+ console.log(clientCode);
2593
+ return;
2594
+ }
2595
+ if (!existsSync(outputDir)) {
2596
+ mkdirSync(outputDir, { recursive: true });
2597
+ }
2598
+ writeFileSync(outputFile, clientCode);
2599
+ saveDomainHash(cwd, domainHash);
2600
+ console.log("DB client generated successfully");
2601
+ }
2602
+
2603
+ // src/commands/dev.ts
2604
+ import { spawn } from "node:child_process";
2605
+ import { join as join3 } from "node:path";
2606
+
2607
+ // src/pipeline/orchestrator.ts
2608
+ import { createCompiler } from "@vertz/compiler";
2609
+ import { generate, createCodegenPipeline } from "@vertz/codegen";
2610
+ var defaultPipelineConfig = {
2611
+ sourceDir: "src",
2612
+ outputDir: ".vertz/generated",
2613
+ typecheck: true,
2614
+ autoSyncDb: true,
2615
+ open: false,
2616
+ port: 3000,
2617
+ host: "localhost"
2618
+ };
2619
+
2620
+ class PipelineOrchestrator {
2621
+ config;
2622
+ compiler = null;
2623
+ appIR = null;
2624
+ isRunning = false;
2625
+ stages = new Map;
2626
+ constructor(config = {}) {
2627
+ this.config = { ...defaultPipelineConfig, ...config };
2628
+ }
2629
+ async initialize() {
2630
+ this.compiler = createCompiler({
2631
+ strict: false,
2632
+ forceGenerate: false,
2633
+ compiler: {
2634
+ sourceDir: this.config.sourceDir,
2635
+ outputDir: this.config.outputDir,
2636
+ entryFile: "src/app.ts",
2637
+ schemas: {
2638
+ enforceNaming: true,
2639
+ enforcePlacement: true
2640
+ },
2641
+ openapi: {
2642
+ output: ".vertz/generated/openapi.json",
2643
+ info: { title: "Vertz App", version: "1.0.0" }
2644
+ },
2645
+ validation: {
2646
+ requireResponseSchema: false,
2647
+ detectDeadCode: false
2648
+ }
2649
+ }
2650
+ });
2651
+ }
2652
+ async runFull() {
2653
+ const startTime = performance.now();
2654
+ const stages = [];
2655
+ let success = true;
2656
+ try {
2657
+ const analyzeResult = await this.runAnalyze();
2658
+ stages.push(analyzeResult);
2659
+ if (!analyzeResult.success) {
2660
+ success = false;
2661
+ }
2662
+ if (success && this.appIR) {
2663
+ const generateResult = await this.runCodegen();
2664
+ stages.push(generateResult);
2665
+ if (!generateResult.success) {
2666
+ success = false;
2667
+ }
2668
+ }
2669
+ } catch (error) {
2670
+ success = false;
2671
+ stages.push({
2672
+ stage: "analyze",
2673
+ success: false,
2674
+ durationMs: performance.now() - startTime,
2675
+ error: error instanceof Error ? error : new Error(String(error))
2676
+ });
2677
+ }
2678
+ return {
2679
+ success,
2680
+ stages,
2681
+ totalDurationMs: performance.now() - startTime,
2682
+ appIR: this.appIR ?? undefined
2683
+ };
2684
+ }
2685
+ async runStages(stages) {
2686
+ const startTime = performance.now();
2687
+ const results = [];
2688
+ for (const stage of stages) {
2689
+ let result;
2690
+ switch (stage) {
2691
+ case "analyze":
2692
+ result = await this.runAnalyze();
2693
+ break;
2694
+ case "codegen":
2695
+ result = await this.runCodegen();
2696
+ break;
2697
+ case "build-ui":
2698
+ result = await this.runBuildUI();
2699
+ break;
2700
+ case "db-sync":
2701
+ result = await this.runDbSync();
2702
+ break;
2703
+ default:
2704
+ continue;
2705
+ }
2706
+ results.push(result);
2707
+ this.stages.set(stage, result);
2708
+ }
2709
+ const allSuccess = results.every((r) => r.success);
2710
+ return {
2711
+ success: allSuccess,
2712
+ stages: results,
2713
+ totalDurationMs: performance.now() - startTime,
2714
+ appIR: this.appIR ?? undefined
2715
+ };
2716
+ }
2717
+ async runAnalyze() {
2718
+ const startTime = performance.now();
2719
+ if (!this.compiler) {
2720
+ await this.initialize();
2721
+ }
2722
+ try {
2723
+ this.appIR = await this.compiler.analyze();
2724
+ const diagnostics = await this.compiler.validate(this.appIR);
2725
+ const hasErrors = diagnostics.some((d) => d.severity === "error");
2726
+ return {
2727
+ stage: "analyze",
2728
+ success: !hasErrors,
2729
+ durationMs: performance.now() - startTime,
2730
+ output: hasErrors ? `${diagnostics.filter((d) => d.severity === "error").length} errors` : "Analysis complete"
2731
+ };
2732
+ } catch (error) {
2733
+ return {
2734
+ stage: "analyze",
2735
+ success: false,
2736
+ durationMs: performance.now() - startTime,
2737
+ error: error instanceof Error ? error : new Error(String(error))
2738
+ };
2739
+ }
2740
+ }
2741
+ async runCodegen() {
2742
+ const startTime = performance.now();
2743
+ if (!this.appIR) {
2744
+ return {
2745
+ stage: "codegen",
2746
+ success: false,
2747
+ durationMs: performance.now() - startTime,
2748
+ error: new Error("No AppIR available. Run analyze first.")
2749
+ };
2750
+ }
2751
+ try {
2752
+ const pipeline = createCodegenPipeline();
2753
+ const config = {
2754
+ generators: ["typescript"],
2755
+ outputDir: this.config.outputDir,
2756
+ format: true,
2757
+ incremental: true
2758
+ };
2759
+ const resolvedConfig = pipeline.resolveConfig(config);
2760
+ const result = await generate(this.appIR, resolvedConfig);
2761
+ return {
2762
+ stage: "codegen",
2763
+ success: true,
2764
+ durationMs: performance.now() - startTime,
2765
+ output: `Generated ${result.fileCount} files`
2766
+ };
2767
+ } catch (error) {
2768
+ return {
2769
+ stage: "codegen",
2770
+ success: false,
2771
+ durationMs: performance.now() - startTime,
2772
+ error: error instanceof Error ? error : new Error(String(error))
2773
+ };
2774
+ }
2775
+ }
2776
+ async runBuildUI() {
2777
+ const startTime = performance.now();
2778
+ return {
2779
+ stage: "build-ui",
2780
+ success: true,
2781
+ durationMs: performance.now() - startTime,
2782
+ output: "UI build delegated to Vite"
2783
+ };
2784
+ }
2785
+ async runDbSync() {
2786
+ const startTime = performance.now();
2787
+ return {
2788
+ stage: "db-sync",
2789
+ success: true,
2790
+ durationMs: performance.now() - startTime,
2791
+ output: "DB sync complete (noop for now)"
2792
+ };
2793
+ }
2794
+ getAppIR() {
2795
+ return this.appIR;
2796
+ }
2797
+ isPipelineRunning() {
2798
+ return this.isRunning;
2799
+ }
2800
+ getStageResult(stage) {
2801
+ return this.stages.get(stage);
2802
+ }
2803
+ async dispose() {
2804
+ this.compiler = null;
2805
+ this.appIR = null;
2806
+ this.stages.clear();
2807
+ }
2808
+ }
2809
+ // src/pipeline/watcher.ts
2810
+ var DEFAULT_IGNORE_PATTERNS = [
2811
+ "/node_modules/",
2812
+ "/.git/",
2813
+ "/.vertz/generated/",
2814
+ "/dist/",
2815
+ "/.turbo/",
2816
+ "/coverage/"
2817
+ ];
2818
+ var DEFAULT_DEBOUNCE_MS = 100;
2819
+ function categorizeFileChange(path) {
2820
+ const normalizedPath = path.replace(/\\/g, "/").toLowerCase();
2821
+ if (normalizedPath.includes(".domain.ts")) {
2822
+ return "domain";
2823
+ }
2824
+ if (normalizedPath.includes(".module.ts")) {
2825
+ return "module";
2826
+ }
2827
+ if (normalizedPath.includes(".schema.ts")) {
2828
+ return "schema";
2829
+ }
2830
+ if (normalizedPath.includes(".service.ts")) {
2831
+ return "service";
2832
+ }
2833
+ if (normalizedPath.includes(".route.ts")) {
2834
+ return "route";
2835
+ }
2836
+ if (normalizedPath.endsWith(".tsx") || normalizedPath.endsWith(".jsx")) {
2837
+ return "component";
2838
+ }
2839
+ if (normalizedPath === "vertz.config.ts" || normalizedPath === "vertz.config.js" || normalizedPath === "vertz.config.mts" || normalizedPath.includes("vertz.config")) {
2840
+ return "config";
2841
+ }
2842
+ return "other";
2843
+ }
2844
+ function getAffectedStages(category) {
2845
+ switch (category) {
2846
+ case "domain":
2847
+ case "module":
2848
+ case "service":
2849
+ case "route":
2850
+ return ["analyze", "codegen"];
2851
+ case "schema":
2852
+ return ["codegen"];
2853
+ case "component":
2854
+ return ["build-ui"];
2855
+ case "config":
2856
+ return ["analyze", "codegen", "build-ui"];
2857
+ case "other":
2858
+ default:
2859
+ return ["build-ui"];
2860
+ }
2861
+ }
2862
+ function getStagesForChanges(changes) {
2863
+ const stages = new Set;
2864
+ for (const change of changes) {
2865
+ const category = change.category ?? categorizeFileChange(change.path);
2866
+ const affected = getAffectedStages(category);
2867
+ affected.forEach((s) => stages.add(s));
2868
+ }
2869
+ if (stages.has("codegen") && !stages.has("analyze")) {
2870
+ stages.add("analyze");
2871
+ }
2872
+ return Array.from(stages);
2873
+ }
2874
+ function createWatcher(config) {
2875
+ const {
2876
+ dir,
2877
+ ignorePatterns = DEFAULT_IGNORE_PATTERNS,
2878
+ debounceMs = DEFAULT_DEBOUNCE_MS,
2879
+ onChange
2880
+ } = config;
2881
+ const handlers = [];
2882
+ let pending = [];
2883
+ let timer;
2884
+ function isIgnored(path) {
2885
+ return ignorePatterns.some((pattern) => path.includes(pattern));
2886
+ }
2887
+ function flush() {
2888
+ if (pending.length === 0)
2889
+ return;
2890
+ const changes = pending.map((change) => ({
2891
+ ...change,
2892
+ category: categorizeFileChange(change.path)
2893
+ }));
2894
+ const batch = pending;
2895
+ pending = [];
2896
+ for (const handler of handlers) {
2897
+ handler(changes);
2898
+ }
2899
+ if (onChange) {
2900
+ onChange(changes);
2901
+ }
2902
+ }
2903
+ return {
2904
+ on(_event, handler) {
2905
+ handlers.push(handler);
2906
+ },
2907
+ _emit(change) {
2908
+ if (isIgnored(change.path))
2909
+ return;
2910
+ pending.push(change);
2911
+ if (timer !== undefined) {
2912
+ clearTimeout(timer);
2913
+ }
2914
+ timer = setTimeout(flush, debounceMs);
2915
+ },
2916
+ close() {
2917
+ if (timer !== undefined) {
2918
+ clearTimeout(timer);
2919
+ }
2920
+ pending = [];
2921
+ }
2922
+ };
2923
+ }
2924
+
2925
+ class PipelineWatcherImpl {
2926
+ handlers = new Map;
2927
+ watcher;
2928
+ config;
2929
+ isClosed = false;
2930
+ constructor(config) {
2931
+ this.config = config;
2932
+ this.watcher = createWatcher({
2933
+ ...config,
2934
+ onChange: (changes) => this.handleChanges(changes)
2935
+ });
2936
+ }
2937
+ handleChanges(changes) {
2938
+ const stages = getStagesForChanges(changes);
2939
+ for (const stage of stages) {
2940
+ const handlers = this.handlers.get(stage);
2941
+ if (handlers) {
2942
+ for (const handler of handlers) {
2943
+ handler(changes);
2944
+ }
2945
+ }
2946
+ }
2947
+ }
2948
+ on(event, handler) {
2949
+ if (this.isClosed)
2950
+ return;
2951
+ const handlers = this.handlers.get(event) ?? [];
2952
+ handlers.push(handler);
2953
+ this.handlers.set(event, handlers);
2954
+ }
2955
+ close() {
2956
+ this.isClosed = true;
2957
+ this.watcher.close();
2958
+ this.handlers.clear();
2959
+ }
2960
+ }
2961
+ function createPipelineWatcher(config) {
2962
+ return new PipelineWatcherImpl(config);
2963
+ }
2964
+ // src/utils/paths.ts
2965
+ import { existsSync as existsSync2 } from "node:fs";
2966
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
2967
+ var ROOT_MARKERS = ["package.json", "vertz.config.ts", "vertz.config.js"];
2968
+ function findProjectRoot(startDir) {
2969
+ let current = resolve(startDir ?? process.cwd());
2970
+ while (true) {
2971
+ for (const marker of ROOT_MARKERS) {
2972
+ if (existsSync2(join2(current, marker))) {
2973
+ return current;
2974
+ }
2975
+ }
2976
+ const parent = dirname2(current);
2977
+ if (parent === current) {
2978
+ break;
2979
+ }
2980
+ current = parent;
2981
+ }
2982
+ return;
2983
+ }
2984
+
2985
+ // src/utils/format.ts
2986
+ function formatDuration(ms) {
2987
+ if (ms < 1000) {
2988
+ return `${Math.round(ms)}ms`;
2989
+ }
2990
+ const seconds = ms / 1000;
2991
+ return `${seconds.toFixed(2)}s`;
2992
+ }
2993
+ function formatFileSize(bytes) {
2994
+ if (bytes < 1024) {
2995
+ return `${bytes} B`;
2996
+ }
2997
+ const kb = bytes / 1024;
2998
+ if (kb < 1024) {
2999
+ return `${kb.toFixed(1)} KB`;
3000
+ }
3001
+ const mb = kb / 1024;
3002
+ return `${mb.toFixed(1)} MB`;
3003
+ }
3004
+
3005
+ // src/commands/dev.ts
3006
+ async function devAction(options = {}) {
3007
+ const {
3008
+ port = 3000,
3009
+ host = "localhost",
3010
+ open = false,
3011
+ typecheck = true,
3012
+ verbose = false
3013
+ } = options;
3014
+ const projectRoot = findProjectRoot(process.cwd());
3015
+ if (!projectRoot) {
3016
+ console.error("Error: Could not find project root. Are you in a Vertz project?");
3017
+ process.exit(1);
3018
+ }
3019
+ console.log(`\uD83D\uDE80 Starting Vertz development server...
3020
+ `);
3021
+ const pipelineConfig = {
3022
+ sourceDir: "src",
3023
+ outputDir: ".vertz/generated",
3024
+ typecheck,
3025
+ autoSyncDb: true,
3026
+ open,
3027
+ port,
3028
+ host
3029
+ };
3030
+ const orchestrator = new PipelineOrchestrator(pipelineConfig);
3031
+ let isRunning = true;
3032
+ let viteProcess = null;
3033
+ const shutdown = async () => {
3034
+ console.log(`
3035
+
3036
+ \uD83D\uDC4B Shutting down...`);
3037
+ isRunning = false;
3038
+ if (viteProcess) {
3039
+ viteProcess.kill("SIGTERM");
3040
+ }
3041
+ await orchestrator.dispose();
3042
+ process.exit(0);
3043
+ };
3044
+ process.on("SIGINT", shutdown);
3045
+ process.on("SIGTERM", shutdown);
3046
+ try {
3047
+ console.log("\uD83D\uDCE6 Running initial pipeline...");
3048
+ const initialResult = await orchestrator.runFull();
3049
+ if (!initialResult.success) {
3050
+ console.error(`
3051
+ ❌ Initial pipeline failed:`);
3052
+ for (const stage of initialResult.stages) {
3053
+ if (!stage.success && stage.error) {
3054
+ console.error(` - ${stage.stage}: ${stage.error.message}`);
3055
+ }
3056
+ }
3057
+ console.log(`
3058
+ \uD83D\uDCA1 Try fixing the errors above and the watcher will retry.`);
3059
+ } else {
3060
+ if (verbose) {
3061
+ console.log(`
3062
+ ✅ Initial pipeline complete:`);
3063
+ for (const stage of initialResult.stages) {
3064
+ console.log(` - ${stage.stage}: ${stage.output} (${formatDuration(stage.durationMs)})`);
3065
+ }
3066
+ }
3067
+ }
3068
+ console.log(`
3069
+ \uD83D\uDC40 Watching for file changes...`);
3070
+ const watcher = createPipelineWatcher({
3071
+ dir: join3(projectRoot, "src"),
3072
+ debounceMs: 100,
3073
+ onChange: async (changes) => {
3074
+ if (!isRunning)
3075
+ return;
3076
+ const stages = getStagesForFileChanges(changes);
3077
+ if (verbose) {
3078
+ console.log(`
3079
+ \uD83D\uDD04 File change detected: ${changes.map((c) => c.path).join(", ")}`);
3080
+ console.log(` Running stages: ${stages.join(", ")}`);
3081
+ }
3082
+ const result = await orchestrator.runStages(stages);
3083
+ if (!result.success) {
3084
+ console.error(`
3085
+ ❌ Pipeline update failed:`);
3086
+ for (const stage of result.stages) {
3087
+ if (!stage.success && stage.error) {
3088
+ console.error(` - ${stage.stage}: ${stage.error.message}`);
3089
+ }
3090
+ }
3091
+ console.log(`
3092
+ \uD83D\uDCA1 Try fixing the errors above.`);
3093
+ } else if (verbose) {
3094
+ for (const stage of result.stages) {
3095
+ console.log(` ✓ ${stage.stage}: ${stage.output}`);
3096
+ }
3097
+ }
3098
+ }
3099
+ });
3100
+ console.log(`
3101
+ \uD83C\uDF10 Starting Vite dev server on http://${host}:${port}...`);
3102
+ viteProcess = spawn("npx", ["vite", "--port", String(port), "--host", host], {
3103
+ cwd: projectRoot,
3104
+ stdio: "inherit",
3105
+ shell: true,
3106
+ env: {
3107
+ ...process.env,
3108
+ VERTZ_GENERATED_DIR: pipelineConfig.outputDir
3109
+ }
3110
+ });
3111
+ viteProcess.on("close", (code) => {
3112
+ if (isRunning && code !== 0) {
3113
+ console.log(`
3114
+ ⚠️ Vite process exited with code ${code}`);
3115
+ }
3116
+ shutdown();
3117
+ });
3118
+ } catch (error) {
3119
+ console.error(`
3120
+ ❌ Fatal error:`, error instanceof Error ? error.message : String(error));
3121
+ await shutdown();
3122
+ process.exit(1);
3123
+ }
3124
+ }
3125
+ function getStagesForFileChanges(changes) {
3126
+ const stages = new Set;
3127
+ for (const change of changes) {
3128
+ const path = change.path.toLowerCase();
3129
+ if (path.includes(".domain.ts") || path.includes(".module.ts") || path.includes(".service.ts") || path.includes(".route.ts")) {
3130
+ stages.add("analyze");
3131
+ stages.add("codegen");
3132
+ } else if (path.includes(".schema.ts")) {
3133
+ stages.add("codegen");
3134
+ } else if (path.endsWith(".tsx") || path.endsWith(".jsx")) {
3135
+ stages.add("build-ui");
3136
+ } else if (path.includes("vertz.config") || path.includes("vite.config")) {
3137
+ stages.add("analyze");
3138
+ stages.add("codegen");
3139
+ stages.add("build-ui");
3140
+ } else {
3141
+ stages.add("build-ui");
3142
+ }
3143
+ }
3144
+ if (stages.has("codegen") && !stages.has("analyze")) {
3145
+ stages.add("analyze");
3146
+ }
3147
+ return Array.from(stages);
3148
+ }
3149
+
3150
+ // src/commands/build.ts
3151
+ import { existsSync as existsSync4 } from "node:fs";
3152
+ import { join as join5 } from "node:path";
3153
+
3154
+ // src/production-build/orchestrator.ts
3155
+ var esbuild = __toESM(require_main(), 1);
3156
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
3157
+ import { join as join4 } from "node:path";
3158
+ import { createCompiler as createCompiler2 } from "@vertz/compiler";
3159
+
3160
+ // src/production-build/types.ts
3161
+ var defaultBuildConfig = {
3162
+ sourceDir: "src",
3163
+ outputDir: ".vertz/build",
3164
+ typecheck: true,
3165
+ minify: true,
3166
+ sourcemap: false,
3167
+ target: "node",
3168
+ entryPoint: "src/app.ts"
3169
+ };
3170
+
3171
+ // src/production-build/orchestrator.ts
3172
+ class BuildOrchestrator {
3173
+ config;
3174
+ pipeline;
3175
+ compiler = null;
3176
+ constructor(config = {}) {
3177
+ this.config = { ...defaultBuildConfig, ...config };
3178
+ const pipelineConfig = {
3179
+ sourceDir: this.config.sourceDir,
3180
+ outputDir: ".vertz/generated",
3181
+ typecheck: this.config.typecheck,
3182
+ autoSyncDb: false,
3183
+ port: 3000,
3184
+ host: "localhost"
3185
+ };
3186
+ this.pipeline = new PipelineOrchestrator(pipelineConfig);
3187
+ }
3188
+ async build() {
3189
+ const startTime = performance.now();
3190
+ const stages = {
3191
+ codegen: false,
3192
+ typecheck: false,
3193
+ bundle: false
3194
+ };
3195
+ let manifest = {
3196
+ entryPoint: this.config.entryPoint,
3197
+ outputDir: this.config.outputDir,
3198
+ generatedFiles: [],
3199
+ size: 0,
3200
+ buildTime: Date.now(),
3201
+ target: this.config.target
3202
+ };
3203
+ try {
3204
+ console.log("\uD83D\uDCE6 Running codegen pipeline...");
3205
+ const codegenResult = await this.runCodegen();
3206
+ stages.codegen = codegenResult.success;
3207
+ if (!codegenResult.success) {
3208
+ return this.createFailureResult(stages, manifest, startTime, `Codegen failed: ${codegenResult.stages.map((s) => s.error?.message).join(", ")}`);
3209
+ }
3210
+ manifest.generatedFiles = this.collectGeneratedFiles();
3211
+ if (this.config.typecheck) {
3212
+ console.log("\uD83D\uDD0D Running TypeScript type checking...");
3213
+ const typecheckResult = await this.runTypecheck();
3214
+ stages.typecheck = typecheckResult;
3215
+ if (!typecheckResult) {
3216
+ return this.createFailureResult(stages, manifest, startTime, "Type checking failed");
3217
+ }
3218
+ }
3219
+ console.log("\uD83D\uDCE6 Bundling application...");
3220
+ const bundleResult = await this.runBundle();
3221
+ stages.bundle = bundleResult.success;
3222
+ if (!bundleResult.success) {
3223
+ return this.createFailureResult(stages, manifest, startTime, bundleResult.error || "Bundling failed");
3224
+ }
3225
+ manifest.size = bundleResult.size || 0;
3226
+ manifest.dependencies = bundleResult.dependencies;
3227
+ manifest.treeShaken = bundleResult.treeShaken;
3228
+ await this.writeManifest(manifest);
3229
+ const durationMs = performance.now() - startTime;
3230
+ console.log(`
3231
+ ✅ Build completed successfully!`);
3232
+ console.log(` Output: ${this.config.outputDir}`);
3233
+ console.log(` Size: ${formatFileSize(manifest.size)}`);
3234
+ console.log(` Time: ${formatDuration(durationMs)}`);
3235
+ return {
3236
+ success: true,
3237
+ stages,
3238
+ manifest,
3239
+ durationMs
3240
+ };
3241
+ } catch (error) {
3242
+ return this.createFailureResult(stages, manifest, startTime, error instanceof Error ? error.message : String(error));
3243
+ }
3244
+ }
3245
+ async runCodegen() {
3246
+ return this.pipeline.runFull();
3247
+ }
3248
+ async runTypecheck() {
3249
+ try {
3250
+ if (!this.compiler) {
3251
+ this.compiler = createCompiler2({
3252
+ strict: false,
3253
+ forceGenerate: false,
3254
+ compiler: {
3255
+ sourceDir: this.config.sourceDir,
3256
+ outputDir: ".vertz/generated",
3257
+ entryFile: this.config.entryPoint,
3258
+ schemas: {
3259
+ enforceNaming: true,
3260
+ enforcePlacement: true
3261
+ },
3262
+ openapi: {
3263
+ output: ".vertz/generated/openapi.json",
3264
+ info: { title: "Vertz App", version: "1.0.0" }
3265
+ },
3266
+ validation: {
3267
+ requireResponseSchema: false,
3268
+ detectDeadCode: false
3269
+ }
3270
+ }
3271
+ });
3272
+ }
3273
+ const ir = await this.compiler.analyze();
3274
+ const diagnostics = await this.compiler.validate(ir);
3275
+ const hasErrors = diagnostics.some((d) => d.severity === "error");
3276
+ if (hasErrors) {
3277
+ const errors = diagnostics.filter((d) => d.severity === "error");
3278
+ console.error(`
3279
+ ❌ Type checking found ${errors.length} error(s):`);
3280
+ errors.forEach((d) => {
3281
+ console.error(` ${d.file || "unknown"}:${d.line}:${d.column} - ${d.message}`);
3282
+ });
3283
+ return false;
3284
+ }
3285
+ const warnings = diagnostics.filter((d) => d.severity === "warning");
3286
+ if (warnings.length > 0) {
3287
+ console.log(`⚠️ Type checking found ${warnings.length} warning(s)`);
3288
+ }
3289
+ return true;
3290
+ } catch (error) {
3291
+ console.error("Type checking error:", error instanceof Error ? error.message : String(error));
3292
+ return false;
3293
+ }
3294
+ }
3295
+ async runBundle() {
3296
+ try {
3297
+ if (!existsSync3(this.config.outputDir)) {
3298
+ mkdirSync2(this.config.outputDir, { recursive: true });
3299
+ }
3300
+ const entryFile = join4(process.cwd(), this.config.entryPoint);
3301
+ const outfile = join4(this.config.outputDir, "index.js");
3302
+ const buildResult = await esbuild.build({
3303
+ entryPoints: [entryFile],
3304
+ bundle: true,
3305
+ platform: "node",
3306
+ format: "esm",
3307
+ outfile,
3308
+ target: this.getEsbuildTarget(),
3309
+ minify: this.config.minify,
3310
+ sourcemap: this.config.sourcemap,
3311
+ external: ["@vertz/*", "@anthropic-ai/sdk"],
3312
+ logLevel: "info",
3313
+ metafile: true
3314
+ });
3315
+ let size = 0;
3316
+ if (existsSync3(outfile)) {
3317
+ size = statSync2(outfile).size;
3318
+ }
3319
+ const dependencies = [];
3320
+ const treeShaken = [];
3321
+ if (buildResult.metafile) {
3322
+ const outputs = buildResult.metafile.outputs;
3323
+ for (const [_path, info] of Object.entries(outputs)) {
3324
+ for (const inputPath of Object.keys(info.inputs)) {
3325
+ if (!dependencies.includes(inputPath)) {
3326
+ dependencies.push(inputPath);
3327
+ }
3328
+ }
3329
+ }
3330
+ }
3331
+ return {
3332
+ success: true,
3333
+ size,
3334
+ dependencies,
3335
+ treeShaken
3336
+ };
3337
+ } catch (error) {
3338
+ return {
3339
+ success: false,
3340
+ error: error instanceof Error ? error.message : String(error)
3341
+ };
3342
+ }
3343
+ }
3344
+ getEsbuildTarget() {
3345
+ switch (this.config.target) {
3346
+ case "edge":
3347
+ return "edge88";
3348
+ case "worker":
3349
+ return "esnext";
3350
+ case "node":
3351
+ default:
3352
+ return "node18";
3353
+ }
3354
+ }
3355
+ collectGeneratedFiles() {
3356
+ const generatedDir = ".vertz/generated";
3357
+ const files = [];
3358
+ if (!existsSync3(generatedDir)) {
3359
+ return files;
3360
+ }
3361
+ const collectRecursive = (dir, basePath = "") => {
3362
+ const entries = readdirSync2(dir);
3363
+ for (const entry of entries) {
3364
+ const fullPath = join4(dir, entry);
3365
+ const relativePath = join4(basePath, entry);
3366
+ const stat = statSync2(fullPath);
3367
+ if (stat.isDirectory()) {
3368
+ collectRecursive(fullPath, relativePath);
3369
+ } else if (stat.isFile()) {
3370
+ const type = this.getFileType(entry);
3371
+ files.push({
3372
+ path: relativePath,
3373
+ size: stat.size,
3374
+ type
3375
+ });
3376
+ }
3377
+ }
3378
+ };
3379
+ try {
3380
+ collectRecursive(generatedDir);
3381
+ } catch {}
3382
+ return files;
3383
+ }
3384
+ getFileType(filename) {
3385
+ const lower = filename.toLowerCase();
3386
+ if (lower.includes("types") || lower.includes(".d.ts"))
3387
+ return "type";
3388
+ if (lower.includes("routes") || lower.includes("router"))
3389
+ return "route";
3390
+ if (lower.includes("openapi") || lower.includes("swagger"))
3391
+ return "openapi";
3392
+ if (lower.includes("client") || lower.includes("sdk"))
3393
+ return "client";
3394
+ return "type";
3395
+ }
3396
+ async writeManifest(manifest) {
3397
+ const manifestPath = join4(this.config.outputDir, "manifest.json");
3398
+ const manifestData = {
3399
+ ...manifest,
3400
+ generatedFiles: manifest.generatedFiles.map((f) => ({
3401
+ ...f,
3402
+ path: f.path.replace(/\\/g, "/")
3403
+ }))
3404
+ };
3405
+ writeFileSync2(manifestPath, JSON.stringify(manifestData, null, 2));
3406
+ console.log(` Manifest: ${manifestPath}`);
3407
+ }
3408
+ createFailureResult(stages, manifest, startTime, error) {
3409
+ return {
3410
+ success: false,
3411
+ stages,
3412
+ manifest,
3413
+ error,
3414
+ durationMs: performance.now() - startTime
3415
+ };
3416
+ }
3417
+ async dispose() {
3418
+ await this.pipeline.dispose();
3419
+ this.compiler = null;
3420
+ }
3421
+ }
3422
+ // src/commands/build.ts
3423
+ async function buildAction(options = {}) {
3424
+ const {
3425
+ strict: _strict = false,
3426
+ output,
3427
+ target = "node",
3428
+ noTypecheck = false,
3429
+ noMinify = false,
3430
+ sourcemap = false,
3431
+ verbose = false
3432
+ } = options;
3433
+ const projectRoot = findProjectRoot(process.cwd());
3434
+ if (!projectRoot) {
3435
+ console.error("Error: Could not find project root. Are you in a Vertz project?");
3436
+ return 1;
3437
+ }
3438
+ const entryPoint = "src/app.ts";
3439
+ const entryPath = join5(projectRoot, entryPoint);
3440
+ if (!existsSync4(entryPath)) {
3441
+ console.error(`Error: Entry point not found at ${entryPoint}`);
3442
+ console.error("Make sure you have an app.ts in your src directory.");
3443
+ return 1;
3444
+ }
3445
+ console.log(`\uD83D\uDE80 Starting Vertz production build...
3446
+ `);
3447
+ const buildConfig = {
3448
+ sourceDir: "src",
3449
+ outputDir: output || ".vertz/build",
3450
+ typecheck: !noTypecheck,
3451
+ minify: !noMinify,
3452
+ sourcemap,
3453
+ target,
3454
+ entryPoint
3455
+ };
3456
+ if (verbose) {
3457
+ console.log("Build configuration:");
3458
+ console.log(` Entry: ${entryPoint}`);
3459
+ console.log(` Output: ${buildConfig.outputDir}`);
3460
+ console.log(` Target: ${target}`);
3461
+ console.log(` Typecheck: ${buildConfig.typecheck ? "enabled" : "disabled"}`);
3462
+ console.log(` Minify: ${buildConfig.minify ? "enabled" : "disabled"}`);
3463
+ console.log(` Sourcemap: ${buildConfig.sourcemap ? "enabled" : "disabled"}`);
3464
+ console.log("");
3465
+ }
3466
+ const orchestrator = new BuildOrchestrator(buildConfig);
3467
+ try {
3468
+ const result = await orchestrator.build();
3469
+ if (!result.success) {
3470
+ console.error(`
3471
+ ❌ Build failed:`);
3472
+ console.error(` ${result.error}`);
3473
+ await orchestrator.dispose();
3474
+ return 1;
3475
+ }
3476
+ console.log(`
3477
+ \uD83D\uDCCA Build Summary:`);
3478
+ console.log(` Entry: ${result.manifest.entryPoint}`);
3479
+ console.log(` Output: ${result.manifest.outputDir}`);
3480
+ console.log(` Size: ${formatFileSize(result.manifest.size)}`);
3481
+ console.log(` Time: ${formatDuration(result.durationMs)}`);
3482
+ console.log(` Target: ${result.manifest.target}`);
3483
+ if (result.manifest.generatedFiles.length > 0) {
3484
+ console.log(`
3485
+ \uD83D\uDCC1 Generated Files (${result.manifest.generatedFiles.length}):`);
3486
+ const byType = new Map;
3487
+ for (const file of result.manifest.generatedFiles) {
3488
+ const count = byType.get(file.type) || 0;
3489
+ byType.set(file.type, count + 1);
3490
+ }
3491
+ for (const [type, count] of byType) {
3492
+ console.log(` - ${type}: ${count} file(s)`);
3493
+ }
3494
+ }
3495
+ await orchestrator.dispose();
3496
+ return 0;
3497
+ } catch (error) {
3498
+ console.error(`
3499
+ ❌ Fatal error:`, error instanceof Error ? error.message : String(error));
3500
+ await orchestrator.dispose();
3501
+ return 1;
3502
+ }
3503
+ }
3504
+
3505
+ // src/commands/create.ts
3506
+ import { resolveOptions, scaffold } from "@vertz/create-vertz-app";
3507
+ async function createAction(options) {
3508
+ const { projectName, runtime, example } = options;
3509
+ if (!projectName) {
3510
+ console.error("Error: Project name is required");
3511
+ console.error("Usage: vertz create <project-name>");
3512
+ process.exit(1);
3513
+ }
3514
+ const validName = /^[a-z0-9-]+$/.test(projectName);
3515
+ if (!validName) {
3516
+ console.error("Error: Project name must be lowercase alphanumeric with hyphens only");
3517
+ process.exit(1);
3518
+ }
3519
+ const validRuntimes = ["bun", "node", "deno"];
3520
+ const runtimeValue = (runtime || "bun").toLowerCase();
3521
+ if (!validRuntimes.includes(runtimeValue)) {
3522
+ console.error(`Error: Invalid runtime. Must be one of: ${validRuntimes.join(", ")}`);
3523
+ process.exit(1);
3524
+ }
3525
+ let includeExample;
3526
+ if (example === true) {
3527
+ includeExample = true;
3528
+ } else if (example === false) {
3529
+ includeExample = false;
3530
+ }
3531
+ const cliOptions = {
3532
+ projectName,
3533
+ runtime: runtimeValue,
3534
+ includeExample
3535
+ };
3536
+ try {
3537
+ const resolved = await resolveOptions(cliOptions);
3538
+ console.log(`Creating Vertz app: ${resolved.projectName}`);
3539
+ console.log(`Runtime: ${resolved.runtime}`);
3540
+ console.log(`Include example: ${resolved.includeExample ? "Yes" : "No"}`);
3541
+ const targetDir = process.cwd();
3542
+ await scaffold(targetDir, resolved);
3543
+ console.log(`
3544
+ ✓ Created ${resolved.projectName}`);
3545
+ console.log(`
3546
+ Next steps:`);
3547
+ console.log(` cd ${resolved.projectName}`);
3548
+ console.log(` bun install`);
3549
+ console.log(` bun run dev`);
3550
+ } catch (error) {
3551
+ if (error instanceof Error && error.message.includes("already exists")) {
3552
+ console.error(`
3553
+ Error: Directory "${projectName}" already exists.`);
3554
+ console.error("Please choose a different project name or remove the existing directory.");
3555
+ } else {
3556
+ console.error("Error:", error instanceof Error ? error.message : error);
3557
+ }
3558
+ process.exit(1);
3559
+ }
3560
+ }
3561
+
3562
+ // src/cli.ts
3563
+ function createCLI() {
3564
+ const program = new Command;
3565
+ program.name("vertz").description("Vertz CLI — build, check, and serve your Vertz app").version("0.1.0");
3566
+ program.command("create <name>").description("Scaffold a new Vertz project").option("-r, --runtime <runtime>", "Runtime to use (bun, node, deno)", "bun").option("-e, --example", "Include example health module").option("--no-example", "Exclude example health module").action(async (name, opts) => {
3567
+ await createAction({
3568
+ projectName: name,
3569
+ runtime: opts.runtime,
3570
+ example: opts.example
3571
+ });
3572
+ });
3573
+ program.command("check").description("Type-check and validate the project").option("--strict", "Enable strict mode").option("--format <format>", "Output format (text, json, github)", "text");
3574
+ program.command("build").description("Compile the project for production").option("--strict", "Enable strict mode").option("-o, --output <dir>", "Output directory", ".vertz/build").option("-t, --target <target>", "Build target (node, edge, worker)", "node").option("--no-typecheck", "Disable type checking").option("--no-minify", "Disable minification").option("--sourcemap", "Generate sourcemaps").option("-v, --verbose", "Verbose output").action(async (opts) => {
3575
+ const exitCode = await buildAction({
3576
+ strict: opts.strict,
3577
+ output: opts.output,
3578
+ target: opts.target,
3579
+ noTypecheck: opts.noTypecheck,
3580
+ noMinify: opts.noMinify,
3581
+ sourcemap: opts.sourcemap,
3582
+ verbose: opts.verbose
3583
+ });
3584
+ process.exit(exitCode);
3585
+ });
3586
+ program.command("dev").description("Start development server with hot reload (unified pipeline)").option("-p, --port <port>", "Server port", "3000").option("--host <host>", "Server host", "localhost").option("--open", "Open browser on start").option("--no-typecheck", "Disable background type checking").option("-v, --verbose", "Verbose output").action(async (opts) => {
3587
+ await devAction({
3588
+ port: parseInt(opts.port, 10),
3589
+ host: opts.host,
3590
+ open: opts.open,
3591
+ typecheck: opts.typecheck !== false && !opts.noTypecheck,
3592
+ verbose: opts.verbose
3593
+ });
3594
+ });
3595
+ program.command("generate [type] [name]").description("Generate a module, service, router, schema, or auto-discover domains").option("--dry-run", "Preview generated files without writing").option("--source-dir <dir>", "Source directory", "src").allowUnknownOption().action(async (type, name, options) => {
3596
+ if (!type) {
3597
+ await generateDomainAction(options);
3598
+ return;
3599
+ }
3600
+ const validTypes = ["module", "service", "router", "schema"];
3601
+ if (!validTypes.includes(type)) {
3602
+ await generateDomainAction(options);
3603
+ return;
3604
+ }
3605
+ const result = generateAction({
3606
+ type,
3607
+ name: name || "",
3608
+ module: options.module,
3609
+ sourceDir: options.sourceDir,
3610
+ dryRun: options.dryRun
3611
+ });
3612
+ if (!result.success) {
3613
+ console.error(result.error);
3614
+ process.exit(1);
3615
+ }
3616
+ });
3617
+ program.command("codegen").description("Generate SDK and CLI clients from the compiled API").option("--dry-run", "Preview generated files without writing").option("--output <dir>", "Output directory");
3618
+ program.command("routes").description("Display the route table").option("--format <format>", "Output format (table, json)", "table");
3619
+ return program;
3620
+ }
3621
+
3622
+ // bin/vertz.ts
3623
+ var program = createCLI();
3624
+ program.parse();