@aziontech/bundler 1.1.3 → 1.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.
@@ -0,0 +1,2290 @@
1
+ import { fetchContext as Ge, FirewallEventContext as qe, FetchEventContext as Ke, AsyncHooksContext as ye, StorageContext as Je, EnvVarsContext as Xe, NetworkListContext as Ye, fsContext as Ze, streamContext as Qe, cryptoContext as et, promisesContext as tt, KVContext as rt } from "@aziontech/builder/polyfills";
2
+ import { load as nt } from "@edge-runtime/primitives/dist/load.js";
3
+ import { D as k, p as st, u as ot, d as y, S as we, B as A, r as it, a as at, b as U, m as ct, e as lt, c as ft, w as ut, f as j, T as R, g as X, h as Y, i as ae, j as Fe, k as dt, l as ke, n as pt } from "./utils-CSEkDVys.js";
4
+ import * as _ from "@aziontech/utils/node";
5
+ import { getPackageManager as ht, feedback as d, copyDirectory as mt } from "@aziontech/utils/node";
6
+ import gt from "chokidar";
7
+ import ce, { existsSync as Ce, readFileSync as yt, promises as V } from "fs";
8
+ import T, { resolve as ue, join as C, relative as J, basename as z, extname as I, dirname as Ae } from "path";
9
+ import { runPhaseWithTelemetry as F, TelemetryCollector as wt, formatHeader as bt, formatBuildConfig as Et } from "@aziontech/bundler-telemetry";
10
+ import { resolvePresetConfig as Z, resolveApiVersion as Q, getFirewallReplacedKeys as vt, DEFAULT_API_VERSION as Tt, validateConfig as le, getApplicationName as St, getStorage as $t, processConfig as Pt, convertJsonConfigToObject as xt } from "@aziontech/config";
11
+ import m, { rm as de, mkdir as Oe, readFile as Ft, stat as kt, writeFile as Ct } from "fs/promises";
12
+ import te from "os";
13
+ import { executeESBuildBuild as At, executeWebpackBuild as Ot, createAzionWebpackConfig as _t, createAzionESBuildConfig as jt } from "@aziontech/builder";
14
+ import Ut from "lodash";
15
+ import { runInContext as pe } from "vm";
16
+ import { pathToFileURL as Rt } from "url";
17
+ import W from "node:vm";
18
+ import Nt from "net";
19
+ import { runServer as It } from "edge-runtime";
20
+ import * as ee from "@aziontech/presets";
21
+ import { listFrameworks as Bt } from "@netlify/framework-info";
22
+ import * as _e from "prettier";
23
+ import { cosmiconfig as Dt } from "cosmiconfig";
24
+ import { TypeScriptLoader as re } from "cosmiconfig-typescript-loader";
25
+ class Wt {
26
+ context;
27
+ constructor(t = {}) {
28
+ const r = W.createContext(
29
+ {},
30
+ {
31
+ name: "Edge Runtime",
32
+ codeGeneration: t.codeGeneration ?? {
33
+ strings: !1,
34
+ wasm: !0
35
+ }
36
+ }
37
+ );
38
+ this.context = t.extend?.(r) ?? r;
39
+ }
40
+ /**
41
+ * Allows to run arbitrary code within the VM.
42
+ */
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ evaluate(t) {
45
+ return W.runInContext(t, this.context, {
46
+ importModuleDynamically: async (r) => {
47
+ try {
48
+ return await import(Rt(ue(r)).href);
49
+ } catch {
50
+ process.env.DEBUG && console.warn(
51
+ ">>> [edge-runtime] dynamic import failed, returning empty module:",
52
+ r
53
+ );
54
+ const n = new W.SourceTextModule("export default {}", { context: this.context });
55
+ return await n.link(() => new W.SourceTextModule("export {}", { context: this.context })), await n.evaluate(), n;
56
+ }
57
+ }
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ });
60
+ }
61
+ }
62
+ let G, q;
63
+ class Mt extends Wt {
64
+ dispatchFetch;
65
+ constructor(t) {
66
+ super({
67
+ ...t,
68
+ extend: (r) => t?.extend ? t.extend(be(r)) : be(r)
69
+ }), Object.defineProperty(this.context, "__onUnhandledRejectionHandlers", {
70
+ set: Ht,
71
+ configurable: !1,
72
+ enumerable: !1
73
+ }), Object.defineProperty(this, "__rejectionHandlers", {
74
+ get: () => G,
75
+ configurable: !1,
76
+ enumerable: !1
77
+ }), Object.defineProperty(this.context, "__onErrorHandlers", {
78
+ set: Vt,
79
+ configurable: !1,
80
+ enumerable: !1
81
+ }), Object.defineProperty(this, "__errorHandlers", {
82
+ get: () => q,
83
+ configurable: !1,
84
+ enumerable: !1
85
+ }), this.evaluate(zt()), this.dispatchFetch = this.evaluate(Gt());
86
+ for (const r of je)
87
+ Lt(r, this.context);
88
+ t?.initialCode && this.evaluate(t.initialCode);
89
+ }
90
+ }
91
+ const je = [
92
+ "Object",
93
+ "Array",
94
+ "RegExp",
95
+ "Uint8Array",
96
+ "ArrayBuffer",
97
+ "Error",
98
+ "SyntaxError",
99
+ "TypeError"
100
+ ];
101
+ function Lt(e, t) {
102
+ const r = eval;
103
+ return t[/* @__PURE__ */ Symbol.for(`node:${e}`)] = r(e), pe(
104
+ `
105
+ globalThis.${e} = new Proxy(${e}, {
106
+ get(target, prop, receiver) {
107
+ if (prop === Symbol.hasInstance && receiver === globalThis.${e}) {
108
+ const nodeTarget = globalThis[Symbol.for('node:${e}')];
109
+ if (nodeTarget) {
110
+ return function(instance) {
111
+ return instance instanceof target || instance instanceof nodeTarget;
112
+ };
113
+ } else {
114
+ throw new Error('node target must exist')
115
+ }
116
+ }
117
+
118
+ return Reflect.get(target, prop, receiver);
119
+ }
120
+ })
121
+ `,
122
+ t
123
+ );
124
+ }
125
+ function Ht(e) {
126
+ G || process.on("unhandledRejection", function(r, n) {
127
+ G.forEach((o) => o({ reason: r, promise: n }));
128
+ }), G = e;
129
+ }
130
+ function Vt(e) {
131
+ q || process.on("uncaughtException", function(r) {
132
+ q.forEach((n) => n(r));
133
+ }), q = e;
134
+ }
135
+ function zt() {
136
+ return `
137
+ Object.defineProperty(self, '__listeners', {
138
+ configurable: false,
139
+ enumerable: false,
140
+ value: {},
141
+ writable: true,
142
+ })
143
+
144
+ function __conditionallyUpdatesHandlerList(eventType) {
145
+ if (eventType === 'unhandledrejection') {
146
+ self.__onUnhandledRejectionHandlers = self.__listeners[eventType];
147
+ } else if (eventType === 'error') {
148
+ self.__onErrorHandlers = self.__listeners[eventType];
149
+ }
150
+ }
151
+
152
+ function addEventListener(type, handler) {
153
+ const eventType = type.toLowerCase();
154
+ if (eventType === 'fetch' && self.__listeners.fetch) {
155
+ throw new TypeError('You can register just one "fetch" event listener');
156
+ }
157
+
158
+ self.__listeners[eventType] = self.__listeners[eventType] || [];
159
+ self.__listeners[eventType].push(handler);
160
+ __conditionallyUpdatesHandlerList(eventType);
161
+ }
162
+
163
+ function removeEventListener(type, handler) {
164
+ const eventType = type.toLowerCase();
165
+ if (self.__listeners[eventType]) {
166
+ self.__listeners[eventType] = self.__listeners[eventType].filter(item => {
167
+ return item !== handler;
168
+ });
169
+
170
+ if (self.__listeners[eventType].length === 0) {
171
+ delete self.__listeners[eventType];
172
+ }
173
+ }
174
+ __conditionallyUpdatesHandlerList(eventType);
175
+ }
176
+ `;
177
+ }
178
+ function Gt() {
179
+ return `(async function dispatchFetch(input, init) {
180
+ const request = new Request(input, init);
181
+ const event = new FetchEvent(request);
182
+ if (!self.__listeners.fetch) {
183
+ throw new Error("No fetch event listeners found");
184
+ }
185
+
186
+ const getResponse = ({ response, error }) => {
187
+ if (error || !response || !(response instanceof Response)) {
188
+ console.error(error ? error.toString() : 'The event listener did not respond')
189
+ response = new Response(null, {
190
+ statusText: 'Internal Server Error',
191
+ status: 500
192
+ })
193
+ }
194
+
195
+ response.waitUntil = () => Promise.all(event.awaiting);
196
+
197
+ if (response.status < 300 || response.status >= 400 ) {
198
+ response.headers.delete('content-encoding');
199
+ response.headers.delete('transform-encoding');
200
+ response.headers.delete('content-length');
201
+ }
202
+
203
+ return response;
204
+ }
205
+
206
+ try {
207
+ await self.__listeners.fetch[0].call(event, event)
208
+ } catch (error) {
209
+ return getResponse({ error })
210
+ }
211
+
212
+ return Promise.resolve(event.response)
213
+ .then(response => getResponse({ response }))
214
+ .catch(error => getResponse({ error }))
215
+ })`;
216
+ }
217
+ function be(e) {
218
+ O(e, "self", { enumerable: !0, value: e }), O(e, "globalThis", { value: e }), O(e, "Symbol", { value: Symbol }), O(e, "clearInterval", { value: clearInterval }), O(e, "clearTimeout", { value: clearTimeout }), O(e, "queueMicrotask", { value: queueMicrotask }), O(e, "EdgeRuntime", { value: "edge-runtime" });
219
+ const t = Kt(e);
220
+ return qt(e, {
221
+ exports: nt({
222
+ ...t,
223
+ WeakRef: pe("WeakRef", e)
224
+ }),
225
+ enumerable: ["crypto"],
226
+ nonenumerable: [
227
+ // Crypto
228
+ "Crypto",
229
+ "CryptoKey",
230
+ "SubtleCrypto",
231
+ // Fetch APIs
232
+ "fetch",
233
+ "File",
234
+ "FormData",
235
+ "Headers",
236
+ "Request",
237
+ "Response",
238
+ "WebSocket",
239
+ // Structured Clone
240
+ "structuredClone",
241
+ // Blob
242
+ "Blob",
243
+ // URL
244
+ "URL",
245
+ "URLSearchParams",
246
+ "URLPattern",
247
+ // AbortController
248
+ "AbortController",
249
+ "AbortSignal",
250
+ "DOMException",
251
+ // Streams
252
+ "ReadableStream",
253
+ "ReadableStreamBYOBReader",
254
+ "ReadableStreamDefaultReader",
255
+ "TextDecoderStream",
256
+ "TextEncoderStream",
257
+ "TransformStream",
258
+ "WritableStream",
259
+ "WritableStreamDefaultWriter",
260
+ // Encoding
261
+ "atob",
262
+ "btoa",
263
+ "TextEncoder",
264
+ "TextDecoder",
265
+ // Events
266
+ "Event",
267
+ "EventTarget",
268
+ "FetchEvent",
269
+ "PromiseRejectionEvent",
270
+ // Console
271
+ "console",
272
+ // Timers
273
+ "setTimeout",
274
+ "setInterval"
275
+ ]
276
+ }), e;
277
+ }
278
+ function O(e, t, r) {
279
+ Object.defineProperty(e, t, {
280
+ configurable: r.configurable ?? !1,
281
+ enumerable: r.enumerable ?? !1,
282
+ value: r.value,
283
+ writable: r.writable ?? !0
284
+ });
285
+ }
286
+ function qt(e, t) {
287
+ for (const r of t.enumerable ?? []) {
288
+ if (!t.exports[r])
289
+ throw new Error(`Attempt to export a nullable value for "${r}"`);
290
+ O(e, r, {
291
+ enumerable: !0,
292
+ value: t.exports[r]
293
+ });
294
+ }
295
+ for (const r of t.nonenumerable ?? []) {
296
+ if (!t.exports[r])
297
+ throw new Error(`Attempt to export a nullable value for "${r}"`);
298
+ O(e, r, {
299
+ value: t.exports[r]
300
+ });
301
+ }
302
+ }
303
+ function Kt(e) {
304
+ const r = `({${je.join(",")}})`;
305
+ return pe(r, e);
306
+ }
307
+ function Jt() {
308
+ const e = C(process.cwd(), k.OUTPUT_ENV_VARS_PATH);
309
+ if (!Ce(e)) return { ...process.env };
310
+ const t = yt(e, "utf-8");
311
+ return Object.fromEntries(
312
+ st(t).map(({ key: r, value: n }) => [r, ot(n)])
313
+ );
314
+ }
315
+ function Ue(e, t = !1) {
316
+ const r = /switch \((\w+)\) \{\n(\s+)case Object:/g;
317
+ e = e.replace(r, (s, i, a) => `if (${i} != null && ${i} !== Object && ${i}.name === "Object") ${i} = Object;
318
+ ${a}` + s);
319
+ const n = (s) => (s.RESERVED_FETCH = s.fetch.bind(s), s.fetch = async (i, a) => Ge(
320
+ s,
321
+ i,
322
+ a,
323
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
324
+ globalThis?.AZION_BUCKET_NAME,
325
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
326
+ globalThis?.AZION_BUCKET_PREFIX
327
+ ), s.FetchEvent = t ? qe : Ke, s.Response = t ? Response : s.Response, s.eval = eval, s.process = { env: Jt() }, s.File = void 0, s.WebSocket = void 0, s.ASYNC_LOCAL_STORAGE = ye, s.AsyncLocalStorage = ye.AsyncLocalStorage, s.STORAGE_CONTEXT = Je, s.ENV_VARS_CONTEXT = Xe, s.NETWORK_LIST_CONTEXT = Ye, s.FS_CONTEXT = Ze, s.STREAM_CONTEXT = Qe, s.CRYPTO_CONTEXT = et, s.TextDecoderStream = TextDecoderStream, s.TextEncoderStream = TextEncoderStream, s.perfomance = { now: performance.now }, s.CompressionStream = CompressionStream, s.CountQueuingStrategy = CountQueuingStrategy, s.DecompressionStream = DecompressionStream, s.Promise = Promise, s.Promise.withResolvers = tt, s.KV_CONTEXT = rt, s);
328
+ return new Mt({ extend: n, initialCode: e, codeGeneration: { strings: !0 } });
329
+ }
330
+ const B = (e) => {
331
+ if (!e) return;
332
+ const t = T.resolve(process.cwd(), e);
333
+ if (!(ce.statSync(t, { throwIfNoEntry: !1 })?.isFile() ?? !1))
334
+ throw new Error(`Config file not found: ${t}`);
335
+ return t;
336
+ };
337
+ class Re extends Error {
338
+ constructor(t, r) {
339
+ super(t), this.code = r, this.name = "PackageJsonError";
340
+ }
341
+ code;
342
+ }
343
+ class Xt extends Error {
344
+ constructor(t) {
345
+ super(`Please install dependencies using ${t}`), this.name = "DependenciesError";
346
+ }
347
+ }
348
+ const Yt = async () => {
349
+ const e = C(process.cwd(), "package.json");
350
+ try {
351
+ const t = await Ft(e, "utf8");
352
+ return JSON.parse(t);
353
+ } catch (t) {
354
+ throw new Re("Failed to read package.json", t.code);
355
+ }
356
+ }, Zt = async () => {
357
+ const e = C(process.cwd(), "node_modules");
358
+ try {
359
+ return (await kt(e)).isDirectory();
360
+ } catch {
361
+ return !1;
362
+ }
363
+ }, Qt = async () => {
364
+ let e;
365
+ try {
366
+ e = await Yt();
367
+ } catch (t) {
368
+ if (t instanceof Re && t.code === "ENOENT")
369
+ return;
370
+ throw t;
371
+ }
372
+ if (e && (e.dependencies || e.devDependencies)) {
373
+ const t = await ht();
374
+ if (!await Zt())
375
+ throw new Xt(t);
376
+ }
377
+ };
378
+ function M({
379
+ inputValue: e,
380
+ fileValue: t,
381
+ storeValue: r,
382
+ defaultValue: n
383
+ }) {
384
+ return ((i) => i === "true" ? !0 : i === "false" ? !1 : i)(e ?? t ?? r ?? n);
385
+ }
386
+ const er = (e, t) => {
387
+ const r = Object.keys(e).map((s) => {
388
+ const a = (s.endsWith(".js") ? s : `${s}.js`).replace(/\.dev\.js$/, ".js");
389
+ return `./${J(k.OUTPUT_BASE_PATH, a)}`;
390
+ }), n = (t ?? []).map((s, i) => ({ func: s, index: i })).filter(({ func: s }) => s.path && !r.includes(s.path));
391
+ if (n.length === 0) return;
392
+ const o = n.map(({ func: s, index: i }) => {
393
+ const a = s.path, c = r[i];
394
+ if (c)
395
+ return ` - functions[${i}] ("${s.name}"): configured path "${a}" does not match generated output "${C(k.OUTPUT_BASE_PATH, c)}". Update the path to "${c}" in azion.config`;
396
+ const l = r.map((f) => `"${f}"`).join(", ");
397
+ return ` - functions[${i}] ("${s.name}"): configured path "${a}" does not match any generated output. Update the path in azion.config to one of: ${l}`;
398
+ }).join(`
399
+ `);
400
+ throw new Error(
401
+ `The "path" declared for the following function(s) in azion.config does not match the file(s) generated by the build:
402
+ ${o}`
403
+ );
404
+ }, tr = async (e) => {
405
+ try {
406
+ await Promise.all(
407
+ e.map(async (t) => {
408
+ try {
409
+ await de(t, { recursive: !0, force: !0 });
410
+ } catch (r) {
411
+ if (r.code !== "ENOENT")
412
+ throw r;
413
+ }
414
+ await Oe(t, { recursive: !0 });
415
+ })
416
+ );
417
+ } catch (t) {
418
+ throw new Error(`Failed to clean directories: ${t}`);
419
+ }
420
+ }, rr = (e) => `//---
421
+ //storages:
422
+ // - name: assets
423
+ // bucket: ${e.bucket}
424
+ // prefix: ${e.prefix}
425
+ //---
426
+ /* this temporary binding is used to inject the storage name and prefix into the function file */
427
+ globalThis.AZION_BUCKET_NAME = '${e.bucket}';
428
+ globalThis.AZION_BUCKET_PREFIX = '${e.prefix}';`, nr = async (e) => {
429
+ try {
430
+ return await m.access(e), !0;
431
+ } catch {
432
+ return !1;
433
+ }
434
+ }, sr = (e) => T.isAbsolute(e) ? e : T.resolve(process.cwd(), k.OUTPUT_BASE_PATH, e), or = (e, t) => t.find((r) => r.name === e), ir = async (e, t, r) => {
435
+ if (!e.path) {
436
+ y.warn(`Function ${e.name} does not have a defined path`);
437
+ return;
438
+ }
439
+ const n = e.bindings?.storage;
440
+ if (!n) {
441
+ y.info(`Function ${e.name} does not have storage bindings`);
442
+ return;
443
+ }
444
+ const o = sr(
445
+ e.path.replace(/\.js$/, r ? ".js" : ".dev.js")
446
+ );
447
+ if (!await nr(o)) {
448
+ d.bindings.warn(`Function file not found: ${o}.`), d.bindings.info(`Binding injection skipped for function ${e.name}`);
449
+ return;
450
+ }
451
+ try {
452
+ const s = await m.readFile(o, "utf-8");
453
+ if (s.includes("//storages:") || s.includes("//---")) {
454
+ y.info(`Function ${e.name} already has injected bindings`);
455
+ return;
456
+ }
457
+ const i = String(n.bucket), a = or(i, t);
458
+ if (!a) {
459
+ y.warn(`Storage '${i}' not found for function ${e.name}`);
460
+ return;
461
+ }
462
+ const c = n.prefix, l = c || a.prefix;
463
+ c || d.postbuild.info(
464
+ `No prefix provided for binding in function '${e.name}', using storage prefix: ${l}`
465
+ );
466
+ const f = rr({
467
+ bucket: i,
468
+ prefix: l
469
+ });
470
+ y.info(`Generated binding template for ${e.name}: ${f}`);
471
+ const u = `${f}
472
+ ${s}`;
473
+ await m.writeFile(o, u), y.info(`Bindings injected into ${o} for function ${e.name}`);
474
+ } catch (s) {
475
+ throw y.error(`Failed to process bindings for function ${e.name}:`, s), s;
476
+ }
477
+ }, ar = async ({
478
+ config: e,
479
+ storageSetup: t,
480
+ isProduction: r
481
+ }) => {
482
+ try {
483
+ const n = e.functions || [];
484
+ if (n.length === 0) {
485
+ y.info("No functions found to inject bindings");
486
+ return;
487
+ }
488
+ y.info("Injecting bindings into functions..."), await Promise.all(
489
+ n.map((o) => ir(o, t, r))
490
+ );
491
+ } catch (n) {
492
+ return y.error("Failed to execute bindings setup:", n), Promise.reject(n);
493
+ }
494
+ }, Ne = (e, t) => {
495
+ const r = Z(e, t).build, n = e.config.build;
496
+ return {
497
+ entry: r?.entry ?? n?.entry,
498
+ bundler: r?.bundler ?? n?.bundler
499
+ };
500
+ }, cr = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10).replace(/-/g, ""), lr = async ({
501
+ entry: e,
502
+ ext: t = "js",
503
+ basePath: r = ".edge/functions",
504
+ production: n = !0,
505
+ bundler: o
506
+ }) => {
507
+ const s = cr(), i = (a, c) => {
508
+ const l = z(a, I(a)), f = Ae(a), u = `azion-${l}-${s}.temp.${t}`, p = ue(f, u), g = o === "webpack" ? ".js" : "", h = n ? "" : ".dev";
509
+ let S;
510
+ if (c) {
511
+ const E = c.replace(/\.[^/.]+$/, "");
512
+ S = C(r, `${E}${h}${g}`);
513
+ } else
514
+ S = C(r, f, `${l}${h}${g}`);
515
+ return { [S]: p };
516
+ };
517
+ if (typeof e == "string") {
518
+ const c = `${z(e, I(e))}${n ? "" : ".dev"}`;
519
+ return { ...i(e, c) };
520
+ }
521
+ return Array.isArray(e) ? e.reduce((a, c) => {
522
+ const f = `${z(c, I(c))}${n ? "" : ".dev"}`;
523
+ return { ...a, ...i(c, f) };
524
+ }, {}) : Object.entries(e).reduce(
525
+ (a, [c, l]) => ({ ...a, ...i(l, c) }),
526
+ {}
527
+ );
528
+ }, fr = async (e, t, r) => {
529
+ const n = Ne(t, Q(e));
530
+ let o = {};
531
+ const s = e.build?.entry, i = async (a) => await lr({
532
+ entry: a,
533
+ ext: t.metadata.ext ?? A.DEFAULT_OUTPUT_EXTENSION,
534
+ production: r,
535
+ bundler: e.build?.bundler ?? n.bundler ?? we.DEFAULT
536
+ });
537
+ if (s ? o = await i(s) : n.entry ? o = await i(n.entry) : t.handler && (o = await i(A.DEFAULT_HANDLER_FILENAME)), Object.keys(o).length === 0) {
538
+ const a = n.entry ? `(default is "${n.entry}")` : "";
539
+ throw new Error(
540
+ `No entry point found ${a}. Please specify one using --entry or create a default entry file in your project.`
541
+ );
542
+ }
543
+ return {
544
+ ...e.build,
545
+ entry: o,
546
+ bundler: e.build?.bundler ?? n.bundler ?? we.DEFAULT,
547
+ preset: t,
548
+ setup: {
549
+ contentToInject: void 0,
550
+ defineVars: {}
551
+ },
552
+ polyfills: !!e.build?.polyfills
553
+ };
554
+ }, ur = (e, t) => jt(e, t), dr = (e, t) => _t(e, t), pr = async (e) => At(e), hr = async (e) => Ot(e), L = {
555
+ createAzionESBuildConfigWrapper: ur,
556
+ createAzionWebpackConfigWrapper: dr,
557
+ executeESBuildBuildWrapper: pr,
558
+ executeWebpackBuildWrapper: hr
559
+ }, mr = (e) => {
560
+ const t = /import\s+.*?from\s*['"](.*?)['"];?/g, r = /(const\s+.*?=\s*require\(.*\).*);/g, n = (e.match(t) || []).map((i) => i.trim()), o = (e.match(r) || []).map((i) => i.trim());
561
+ let s = e.replace(t, "").replace(r, "").replace(/\n\s*\n\s*\n/g, `
562
+
563
+ `);
564
+ return (n.length || o.length) && (s = `${[...n, ...o].join(`
565
+ `)}
566
+
567
+ ${s.trim()}`), s;
568
+ }, gr = (e, t, r) => t.polyfills && r.production ? `import SRC_NODE_FS from "node:fs";
569
+ ${e}` : e, H = async (e, t, r, n, o, s) => !e || !t ? s() : F(
570
+ e,
571
+ t,
572
+ r,
573
+ n,
574
+ o,
575
+ s
576
+ ), yr = async ({
577
+ buildConfig: e,
578
+ prebuildResult: t,
579
+ ctx: r,
580
+ telemetry: n,
581
+ telemetryEnabled: o,
582
+ telemetryOutputFormat: s
583
+ }) => {
584
+ try {
585
+ const i = typeof e.entry == "string" ? [e.entry] : Array.isArray(e.entry) ? e.entry : Object.values(e.entry);
586
+ if (t.filesToInject.length > 0) {
587
+ const c = await Promise.all(
588
+ t.filesToInject.map((l) => m.readFile(l, "utf-8"))
589
+ ).then((l) => l.join(" "));
590
+ await Promise.all(
591
+ i.map(async (l) => {
592
+ const f = await m.readFile(l, "utf-8"), u = `${c} ${f}`, p = mr(u);
593
+ return m.writeFile(l, p);
594
+ })
595
+ );
596
+ }
597
+ const a = {
598
+ ...e,
599
+ setup: {
600
+ contentToInject: t.injection.banner,
601
+ defineVars: Object.fromEntries(
602
+ // Get all entries from defineVars
603
+ Object.entries(t.bundler.defineVars).filter(([c, l]) => l !== void 0).map(([c, l]) => [c, l])
604
+ )
605
+ }
606
+ };
607
+ return await wr(a, r, n, o, s), Promise.all(
608
+ Object.entries(a.entry).map(async ([c]) => {
609
+ const l = c.endsWith(".js") ? c : `${c}.js`, f = await m.readFile(l, "utf-8");
610
+ if (!r.production) return f;
611
+ const u = gr(
612
+ f,
613
+ e,
614
+ r
615
+ );
616
+ return await m.writeFile(l, u), u;
617
+ })
618
+ );
619
+ } catch (i) {
620
+ return Promise.reject(i);
621
+ }
622
+ }, wr = async (e, t, r, n, o) => {
623
+ switch (e.bundler) {
624
+ case "esbuild": {
625
+ A.IS_DEBUG && (d.build.info("=== System Info ==="), d.build.info("CPUs:", te.cpus().length), d.build.info("Total Memory:", te.totalmem() / 1024 / 1024, "MB"), d.build.info("Free Memory:", te.freemem() / 1024 / 1024, "MB"));
626
+ const s = await H(
627
+ r,
628
+ n,
629
+ o,
630
+ "esbuild-config-create",
631
+ "ESBuild Config Create",
632
+ async () => L.createAzionESBuildConfigWrapper(e, t)
633
+ );
634
+ let i, a;
635
+ A.IS_DEBUG && (d.build.info("=== Build Test ==="), i = Date.now(), a = process.memoryUsage());
636
+ const c = await H(
637
+ r,
638
+ n,
639
+ o,
640
+ "esbuild-execution",
641
+ "ESBuild Execution",
642
+ async () => L.executeESBuildBuildWrapper(s)
643
+ );
644
+ if (A.IS_DEBUG) {
645
+ const l = Date.now() - i, f = process.memoryUsage();
646
+ d.build.info("=== Results ==="), d.build.info("Duration:", l, "ms");
647
+ const u = {
648
+ heapUsed: `${(f.heapUsed - a.heapUsed) / 1024 / 1024} MB`,
649
+ rss: `${(f.rss - a.rss) / 1024 / 1024} MB`
650
+ };
651
+ d.build.info("Memory heapUsed:", u.heapUsed), d.build.info("Memory rss:", u.rss);
652
+ }
653
+ return c;
654
+ }
655
+ case "webpack": {
656
+ const s = await H(
657
+ r,
658
+ n,
659
+ o,
660
+ "webpack-config-create",
661
+ "Webpack Config Create",
662
+ async () => L.createAzionWebpackConfigWrapper(e, t)
663
+ );
664
+ return H(
665
+ r,
666
+ n,
667
+ o,
668
+ "webpack-execution",
669
+ "Webpack Execution",
670
+ async () => L.executeWebpackBuildWrapper(s)
671
+ );
672
+ }
673
+ default:
674
+ throw new Error(`Unsupported bundler: ${e.bundler}`);
675
+ }
676
+ }, br = (e, t) => {
677
+ const r = (n, o) => {
678
+ if (n && !n.build || Array.isArray(n) && !Array.isArray(o))
679
+ return o;
680
+ };
681
+ return Ut.mergeWith({}, e, t, r);
682
+ }, Er = { mergeConfigWithUserOverrides: br }, Ee = async ({
683
+ config: e,
684
+ preset: t,
685
+ configFile: r
686
+ }) => {
687
+ try {
688
+ const n = Q(e), o = Z(t, n);
689
+ e.firewall && vt(n).forEach((c) => {
690
+ delete o[c];
691
+ });
692
+ let s = Er.mergeConfigWithUserOverrides(
693
+ o,
694
+ e
695
+ );
696
+ const i = { ...s };
697
+ return delete i.version, s = { version: n, ...i }, s.build?.preset || (s.build = {
698
+ ...s.build,
699
+ preset: t.metadata.name,
700
+ ...!t.handler && e.build?.entry && {
701
+ entry: e.build?.entry
702
+ }
703
+ }), !await $e.readAzionConfig(r) && !r && await $e.writeUserConfig(s), s;
704
+ } catch (n) {
705
+ throw new Error(`Failed to set environment: ${n.message}`);
706
+ }
707
+ }, ve = (e) => e ? typeof e == "string" ? [e] : Array.isArray(e) ? e : Object.values(e) : [], vr = async ({
708
+ entrypoint: e,
709
+ preset: t,
710
+ version: r
711
+ }) => {
712
+ if (e && !t.handler) {
713
+ const o = ve(e), s = o.map((i) => T.resolve(i));
714
+ return await Promise.all(
715
+ s.map(async (i) => {
716
+ try {
717
+ await m.access(i);
718
+ } catch (a) {
719
+ throw y.error(a), new Error(
720
+ `Entry point "${J(process.cwd(), i)}" was not found.
721
+ - Fix the "build.entry" property in your azion.config, or
722
+ - Pass the correct file via the --entry flag.
723
+ If not specified, the entry defaults to index.ts or index.js" in the project root.`
724
+ );
725
+ }
726
+ })
727
+ ), _.feedback.build.info(
728
+ `Using entry point(s): ${o.map((i) => J(process.cwd(), i)).join(", ")}`
729
+ ), s;
730
+ }
731
+ if (t.handler) {
732
+ const o = globalThis.bundler.root.includes("node_modules") ? T.resolve(globalThis.bundler.root, "../../") : T.resolve(globalThis.bundler.root, "node_modules"), s = T.resolve(
733
+ o,
734
+ "@aziontech/presets/dist/presets",
735
+ t.metadata.name,
736
+ "handler.js"
737
+ );
738
+ try {
739
+ await m.access(s);
740
+ } catch (i) {
741
+ throw y.error(i), new Error(
742
+ `Missing handler "${s}" (default for "${t.metadata.name}" preset). Either create this file or specify a custom entry point using --entry.`
743
+ );
744
+ }
745
+ return _.feedback.build.info(`Using built-in handler from "${t.metadata.name}" preset.`), [s];
746
+ }
747
+ const n = Ne(t, r).entry;
748
+ if (n) {
749
+ const o = ve(n), s = o.map((i) => T.resolve(i));
750
+ return await Promise.all(
751
+ s.map(async (i) => {
752
+ try {
753
+ await m.access(i);
754
+ } catch (a) {
755
+ throw y.error(a), new Error(
756
+ `Missing default entry point "${i}" for "${t.metadata.name}" preset. Either create this file or specify a custom entry point using --entry.`
757
+ );
758
+ }
759
+ })
760
+ ), _.feedback.build.info(`Using preset default entry: ${o.join(", ")}`), s;
761
+ }
762
+ throw new Error(
763
+ "Cannot determine entry point. Please specify one using --entry or in your configuration."
764
+ );
765
+ }, Tr = async ({ buildConfig: e, ctx: t }) => {
766
+ const { postbuild: r } = e.preset;
767
+ r && await r(e, { ...t });
768
+ }, Sr = async ({
769
+ namespace: e,
770
+ property: t,
771
+ dirs: r
772
+ }) => {
773
+ const n = {}, o = async (s) => {
774
+ await Promise.all(
775
+ s.map(async (i) => {
776
+ const a = await m.readdir(i);
777
+ await Promise.all(
778
+ a.map(async (c) => {
779
+ const l = C(i, c), f = await m.stat(l);
780
+ if (f.isDirectory())
781
+ await o([l]);
782
+ else if (f.isFile()) {
783
+ const u = await m.readFile(l);
784
+ let p = l;
785
+ l.startsWith("/") || (p = `/${l}`), n[p] = { content: u.toString("base64") };
786
+ }
787
+ })
788
+ );
789
+ })
790
+ );
791
+ };
792
+ return await o(r), `globalThis.${e}.${t}=${JSON.stringify(n)};`;
793
+ }, $r = async ({ dirs: e, prefix: t, outputPath: r }) => {
794
+ await Promise.all(
795
+ e.map(async (n) => {
796
+ const o = t ? n.replace(t, "") : n, s = C(r, o);
797
+ await m.access(s).then(() => !0).catch(() => !1) || await m.mkdir(s, { recursive: !0 }), await m.cp(n, s, { recursive: !0 });
798
+ })
799
+ );
800
+ }, Pr = ({ namespace: e, property: t, vars: r }) => Object.entries(r).reduce(
801
+ (n, [o, s]) => {
802
+ const i = t ? `${e}.${t}` : e;
803
+ return `${n} globalThis.${i}.${o}=${s};`;
804
+ },
805
+ t ? `globalThis.${e}.${t}={};` : `globalThis.${e}={};`
806
+ ), xr = async (e, t) => {
807
+ const r = it(t);
808
+ if (!r) return {};
809
+ const n = await at(e, !0);
810
+ return n.length === 0 ? {} : Object.fromEntries(
811
+ n.map(({ key: o }) => [`process.env.${o}`, `process.env.${r}${o}`])
812
+ );
813
+ }, Fr = async ({
814
+ namespace: e,
815
+ property: t,
816
+ prefix: r
817
+ }) => `globalThis.${e} = { ...globalThis.${e}, ${t}: '${r && typeof r == "string" && r !== "" ? r : '""'}'};`, N = {
818
+ injectWorkerMemoryFiles: Sr,
819
+ copyFilesToLocalEdgeStorage: $r,
820
+ injectWorkerGlobals: Pr,
821
+ injectWorkerPathPrefix: Fr,
822
+ buildEnvAliasDefineVars: xr
823
+ }, kr = {
824
+ filesToInject: [],
825
+ injection: {
826
+ globals: {}
827
+ },
828
+ bundler: {
829
+ defineVars: {},
830
+ plugins: []
831
+ }
832
+ }, Cr = async ({
833
+ buildConfig: e,
834
+ ctx: t,
835
+ applicationName: r
836
+ }) => {
837
+ const n = await e.preset.prebuild?.(e, t) || kr, o = N.injectWorkerGlobals({
838
+ namespace: A.NAMESPACE,
839
+ // Transform globals object:
840
+ // 1. Convert object to entries
841
+ // 2. Remove any entries with undefined values
842
+ // 3. Ensure remaining values are typed as string
843
+ vars: Object.fromEntries(
844
+ Object.entries(n.injection?.globals || {}).filter(([l, f]) => f !== void 0).map(([l, f]) => [l, f])
845
+ )
846
+ }), s = await N.injectWorkerMemoryFiles({
847
+ namespace: A.NAMESPACE,
848
+ property: "__FILES__",
849
+ dirs: e.memoryFS?.injectionDirs || []
850
+ });
851
+ e.memoryFS && N.copyFilesToLocalEdgeStorage({
852
+ dirs: e.memoryFS?.injectionDirs,
853
+ prefix: e.memoryFS?.removePathPrefix,
854
+ outputPath: k.OUTPUT_STORAGE_PATH
855
+ });
856
+ const i = await N.injectWorkerPathPrefix({
857
+ namespace: A.NAMESPACE,
858
+ property: "FS_PATH_PREFIX_TO_REMOVE",
859
+ prefix: e.memoryFS?.removePathPrefix || ""
860
+ }), a = `${o}${i}
861
+ ${s}`, c = t.production ? await N.buildEnvAliasDefineVars(process.cwd(), r) : {};
862
+ return {
863
+ filesToInject: n.filesToInject || [],
864
+ injection: {
865
+ globals: n.injection?.globals || {},
866
+ entry: "",
867
+ banner: a
868
+ },
869
+ bundler: {
870
+ defineVars: { ...n.bundler?.defineVars, ...c },
871
+ plugins: n.bundler?.plugins || []
872
+ }
873
+ };
874
+ }, Ar = ({ projectDir: e = process.cwd() }) => Bt({
875
+ projectDir: e
876
+ }), Or = { listFrameworks: Ar };
877
+ async function _r() {
878
+ try {
879
+ const e = await Or.listFrameworks({
880
+ projectDir: process.cwd()
881
+ });
882
+ if (e[0]?.id && Object.values(ee).some(
883
+ (i) => i.metadata?.name === e[0].id
884
+ ))
885
+ return e[0].id;
886
+ const t = C(process.cwd(), "tsconfig.json");
887
+ return ce.existsSync(t) || ce.readdirSync(process.cwd()).some((s) => [".ts", ".tsx"].includes(I(s))) ? "typescript" : "javascript";
888
+ } catch {
889
+ return "javascript";
890
+ }
891
+ }
892
+ const jr = { inferPreset: _r }, Ur = (e) => Object.values(ee).find((t) => t.metadata?.name === e), Rr = async (e) => {
893
+ if (e) {
894
+ const t = typeof e == "string" ? e : e.metadata?.name;
895
+ _.feedback.build.info(`Using preset: ${t}`);
896
+ }
897
+ if (e || (_.feedback.build.info("No preset specified, using automatic detection..."), e = await jr.inferPreset(), _.feedback.build.info(`Detected preset: ${e}`)), typeof e == "string") {
898
+ const t = Ur(e);
899
+ if (!t)
900
+ throw new Error(`Invalid build preset name: '${e}'`);
901
+ return t;
902
+ }
903
+ return e;
904
+ }, Nr = () => `${Date.now()}`, Ie = async (e) => {
905
+ try {
906
+ return await m.access(e), (await m.stat(e)).isDirectory();
907
+ } catch {
908
+ return !1;
909
+ }
910
+ }, Ir = async (e, t) => {
911
+ try {
912
+ const r = k.OUTPUT_STORAGE_METADATA_PATH;
913
+ let n = [];
914
+ try {
915
+ const s = await m.readFile(r, "utf-8");
916
+ n = JSON.parse(s);
917
+ } catch {
918
+ y.info("Creating new storage metadata file");
919
+ }
920
+ const o = {
921
+ ...t,
922
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
923
+ };
924
+ n = n.filter((s) => s.name !== e), n.push(o), await m.writeFile(r, JSON.stringify(n, null, 2), "utf-8"), y.info(`Storage metadata saved for: ${e}`);
925
+ } catch (r) {
926
+ throw y.error(`Failed to save storage metadata for ${e}:`, r), r;
927
+ }
928
+ }, Br = async (e, t, r, n) => {
929
+ const o = e.name;
930
+ try {
931
+ const s = T.join(r, o, n);
932
+ await m.mkdir(T.join(r, o), { recursive: !0 });
933
+ try {
934
+ const i = await m.readdir(T.join(r, o));
935
+ await Promise.all(
936
+ i.filter((a) => a !== n).map(async (a) => {
937
+ const c = T.join(r, o, a);
938
+ try {
939
+ const l = await m.lstat(c);
940
+ l.isSymbolicLink() ? await m.unlink(c) : l.isDirectory() ? await m.rm(c, { recursive: !0, force: !0 }) : await m.unlink(c);
941
+ } catch (l) {
942
+ y.warn(`Failed to remove ${c}:`, l);
943
+ }
944
+ })
945
+ ), y.info(`Cleaned up existing storage items in: ${T.join(r, o)}`);
946
+ } catch {
947
+ y.warn(`Storage directory not found or empty: ${T.join(r, o)}`);
948
+ }
949
+ try {
950
+ const i = await m.lstat(s);
951
+ i.isSymbolicLink() ? (await m.unlink(s), y.info(`Removed existing symlink: ${s}`)) : i.isDirectory() && (await m.rm(s, { recursive: !0, force: !0 }), y.info(`Removed existing directory: ${s}`));
952
+ } catch {
953
+ }
954
+ await m.symlink(t, s, "dir"), y.info(`Storage link created: ${o} -> ${t}`), await Ir(o, {
955
+ name: o,
956
+ workloadsAccess: e.workloadsAccess || "read_only",
957
+ sourceDir: t,
958
+ targetDir: s,
959
+ prefix: n
960
+ });
961
+ } catch (s) {
962
+ throw y.error(`Failed to create storage link for ${o}:`, s), s;
963
+ }
964
+ }, Dr = (e) => !e.name || !e.dir ? (y.warn("Storage configuration is missing required fields (name or dir)"), !1) : !0, Wr = async (e) => {
965
+ const r = (e && Z(e, Tt))?.storage?.[0]?.dir;
966
+ if (!r)
967
+ return y.info("The preset has no static files directory to copy to the v3 storage"), [];
968
+ const n = T.resolve(process.cwd(), r);
969
+ if (!await Ie(n))
970
+ throw new Error(
971
+ `Storage directory not found: ${n}.
972
+ - Please check the output directory of the "${e?.metadata.name}" preset`
973
+ );
974
+ return mt(n, k.OUTPUT_STORAGE_PATH), d.storage.info(`Static files copied to ${k.OUTPUT_STORAGE_PATH}`), [];
975
+ }, Mr = async ({
976
+ config: e,
977
+ preset: t
978
+ }) => {
979
+ if (Q(e) === 3) return Wr(t);
980
+ try {
981
+ const r = e.storage || [], n = [];
982
+ if (r.length === 0)
983
+ return y.info("No storages found to setup"), n;
984
+ await m.mkdir(k.OUTPUT_STORAGE_PATH, { recursive: !0 });
985
+ for (const o of r) {
986
+ if (!Dr(o))
987
+ continue;
988
+ const s = T.resolve(process.cwd(), o.dir);
989
+ if (!await Ie(s))
990
+ throw new Error(
991
+ `Storage directory not found: ${s}.
992
+ - Please check the path provided in the azion.config file on storage[].dir`
993
+ );
994
+ const i = o.prefix, a = i || Nr();
995
+ i || d.storage.info(
996
+ `No prefix provided for storage '${o.name}', generating version prefix: ${a}`
997
+ ), i && d.storage.info(`Using provided prefix for storage '${o.name}': ${a}`), await Br(o, s, k.OUTPUT_STORAGE_PATH, a), n.push({
998
+ ...o,
999
+ prefix: a
1000
+ });
1001
+ }
1002
+ return y.info("Storage setup completed successfully"), n;
1003
+ } catch (r) {
1004
+ throw y.error("Failed to setup storages:", r), r;
1005
+ }
1006
+ }, ne = {
1007
+ LEGACY_DEPRECATION: "DEPRECATED: Migrate handler to → export default { fetch: (request, env, ctx) => {...} }",
1008
+ UNSUPPORTED_PATTERN_DETECTED: "Unsupported handler pattern detected. Generating Service Worker wrapper as fallback.",
1009
+ UNSUPPORTED_PATTERN_SUGGESTIONS: "Consider updating your handler to use ES Modules pattern."
1010
+ }, se = `
1011
+ const request = event.request;
1012
+ const env = process.env; // or any other environment variables you want to pass
1013
+ const ctx = { waitUntil: event.waitUntil?.bind(event) };`, oe = {
1014
+ baseImport: (e) => `
1015
+ import module from '${e}';
1016
+
1017
+ // Object export pattern: export default { fetch, firewall }
1018
+ const handlers = module.default || module;`,
1019
+ contextSetup: se,
1020
+ // The firewall ctx also exposes the event actions, so that
1021
+ // export default { firewall: (request, env, ctx) => ctx.deny() } behaves like
1022
+ // addEventListener('firewall', (event) => event.deny())
1023
+ firewallHandler: `
1024
+ const firewallHandler = handlers.firewall;
1025
+ addEventListener('firewall', (event) => {
1026
+ (async () => {
1027
+ const request = event.request;
1028
+ const env = process.env; // or any other environment variables you want to pass
1029
+ const ctx = {
1030
+ waitUntil: event.waitUntil?.bind(event),
1031
+ deny: event.deny?.bind(event),
1032
+ drop: event.drop?.bind(event),
1033
+ continue: event.continue?.bind(event),
1034
+ respondWith: event.respondWith?.bind(event),
1035
+ addRequestHeader: event.addRequestHeader?.bind(event),
1036
+ addResponseHeader: event.addResponseHeader?.bind(event),
1037
+ };
1038
+
1039
+ await firewallHandler(request, env, ctx);
1040
+ })().catch(console.error);
1041
+ });`,
1042
+ fetchHandler: (e) => `
1043
+ ${e ? "export default module;" : `
1044
+ const fetchHandler = handlers.fetch;
1045
+ addEventListener('fetch', (event) => {${se}
1046
+ event.respondWith((async () => {
1047
+ return fetchHandler(request, env, ctx);
1048
+ })());
1049
+ });`}
1050
+ `,
1051
+ fallbackHandler: (e) => `${`
1052
+ import module from '${e}';
1053
+
1054
+ // Object export pattern: export default { fetch, firewall }
1055
+ const handlers = module.default || module;`}
1056
+ const fetchHandler = handlers.fetch;
1057
+
1058
+ if (fetchHandler) {
1059
+ addEventListener('fetch', (event) => {${se}
1060
+
1061
+ event.respondWith((async () => {
1062
+ return fetchHandler(request, env, ctx);
1063
+ })());
1064
+ });
1065
+ } else {
1066
+ throw new Error("No fetch handler found in default export object.");
1067
+ }`
1068
+ }, Be = (e) => {
1069
+ const t = e.split(`
1070
+ `), r = /addEventListener\s*\(\s*['"`](fetch|firewall)['"`]\s*,/;
1071
+ return t.some((n) => {
1072
+ const o = n.trim();
1073
+ return o.startsWith("//") || o.startsWith("/*") ? !1 : r.test(n);
1074
+ });
1075
+ }, Lr = async (e) => {
1076
+ try {
1077
+ const t = await import(e), r = t.default || t;
1078
+ return {
1079
+ hasFirewall: !!r.firewall,
1080
+ hasFetch: !!r.fetch
1081
+ };
1082
+ } catch {
1083
+ return {
1084
+ hasFirewall: !1,
1085
+ hasFetch: !0
1086
+ };
1087
+ }
1088
+ }, Hr = async (e, t) => {
1089
+ const { hasFirewall: r, hasFetch: n } = await Lr(e);
1090
+ if (!r && !n)
1091
+ return `// No fetch or firewall handlers found in: ${e}
1092
+ // The original file will be used as-is in production mode.
1093
+ // Consider adding: export default { fetch: (request, env, ctx) => { ... } }
1094
+
1095
+ console.warn('No Edge Function handlers found. File will run as-is.');`;
1096
+ const o = [oe.baseImport(e)];
1097
+ return r && o.push(oe.firewallHandler), n && o.push(oe.fetchHandler(t)), o.join(`
1098
+ `);
1099
+ }, Vr = (e) => `
1100
+ import handler from '${e}';
1101
+
1102
+ // Legacy pattern wrapper: export default function → addEventListener
1103
+ addEventListener('fetch', (event) => {
1104
+ event.respondWith((async () => {
1105
+ return await handler(event);
1106
+ })());
1107
+ });
1108
+ `, he = (e) => /export\s+default\s*\{[\s\S]*fetch[\s\S]*\}/.test(e), De = (e) => !(!/export\s+default\s+/.test(e) || he(e)), zr = async (e) => {
1109
+ try {
1110
+ const t = await import(e);
1111
+ return typeof t.default > "u" && !t.fetch && !t.firewall ? "serviceWorker" : t.default && typeof t.default == "object" && (t.default.fetch || t.default.firewall) ? "ESModules" : t.default ? "legacy" : "unsupported";
1112
+ } catch {
1113
+ const r = await (await import("fs/promises")).readFile(e, "utf-8");
1114
+ return Be(r) ? "serviceWorker" : he(r) ? "ESModules" : De(r) ? "legacy" : "unsupported";
1115
+ }
1116
+ }, Gr = (e) => typeof e == "string" ? [e] : Array.isArray(e) ? e : Object.values(e), qr = (e) => Be(e) ? "serviceWorker" : he(e) ? "ESModules" : De(e) ? "legacy" : "unsupported", Kr = async (e, t, r) => {
1117
+ let n;
1118
+ try {
1119
+ n = await zr(t);
1120
+ } catch {
1121
+ n = qr(e);
1122
+ }
1123
+ switch (n) {
1124
+ case "serviceWorker":
1125
+ return e;
1126
+ case "ESModules":
1127
+ return await Hr(t, r);
1128
+ case "legacy":
1129
+ return d.build.warn(ne.LEGACY_DEPRECATION), Vr(t);
1130
+ default:
1131
+ return d.build.warn(ne.UNSUPPORTED_PATTERN_DETECTED), d.build.info(ne.UNSUPPORTED_PATTERN_SUGGESTIONS), e;
1132
+ }
1133
+ }, Jr = async (e, t) => {
1134
+ try {
1135
+ const r = Gr(t.handler), n = e.entry || {}, o = await Promise.all(
1136
+ r.map(async (s, i) => {
1137
+ const a = Object.values(n)[i], c = await m.readFile(s, "utf-8"), l = await Kr(c, s, t.production);
1138
+ return [a, l];
1139
+ })
1140
+ );
1141
+ return Object.fromEntries(o);
1142
+ } catch (r) {
1143
+ throw new Error(
1144
+ `Failed to setup worker code: ${r instanceof Error ? r.message : String(r)}`
1145
+ );
1146
+ }
1147
+ }, Xr = (e) => e === !0 ? !0 : process.env[R.ENV_ENABLED] === "true", Yr = () => {
1148
+ const e = process.env[R.ENV_FORMAT];
1149
+ return e === "console" || e === "json" || e === "html" || e === "both" ? e : R.DEFAULT_FORMAT;
1150
+ }, Zr = () => process.env[R.ENV_OUTPUT] || R.DEFAULT_OUTPUT_PATH, Qr = () => R.DEFAULT_HTML_OUTPUT_PATH, en = async (e) => {
1151
+ const { config: t, options: r } = e, n = !!r.production, o = Xr(r.telemetry), s = t.build?.bundler || "esbuild", i = {
1152
+ enabled: o,
1153
+ outputFormat: Yr(),
1154
+ outputPath: Zr(),
1155
+ htmlOutputPath: Qr()
1156
+ }, a = {
1157
+ bundlerVersion: A.VERSION,
1158
+ preset: t.build?.preset?.toString() || "javascript",
1159
+ bundler: s,
1160
+ production: n,
1161
+ entry: typeof t.build?.entry == "string" || Array.isArray(t.build?.entry) ? t.build.entry : t.build?.entry ? Object.values(t.build.entry) : ["./main.js"]
1162
+ }, c = new wt(i, a);
1163
+ try {
1164
+ const l = c.startSpan("build", {
1165
+ preset: a.preset,
1166
+ bundler: a.bundler,
1167
+ production: a.production
1168
+ });
1169
+ o && i.outputFormat !== "json" && (console.log(bt(A.VERSION)), console.log(Et(a)), console.log(`
1170
+ ⚙️ Starting build pipeline...
1171
+ `)), r.skipFrameworkBuild && d.build.warn("Skipping framework build"), await F(
1172
+ c,
1173
+ o,
1174
+ i.outputFormat,
1175
+ "dependencies-check",
1176
+ "Dependencies Check",
1177
+ async () => Qt()
1178
+ );
1179
+ const f = await F(
1180
+ c,
1181
+ o,
1182
+ i.outputFormat,
1183
+ "preset-resolution",
1184
+ "Preset Resolution",
1185
+ async () => Rr(t.build?.preset)
1186
+ ), u = await F(
1187
+ c,
1188
+ o,
1189
+ i.outputFormat,
1190
+ "build-config-setup",
1191
+ "Build Config Setup",
1192
+ async () => fr(t, f, n)
1193
+ );
1194
+ if (r.onlyGenerateConfig) {
1195
+ const b = await Ee({
1196
+ config: t,
1197
+ preset: f,
1198
+ configFile: r.configFile,
1199
+ ctx: {
1200
+ production: n ?? U.PRODUCTION,
1201
+ skipFrameworkBuild: !!r.skipFrameworkBuild,
1202
+ handler: ""
1203
+ }
1204
+ });
1205
+ return d.build.success("Build completed successfully with only azion.config"), le(b), c.endSpan(l), c.printToConsole(), await c.saveReport(), {
1206
+ config: b,
1207
+ ctx: {
1208
+ production: n ?? U.PRODUCTION,
1209
+ skipFrameworkBuild: !!r.skipFrameworkBuild,
1210
+ handler: ""
1211
+ },
1212
+ setup: u
1213
+ };
1214
+ }
1215
+ let p = {
1216
+ production: n ?? U.PRODUCTION,
1217
+ skipFrameworkBuild: !!r.skipFrameworkBuild,
1218
+ handler: ""
1219
+ };
1220
+ const g = await F(
1221
+ c,
1222
+ o,
1223
+ i.outputFormat,
1224
+ "environment-setup",
1225
+ "Environment Setup",
1226
+ async () => {
1227
+ const b = await Ee({
1228
+ config: t,
1229
+ preset: f,
1230
+ configFile: r.configFile,
1231
+ ctx: p
1232
+ });
1233
+ return le(b), b;
1234
+ }
1235
+ );
1236
+ d.prebuild.info("Starting pre-build...");
1237
+ const h = await F(
1238
+ c,
1239
+ o,
1240
+ i.outputFormat,
1241
+ "prebuild",
1242
+ "Prebuild",
1243
+ async () => Cr({
1244
+ buildConfig: u,
1245
+ ctx: p,
1246
+ applicationName: St(g)
1247
+ })
1248
+ );
1249
+ d.prebuild.info("Pre-build completed successfully");
1250
+ const S = await F(
1251
+ c,
1252
+ o,
1253
+ i.outputFormat,
1254
+ "handler-resolution",
1255
+ "Handler Resolution",
1256
+ async () => vr({
1257
+ entrypoint: t.build?.entry,
1258
+ preset: f,
1259
+ version: Q(t)
1260
+ })
1261
+ );
1262
+ p = {
1263
+ production: n ?? U.PRODUCTION,
1264
+ handler: S,
1265
+ skipFrameworkBuild: !!r.skipFrameworkBuild
1266
+ }, await F(
1267
+ c,
1268
+ o,
1269
+ i.outputFormat,
1270
+ "worker-setup",
1271
+ "Worker Setup",
1272
+ async () => {
1273
+ const b = await Jr(u, p), v = [];
1274
+ await Promise.all(
1275
+ Object.entries(b).map(async ([w, $]) => {
1276
+ await Oe(Ae(w), { recursive: !0 }), await Ct(w, $, "utf-8"), v.push(w);
1277
+ })
1278
+ );
1279
+ for (const w of v)
1280
+ await ct(w);
1281
+ return b;
1282
+ }
1283
+ ), d.build.info("Starting build..."), await F(
1284
+ c,
1285
+ o,
1286
+ i.outputFormat,
1287
+ "core-build",
1288
+ "Core Build",
1289
+ async () => yr({
1290
+ buildConfig: u,
1291
+ prebuildResult: h,
1292
+ ctx: p,
1293
+ telemetry: c,
1294
+ telemetryEnabled: o,
1295
+ telemetryOutputFormat: i.outputFormat
1296
+ })
1297
+ ), d.build.success("Build completed successfully"), await lt(), er(u.entry, g.functions), d.postbuild.info("Starting post-build..."), await F(
1298
+ c,
1299
+ o,
1300
+ i.outputFormat,
1301
+ "postbuild",
1302
+ "Postbuild",
1303
+ async () => {
1304
+ await Tr({ buildConfig: u, ctx: p });
1305
+ }
1306
+ ), d.postbuild.success("Post-build completed successfully");
1307
+ const E = await F(
1308
+ c,
1309
+ o,
1310
+ i.outputFormat,
1311
+ "storage-setup",
1312
+ "Storage Setup",
1313
+ async () => Mr({ config: g, preset: f })
1314
+ );
1315
+ return await F(
1316
+ c,
1317
+ o,
1318
+ i.outputFormat,
1319
+ "bindings-setup",
1320
+ "Bindings Setup",
1321
+ async () => {
1322
+ await ar({ config: g, storageSetup: E, isProduction: n });
1323
+ }
1324
+ ), await F(
1325
+ c,
1326
+ o,
1327
+ i.outputFormat,
1328
+ "env-vars-copy",
1329
+ "Copy Env Vars",
1330
+ async () => {
1331
+ await ft(p.production), await ut(g.applications?.[0]?.name, p.production);
1332
+ }
1333
+ ), c.endSpan(l), o && (c.printToConsole(), await c.saveReport()), {
1334
+ config: g,
1335
+ ctx: p,
1336
+ setup: u
1337
+ };
1338
+ } catch (l) {
1339
+ y.error("Build process failed:", l), d.build.error(
1340
+ `${l instanceof Error ? l.message : String(l)}${j}`
1341
+ ), c.markFailed(l instanceof Error ? l.message : String(l)), o && (c.printToConsole(), await c.saveReport()), process.exit(1);
1342
+ }
1343
+ };
1344
+ async function tn(e) {
1345
+ let t;
1346
+ try {
1347
+ t = B(e.configFile);
1348
+ } catch (a) {
1349
+ d.build.error(
1350
+ `${a instanceof Error ? a.message : String(a)}${j}`
1351
+ ), process.exit(1);
1352
+ }
1353
+ const r = await X(t, { configVersion: e.configVersion }) || {};
1354
+ let n;
1355
+ try {
1356
+ n = Y({ flag: e.configVersion, config: r });
1357
+ } catch (a) {
1358
+ d.build.error(
1359
+ `${a instanceof Error ? a.message : String(a)}${j}`
1360
+ ), process.exit(1);
1361
+ }
1362
+ const { build: o } = r, s = {
1363
+ preset: M({
1364
+ inputValue: e.preset,
1365
+ fileValue: o?.preset,
1366
+ defaultValue: U.PRESET
1367
+ }),
1368
+ entry: M({
1369
+ inputValue: e.entry,
1370
+ fileValue: o?.entry,
1371
+ defaultValue: U.ENTRY
1372
+ }),
1373
+ bundler: M({
1374
+ inputValue: void 0,
1375
+ fileValue: o?.bundler,
1376
+ defaultValue: U.BUNDLER
1377
+ }),
1378
+ polyfills: M({
1379
+ inputValue: o?.polyfills,
1380
+ fileValue: e.polyfills,
1381
+ defaultValue: U.POLYFILLS
1382
+ })
1383
+ }, i = {
1384
+ ...r,
1385
+ // the pipeline is typed with the default (v4) config; v3 specific fields are read through @aziontech/config accessors
1386
+ version: n,
1387
+ build: {
1388
+ ...s,
1389
+ memoryFS: r?.build?.memoryFS,
1390
+ extend: r?.build?.extend
1391
+ }
1392
+ };
1393
+ return e.production && await tr([k.OUTPUT_BASE_PATH]), en({
1394
+ config: i,
1395
+ options: {
1396
+ production: e.production,
1397
+ skipFrameworkBuild: e.skipFrameworkBuild,
1398
+ onlyGenerateConfig: e.onlyGenerateConfig,
1399
+ telemetry: e.telemetry,
1400
+ configFile: t
1401
+ }
1402
+ });
1403
+ }
1404
+ const rn = [
1405
+ ".git",
1406
+ ".vscode",
1407
+ ".idea",
1408
+ ".sublime-text",
1409
+ ".history",
1410
+ ".edge",
1411
+ ".vercel"
1412
+ ], We = (e) => {
1413
+ const r = (T.isAbsolute(e) ? T.relative(process.cwd(), e) : e).split(/[\\/]+/).filter((o) => o && o !== "."), [n] = r;
1414
+ return n ? !!(r.includes("node_modules") || rn.includes(n) || n.startsWith(".azion-bundler") || r.length === 1 && n.startsWith("azion") && n.includes(".temp")) : !1;
1415
+ };
1416
+ let ie, K = !1, Me = { skipFrameworkBuild: !1 };
1417
+ const nn = (e, t, r, n = !0) => {
1418
+ let o = r;
1419
+ const s = new RegExp(`addEventListener\\((['"]?)${e}\\1,`, "g"), i = /firewall:\s*\(event\)\s*=>\s*{/g, a = !!r.match(i), c = /eventType\s*=\s*['"]firewall['"];/g, l = !!r.match(s);
1420
+ return (n && l || a) && (o = r.replace(s, `addEventListener("${t}",`), a && (o = o.replace(c, "eventType = 'fetch';"))), { matchEvent: l || a, codeChanged: o };
1421
+ };
1422
+ function sn(e) {
1423
+ return new Promise((t) => {
1424
+ const r = new Nt.Socket();
1425
+ r.setTimeout(1e3), r.on("connect", () => {
1426
+ r.destroy(), t(!0);
1427
+ }), r.on("timeout", () => {
1428
+ r.destroy(), t(!1);
1429
+ }), r.on("error", (n) => {
1430
+ r.destroy(), n.message.includes("ECONNREFUSED") ? t(!1) : t(!0);
1431
+ }), r.connect(e, "127.0.0.1");
1432
+ });
1433
+ }
1434
+ async function on(e) {
1435
+ try {
1436
+ return await m.access(e), await m.readFile(e, "utf8");
1437
+ } catch (t) {
1438
+ if (t.message.includes("ENOENT")) {
1439
+ const r = z(e);
1440
+ throw new Error(
1441
+ `Server entry file "${r}" not found. Please specify your entry point using "azion dev <path>" or create the default handler file.${j}`
1442
+ );
1443
+ }
1444
+ throw new Error(`Error reading file ${e}: ${t.message}${j}`);
1445
+ }
1446
+ }
1447
+ async function an(e, t) {
1448
+ const { matchEvent: r, codeChanged: n } = (
1449
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1450
+ nn("firewall", "fetch", t)
1451
+ ), s = Ue(r ? n : t, r);
1452
+ return It({ port: e, host: "0.0.0.0", runtime: s });
1453
+ }
1454
+ function Te(e, t) {
1455
+ const r = t && $t(t), n = e?.bindings?.storage?.bucket || r?.bucket || "", o = e?.bindings?.storage?.prefix || r?.prefix || "";
1456
+ return { bucketName: n, prefix: o };
1457
+ }
1458
+ function cn(e, t, r) {
1459
+ const n = Object.keys(e).find((o) => {
1460
+ const s = o.replace(/\.dev$/, "").replace(/\.edge\//, "");
1461
+ return r.replace(/\.js$/, "").endsWith(s);
1462
+ });
1463
+ if (!n)
1464
+ throw new Error(`Entry path not found for function "${t}"`);
1465
+ return n;
1466
+ }
1467
+ function Se(e) {
1468
+ return e.endsWith(".js") ? e : `${e}.js`;
1469
+ }
1470
+ function ln(e, t, r) {
1471
+ if (!e || Object.keys(e).length === 0)
1472
+ throw new Error("No entries provided");
1473
+ if (r) {
1474
+ const i = t.functions?.find((l) => l.name === r);
1475
+ if (!i)
1476
+ throw new Error(`Function "${r}" not found in edge functions configuration`);
1477
+ const a = cn(e, r, i.path), c = Te(i, t);
1478
+ return {
1479
+ name: i.name,
1480
+ bucket: c.bucketName,
1481
+ prefix: c.prefix,
1482
+ path: Se(a)
1483
+ };
1484
+ }
1485
+ const n = Object.keys(e)[0], o = t.functions?.[0], s = Te(o, t);
1486
+ return {
1487
+ name: o?.name,
1488
+ bucket: s.bucketName,
1489
+ prefix: s.prefix,
1490
+ path: Se(n)
1491
+ };
1492
+ }
1493
+ async function me(e, t) {
1494
+ const { skipFrameworkBuild: r, functionName: n, configVersion: o, configFile: s } = Me;
1495
+ try {
1496
+ ie && await ie.close();
1497
+ const {
1498
+ setup: { entry: i },
1499
+ config: a
1500
+ } = await tn({
1501
+ production: !1,
1502
+ skipFrameworkBuild: r,
1503
+ configVersion: o,
1504
+ configFile: s
1505
+ });
1506
+ let c;
1507
+ try {
1508
+ const {
1509
+ path: l,
1510
+ bucket: f,
1511
+ prefix: u
1512
+ } = ln(i, a, n);
1513
+ globalThis.AZION_BUCKET_NAME = f, globalThis.AZION_BUCKET_PREFIX = u, c = await on(l);
1514
+ } catch (l) {
1515
+ d.server.error(l.message), y.error(`Error reading worker file: ${l}`), process.exit(1);
1516
+ }
1517
+ try {
1518
+ ie = await an(t, c), d.server.success(
1519
+ `Function running on port 0.0.0.0:${t}, url: http://localhost:${t}`
1520
+ );
1521
+ } catch (l) {
1522
+ if (l.message.includes("EADDRINUSE"))
1523
+ await me(e, t + 1);
1524
+ else
1525
+ throw l;
1526
+ }
1527
+ } catch (i) {
1528
+ d.server.error(
1529
+ `${i instanceof Error ? i.message : String(i)}${j}`
1530
+ ), y.error(`Server management error: ${i}`), process.exit(1);
1531
+ } finally {
1532
+ K = !1;
1533
+ }
1534
+ }
1535
+ async function fn(e, t, r) {
1536
+ if (!K && !We(e)) {
1537
+ K = !0;
1538
+ try {
1539
+ d.build.info("Rebuilding with the new changes..."), await me(t, r);
1540
+ } catch (n) {
1541
+ y.error(`Build or server restart failed: ${n}`);
1542
+ } finally {
1543
+ K = !1;
1544
+ }
1545
+ }
1546
+ }
1547
+ async function Le(e, t, r = !1, n, o, s) {
1548
+ Me = { skipFrameworkBuild: r, functionName: n, configVersion: o, configFile: s }, await sn(t) && (d.server.error(`Port ${t} is in use. Please choose another port.`), process.exit(1)), await me(e, t);
1549
+ const a = s && J(process.cwd(), s).startsWith(".."), c = gt.watch(a ? ["./", s] : "./", {
1550
+ persistent: !0,
1551
+ ignoreInitial: !0,
1552
+ // Ignore the initial add events
1553
+ depth: 99,
1554
+ // never open watchers in node_modules and the folders the bundler writes: see isIgnoredByWatcher
1555
+ ignored: We
1556
+ }), l = async (f) => {
1557
+ await fn(f, e, t);
1558
+ };
1559
+ c.on("add", l).on("change", l).on("unlink", l).on("addDir", l).on("unlinkDir", l).on("error", (f) => y.error(`Watcher error: ${f}`)).on("ready", () => d.server.info("Initial scan complete. Ready for changes."));
1560
+ }
1561
+ const $e = {
1562
+ runtime: Ue,
1563
+ server: Le,
1564
+ readStore: dt,
1565
+ readAzionConfig: X,
1566
+ writeStore: Fe,
1567
+ writeUserConfig: ae
1568
+ };
1569
+ async function Xn({
1570
+ entry: e,
1571
+ port: t,
1572
+ skipFrameworkBuild: r = !1,
1573
+ functionName: n,
1574
+ configVersion: o,
1575
+ configFile: s
1576
+ }) {
1577
+ const i = parseInt(t, 10), a = e || null;
1578
+ let c;
1579
+ try {
1580
+ c = B(s);
1581
+ } catch (l) {
1582
+ d.server.error(
1583
+ `${l instanceof Error ? l.message : String(l)}${j}`
1584
+ ), process.exit(1);
1585
+ }
1586
+ Le(
1587
+ a,
1588
+ i,
1589
+ r,
1590
+ n,
1591
+ o,
1592
+ c
1593
+ );
1594
+ }
1595
+ function Pe() {
1596
+ return Object.values(ee).filter((t) => t.metadata?.name).map((t) => t.metadata.name);
1597
+ }
1598
+ function un(e, t, r) {
1599
+ const n = ee[e];
1600
+ if (!n)
1601
+ throw new Error(
1602
+ `Preset '${e}' not found. Run 'ef presets ls' to see available presets.`
1603
+ );
1604
+ return Z(n, Y({ flag: t, config: r }));
1605
+ }
1606
+ async function Yn(e, t = {}) {
1607
+ const r = process.env.CLEAN_OUTPUT_MODE === "true";
1608
+ switch (e) {
1609
+ case "ls":
1610
+ r && Pe().forEach((n) => console.log(n?.toLowerCase())), r || Pe().forEach((n) => d.option(n));
1611
+ break;
1612
+ case "config":
1613
+ if (!t.preset) {
1614
+ d.error("Preset name is required. Use: ef presets config <preset-name>");
1615
+ return;
1616
+ }
1617
+ try {
1618
+ const n = B(t.configFile), o = n ? await X(n, { configVersion: t.configVersion }) : null, s = un(t.preset, t.configVersion, o);
1619
+ console.log(JSON.stringify(s, null, 2));
1620
+ } catch (n) {
1621
+ d.error(n instanceof Error ? n.message : "Unknown error occurred");
1622
+ }
1623
+ break;
1624
+ default:
1625
+ d.error("Invalid argument provided. Available commands: ls, config");
1626
+ break;
1627
+ }
1628
+ }
1629
+ function dn(e) {
1630
+ return Pt(e);
1631
+ }
1632
+ const pn = { processConfigWrapper: dn }, hn = ".edge/manifest.json", mn = "azion.config", gn = async (e, t = C(process.cwd(), ".edge"), r = {}) => {
1633
+ try {
1634
+ await V.access(t);
1635
+ } catch {
1636
+ await V.mkdir(t, { recursive: !0 });
1637
+ }
1638
+ let n;
1639
+ if (typeof e == "object")
1640
+ n = e;
1641
+ else {
1642
+ const i = await ke.readAzionConfig(e, r);
1643
+ if (!i)
1644
+ throw new Error(
1645
+ e ? `Failed to load config from ${e}` : "No configuration found. Please provide a config file or object."
1646
+ );
1647
+ n = i;
1648
+ }
1649
+ n = {
1650
+ ...n,
1651
+ version: Y({
1652
+ flag: r.configVersion,
1653
+ config: n
1654
+ })
1655
+ }, le(n);
1656
+ const o = pn.processConfigWrapper(n), s = C(t, "manifest.json");
1657
+ await V.writeFile(s, JSON.stringify(o, null, 2)), _.feedback.manifest.success(`Manifest generated successfully at ${s}`);
1658
+ }, yn = async (e, t = mn, r = {}) => {
1659
+ const o = await (async (i) => {
1660
+ const a = ue(process.cwd(), i);
1661
+ if (I(a) !== ".json")
1662
+ throw new Error("Input file must be .json");
1663
+ const c = await V.readFile(a, "utf8");
1664
+ return xt(c, {
1665
+ version: pt(r.configVersion)
1666
+ });
1667
+ })(e || hn), s = Y({ flag: r.configVersion });
1668
+ await ke.writeUserConfig({ ...o, version: s }, t), _.feedback.manifest.success(`Config file generated successfully at ${t}`);
1669
+ };
1670
+ async function Zn(e) {
1671
+ try {
1672
+ const t = e.action || "generate", n = {
1673
+ generate: async () => {
1674
+ const o = e.entry || e.config || B(e.configFile);
1675
+ await gn(o, e.output, { configVersion: e.configVersion });
1676
+ },
1677
+ transform: async () => {
1678
+ await yn(e.entry, e.output, {
1679
+ configVersion: e.configVersion
1680
+ });
1681
+ }
1682
+ }[t];
1683
+ n && await n(), n || (d.manifest.error(
1684
+ "Only transform and generate actions are supported"
1685
+ ), process.exit(1));
1686
+ } catch (t) {
1687
+ y.error(t), d.error(`${t instanceof Error ? t.message : String(t)}${j}`), await de(k.OUTPUT_BASE_PATH, { recursive: !0, force: !0 }), process.exit(1);
1688
+ }
1689
+ }
1690
+ async function Qn({ command: e, options: t }) {
1691
+ const r = JSON.parse(
1692
+ typeof t.config == "string" ? t.config : "{}"
1693
+ ), n = t.scope || "global";
1694
+ try {
1695
+ switch (e) {
1696
+ case "init": {
1697
+ const o = { ...r };
1698
+ await Fe(o, n), d.info(`Store file initialized with scope: ${n}`);
1699
+ break;
1700
+ }
1701
+ case "destroy":
1702
+ await de(globalThis.bundler.tempPath, { recursive: !0, force: !0 }), d.info("Temporary store directory removed");
1703
+ break;
1704
+ default:
1705
+ throw new Error(`Invalid command: ${e}`);
1706
+ }
1707
+ } catch (o) {
1708
+ d.error(`${o instanceof Error ? o.message : String(o)}${j}`), process.exit(1);
1709
+ }
1710
+ }
1711
+ function fe(e) {
1712
+ if (typeof e != "string")
1713
+ return e;
1714
+ const t = e.trim();
1715
+ if (!t.startsWith("{") && !t.startsWith("["))
1716
+ return e;
1717
+ try {
1718
+ return JSON.parse(e);
1719
+ } catch {
1720
+ return e;
1721
+ }
1722
+ }
1723
+ async function wn(e) {
1724
+ if (e)
1725
+ return { configPath: e, fileContent: await m.readFile(e, "utf8") };
1726
+ const r = await Dt("azion", {
1727
+ searchPlaces: [
1728
+ "azion.config.ts",
1729
+ "azion.config.mts",
1730
+ "azion.config.cts",
1731
+ "azion.config.js",
1732
+ "azion.config.mjs",
1733
+ "azion.config.cjs",
1734
+ "azion.config.json"
1735
+ ],
1736
+ loaders: {
1737
+ ".ts": re(),
1738
+ ".mts": re(),
1739
+ ".cts": re()
1740
+ }
1741
+ }).search();
1742
+ if (!r)
1743
+ throw new Error("No azion config file found");
1744
+ const n = r.filepath, o = await m.readFile(n, "utf8");
1745
+ return { configPath: n, fileContent: o };
1746
+ }
1747
+ const He = {
1748
+ findAndReadConfigFile: wn,
1749
+ tryParseJSON: fe
1750
+ };
1751
+ function bn(e) {
1752
+ const t = {}, r = e.key.split(".");
1753
+ let n = t;
1754
+ for (let o = 0; o < r.length; o++) {
1755
+ const s = r[o], i = s.match(/^(.+)\[(\d+)\]$/);
1756
+ if (i) {
1757
+ const a = i[1], c = parseInt(i[2]);
1758
+ o === r.length - 1 ? (n[a] || (n[a] = []), n[a][c] = fe(e.value)) : (n[a] || (n[a] = []), n[a][c] || (n[a][c] = {}), n = n[a][c]);
1759
+ } else
1760
+ o === r.length - 1 ? n[s] = fe(e.value) : (n[s] || (n[s] = {}), n = n[s]);
1761
+ }
1762
+ return t;
1763
+ }
1764
+ function En(e) {
1765
+ if (!e.config)
1766
+ throw new Error("Config is required for read");
1767
+ const t = e.config, r = e.key.split(".").flatMap((o) => {
1768
+ const s = o.match(/^(.+)\[(\d+)\]$/);
1769
+ return s ? [s[1], parseInt(s[2])] : [o];
1770
+ });
1771
+ let n = t;
1772
+ for (let o = 0; o < r.length; o++) {
1773
+ const s = r[o], i = r[o + 1];
1774
+ if (typeof s == "number") {
1775
+ if (!Array.isArray(n))
1776
+ throw new Error("Property is not an array");
1777
+ if (!n[s])
1778
+ throw new Error(`Array index ${s} does not exist`);
1779
+ n = n[s];
1780
+ } else {
1781
+ if (!(s in n))
1782
+ throw new Error(`Property '${s}' does not exist`);
1783
+ if (typeof i == "number") {
1784
+ if (!Array.isArray(n[s]))
1785
+ throw new Error(`Property '${s}' is not an array`);
1786
+ if (!n[s][i])
1787
+ throw new Error(`Array index ${i} does not exist in '${s}'`);
1788
+ n = n[s][i], o++;
1789
+ } else
1790
+ n = n[s];
1791
+ }
1792
+ }
1793
+ return n;
1794
+ }
1795
+ function vn(e) {
1796
+ if (!e.config)
1797
+ throw new Error("Config is required for delete");
1798
+ const t = { ...e.config }, r = e.key.split(".");
1799
+ let n = t;
1800
+ for (let i = 0; i < r.length - 1; i++) {
1801
+ const a = r[i], c = a.match(/^(.+)\[(\d+)\]$/);
1802
+ if (c) {
1803
+ const l = c[1], f = parseInt(c[2]);
1804
+ if (!n[l])
1805
+ throw new Error(`Property '${l}' does not exist`);
1806
+ if (!Array.isArray(n[l]))
1807
+ throw new Error(`Property '${l}' is not an array`);
1808
+ if (f >= n[l].length)
1809
+ throw new Error(`Array index ${f} does not exist in '${l}'`);
1810
+ n = n[l][f];
1811
+ } else {
1812
+ if (!n[a])
1813
+ throw new Error(`Property '${a}' does not exist`);
1814
+ n = n[a];
1815
+ }
1816
+ }
1817
+ const o = r[r.length - 1], s = o.match(/^(.+)\[(\d+)\]$/);
1818
+ if (s) {
1819
+ const i = s[1], a = parseInt(s[2]);
1820
+ if (!n[i])
1821
+ throw new Error(`Property '${i}' does not exist`);
1822
+ if (!Array.isArray(n[i]))
1823
+ throw new Error(`Property '${i}' is not an array`);
1824
+ if (a >= n[i].length)
1825
+ throw new Error(`Array index ${a} does not exist in '${i}'`);
1826
+ n[i].splice(a, 1);
1827
+ } else {
1828
+ if (!(o in n))
1829
+ throw new Error(`Property '${o}' does not exist`);
1830
+ delete n[o];
1831
+ }
1832
+ return t;
1833
+ }
1834
+ function Tn(e) {
1835
+ const t = e.match(
1836
+ /^\s*export\s+default\s+defineConfig\s*\(\s*/m
1837
+ ), r = e.match(
1838
+ /^\s*module\.exports\s*=\s*defineConfig\s*\(\s*/m
1839
+ ), n = e.match(/^\s*export\s+default\s+/m), o = e.match(/^\s*module\.exports\s*=\s*/m);
1840
+ let s = -1;
1841
+ if (t)
1842
+ s = t.index + t[0].length;
1843
+ else if (r)
1844
+ s = r.index + r[0].length;
1845
+ else if (n) {
1846
+ const g = n.index + n[0].length;
1847
+ let h = g;
1848
+ for (; h < e.length && e[h].match(/\s/); )
1849
+ h++;
1850
+ const S = e.slice(h).match(/^defineConfig\s*\(\s*/);
1851
+ S ? s = h + S[0].length : s = g;
1852
+ } else if (o) {
1853
+ const g = o.index + o[0].length;
1854
+ let h = g;
1855
+ for (; h < e.length && e[h].match(/\s/); )
1856
+ h++;
1857
+ const S = e.slice(h).match(/^defineConfig\s*\(\s*/);
1858
+ S ? s = h + S[0].length : s = g;
1859
+ }
1860
+ if (s === -1)
1861
+ throw new Error("Could not find module.exports or export default in config file");
1862
+ let i = s;
1863
+ for (; i < e.length && e[i].match(/\s/); )
1864
+ i++;
1865
+ if (i >= e.length)
1866
+ throw new Error("Could not find opening brace or parenthesis for config object");
1867
+ const a = e[i], c = a === "{" ? "}" : a === "(" ? ")" : null;
1868
+ if (!c)
1869
+ throw new Error("Config object must start with { or (");
1870
+ let l = 1, f = !1, u = "", p = e.length;
1871
+ for (let g = i + 1; g < e.length; g++) {
1872
+ const h = e[g], S = g > 0 ? e[g - 1] : "";
1873
+ if ((h === '"' || h === "'" || h === "`") && S !== "\\") {
1874
+ f ? h === u && (f = !1, u = "") : (f = !0, u = h);
1875
+ continue;
1876
+ }
1877
+ if (!f && (h === a ? l++ : h === c && l--, l === 0)) {
1878
+ p = g + 1;
1879
+ break;
1880
+ }
1881
+ }
1882
+ return { start: s, end: p };
1883
+ }
1884
+ async function Sn(e, t) {
1885
+ const r = Array.isArray(e) ? void 0 : t, n = Array.isArray(e) ? t : void 0;
1886
+ try {
1887
+ const o = Array.isArray(e) ? e : [{ placeholder: e, value: r }];
1888
+ for (const { placeholder: E, value: b } of o)
1889
+ if (typeof E != "string" || typeof b != "string")
1890
+ throw new Error("Placeholder and value must be strings");
1891
+ const { configPath: s, fileContent: i } = await He.findAndReadConfigFile(n), { start: a, end: c } = Tn(i), l = i.slice(0, a);
1892
+ let f = i.slice(a, c);
1893
+ const u = i.slice(c), p = /* @__PURE__ */ new Map();
1894
+ for (const { placeholder: E, value: b } of o) {
1895
+ let v = 0, w = 0;
1896
+ for (; w < f.length; ) {
1897
+ const $ = f.indexOf(E, w);
1898
+ if ($ === -1) break;
1899
+ const D = $ > 0 ? f[$ - 1] : "", x = $ + E.length < f.length ? f[$ + E.length] : "";
1900
+ let P = !0;
1901
+ if (typeof E == "string" && E.match(/[A-Za-z0-9_$]/)) {
1902
+ const Ve = D && D.match(/[A-Za-z0-9_$]/), ze = x && x.match(/[A-Za-z0-9_]/);
1903
+ (Ve || ze) && (P = !1);
1904
+ }
1905
+ P ? (f = f.slice(0, $) + b + f.slice($ + E.length), w = $ + b.length, v++) : w = $ + 1;
1906
+ }
1907
+ v > 0 && p.set(E, v);
1908
+ }
1909
+ const g = l + f + u;
1910
+ let h;
1911
+ try {
1912
+ h = await _e.format(g, {
1913
+ parser: "babel",
1914
+ semi: !1,
1915
+ singleQuote: !0,
1916
+ trailingComma: "none"
1917
+ });
1918
+ } catch {
1919
+ h = g;
1920
+ }
1921
+ await m.writeFile(s, h, "utf8");
1922
+ const S = Array.from(p.values()).reduce((E, b) => E + b, 0);
1923
+ if (S === 0)
1924
+ d.info(`No placeholders found to replace in ${T.basename(s)}`);
1925
+ else if (p.size === 1) {
1926
+ const [E, b] = Array.from(p.entries())[0], v = o.find((w) => w.placeholder === E);
1927
+ d.info(
1928
+ `Successfully replaced "${E}" with "${v?.value}" (${b} occurrence${b > 1 ? "s" : ""}) in ${T.basename(s)}`
1929
+ );
1930
+ } else {
1931
+ const E = Array.from(p.entries()).map(([b, v]) => {
1932
+ const w = o.find(($) => $.placeholder === b);
1933
+ return `"${b}" -> "${w?.value}" (${v})`;
1934
+ }).join(", ");
1935
+ d.info(
1936
+ `Successfully replaced ${S} occurrences of ${p.size} placeholders (${E}) in ${T.basename(s)}`
1937
+ );
1938
+ }
1939
+ } catch (o) {
1940
+ throw new Error(
1941
+ `Failed to replace in config file: ${o instanceof Error ? o.message : String(o)}`
1942
+ );
1943
+ }
1944
+ }
1945
+ async function $n(e, t, r) {
1946
+ try {
1947
+ const { configPath: n, fileContent: o } = await He.findAndReadConfigFile(r), s = Pn(o, e, t);
1948
+ let i;
1949
+ try {
1950
+ i = await _e.format(s, {
1951
+ parser: "babel",
1952
+ semi: !1,
1953
+ singleQuote: !0,
1954
+ trailingComma: "none"
1955
+ });
1956
+ } catch {
1957
+ i = s;
1958
+ }
1959
+ await m.writeFile(n, i, "utf8"), _.feedback.info(
1960
+ `Successfully updated "${e}" to "${t}" in ${T.basename(n)}`
1961
+ );
1962
+ } catch (n) {
1963
+ throw new Error(
1964
+ `Failed to update config file: ${n instanceof Error ? n.message : String(n)}`
1965
+ );
1966
+ }
1967
+ }
1968
+ function Pn(e, t, r) {
1969
+ return xn(e, t, r);
1970
+ }
1971
+ function xn(e, t, r) {
1972
+ const n = kn(r), o = e.replace(/\n\s*/g, " ").replace(/\s+/g, " "), s = o.match(
1973
+ /(.*(?:module\.exports\s*=(?:\s+\w+\()?|export default(?:\s+\w+\()?)\s*)\{/
1974
+ );
1975
+ if (!s)
1976
+ return e;
1977
+ const i = s[0].length;
1978
+ let a = 1, c = i, l = !1, f = "";
1979
+ for (let x = i; x < o.length && a > 0; x++) {
1980
+ const P = o[x];
1981
+ if (l ? P === f && o[x - 1] !== "\\" && (l = !1) : P === '"' || P === "'" ? (l = !0, f = P) : P === "{" ? a++ : P === "}" && a--, a === 0) {
1982
+ c = x;
1983
+ break;
1984
+ }
1985
+ }
1986
+ if (a !== 0)
1987
+ return e;
1988
+ const u = o.substring(i, c), p = Fn(t), g = ge(u, p, n), h = e.match(
1989
+ /(.*(?:module\.exports\s*=(?:\s+\w+\()?|export default(?:\s+\w+\()?)\s*)\{/s
1990
+ );
1991
+ if (!h)
1992
+ return e;
1993
+ const S = h[1] + "{", E = h[0].length;
1994
+ let b = 1, v = E, w = !1, $ = "";
1995
+ for (let x = E; x < e.length && b > 0; x++) {
1996
+ const P = e[x];
1997
+ if (w ? P === $ && e[x - 1] !== "\\" && (w = !1) : P === '"' || P === "'" ? (w = !0, $ = P) : P === "{" ? b++ : P === "}" && b--, b === 0) {
1998
+ v = x;
1999
+ break;
2000
+ }
2001
+ }
2002
+ const D = "}" + e.substring(v + 1);
2003
+ return S + g + D;
2004
+ }
2005
+ function Fn(e) {
2006
+ const t = [];
2007
+ let r = "", n = 0;
2008
+ for (; n < e.length; ) {
2009
+ const o = e[n];
2010
+ if (o === ".")
2011
+ r && (t.push(r), r = "");
2012
+ else if (o === "[") {
2013
+ r && (t.push(r), r = ""), n++;
2014
+ let s = "";
2015
+ for (; n < e.length && e[n] !== "]"; )
2016
+ s += e[n], n++;
2017
+ t.push(parseInt(s));
2018
+ } else
2019
+ r += o;
2020
+ n++;
2021
+ }
2022
+ return r && t.push(r), t;
2023
+ }
2024
+ function ge(e, t, r) {
2025
+ if (t.length === 0) return e;
2026
+ const [n, ...o] = t;
2027
+ if (typeof n == "string") {
2028
+ const s = n.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
2029
+ if (o.length === 0) {
2030
+ const i = new RegExp(`(${s}\\s*:\\s*)([^,}]+)`);
2031
+ return e.replace(i, `$1${r}`);
2032
+ } else {
2033
+ const i = e.match(
2034
+ new RegExp(`(.*${s}\\s*:\\s*)([^,}]+)(.*)`)
2035
+ );
2036
+ if (i) {
2037
+ const [, , a] = i;
2038
+ if (a.trim().startsWith("{")) {
2039
+ const c = e.indexOf(a.trim());
2040
+ if (c === -1)
2041
+ return e;
2042
+ let l = 0, f = !1, u = "", p = -1;
2043
+ for (let v = c; v < e.length; v++) {
2044
+ const w = e[v];
2045
+ if (f)
2046
+ w === u && e[v - 1] !== "\\" && (f = !1);
2047
+ else if (w === '"' || w === "'")
2048
+ f = !0, u = w;
2049
+ else if (w === "{")
2050
+ l++;
2051
+ else if (w === "}" && (l--, l === 0)) {
2052
+ p = v;
2053
+ break;
2054
+ }
2055
+ }
2056
+ if (p === -1)
2057
+ return e;
2058
+ const h = e.substring(c, p + 1).slice(1, -1), S = ge(h, o, r), E = e.substring(0, c), b = e.substring(p + 1);
2059
+ return E + `{ ${S} }` + b;
2060
+ } else if (a.trim().startsWith("[")) {
2061
+ const c = e.indexOf(a.trim());
2062
+ if (c === -1)
2063
+ return e;
2064
+ let l = 0, f = !1, u = "", p = -1;
2065
+ for (let v = c; v < e.length; v++) {
2066
+ const w = e[v];
2067
+ if (f)
2068
+ w === u && e[v - 1] !== "\\" && (f = !1);
2069
+ else if (w === '"' || w === "'")
2070
+ f = !0, u = w;
2071
+ else if (w === "[")
2072
+ l++;
2073
+ else if (w === "]" && (l--, l === 0)) {
2074
+ p = v;
2075
+ break;
2076
+ }
2077
+ }
2078
+ if (p === -1)
2079
+ return e;
2080
+ const h = e.substring(c, p + 1).slice(1, -1), S = xe(h, o, r), E = e.substring(0, c), b = e.substring(p + 1);
2081
+ return E + `[ ${S} ]` + b;
2082
+ }
2083
+ }
2084
+ }
2085
+ } else if (typeof n == "number")
2086
+ return xe(e, t, r);
2087
+ return e;
2088
+ }
2089
+ function xe(e, t, r) {
2090
+ if (t.length === 0) return e;
2091
+ const [n, ...o] = t;
2092
+ if (typeof n != "number") return e;
2093
+ const s = [];
2094
+ let i = 0;
2095
+ for (; i < e.length; ) {
2096
+ for (; i < e.length && /\s/.test(e[i]); )
2097
+ i++;
2098
+ if (i >= e.length) break;
2099
+ if (e[i] === "{") {
2100
+ let a = 0, c = !1, l = "";
2101
+ const f = i;
2102
+ for (; i < e.length; ) {
2103
+ const u = e[i];
2104
+ if (c)
2105
+ u === l && e[i - 1] !== "\\" && (c = !1);
2106
+ else if (u === '"' || u === "'")
2107
+ c = !0, l = u;
2108
+ else if (u === "{")
2109
+ a++;
2110
+ else if (u === "}" && (a--, a === 0)) {
2111
+ const p = e.substring(f, i + 1);
2112
+ for (s.push(p.trim()), i++; i < e.length && /[\s,]/.test(e[i]); )
2113
+ i++;
2114
+ break;
2115
+ }
2116
+ i++;
2117
+ }
2118
+ } else {
2119
+ const a = i;
2120
+ let c = !1, l = "";
2121
+ for (; i < e.length; ) {
2122
+ const f = e[i];
2123
+ if (c)
2124
+ f === l && e[i - 1] !== "\\" && (c = !1);
2125
+ else if (f === '"' || f === "'")
2126
+ c = !0, l = f;
2127
+ else if (f === ",") {
2128
+ const u = e.substring(a, i);
2129
+ for (s.push(u.trim()), i++; i < e.length && /\s/.test(e[i]); )
2130
+ i++;
2131
+ break;
2132
+ }
2133
+ i++;
2134
+ }
2135
+ if (i >= e.length && a < e.length) {
2136
+ const f = e.substring(a);
2137
+ f.trim() && s.push(f.trim());
2138
+ }
2139
+ }
2140
+ }
2141
+ if (n < s.length)
2142
+ if (o.length === 0)
2143
+ s[n] = r;
2144
+ else {
2145
+ const a = s[n];
2146
+ if (a.startsWith("{") && a.endsWith("}")) {
2147
+ const c = a.slice(1, -1), l = ge(c, o, r);
2148
+ s[n] = `{ ${l} }`;
2149
+ }
2150
+ }
2151
+ return s.join(", ");
2152
+ }
2153
+ function kn(e) {
2154
+ if (typeof e == "string") {
2155
+ if (e.startsWith('"') && e.endsWith('"') || e.startsWith("'") && e.endsWith("'"))
2156
+ return e;
2157
+ const t = e.trim();
2158
+ return t.startsWith("{") && t.endsWith("}") || t.startsWith("[") && t.endsWith("]") || e.includes("=>") || e.trim().startsWith("function") ? e : `'${e}'`;
2159
+ }
2160
+ return String(e);
2161
+ }
2162
+ async function es({ command: e, options: t }) {
2163
+ try {
2164
+ const r = B(t.configFile);
2165
+ if (!(!r || [".js", ".mjs", ".cjs", ".ts"].includes(T.extname(r))) && (e === "create" || e === "delete"))
2166
+ throw new Error(
2167
+ `The ${e} command cannot write ${r}: use a .js, .mjs, .cjs or .ts config file`
2168
+ );
2169
+ const o = await X(r);
2170
+ if (t.all) {
2171
+ let u;
2172
+ switch (e) {
2173
+ case "read":
2174
+ return u = o || {}, console.log(JSON.stringify(u, null, 2)), u;
2175
+ case "delete":
2176
+ return await ae({}, r), {};
2177
+ default:
2178
+ throw new Error("--all flag is only supported for read and delete commands");
2179
+ }
2180
+ }
2181
+ const s = Array.isArray(t.key) ? t.key : t.key ? [t.key] : [], i = Array.isArray(t.value) ? t.value : t.value !== void 0 ? [t.value] : [];
2182
+ if (s.length === 0 && e !== "replace")
2183
+ throw new Error("Key is required when --all is not used");
2184
+ const a = s[0], c = i[0];
2185
+ let l, f;
2186
+ switch (e) {
2187
+ case "create":
2188
+ if (o)
2189
+ throw new Error("Configuration already exists. Use update command instead.");
2190
+ if (c === void 0)
2191
+ throw new Error("Value is required for create command");
2192
+ l = bn({
2193
+ key: a,
2194
+ value: c
2195
+ });
2196
+ break;
2197
+ case "update":
2198
+ if (!o)
2199
+ throw new Error("No configuration found. Use create command first.");
2200
+ if (c === void 0)
2201
+ throw new Error("Value is required for update command");
2202
+ return await $n(a, c, r), {};
2203
+ case "read":
2204
+ if (!o)
2205
+ throw new Error("No configuration found");
2206
+ return f = En({
2207
+ key: a,
2208
+ config: o
2209
+ }), f;
2210
+ case "delete":
2211
+ if (!o)
2212
+ throw new Error("No configuration found");
2213
+ l = vn({
2214
+ key: a,
2215
+ config: o
2216
+ });
2217
+ break;
2218
+ case "replace": {
2219
+ const u = [];
2220
+ if (t.replacements) {
2221
+ let p;
2222
+ if (typeof t.replacements == "string")
2223
+ try {
2224
+ p = JSON.parse(t.replacements);
2225
+ } catch {
2226
+ try {
2227
+ const g = t.replacements.replace(/\\"/g, '"');
2228
+ p = JSON.parse(g);
2229
+ } catch (g) {
2230
+ const h = g instanceof Error ? g.message : String(g);
2231
+ throw new Error(
2232
+ `Invalid JSON format for --replacements option: ${h}. Received: ${t.replacements}`
2233
+ );
2234
+ }
2235
+ }
2236
+ else if (typeof t.replacements == "object")
2237
+ p = t.replacements;
2238
+ else
2239
+ throw new Error("Invalid format for --replacements option");
2240
+ for (const [g, h] of Object.entries(p))
2241
+ u.push({ placeholder: g, value: String(h) });
2242
+ } else if (s.length > 0 && i.length > 0)
2243
+ for (let p = 0; p < Math.min(s.length, i.length); p++)
2244
+ u.push({ placeholder: s[p], value: String(i[p]) });
2245
+ if (u.length === 0)
2246
+ throw new Error(
2247
+ "Replacements are required for replace command. Use -k/-v pairs or --replacements JSON"
2248
+ );
2249
+ return await Sn(u, r), {};
2250
+ }
2251
+ default:
2252
+ throw new Error(`Unknown command: ${e}`);
2253
+ }
2254
+ return await ae(l, r), l;
2255
+ } catch (r) {
2256
+ y.error(r), d.error(`${r instanceof Error ? r.message : String(r)}`), process.exit(1);
2257
+ }
2258
+ }
2259
+ async function ts(e = {}) {
2260
+ const t = e.path || C(k.OUTPUT_BASE_PATH, "telemetry-report.html");
2261
+ Ce(t) || (d.error(
2262
+ `Telemetry report not found at: ${t}
2263
+
2264
+ Make sure you have run a build with the --telemetry flag first.
2265
+ Example: ef build --telemetry html
2266
+ Or: ef build --telemetry`
2267
+ ), process.exit(1));
2268
+ try {
2269
+ const r = process.platform;
2270
+ let n;
2271
+ r === "darwin" ? n = `open "${t}"` : r === "win32" ? n = `start "" "${t}"` : n = `xdg-open "${t}"`;
2272
+ const { exec: o } = await import("child_process");
2273
+ o(n, (s) => {
2274
+ s && (d.error(`Failed to open telemetry report: ${s.message}`), process.exit(1)), d.success(`Opened telemetry report: ${t}`);
2275
+ });
2276
+ } catch (r) {
2277
+ d.error(
2278
+ `Failed to open telemetry report: ${r instanceof Error ? r.message : "Unknown error"}`
2279
+ ), process.exit(1);
2280
+ }
2281
+ }
2282
+ export {
2283
+ tn as buildCommand,
2284
+ es as configCommand,
2285
+ Xn as devCommand,
2286
+ Zn as manifestCommand,
2287
+ Yn as presetsCommand,
2288
+ Qn as storeCommand,
2289
+ ts as telemetryCommand
2290
+ };