@vtex-email/cli 0.0.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.
Files changed (60) hide show
  1. package/dist/bin.d.ts +2 -0
  2. package/dist/bin.d.ts.map +1 -0
  3. package/dist/bin.js +2969 -0
  4. package/dist/commands/args.d.ts +39 -0
  5. package/dist/commands/args.d.ts.map +1 -0
  6. package/dist/commands/dev-notices.d.ts +51 -0
  7. package/dist/commands/dev-notices.d.ts.map +1 -0
  8. package/dist/commands/dev-presenter.d.ts +20 -0
  9. package/dist/commands/dev-presenter.d.ts.map +1 -0
  10. package/dist/commands/dev.d.ts +6 -0
  11. package/dist/commands/dev.d.ts.map +1 -0
  12. package/dist/commands/preview-export.d.ts +8 -0
  13. package/dist/commands/preview-export.d.ts.map +1 -0
  14. package/dist/commands/project-commands.d.ts +9 -0
  15. package/dist/commands/project-commands.d.ts.map +1 -0
  16. package/dist/commands/report.d.ts +40 -0
  17. package/dist/commands/report.d.ts.map +1 -0
  18. package/dist/commands/run.d.ts +3 -0
  19. package/dist/commands/run.d.ts.map +1 -0
  20. package/dist/config/config.d.ts +81 -0
  21. package/dist/config/config.d.ts.map +1 -0
  22. package/dist/config/load-config.d.ts +10 -0
  23. package/dist/config/load-config.d.ts.map +1 -0
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +126 -0
  27. package/dist/project/build-project.d.ts +21 -0
  28. package/dist/project/build-project.d.ts.map +1 -0
  29. package/dist/project/catalogs.d.ts +4 -0
  30. package/dist/project/catalogs.d.ts.map +1 -0
  31. package/dist/project/compile-email.d.ts +4 -0
  32. package/dist/project/compile-email.d.ts.map +1 -0
  33. package/dist/project/discover.d.ts +15 -0
  34. package/dist/project/discover.d.ts.map +1 -0
  35. package/dist/project/fixtures.d.ts +8 -0
  36. package/dist/project/fixtures.d.ts.map +1 -0
  37. package/dist/project/manifest.d.ts +4 -0
  38. package/dist/project/manifest.d.ts.map +1 -0
  39. package/dist/project/merge-variants.d.ts +17 -0
  40. package/dist/project/merge-variants.d.ts.map +1 -0
  41. package/dist/project/module-loader.d.ts +12 -0
  42. package/dist/project/module-loader.d.ts.map +1 -0
  43. package/dist/project/policy.d.ts +4 -0
  44. package/dist/project/policy.d.ts.map +1 -0
  45. package/dist/project/preview-evaluation.d.ts +26 -0
  46. package/dist/project/preview-evaluation.d.ts.map +1 -0
  47. package/dist/project/revalidate.d.ts +4 -0
  48. package/dist/project/revalidate.d.ts.map +1 -0
  49. package/dist/project/settings.d.ts +9 -0
  50. package/dist/project/settings.d.ts.map +1 -0
  51. package/dist/project/types.d.ts +113 -0
  52. package/dist/project/types.d.ts.map +1 -0
  53. package/dist/project/write-output.d.ts +12 -0
  54. package/dist/project/write-output.d.ts.map +1 -0
  55. package/dist/project-api.d.ts +10 -0
  56. package/dist/project-api.d.ts.map +1 -0
  57. package/dist/project.d.ts +11 -0
  58. package/dist/project.d.ts.map +1 -0
  59. package/dist/project.js +2590 -0
  60. package/package.json +35 -0
package/dist/bin.js ADDED
@@ -0,0 +1,2969 @@
1
+ #!/usr/bin/env node
2
+ // src/bin.ts
3
+ import { readFileSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ // src/commands/args.ts
7
+ var valued = /* @__PURE__ */ new Set(["--config", "--format", "--locale", "--fixture", "--out"]);
8
+ function parseArgs(argv) {
9
+ let help = false;
10
+ let version = false;
11
+ let format2;
12
+ let config;
13
+ let locale;
14
+ let fixture;
15
+ let out;
16
+ let warningsAsErrors = false;
17
+ const seen = /* @__PURE__ */ new Set();
18
+ const positionals = [];
19
+ const errors = [];
20
+ const tokens = argv.slice(2);
21
+ for (let index = 0; index < tokens.length; index += 1) {
22
+ const token = tokens[index] ?? "";
23
+ if (token === "--help" || token === "-h") {
24
+ help = true;
25
+ continue;
26
+ }
27
+ if (token === "--version" || token === "-V") {
28
+ version = true;
29
+ continue;
30
+ }
31
+ if (token === "--warnings-as-errors") {
32
+ if (seen.has(token)) errors.push(`Duplicate option: ${token}`);
33
+ seen.add(token);
34
+ warningsAsErrors = true;
35
+ continue;
36
+ }
37
+ if (token.startsWith("-")) {
38
+ if (!valued.has(token)) {
39
+ errors.push(`Unknown option: ${token}`);
40
+ continue;
41
+ }
42
+ if (seen.has(token)) errors.push(`Duplicate option: ${token}`);
43
+ seen.add(token);
44
+ const value = tokens[index + 1];
45
+ if (!value || value.startsWith("-")) {
46
+ errors.push(`Option ${token} requires a value.`);
47
+ continue;
48
+ }
49
+ index += 1;
50
+ switch (token) {
51
+ case "--config":
52
+ config = value;
53
+ break;
54
+ case "--locale":
55
+ locale = value;
56
+ break;
57
+ case "--fixture":
58
+ fixture = value;
59
+ break;
60
+ case "--out":
61
+ out = value;
62
+ break;
63
+ case "--format":
64
+ if (value === "text" || value === "json") format2 = value;
65
+ else errors.push(`Invalid format: ${value}`);
66
+ break;
67
+ }
68
+ continue;
69
+ }
70
+ positionals.push(token);
71
+ }
72
+ const resolvedFormat = format2 ?? "text";
73
+ const fail = (message) => ({
74
+ kind: "error",
75
+ format: resolvedFormat,
76
+ message,
77
+ ...config ? { config } : {}
78
+ });
79
+ if (errors.length > 0) return fail(errors.join("\n"));
80
+ if (help) return { kind: "help" };
81
+ if (version) return { kind: "version" };
82
+ const [command, ...rest] = positionals;
83
+ const shared = {
84
+ format: resolvedFormat,
85
+ ...config ? { config } : {},
86
+ warningsAsErrors
87
+ };
88
+ switch (command) {
89
+ case void 0:
90
+ return fail("Missing command.");
91
+ case "build":
92
+ if (fixture || out) return fail("--fixture and --out are only valid for preview.");
93
+ if (rest.length > 1) return fail("build accepts at most one email id.");
94
+ return {
95
+ kind: "build",
96
+ ...shared,
97
+ ...locale ? { locale } : {},
98
+ ...rest[0] ? { emailId: rest[0] } : {}
99
+ };
100
+ case "validate":
101
+ if (rest.length > 0) return fail("validate does not accept an email id.");
102
+ if (locale) return fail("--locale is only valid for build.");
103
+ if (fixture || out) return fail("Unknown option for validate.");
104
+ return { kind: "validate", ...shared };
105
+ case "dev":
106
+ if (rest.length > 0) return fail("dev does not accept an email id.");
107
+ if (locale) return fail("--locale is only valid for build.");
108
+ if (fixture || out) return fail("--fixture and --out are only valid for preview.");
109
+ return { kind: "dev", ...shared };
110
+ case "preview":
111
+ if (locale) return fail("--locale is only valid for build.");
112
+ if (rest.length !== 1) return fail("preview requires an email id.");
113
+ if (!fixture) return fail("preview requires --fixture.");
114
+ if (!out) return fail("preview requires --out.");
115
+ return {
116
+ kind: "preview",
117
+ ...shared,
118
+ emailId: rest[0] ?? "",
119
+ fixtureId: fixture,
120
+ outDir: out
121
+ };
122
+ default:
123
+ return fail(`Unknown command: ${command}`);
124
+ }
125
+ }
126
+ function helpText() {
127
+ return [
128
+ "vtex-email build [email-id]",
129
+ "vtex-email validate",
130
+ "vtex-email dev",
131
+ "vtex-email preview <email-id> --fixture <fixture-id> --out <directory>",
132
+ "",
133
+ "Options:",
134
+ " --config <path>",
135
+ " --format text|json",
136
+ " --warnings-as-errors",
137
+ " --locale <locale> build only",
138
+ " -h, --help",
139
+ " -V, --version",
140
+ ""
141
+ ].join("\n");
142
+ }
143
+
144
+ // src/commands/run.ts
145
+ import path11 from "node:path";
146
+
147
+ // src/project/types.ts
148
+ var exitOk = 0;
149
+ var exitValidation = 1;
150
+ var exitUsage = 2;
151
+ function emptyProject(exitCode, diagnostics) {
152
+ return { ok: false, exitCode, diagnostics, manifest: null, emails: [], wrote: [], preserved: [] };
153
+ }
154
+
155
+ // src/commands/dev.ts
156
+ import { createRequire } from "node:module";
157
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
158
+
159
+ // src/commands/report.ts
160
+ import path from "node:path";
161
+ function buildReport(input) {
162
+ const diagnostics = input.diagnostics.map((item) => publicDiagnostic(item, input.configDir));
163
+ return {
164
+ formatVersion: 1,
165
+ command: input.command,
166
+ ok: input.ok,
167
+ exitCode: input.exitCode,
168
+ diagnostics,
169
+ manifest: input.manifest,
170
+ wrote: [...input.wrote],
171
+ preserved: [...input.preserved],
172
+ unverifiedCapabilities: unverifiedCapabilities(diagnostics)
173
+ };
174
+ }
175
+ function reportJson(report) {
176
+ return `${JSON.stringify(report)}
177
+ `;
178
+ }
179
+ function reportText(report) {
180
+ const lines = [];
181
+ if (report.manifest?.homologation === "experimental") lines.push("homologation experimental");
182
+ for (const item of report.diagnostics) {
183
+ const where = [item.templateId, item.locale, item.fixtureId, item.origin].filter((part) => part && part.length > 0);
184
+ lines.push([item.code, item.severity, ...where, item.message].join(" "));
185
+ }
186
+ for (const capability of report.unverifiedCapabilities) {
187
+ lines.push(`unverified ${capability.templateId} ${capability.name} ${capability.evidence} ${capability.severity}`);
188
+ }
189
+ if (report.wrote.length > 0) lines.push(`wrote ${report.wrote.join(" ")}`);
190
+ if (report.preserved.length > 0) lines.push(`preserved ${report.preserved.join(" ")}`);
191
+ if (lines.length === 0) lines.push(report.ok ? "ok" : "failed");
192
+ return `${lines.join("\n")}
193
+ `;
194
+ }
195
+ function publicDiagnostic(item, configDir) {
196
+ const diagnostic = {
197
+ code: item.code,
198
+ severity: item.severity,
199
+ message: scrub(item.message, configDir)
200
+ };
201
+ if (item.templateId) diagnostic.templateId = item.templateId;
202
+ if (item.locale) diagnostic.locale = item.locale;
203
+ if (item.fixtureId) diagnostic.fixtureId = item.fixtureId;
204
+ if (item.origin) diagnostic.origin = item.origin;
205
+ if (item.path) diagnostic.path = scrub(item.path, configDir);
206
+ if (item.capability) diagnostic.capability = item.capability;
207
+ if (item.source?.file) {
208
+ diagnostic.source = {
209
+ file: relativeFile(item.source.file, configDir),
210
+ ...typeof item.source.line === "number" ? { line: item.source.line } : {},
211
+ ...typeof item.source.column === "number" ? { column: item.source.column } : {}
212
+ };
213
+ }
214
+ return diagnostic;
215
+ }
216
+ function unverifiedCapabilities(diagnostics) {
217
+ const map = /* @__PURE__ */ new Map();
218
+ for (const item of diagnostics) {
219
+ if (item.code !== "TARGET001" || !item.templateId || !item.capability) continue;
220
+ const severity = item.severity === "error" ? "error" : "warning";
221
+ const key = `${item.templateId}\0${item.capability.name}`;
222
+ const current = map.get(key);
223
+ if (!current || severity === "error") {
224
+ map.set(key, {
225
+ templateId: item.templateId,
226
+ name: item.capability.name,
227
+ evidence: item.capability.evidence,
228
+ severity
229
+ });
230
+ }
231
+ }
232
+ return [...map.values()];
233
+ }
234
+ function relativeFile(file, configDir) {
235
+ if (!path.isAbsolute(file)) return file.split(path.sep).join("/");
236
+ const relative = path.relative(configDir, file);
237
+ if (relative.length === 0 || relative.startsWith("..") || path.isAbsolute(relative)) return path.basename(file);
238
+ return relative.split(path.sep).join("/");
239
+ }
240
+ function scrub(value, configDir) {
241
+ if (configDir.length === 0) return value;
242
+ const prefix = configDir.endsWith(path.sep) ? configDir : `${configDir}${path.sep}`;
243
+ return value.split(prefix).join("").split(configDir).join(".");
244
+ }
245
+ async function emitReport(report, format2) {
246
+ if (format2 === "json") {
247
+ await writeStream(process.stdout, reportJson(report));
248
+ await writeStream(process.stderr, reportText(report));
249
+ return;
250
+ }
251
+ await writeStream(report.ok ? process.stdout : process.stderr, reportText(report));
252
+ }
253
+ function writeStream(stream, text) {
254
+ if (text.length === 0) return Promise.resolve();
255
+ return new Promise((resolve, reject) => {
256
+ stream.write(text, (error) => {
257
+ if (error) reject(error);
258
+ else resolve();
259
+ });
260
+ });
261
+ }
262
+
263
+ // src/commands/dev-presenter.ts
264
+ var BANNER_ASCII = [
265
+ "__ ___ _____ _______ __",
266
+ "\\ \\ / / |_ _| ____\\ \\/ /",
267
+ " \\ \\ / / | | | _| \\ / ",
268
+ " \\ V / | | | |___ / \\ ",
269
+ " \\_/ |_| |_____/_/\\_\\",
270
+ " email React"
271
+ ];
272
+ var BANNER_COMPACT = "VTEX email React";
273
+ var BANNER_WIDTH = Math.max(...BANNER_ASCII.map((line2) => line2.length));
274
+ function createDevPresenter(options) {
275
+ const stdout = options.stdout ?? process.stdout;
276
+ const stderr = options.stderr ?? process.stderr;
277
+ const env = options.env ?? process.env;
278
+ const color = supportsColor(stdout, env);
279
+ const json = options.format === "json";
280
+ let bannerPrinted = false;
281
+ let hadCompileFailure = false;
282
+ return { printBanner, handle };
283
+ async function printBanner() {
284
+ if (bannerPrinted) return;
285
+ bannerPrinted = true;
286
+ if (json) {
287
+ await handle({ kind: "version", version: options.version });
288
+ return;
289
+ }
290
+ const columns = resolveColumns(options.columns, stdout);
291
+ const art = columns !== void 0 && columns < BANNER_WIDTH ? BANNER_COMPACT : BANNER_ASCII.join("\n");
292
+ await writeStream(stdout, `${colorBanner(art, color)}
293
+
294
+ `);
295
+ await line(stdout, dim(`vtex-email ${options.version}`, color));
296
+ }
297
+ async function handle(notice) {
298
+ if (json) {
299
+ await writeStream(stdout, `${JSON.stringify(notice)}
300
+ `);
301
+ return;
302
+ }
303
+ switch (notice.kind) {
304
+ case "version":
305
+ await line(stdout, dim(`vtex-email ${notice.version}`, color));
306
+ return;
307
+ case "phase":
308
+ await line(stdout, dim(`starting ${notice.phase}`, color));
309
+ return;
310
+ case "project":
311
+ await line(stdout, dim(`project ${notice.name}`, color));
312
+ return;
313
+ case "discovered":
314
+ await line(stdout, dim(`${notice.emails} emails \xB7 ${notice.fixtures} fixtures`, color));
315
+ return;
316
+ case "listening":
317
+ await line(stdout, `preview ${notice.url}`);
318
+ return;
319
+ case "startup":
320
+ if (notice.templatesReady) {
321
+ await line(stdout, `ready in ${formatElapsed(notice.elapsedMs)}`);
322
+ } else if (notice.diagnostics.length > 0) {
323
+ await writeStream(stderr, diagnosticsText(notice.diagnostics));
324
+ await line(stdout, dim("server listening \xB7 templates have diagnostics", color));
325
+ } else {
326
+ await line(stdout, dim("server listening", color));
327
+ }
328
+ await line(stdout, dim("Ctrl+C to stop", color));
329
+ return;
330
+ case "failed":
331
+ await writeStream(stderr, diagnosticsText(notice.diagnostics));
332
+ return;
333
+ case "ingest":
334
+ await handleIngest(notice);
335
+ return;
336
+ case "vite":
337
+ await line(notice.level === "error" ? stderr : stdout, notice.message.trimEnd());
338
+ return;
339
+ case "stopped":
340
+ await line(stdout, dim("stopped", color));
341
+ }
342
+ }
343
+ async function handleIngest(notice) {
344
+ if (notice.plan.kind === "full") {
345
+ await line(stdout, "recompiled");
346
+ } else {
347
+ for (const id of notice.plan.compile) await line(stdout, `recompiled ${id}`);
348
+ for (const id of notice.plan.fixtures) await line(stdout, `fixture updated ${id}`);
349
+ for (const id of notice.plan.schemas) await line(stdout, `schema updated ${id}`);
350
+ }
351
+ for (const id of notice.added) await line(stdout, `email added ${id}`);
352
+ for (const id of notice.removed) await line(stdout, `email removed ${id}`);
353
+ if (notice.failed) {
354
+ hadCompileFailure = true;
355
+ await line(stderr, "compile failed");
356
+ if (notice.diagnostics.length > 0) await writeStream(stderr, diagnosticsText(notice.diagnostics));
357
+ return;
358
+ }
359
+ if (hadCompileFailure) {
360
+ hadCompileFailure = false;
361
+ await line(stdout, "recovered");
362
+ }
363
+ }
364
+ }
365
+ function supportsColor(stream, env = process.env) {
366
+ if (Object.prototype.hasOwnProperty.call(env, "NO_COLOR")) return false;
367
+ if (env.CI) return false;
368
+ if (env.FORCE_COLOR === "0") return false;
369
+ return stream.isTTY === true;
370
+ }
371
+ function resolveColumns(override, stdout) {
372
+ if (typeof override === "number") return override;
373
+ return typeof stdout.columns === "number" ? stdout.columns : void 0;
374
+ }
375
+ function colorBanner(art, color) {
376
+ if (!color) return art;
377
+ if (art === BANNER_COMPACT) {
378
+ return `${magenta("VTEX")} ${cyan("email React")}`;
379
+ }
380
+ const lines = art.split("\n");
381
+ const body = lines.slice(0, -1).map((line2) => magenta(line2));
382
+ const caption = lines[lines.length - 1] ?? "";
383
+ const trimmed = caption.trimStart();
384
+ const pad = caption.slice(0, caption.length - trimmed.length);
385
+ return [...body, `${pad}${cyan(trimmed)}`].join("\n");
386
+ }
387
+ function dim(text, color) {
388
+ return color ? `\x1B[2m${text}\x1B[0m` : text;
389
+ }
390
+ function magenta(text) {
391
+ return `\x1B[35m${text}\x1B[0m`;
392
+ }
393
+ function cyan(text) {
394
+ return `\x1B[36m${text}\x1B[0m`;
395
+ }
396
+ function formatElapsed(elapsedMs) {
397
+ if (elapsedMs < 1e3) return `${Math.round(elapsedMs)}ms`;
398
+ return `${(elapsedMs / 1e3).toFixed(1)}s`;
399
+ }
400
+ function diagnosticsText(diagnostics) {
401
+ const report = {
402
+ formatVersion: 1,
403
+ command: "usage",
404
+ ok: false,
405
+ exitCode: 1,
406
+ diagnostics: [...diagnostics],
407
+ manifest: null,
408
+ wrote: [],
409
+ preserved: [],
410
+ unverifiedCapabilities: []
411
+ };
412
+ return reportText(report);
413
+ }
414
+ async function line(stream, text) {
415
+ await writeStream(stream, `${text}
416
+ `);
417
+ }
418
+
419
+ // src/project/build-project.ts
420
+ import { errorDiagnostic as errorDiagnostic10, syntaxHelperNames as syntaxHelperNames2 } from "@vtex-email/core";
421
+
422
+ // src/config/load-config.ts
423
+ import { errorDiagnostic as errorDiagnostic3 } from "@vtex-email/core";
424
+ import path4 from "node:path";
425
+
426
+ // src/project/module-loader.ts
427
+ import { errorDiagnostic } from "@vtex-email/core";
428
+ import * as esbuild from "esbuild";
429
+ import { existsSync, rmSync } from "node:fs";
430
+ import { mkdtemp, rm } from "node:fs/promises";
431
+ import { tmpdir } from "node:os";
432
+ import path2 from "node:path";
433
+ import { pathToFileURL } from "node:url";
434
+ var external = [
435
+ "react",
436
+ "react-dom",
437
+ "react/jsx-runtime",
438
+ "react/jsx-dev-runtime",
439
+ "@react-email/components",
440
+ "@react-email/render",
441
+ "@react-email/tailwind",
442
+ "esbuild",
443
+ "zod"
444
+ ];
445
+ var externalExact = new Set(external);
446
+ var sequence = 0;
447
+ var pendingCaches = /* @__PURE__ */ new Set();
448
+ var cleanupKey = "__vtexEmailBundleCleanup";
449
+ if (!globalThis[cleanupKey]) {
450
+ ;
451
+ globalThis[cleanupKey] = true;
452
+ process.once("exit", () => {
453
+ for (const directory of pendingCaches) {
454
+ try {
455
+ rmSync(directory, { recursive: true, force: true });
456
+ } catch {
457
+ }
458
+ }
459
+ });
460
+ }
461
+ async function importBundled(entry) {
462
+ const loaded = await bundleEntry(entry, { metafile: false, guardTemplate: false });
463
+ return loaded.module;
464
+ }
465
+ async function loadEmailEntry(entry) {
466
+ let rejection = null;
467
+ try {
468
+ return await bundleEntry(entry, {
469
+ metafile: true,
470
+ guardTemplate: true,
471
+ onReject(kind) {
472
+ rejection = kind;
473
+ }
474
+ });
475
+ } catch (error) {
476
+ if (rejection) {
477
+ const message2 = rejection === "preview" ? "Preview module imported by the template." : "Fixture imported by the template.";
478
+ return { ok: false, diagnostics: [errorDiagnostic("DSL001", message2, { source: { file: entry } })] };
479
+ }
480
+ const message = error instanceof Error ? error.message : "Failed to load the template.";
481
+ return { ok: false, diagnostics: [errorDiagnostic("CFG001", message, { source: { file: entry } })] };
482
+ }
483
+ }
484
+ async function bundleEntry(entry, options) {
485
+ sequence += 1;
486
+ const directory = await mkdtemp(path2.join(tmpdir(), `vtex-email-bundle-${process.pid}-`));
487
+ pendingCaches.add(directory);
488
+ const outfile = path2.join(directory, `bundle-${process.pid}-${sequence}.mjs`);
489
+ const modules = dependencyModules(entry);
490
+ const resolveFrom = pathToFileURL(path2.join(path2.dirname(modules), "package.json")).href;
491
+ try {
492
+ const built = await esbuild.build({
493
+ absWorkingDir: path2.dirname(entry),
494
+ entryPoints: [entry],
495
+ bundle: true,
496
+ platform: "node",
497
+ format: "esm",
498
+ outfile,
499
+ jsx: "automatic",
500
+ logLevel: "silent",
501
+ metafile: options.metafile,
502
+ mainFields: ["module", "main"],
503
+ conditions: ["import", "module", "default"],
504
+ plugins: [
505
+ absoluteExternals(resolveFrom),
506
+ ...options.guardTemplate ? [rejectTemplateImports(entry, options.onReject)] : []
507
+ ]
508
+ });
509
+ const loaded = await import(pathToFileURL(outfile).href);
510
+ const dependencies = Object.keys(built.metafile?.inputs ?? {}).map(
511
+ (file) => path2.resolve(path2.dirname(entry), file)
512
+ );
513
+ return { ok: true, module: loaded, dependencies };
514
+ } finally {
515
+ await rm(directory, { recursive: true, force: true }).then(
516
+ () => {
517
+ pendingCaches.delete(directory);
518
+ },
519
+ () => {
520
+ }
521
+ );
522
+ }
523
+ }
524
+ function absoluteExternals(resolveFrom) {
525
+ return {
526
+ name: "absolute-externals",
527
+ setup(build2) {
528
+ build2.onResolve({ filter: /.*/ }, (args) => {
529
+ if (!externalExact.has(args.path)) return null;
530
+ try {
531
+ return { path: import.meta.resolve(args.path, resolveFrom), external: true };
532
+ } catch {
533
+ return { path: args.path, external: true };
534
+ }
535
+ });
536
+ }
537
+ };
538
+ }
539
+ function dependencyModules(start) {
540
+ let dir = path2.resolve(path2.dirname(start));
541
+ while (true) {
542
+ const candidate = path2.join(dir, "node_modules");
543
+ if (existsSync(path2.join(candidate, "react"))) return candidate;
544
+ const parent = path2.dirname(dir);
545
+ if (parent === dir) break;
546
+ dir = parent;
547
+ }
548
+ throw new Error("Project dependencies were not found.");
549
+ }
550
+ function rejectTemplateImports(entry, onReject) {
551
+ return {
552
+ name: "reject-fixtures",
553
+ setup(build2) {
554
+ build2.onResolve({ filter: /.*/ }, (args) => {
555
+ if (args.path === "@vtex-email/preview" || args.path === "@react-email/preview") {
556
+ onReject?.("preview");
557
+ return { errors: [{ text: "DSL001 preview module imported by the template" }] };
558
+ }
559
+ if (!args.path.startsWith(".") && !path2.isAbsolute(args.path)) return null;
560
+ const base = args.resolveDir || path2.dirname(args.importer || entry);
561
+ const resolved = path2.resolve(base, args.path);
562
+ if (resolved.split(/[\\/]/).includes("fixtures")) {
563
+ onReject?.("fixture");
564
+ return { errors: [{ text: "DSL001 fixture imported by the template" }] };
565
+ }
566
+ return null;
567
+ });
568
+ }
569
+ };
570
+ }
571
+
572
+ // src/config/config.ts
573
+ import { errorDiagnostic as errorDiagnostic2 } from "@vtex-email/core";
574
+ import path3 from "node:path";
575
+ import { z } from "zod";
576
+ var defaults = {
577
+ fixturesDir: "fixtures",
578
+ schemasDir: "schemas",
579
+ validation: {
580
+ unknownPath: "error",
581
+ unverifiedCapability: "error",
582
+ warningsAsErrors: false
583
+ },
584
+ compatibility: {
585
+ policy: "conservative",
586
+ maxSourceBytes: 25e4,
587
+ warnRenderedBytes: 9e4
588
+ },
589
+ preview: {
590
+ host: "127.0.0.1",
591
+ port: 3e3
592
+ }
593
+ };
594
+ var ConfigSchema = z.strictObject({
595
+ emails: z.array(z.string().min(1)).min(1),
596
+ outDir: z.string().min(1),
597
+ fixturesDir: z.string().min(1).optional(),
598
+ schemasDir: z.string().min(1).optional(),
599
+ target: z.strictObject({
600
+ profile: z.string().min(1)
601
+ }),
602
+ i18n: z.strictObject({
603
+ locales: z.array(z.string().min(1)).min(1),
604
+ defaultLocale: z.string().min(1),
605
+ catalogs: z.string().min(1),
606
+ missingKey: z.literal("error"),
607
+ localePath: z.string().min(1).optional()
608
+ }),
609
+ tailwind: z.custom(
610
+ (value) => value !== null && typeof value === "object" && !Array.isArray(value)
611
+ ),
612
+ validation: z.strictObject({
613
+ unknownPath: z.enum(["error", "warning"]),
614
+ unverifiedCapability: z.enum(["error", "warning"]),
615
+ warningsAsErrors: z.boolean()
616
+ }).optional(),
617
+ compatibility: z.strictObject({
618
+ policy: z.literal("conservative"),
619
+ maxSourceBytes: z.number().int().positive(),
620
+ warnRenderedBytes: z.number().int().positive()
621
+ }).optional(),
622
+ preview: z.strictObject({
623
+ host: z.string().min(1),
624
+ port: z.number().int().positive()
625
+ }).optional()
626
+ });
627
+ function validateConfig(value, configDir) {
628
+ const parsed2 = ConfigSchema.safeParse(value);
629
+ if (!parsed2.success) {
630
+ return {
631
+ ok: false,
632
+ diagnostics: parsed2.error.issues.map(
633
+ (issue) => errorDiagnostic2("CFG001", issue.message, {
634
+ path: issue.path.join(".")
635
+ })
636
+ )
637
+ };
638
+ }
639
+ if (!parsed2.data.i18n.locales.includes(parsed2.data.i18n.defaultLocale)) {
640
+ return { ok: false, diagnostics: [errorDiagnostic2("CFG001", "defaultLocale must be one of locales.")] };
641
+ }
642
+ const fixturesDir = parsed2.data.fixturesDir ?? defaults.fixturesDir;
643
+ const schemasDir = parsed2.data.schemasDir ?? defaults.schemasDir;
644
+ const outDir = path3.resolve(configDir, parsed2.data.outDir);
645
+ const sourceDirs = [
646
+ staticRoot(parsed2.data.emails[0] ?? "emails"),
647
+ staticRoot(parsed2.data.i18n.catalogs),
648
+ staticRoot(fixturesDir),
649
+ staticRoot(schemasDir)
650
+ ];
651
+ const outputError = outputDirectoryError(configDir, outDir, sourceDirs);
652
+ if (outputError) return { ok: false, diagnostics: [errorDiagnostic2("CFG001", outputError)] };
653
+ return {
654
+ ok: true,
655
+ config: {
656
+ configDir,
657
+ emails: parsed2.data.emails,
658
+ outDir,
659
+ fixturesDir,
660
+ schemasDir,
661
+ localePath: parsed2.data.i18n.localePath ?? null,
662
+ profilePath: path3.resolve(configDir, parsed2.data.target.profile),
663
+ locales: parsed2.data.i18n.locales,
664
+ defaultLocale: parsed2.data.i18n.defaultLocale,
665
+ catalogs: parsed2.data.i18n.catalogs,
666
+ tailwind: parsed2.data.tailwind,
667
+ validation: { ...defaults.validation, ...parsed2.data.validation },
668
+ compatibility: { ...defaults.compatibility, ...parsed2.data.compatibility },
669
+ preview: { ...defaults.preview, ...parsed2.data.preview }
670
+ }
671
+ };
672
+ }
673
+ function staticRoot(pattern) {
674
+ const normalized = pattern.replaceAll("\\", "/");
675
+ const [first] = normalized.split("/");
676
+ if (!first || first.includes("*")) return "";
677
+ return first;
678
+ }
679
+ function configuredOutputError(config, candidate) {
680
+ const outDir = path3.resolve(candidate);
681
+ if (outDir === config.outDir) return "outDir cannot be the project output directory.";
682
+ return outputDirectoryError(config.configDir, outDir, [
683
+ staticRoot(config.emails[0] ?? "emails"),
684
+ staticRoot(config.catalogs),
685
+ staticRoot(config.fixturesDir),
686
+ staticRoot(config.schemasDir)
687
+ ]);
688
+ }
689
+ function outputDirectoryError(configDir, outDir, sourceDirs) {
690
+ const relativeToOutput = path3.relative(outDir, configDir);
691
+ if (relativeToOutput === "" || !relativeToOutput.startsWith("..") && !path3.isAbsolute(relativeToOutput)) {
692
+ return "outDir cannot be the project root or an ancestor of it.";
693
+ }
694
+ for (const source of sourceDirs) {
695
+ if (source.length === 0) continue;
696
+ if (path3.resolve(configDir, source) === outDir) return "outDir cannot be a source directory.";
697
+ }
698
+ return null;
699
+ }
700
+
701
+ // src/config/load-config.ts
702
+ async function loadProjectConfig(configPath) {
703
+ const configDir = path4.dirname(configPath);
704
+ let loaded;
705
+ try {
706
+ loaded = await importBundled(configPath);
707
+ } catch (error) {
708
+ const message = error instanceof Error ? error.message : "Failed to load the config.";
709
+ return { ok: false, diagnostics: [errorDiagnostic3("CFG001", message, { source: { file: configPath } })] };
710
+ }
711
+ return validateConfig(loaded.default, configDir);
712
+ }
713
+
714
+ // src/project/compile-email.ts
715
+ import {
716
+ analyzePaths,
717
+ analyzeRootPath,
718
+ checkCatalogs,
719
+ errorDiagnostic as errorDiagnostic7,
720
+ sha256 as sha2562
721
+ } from "@vtex-email/core";
722
+ import { compileEmail, diagnoseStyles } from "@vtex-email/react";
723
+
724
+ // src/project/catalogs.ts
725
+ import { errorDiagnostic as errorDiagnostic4 } from "@vtex-email/core";
726
+ import { readFile } from "node:fs/promises";
727
+ import path5 from "node:path";
728
+ async function readCatalogs(config, locales, diagnostics) {
729
+ const catalogs = {};
730
+ for (const locale of locales) {
731
+ const relative = config.catalogs.replaceAll("{locale}", locale);
732
+ const file = path5.resolve(config.configDir, relative);
733
+ try {
734
+ const parsed2 = JSON.parse(await readFile(file, "utf8"));
735
+ if (!isFlatCatalog(parsed2)) {
736
+ diagnostics.push(errorDiagnostic4("I18N001", `Catalog ${locale} must be a flat string map.`, { locale }));
737
+ continue;
738
+ }
739
+ catalogs[locale] = parsed2;
740
+ } catch (error) {
741
+ const message = error instanceof Error ? error.message : `Missing catalog for ${locale}.`;
742
+ diagnostics.push(errorDiagnostic4("I18N001", message, { locale }));
743
+ }
744
+ }
745
+ return catalogs;
746
+ }
747
+ function isFlatCatalog(value) {
748
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
749
+ return Object.values(value).every((item) => typeof item === "string");
750
+ }
751
+
752
+ // src/project/fixtures.ts
753
+ import { checkFixture, errorDiagnostic as errorDiagnostic5 } from "@vtex-email/core";
754
+
755
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
756
+ function createScanner(text, ignoreTrivia = false) {
757
+ const len = text.length;
758
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
759
+ function scanHexDigits(count, exact) {
760
+ let digits = 0;
761
+ let value2 = 0;
762
+ while (digits < count || !exact) {
763
+ let ch = text.charCodeAt(pos);
764
+ if (ch >= 48 && ch <= 57) {
765
+ value2 = value2 * 16 + ch - 48;
766
+ } else if (ch >= 65 && ch <= 70) {
767
+ value2 = value2 * 16 + ch - 65 + 10;
768
+ } else if (ch >= 97 && ch <= 102) {
769
+ value2 = value2 * 16 + ch - 97 + 10;
770
+ } else {
771
+ break;
772
+ }
773
+ pos++;
774
+ digits++;
775
+ }
776
+ if (digits < count) {
777
+ value2 = -1;
778
+ }
779
+ return value2;
780
+ }
781
+ function setPosition(newPosition) {
782
+ pos = newPosition;
783
+ value = "";
784
+ tokenOffset = 0;
785
+ token = 16;
786
+ scanError = 0;
787
+ }
788
+ function scanNumber() {
789
+ let start = pos;
790
+ if (text.charCodeAt(pos) === 48) {
791
+ pos++;
792
+ } else {
793
+ pos++;
794
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
795
+ pos++;
796
+ }
797
+ }
798
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
799
+ pos++;
800
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
801
+ pos++;
802
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
803
+ pos++;
804
+ }
805
+ } else {
806
+ scanError = 3;
807
+ return text.substring(start, pos);
808
+ }
809
+ }
810
+ let end = pos;
811
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
812
+ pos++;
813
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
814
+ pos++;
815
+ }
816
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
817
+ pos++;
818
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
819
+ pos++;
820
+ }
821
+ end = pos;
822
+ } else {
823
+ scanError = 3;
824
+ }
825
+ }
826
+ return text.substring(start, end);
827
+ }
828
+ function scanString() {
829
+ let result = "", start = pos;
830
+ while (true) {
831
+ if (pos >= len) {
832
+ result += text.substring(start, pos);
833
+ scanError = 2;
834
+ break;
835
+ }
836
+ const ch = text.charCodeAt(pos);
837
+ if (ch === 34) {
838
+ result += text.substring(start, pos);
839
+ pos++;
840
+ break;
841
+ }
842
+ if (ch === 92) {
843
+ result += text.substring(start, pos);
844
+ pos++;
845
+ if (pos >= len) {
846
+ scanError = 2;
847
+ break;
848
+ }
849
+ const ch2 = text.charCodeAt(pos++);
850
+ switch (ch2) {
851
+ case 34:
852
+ result += '"';
853
+ break;
854
+ case 92:
855
+ result += "\\";
856
+ break;
857
+ case 47:
858
+ result += "/";
859
+ break;
860
+ case 98:
861
+ result += "\b";
862
+ break;
863
+ case 102:
864
+ result += "\f";
865
+ break;
866
+ case 110:
867
+ result += "\n";
868
+ break;
869
+ case 114:
870
+ result += "\r";
871
+ break;
872
+ case 116:
873
+ result += " ";
874
+ break;
875
+ case 117:
876
+ const ch3 = scanHexDigits(4, true);
877
+ if (ch3 >= 0) {
878
+ result += String.fromCharCode(ch3);
879
+ } else {
880
+ scanError = 4;
881
+ }
882
+ break;
883
+ default:
884
+ scanError = 5;
885
+ }
886
+ start = pos;
887
+ continue;
888
+ }
889
+ if (ch >= 0 && ch <= 31) {
890
+ if (isLineBreak(ch)) {
891
+ result += text.substring(start, pos);
892
+ scanError = 2;
893
+ break;
894
+ } else {
895
+ scanError = 6;
896
+ }
897
+ }
898
+ pos++;
899
+ }
900
+ return result;
901
+ }
902
+ function scanNext() {
903
+ value = "";
904
+ scanError = 0;
905
+ tokenOffset = pos;
906
+ lineStartOffset = lineNumber;
907
+ prevTokenLineStartOffset = tokenLineStartOffset;
908
+ if (pos >= len) {
909
+ tokenOffset = len;
910
+ return token = 17;
911
+ }
912
+ let code2 = text.charCodeAt(pos);
913
+ if (isWhiteSpace(code2)) {
914
+ do {
915
+ pos++;
916
+ value += String.fromCharCode(code2);
917
+ code2 = text.charCodeAt(pos);
918
+ } while (isWhiteSpace(code2));
919
+ return token = 15;
920
+ }
921
+ if (isLineBreak(code2)) {
922
+ pos++;
923
+ value += String.fromCharCode(code2);
924
+ if (code2 === 13 && text.charCodeAt(pos) === 10) {
925
+ pos++;
926
+ value += "\n";
927
+ }
928
+ lineNumber++;
929
+ tokenLineStartOffset = pos;
930
+ return token = 14;
931
+ }
932
+ switch (code2) {
933
+ // tokens: []{}:,
934
+ case 123:
935
+ pos++;
936
+ return token = 1;
937
+ case 125:
938
+ pos++;
939
+ return token = 2;
940
+ case 91:
941
+ pos++;
942
+ return token = 3;
943
+ case 93:
944
+ pos++;
945
+ return token = 4;
946
+ case 58:
947
+ pos++;
948
+ return token = 6;
949
+ case 44:
950
+ pos++;
951
+ return token = 5;
952
+ // strings
953
+ case 34:
954
+ pos++;
955
+ value = scanString();
956
+ return token = 10;
957
+ // comments
958
+ case 47:
959
+ const start = pos - 1;
960
+ if (text.charCodeAt(pos + 1) === 47) {
961
+ pos += 2;
962
+ while (pos < len) {
963
+ if (isLineBreak(text.charCodeAt(pos))) {
964
+ break;
965
+ }
966
+ pos++;
967
+ }
968
+ value = text.substring(start, pos);
969
+ return token = 12;
970
+ }
971
+ if (text.charCodeAt(pos + 1) === 42) {
972
+ pos += 2;
973
+ const safeLength = len - 1;
974
+ let commentClosed = false;
975
+ while (pos < safeLength) {
976
+ const ch = text.charCodeAt(pos);
977
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
978
+ pos += 2;
979
+ commentClosed = true;
980
+ break;
981
+ }
982
+ pos++;
983
+ if (isLineBreak(ch)) {
984
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
985
+ pos++;
986
+ }
987
+ lineNumber++;
988
+ tokenLineStartOffset = pos;
989
+ }
990
+ }
991
+ if (!commentClosed) {
992
+ pos++;
993
+ scanError = 1;
994
+ }
995
+ value = text.substring(start, pos);
996
+ return token = 13;
997
+ }
998
+ value += String.fromCharCode(code2);
999
+ pos++;
1000
+ return token = 16;
1001
+ // numbers
1002
+ case 45:
1003
+ value += String.fromCharCode(code2);
1004
+ pos++;
1005
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
1006
+ return token = 16;
1007
+ }
1008
+ // found a minus, followed by a number so
1009
+ // we fall through to proceed with scanning
1010
+ // numbers
1011
+ case 48:
1012
+ case 49:
1013
+ case 50:
1014
+ case 51:
1015
+ case 52:
1016
+ case 53:
1017
+ case 54:
1018
+ case 55:
1019
+ case 56:
1020
+ case 57:
1021
+ value += scanNumber();
1022
+ return token = 11;
1023
+ // literals and unknown symbols
1024
+ default:
1025
+ while (pos < len && isUnknownContentCharacter(code2)) {
1026
+ pos++;
1027
+ code2 = text.charCodeAt(pos);
1028
+ }
1029
+ if (tokenOffset !== pos) {
1030
+ value = text.substring(tokenOffset, pos);
1031
+ switch (value) {
1032
+ case "true":
1033
+ return token = 8;
1034
+ case "false":
1035
+ return token = 9;
1036
+ case "null":
1037
+ return token = 7;
1038
+ }
1039
+ return token = 16;
1040
+ }
1041
+ value += String.fromCharCode(code2);
1042
+ pos++;
1043
+ return token = 16;
1044
+ }
1045
+ }
1046
+ function isUnknownContentCharacter(code2) {
1047
+ if (isWhiteSpace(code2) || isLineBreak(code2)) {
1048
+ return false;
1049
+ }
1050
+ switch (code2) {
1051
+ case 125:
1052
+ case 93:
1053
+ case 123:
1054
+ case 91:
1055
+ case 34:
1056
+ case 58:
1057
+ case 44:
1058
+ case 47:
1059
+ return false;
1060
+ }
1061
+ return true;
1062
+ }
1063
+ function scanNextNonTrivia() {
1064
+ let result;
1065
+ do {
1066
+ result = scanNext();
1067
+ } while (result >= 12 && result <= 15);
1068
+ return result;
1069
+ }
1070
+ return {
1071
+ setPosition,
1072
+ getPosition: () => pos,
1073
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
1074
+ getToken: () => token,
1075
+ getTokenValue: () => value,
1076
+ getTokenOffset: () => tokenOffset,
1077
+ getTokenLength: () => pos - tokenOffset,
1078
+ getTokenStartLine: () => lineStartOffset,
1079
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
1080
+ getTokenError: () => scanError
1081
+ };
1082
+ }
1083
+ function isWhiteSpace(ch) {
1084
+ return ch === 32 || ch === 9;
1085
+ }
1086
+ function isLineBreak(ch) {
1087
+ return ch === 10 || ch === 13;
1088
+ }
1089
+ function isDigit(ch) {
1090
+ return ch >= 48 && ch <= 57;
1091
+ }
1092
+ var CharacterCodes;
1093
+ (function(CharacterCodes2) {
1094
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
1095
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
1096
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
1097
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
1098
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
1099
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
1100
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
1101
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
1102
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
1103
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
1104
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
1105
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
1106
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
1107
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
1108
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
1109
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
1110
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
1111
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
1112
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
1113
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
1114
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
1115
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
1116
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
1117
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
1118
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
1119
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
1120
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
1121
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
1122
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
1123
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
1124
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
1125
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
1126
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
1127
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
1128
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
1129
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
1130
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
1131
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
1132
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
1133
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
1134
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
1135
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
1136
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
1137
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
1138
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
1139
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
1140
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
1141
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
1142
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
1143
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
1144
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
1145
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
1146
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
1147
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
1148
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
1149
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
1150
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
1151
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
1152
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
1153
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
1154
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
1155
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
1156
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
1157
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
1158
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
1159
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
1160
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
1161
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
1162
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
1163
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
1164
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
1165
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
1166
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
1167
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
1168
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
1169
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
1170
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
1171
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
1172
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
1173
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
1174
+ })(CharacterCodes || (CharacterCodes = {}));
1175
+
1176
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
1177
+ var cachedSpaces = new Array(20).fill(0).map((_, index) => {
1178
+ return " ".repeat(index);
1179
+ });
1180
+ var maxCachedValues = 200;
1181
+ var cachedBreakLinesWithSpaces = {
1182
+ " ": {
1183
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1184
+ return "\n" + " ".repeat(index);
1185
+ }),
1186
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1187
+ return "\r" + " ".repeat(index);
1188
+ }),
1189
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1190
+ return "\r\n" + " ".repeat(index);
1191
+ })
1192
+ },
1193
+ " ": {
1194
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1195
+ return "\n" + " ".repeat(index);
1196
+ }),
1197
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
1198
+ return "\r" + " ".repeat(index);
1199
+ }),
1200
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
1201
+ return "\r\n" + " ".repeat(index);
1202
+ })
1203
+ }
1204
+ };
1205
+
1206
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
1207
+ var ParseOptions;
1208
+ (function(ParseOptions2) {
1209
+ ParseOptions2.DEFAULT = {
1210
+ allowTrailingComma: false
1211
+ };
1212
+ })(ParseOptions || (ParseOptions = {}));
1213
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
1214
+ let currentProperty = null;
1215
+ let currentParent = [];
1216
+ const previousParents = [];
1217
+ function onValue(value) {
1218
+ if (Array.isArray(currentParent)) {
1219
+ currentParent.push(value);
1220
+ } else if (currentProperty !== null) {
1221
+ currentParent[currentProperty] = value;
1222
+ }
1223
+ }
1224
+ const visitor = {
1225
+ onObjectBegin: () => {
1226
+ const object = {};
1227
+ onValue(object);
1228
+ previousParents.push(currentParent);
1229
+ currentParent = object;
1230
+ currentProperty = null;
1231
+ },
1232
+ onObjectProperty: (name) => {
1233
+ currentProperty = name;
1234
+ },
1235
+ onObjectEnd: () => {
1236
+ currentParent = previousParents.pop();
1237
+ },
1238
+ onArrayBegin: () => {
1239
+ const array = [];
1240
+ onValue(array);
1241
+ previousParents.push(currentParent);
1242
+ currentParent = array;
1243
+ currentProperty = null;
1244
+ },
1245
+ onArrayEnd: () => {
1246
+ currentParent = previousParents.pop();
1247
+ },
1248
+ onLiteralValue: onValue,
1249
+ onError: (error, offset, length) => {
1250
+ errors.push({ error, offset, length });
1251
+ }
1252
+ };
1253
+ visit(text, visitor, options);
1254
+ return currentParent[0];
1255
+ }
1256
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
1257
+ const _scanner = createScanner(text, false);
1258
+ const _jsonPath = [];
1259
+ let suppressedCallbacks = 0;
1260
+ function toNoArgVisit(visitFunction) {
1261
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1262
+ }
1263
+ function toOneArgVisit(visitFunction) {
1264
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
1265
+ }
1266
+ function toOneArgVisitWithPath(visitFunction) {
1267
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
1268
+ }
1269
+ function toBeginVisit(visitFunction) {
1270
+ return visitFunction ? () => {
1271
+ if (suppressedCallbacks > 0) {
1272
+ suppressedCallbacks++;
1273
+ } else {
1274
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
1275
+ if (cbReturn === false) {
1276
+ suppressedCallbacks = 1;
1277
+ }
1278
+ }
1279
+ } : () => true;
1280
+ }
1281
+ function toEndVisit(visitFunction) {
1282
+ return visitFunction ? () => {
1283
+ if (suppressedCallbacks > 0) {
1284
+ suppressedCallbacks--;
1285
+ }
1286
+ if (suppressedCallbacks === 0) {
1287
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
1288
+ }
1289
+ } : () => true;
1290
+ }
1291
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
1292
+ const disallowComments = options && options.disallowComments;
1293
+ const allowTrailingComma = options && options.allowTrailingComma;
1294
+ function scanNext() {
1295
+ while (true) {
1296
+ const token = _scanner.scan();
1297
+ switch (_scanner.getTokenError()) {
1298
+ case 4:
1299
+ handleError(
1300
+ 14
1301
+ /* ParseErrorCode.InvalidUnicode */
1302
+ );
1303
+ break;
1304
+ case 5:
1305
+ handleError(
1306
+ 15
1307
+ /* ParseErrorCode.InvalidEscapeCharacter */
1308
+ );
1309
+ break;
1310
+ case 3:
1311
+ handleError(
1312
+ 13
1313
+ /* ParseErrorCode.UnexpectedEndOfNumber */
1314
+ );
1315
+ break;
1316
+ case 1:
1317
+ if (!disallowComments) {
1318
+ handleError(
1319
+ 11
1320
+ /* ParseErrorCode.UnexpectedEndOfComment */
1321
+ );
1322
+ }
1323
+ break;
1324
+ case 2:
1325
+ handleError(
1326
+ 12
1327
+ /* ParseErrorCode.UnexpectedEndOfString */
1328
+ );
1329
+ break;
1330
+ case 6:
1331
+ handleError(
1332
+ 16
1333
+ /* ParseErrorCode.InvalidCharacter */
1334
+ );
1335
+ break;
1336
+ }
1337
+ switch (token) {
1338
+ case 12:
1339
+ case 13:
1340
+ if (disallowComments) {
1341
+ handleError(
1342
+ 10
1343
+ /* ParseErrorCode.InvalidCommentToken */
1344
+ );
1345
+ } else {
1346
+ onComment();
1347
+ }
1348
+ break;
1349
+ case 16:
1350
+ handleError(
1351
+ 1
1352
+ /* ParseErrorCode.InvalidSymbol */
1353
+ );
1354
+ break;
1355
+ case 15:
1356
+ case 14:
1357
+ break;
1358
+ default:
1359
+ return token;
1360
+ }
1361
+ }
1362
+ }
1363
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
1364
+ onError(error);
1365
+ if (skipUntilAfter.length + skipUntil.length > 0) {
1366
+ let token = _scanner.getToken();
1367
+ while (token !== 17) {
1368
+ if (skipUntilAfter.indexOf(token) !== -1) {
1369
+ scanNext();
1370
+ break;
1371
+ } else if (skipUntil.indexOf(token) !== -1) {
1372
+ break;
1373
+ }
1374
+ token = scanNext();
1375
+ }
1376
+ }
1377
+ }
1378
+ function parseString(isValue) {
1379
+ const value = _scanner.getTokenValue();
1380
+ if (isValue) {
1381
+ onLiteralValue(value);
1382
+ } else {
1383
+ onObjectProperty(value);
1384
+ _jsonPath.push(value);
1385
+ }
1386
+ scanNext();
1387
+ return true;
1388
+ }
1389
+ function parseLiteral() {
1390
+ switch (_scanner.getToken()) {
1391
+ case 11:
1392
+ const tokenValue = _scanner.getTokenValue();
1393
+ let value = Number(tokenValue);
1394
+ if (isNaN(value)) {
1395
+ handleError(
1396
+ 2
1397
+ /* ParseErrorCode.InvalidNumberFormat */
1398
+ );
1399
+ value = 0;
1400
+ }
1401
+ onLiteralValue(value);
1402
+ break;
1403
+ case 7:
1404
+ onLiteralValue(null);
1405
+ break;
1406
+ case 8:
1407
+ onLiteralValue(true);
1408
+ break;
1409
+ case 9:
1410
+ onLiteralValue(false);
1411
+ break;
1412
+ default:
1413
+ return false;
1414
+ }
1415
+ scanNext();
1416
+ return true;
1417
+ }
1418
+ function parseProperty() {
1419
+ if (_scanner.getToken() !== 10) {
1420
+ handleError(3, [], [
1421
+ 2,
1422
+ 5
1423
+ /* SyntaxKind.CommaToken */
1424
+ ]);
1425
+ return false;
1426
+ }
1427
+ parseString(false);
1428
+ if (_scanner.getToken() === 6) {
1429
+ onSeparator(":");
1430
+ scanNext();
1431
+ if (!parseValue()) {
1432
+ handleError(4, [], [
1433
+ 2,
1434
+ 5
1435
+ /* SyntaxKind.CommaToken */
1436
+ ]);
1437
+ }
1438
+ } else {
1439
+ handleError(5, [], [
1440
+ 2,
1441
+ 5
1442
+ /* SyntaxKind.CommaToken */
1443
+ ]);
1444
+ }
1445
+ _jsonPath.pop();
1446
+ return true;
1447
+ }
1448
+ function parseObject() {
1449
+ onObjectBegin();
1450
+ scanNext();
1451
+ let needsComma = false;
1452
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
1453
+ if (_scanner.getToken() === 5) {
1454
+ if (!needsComma) {
1455
+ handleError(4, [], []);
1456
+ }
1457
+ onSeparator(",");
1458
+ scanNext();
1459
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
1460
+ break;
1461
+ }
1462
+ } else if (needsComma) {
1463
+ handleError(6, [], []);
1464
+ }
1465
+ if (!parseProperty()) {
1466
+ handleError(4, [], [
1467
+ 2,
1468
+ 5
1469
+ /* SyntaxKind.CommaToken */
1470
+ ]);
1471
+ }
1472
+ needsComma = true;
1473
+ }
1474
+ onObjectEnd();
1475
+ if (_scanner.getToken() !== 2) {
1476
+ handleError(7, [
1477
+ 2
1478
+ /* SyntaxKind.CloseBraceToken */
1479
+ ], []);
1480
+ } else {
1481
+ scanNext();
1482
+ }
1483
+ return true;
1484
+ }
1485
+ function parseArray() {
1486
+ onArrayBegin();
1487
+ scanNext();
1488
+ let isFirstElement = true;
1489
+ let needsComma = false;
1490
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
1491
+ if (_scanner.getToken() === 5) {
1492
+ if (!needsComma) {
1493
+ handleError(4, [], []);
1494
+ }
1495
+ onSeparator(",");
1496
+ scanNext();
1497
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
1498
+ break;
1499
+ }
1500
+ } else if (needsComma) {
1501
+ handleError(6, [], []);
1502
+ }
1503
+ if (isFirstElement) {
1504
+ _jsonPath.push(0);
1505
+ isFirstElement = false;
1506
+ } else {
1507
+ _jsonPath[_jsonPath.length - 1]++;
1508
+ }
1509
+ if (!parseValue()) {
1510
+ handleError(4, [], [
1511
+ 4,
1512
+ 5
1513
+ /* SyntaxKind.CommaToken */
1514
+ ]);
1515
+ }
1516
+ needsComma = true;
1517
+ }
1518
+ onArrayEnd();
1519
+ if (!isFirstElement) {
1520
+ _jsonPath.pop();
1521
+ }
1522
+ if (_scanner.getToken() !== 4) {
1523
+ handleError(8, [
1524
+ 4
1525
+ /* SyntaxKind.CloseBracketToken */
1526
+ ], []);
1527
+ } else {
1528
+ scanNext();
1529
+ }
1530
+ return true;
1531
+ }
1532
+ function parseValue() {
1533
+ switch (_scanner.getToken()) {
1534
+ case 3:
1535
+ return parseArray();
1536
+ case 1:
1537
+ return parseObject();
1538
+ case 10:
1539
+ return parseString(true);
1540
+ default:
1541
+ return parseLiteral();
1542
+ }
1543
+ }
1544
+ scanNext();
1545
+ if (_scanner.getToken() === 17) {
1546
+ if (options.allowEmptyContent) {
1547
+ return true;
1548
+ }
1549
+ handleError(4, [], []);
1550
+ return false;
1551
+ }
1552
+ if (!parseValue()) {
1553
+ handleError(4, [], []);
1554
+ return false;
1555
+ }
1556
+ if (_scanner.getToken() !== 17) {
1557
+ handleError(9, [], []);
1558
+ }
1559
+ return true;
1560
+ }
1561
+
1562
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
1563
+ var ScanError;
1564
+ (function(ScanError2) {
1565
+ ScanError2[ScanError2["None"] = 0] = "None";
1566
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
1567
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
1568
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
1569
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
1570
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
1571
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
1572
+ })(ScanError || (ScanError = {}));
1573
+ var SyntaxKind;
1574
+ (function(SyntaxKind2) {
1575
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
1576
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
1577
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
1578
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
1579
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
1580
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
1581
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
1582
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
1583
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
1584
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
1585
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
1586
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
1587
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
1588
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
1589
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
1590
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
1591
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
1592
+ })(SyntaxKind || (SyntaxKind = {}));
1593
+ var parse2 = parse;
1594
+ var ParseErrorCode;
1595
+ (function(ParseErrorCode2) {
1596
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
1597
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
1598
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
1599
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
1600
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
1601
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
1602
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
1603
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
1604
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
1605
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
1606
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
1607
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
1608
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
1609
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
1610
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
1611
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
1612
+ })(ParseErrorCode || (ParseErrorCode = {}));
1613
+ function printParseErrorCode(code2) {
1614
+ switch (code2) {
1615
+ case 1:
1616
+ return "InvalidSymbol";
1617
+ case 2:
1618
+ return "InvalidNumberFormat";
1619
+ case 3:
1620
+ return "PropertyNameExpected";
1621
+ case 4:
1622
+ return "ValueExpected";
1623
+ case 5:
1624
+ return "ColonExpected";
1625
+ case 6:
1626
+ return "CommaExpected";
1627
+ case 7:
1628
+ return "CloseBraceExpected";
1629
+ case 8:
1630
+ return "CloseBracketExpected";
1631
+ case 9:
1632
+ return "EndOfFileExpected";
1633
+ case 10:
1634
+ return "InvalidCommentToken";
1635
+ case 11:
1636
+ return "UnexpectedEndOfComment";
1637
+ case 12:
1638
+ return "UnexpectedEndOfString";
1639
+ case 13:
1640
+ return "UnexpectedEndOfNumber";
1641
+ case 14:
1642
+ return "InvalidUnicode";
1643
+ case 15:
1644
+ return "InvalidEscapeCharacter";
1645
+ case 16:
1646
+ return "InvalidCharacter";
1647
+ }
1648
+ return "<unknown ParseErrorCode>";
1649
+ }
1650
+
1651
+ // src/project/fixtures.ts
1652
+ import { access, readdir, readFile as readFile2 } from "node:fs/promises";
1653
+ import path6 from "node:path";
1654
+ var PAYLOAD_EXTENSIONS = [".json", ".jsonc"];
1655
+ async function readFixtures(configDir, emailId, fixturesRelative, diagnostics) {
1656
+ const directory = path6.resolve(configDir, fixturesRelative);
1657
+ if (!await exists(directory)) {
1658
+ diagnostics.push(
1659
+ errorDiagnostic5("CFG001", `Fixtures directory not found: ${toPosix(fixturesRelative)}`, {
1660
+ templateId: emailId,
1661
+ source: { file: directory }
1662
+ })
1663
+ );
1664
+ return [];
1665
+ }
1666
+ const entries = await readdir(directory, { withFileTypes: true });
1667
+ const payloads = entries.filter((entry) => entry.isFile() && isPayloadFile(entry.name));
1668
+ const byId = /* @__PURE__ */ new Map();
1669
+ for (const entry of payloads) {
1670
+ const id = fixtureIdFromName(entry.name);
1671
+ if (!id) continue;
1672
+ const list = byId.get(id) ?? [];
1673
+ list.push(entry.name);
1674
+ byId.set(id, list);
1675
+ }
1676
+ const fixtures = [];
1677
+ for (const [id, names] of [...byId.entries()].sort((left, right) => left[0].localeCompare(right[0]))) {
1678
+ if (names.length > 1) {
1679
+ diagnostics.push(
1680
+ errorDiagnostic5(
1681
+ "CFG001",
1682
+ `Fixture id "${id}" collides between ${names.sort().join(" and ")}. Keep only one of .json or .jsonc.`,
1683
+ { templateId: emailId, fixtureId: id, source: { file: directory } }
1684
+ )
1685
+ );
1686
+ continue;
1687
+ }
1688
+ const name = names[0];
1689
+ const file = path6.join(directory, name);
1690
+ const metaFile = path6.join(directory, `${id}.meta.json`);
1691
+ const parsed2 = await parseFixtureFile(file);
1692
+ if (!parsed2.ok) {
1693
+ diagnostics.push({
1694
+ ...parsed2.diagnostic,
1695
+ templateId: emailId,
1696
+ fixtureId: id
1697
+ });
1698
+ continue;
1699
+ }
1700
+ let metaRaw;
1701
+ try {
1702
+ metaRaw = JSON.parse(await readFile2(metaFile, "utf8"));
1703
+ } catch (error) {
1704
+ const message = error instanceof Error ? error.message : `Failed to read fixture meta ${id}.`;
1705
+ diagnostics.push(
1706
+ errorDiagnostic5("CFG001", message, {
1707
+ templateId: emailId,
1708
+ fixtureId: id,
1709
+ source: { file: metaFile }
1710
+ })
1711
+ );
1712
+ continue;
1713
+ }
1714
+ const meta = parseMeta(metaRaw);
1715
+ if (!meta) {
1716
+ diagnostics.push(
1717
+ errorDiagnostic5("CFG001", `Fixture ${id} has an invalid sidecar.`, {
1718
+ templateId: emailId,
1719
+ fixtureId: id,
1720
+ source: { file: metaFile }
1721
+ })
1722
+ );
1723
+ continue;
1724
+ }
1725
+ fixtures.push({ id, file, data: parsed2.data, meta, negative: meta.expect === "invalid" });
1726
+ }
1727
+ return fixtures;
1728
+ }
1729
+ function checkLoadedFixtures(emailId, schema, fixtures) {
1730
+ const diagnostics = [];
1731
+ for (const fixture of fixtures) {
1732
+ const issue = checkFixture(schema, fixture.data);
1733
+ if (fixture.negative) {
1734
+ if (!issue) {
1735
+ diagnostics.push(
1736
+ errorDiagnostic5("DATA001", `Negative fixture ${fixture.id} was accepted by the schema.`, {
1737
+ templateId: emailId,
1738
+ fixtureId: fixture.id,
1739
+ origin: fixture.meta.origin
1740
+ })
1741
+ );
1742
+ }
1743
+ continue;
1744
+ }
1745
+ if (issue) {
1746
+ diagnostics.push({ ...issue, templateId: emailId, fixtureId: fixture.id, origin: fixture.meta.origin });
1747
+ }
1748
+ }
1749
+ return diagnostics;
1750
+ }
1751
+ function isPayloadFile(name) {
1752
+ const lower = name.toLowerCase();
1753
+ if (lower.endsWith(".meta.json") || lower.endsWith(".meta.jsonc")) return false;
1754
+ return PAYLOAD_EXTENSIONS.some((extension) => lower.endsWith(extension));
1755
+ }
1756
+ function fixtureIdFromName(name) {
1757
+ const lower = name.toLowerCase();
1758
+ if (lower.endsWith(".meta.json") || lower.endsWith(".meta.jsonc")) return null;
1759
+ if (lower.endsWith(".jsonc")) return name.slice(0, -".jsonc".length);
1760
+ if (lower.endsWith(".json")) return name.slice(0, -".json".length);
1761
+ return null;
1762
+ }
1763
+ async function parseFixtureFile(file) {
1764
+ let text;
1765
+ try {
1766
+ text = await readFile2(file, "utf8");
1767
+ } catch (error) {
1768
+ const message = error instanceof Error ? error.message : "Failed to read fixture.";
1769
+ return { ok: false, diagnostic: errorDiagnostic5("CFG001", message, { source: { file } }) };
1770
+ }
1771
+ if (file.toLowerCase().endsWith(".jsonc")) {
1772
+ const errors = [];
1773
+ const data = parse2(text, errors, { allowTrailingComma: true, disallowComments: false });
1774
+ if (errors.length > 0) {
1775
+ const first = errors[0];
1776
+ const position = offsetToPosition(text, first.offset);
1777
+ return {
1778
+ ok: false,
1779
+ diagnostic: errorDiagnostic5("CFG001", `Invalid JSONC: ${printParseErrorCode(first.error)}`, {
1780
+ source: { file, line: position.line, column: position.column }
1781
+ })
1782
+ };
1783
+ }
1784
+ return { ok: true, data };
1785
+ }
1786
+ try {
1787
+ return { ok: true, data: JSON.parse(text) };
1788
+ } catch (error) {
1789
+ const message = error instanceof Error ? error.message : "Invalid JSON.";
1790
+ const position = jsonErrorPosition(message, text);
1791
+ return {
1792
+ ok: false,
1793
+ diagnostic: errorDiagnostic5("CFG001", message, {
1794
+ source: { file, ...position }
1795
+ })
1796
+ };
1797
+ }
1798
+ }
1799
+ function parseMeta(value) {
1800
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1801
+ const record = value;
1802
+ const allowed = /* @__PURE__ */ new Set(["description", "origin", "event", "purpose", "expectedLocale", "expect"]);
1803
+ if (Object.keys(record).some((key) => !allowed.has(key))) return null;
1804
+ if (typeof record.description !== "string" || typeof record.origin !== "string" || typeof record.event !== "string" || typeof record.purpose !== "string") {
1805
+ return null;
1806
+ }
1807
+ if (record.expectedLocale !== void 0 && typeof record.expectedLocale !== "string") return null;
1808
+ const expect = record.expect ?? "valid";
1809
+ if (expect !== "valid" && expect !== "invalid") return null;
1810
+ return {
1811
+ description: record.description,
1812
+ origin: record.origin,
1813
+ event: record.event,
1814
+ purpose: record.purpose,
1815
+ expect,
1816
+ ...typeof record.expectedLocale === "string" ? { expectedLocale: record.expectedLocale } : {}
1817
+ };
1818
+ }
1819
+ function offsetToPosition(text, offset) {
1820
+ let line2 = 1;
1821
+ let column = 1;
1822
+ const end = Math.min(offset, text.length);
1823
+ for (let index = 0; index < end; index += 1) {
1824
+ if (text[index] === "\n") {
1825
+ line2 += 1;
1826
+ column = 1;
1827
+ } else {
1828
+ column += 1;
1829
+ }
1830
+ }
1831
+ return { line: line2, column };
1832
+ }
1833
+ function jsonErrorPosition(message, text) {
1834
+ const match = /position\s+(\d+)/i.exec(message);
1835
+ if (!match) return null;
1836
+ return offsetToPosition(text, Number(match[1]));
1837
+ }
1838
+ async function exists(file) {
1839
+ try {
1840
+ await access(file);
1841
+ return true;
1842
+ } catch {
1843
+ return false;
1844
+ }
1845
+ }
1846
+ function toPosix(value) {
1847
+ return value.replaceAll("\\", "/");
1848
+ }
1849
+
1850
+ // src/project/merge-variants.ts
1851
+ import {
1852
+ errorDiagnostic as errorDiagnostic6,
1853
+ findCapability,
1854
+ mergeLocaleDocuments,
1855
+ normalizeOutput,
1856
+ sha256,
1857
+ syntaxHelperNames,
1858
+ unverifiedCapabilityDiagnostic,
1859
+ validateHandlebarsSyntax
1860
+ } from "@vtex-email/core";
1861
+ function mergeVariants(input) {
1862
+ const { email, profile, documents, files, diagnostics } = input;
1863
+ let documentManifest = input.manifest;
1864
+ if (email.output === "merged" && !diagnostics.some((item) => item.severity === "error") && documents.length === email.locales.length) {
1865
+ const branches = documents.filter((document) => document.locale !== email.defaultLocale).length + email.aliases.length;
1866
+ if (branches > 0 && !profile.emission.capabilities.some((item) => item.name === "eq" && item.form === "block")) {
1867
+ diagnostics.push(
1868
+ errorDiagnostic6("HBS002", "Merged output requires the experimental eq capability.", {
1869
+ templateId: email.definition.id
1870
+ })
1871
+ );
1872
+ } else {
1873
+ const merged = normalizeOutput(
1874
+ mergeLocaleDocuments({
1875
+ localePath: email.localePath,
1876
+ defaultLocale: email.defaultLocale,
1877
+ documents: documents.map((document) => ({ locale: document.locale, html: document.html })),
1878
+ aliases: email.aliases,
1879
+ equality: "eq"
1880
+ })
1881
+ );
1882
+ const syntax = validateHandlebarsSyntax(merged, syntaxHelperNames(profile.emission));
1883
+ if (syntax) diagnostics.push({ ...syntax, templateId: email.definition.id });
1884
+ else {
1885
+ files.push({
1886
+ name: `${email.definition.id}.html`,
1887
+ content: merged,
1888
+ sha256: sha256(merged),
1889
+ role: "merged"
1890
+ });
1891
+ if (branches > 0)
1892
+ documentManifest = recordEmittedEquality(profile, email.definition.id, diagnostics, documentManifest);
1893
+ }
1894
+ }
1895
+ }
1896
+ if (email.output === "per-locale") {
1897
+ const mergedIndex = files.findIndex((file) => file.role === "merged");
1898
+ if (mergedIndex >= 0) files.splice(mergedIndex, 1);
1899
+ }
1900
+ return documentManifest;
1901
+ }
1902
+ function recordEmittedEquality(profile, templateId, diagnostics, manifest) {
1903
+ const eq = findCapability(profile.emission, "eq", "block");
1904
+ if (!eq) return manifest;
1905
+ if (eq.evidence !== "verified") {
1906
+ const issue = unverifiedCapabilityDiagnostic(eq, templateId);
1907
+ if (issue) diagnostics.push(issue);
1908
+ }
1909
+ if (!manifest || manifest.capabilities.some((item) => item.name === eq.name)) return manifest;
1910
+ return {
1911
+ ...manifest,
1912
+ capabilities: [...manifest.capabilities, { name: eq.name, evidence: eq.evidence, note: eq.note }]
1913
+ };
1914
+ }
1915
+
1916
+ // src/project/policy.ts
1917
+ function applyPolicy(diagnostics, email) {
1918
+ return diagnostics.map((issue) => {
1919
+ let severity = issue.severity;
1920
+ if (issue.code === "PATH001" && email.unknownPath === "warning") severity = "warning";
1921
+ if (issue.code === "TARGET001" && email.unverifiedCapability === "error") severity = "error";
1922
+ if (severity === "warning" && email.warningsAsErrors) severity = "error";
1923
+ return severity === issue.severity ? issue : { ...issue, severity };
1924
+ });
1925
+ }
1926
+
1927
+ // src/project/compile-email.ts
1928
+ async function compileOne(config, profile, email) {
1929
+ const diagnostics = [];
1930
+ const catalogs = await readCatalogs(config, email.locales, diagnostics);
1931
+ diagnostics.push(
1932
+ ...checkCatalogs(email.locales, catalogs).map((issue) => ({ ...issue, templateId: email.definition.id }))
1933
+ );
1934
+ const fixtures = await readFixtures(config.configDir, email.definition.id, email.definition.fixtures, diagnostics);
1935
+ const compiled = await compileLocales(config, profile, email, catalogs, diagnostics);
1936
+ if (compiled) analyzeContract(email, compiled.structure, diagnostics);
1937
+ diagnostics.push(...checkLoadedFixtures(email.definition.id, email.definition.schema, fixtures));
1938
+ const files = (compiled?.documents ?? []).map((document) => ({
1939
+ name: `locales/${document.locale}/${email.definition.id}.html`,
1940
+ content: document.html,
1941
+ sha256: document.sha256,
1942
+ role: "locale",
1943
+ locale: document.locale
1944
+ }));
1945
+ const documentManifest = mergeVariants({
1946
+ email,
1947
+ profile,
1948
+ documents: compiled?.documents ?? [],
1949
+ files,
1950
+ diagnostics,
1951
+ manifest: compiled?.manifest ?? null
1952
+ });
1953
+ const adjusted = applyPolicy(diagnostics, email);
1954
+ return {
1955
+ id: email.definition.id,
1956
+ event: email.definition.event,
1957
+ output: email.output,
1958
+ locales: email.locales,
1959
+ defaultLocale: email.defaultLocale,
1960
+ localePath: email.localePath,
1961
+ files: email.output === "per-locale" ? files.filter((file) => file.role === "locale") : files,
1962
+ diagnostics: adjusted,
1963
+ structure: compiled?.structure ?? [],
1964
+ dependencies: email.dependencies,
1965
+ fixtures,
1966
+ fixturesPattern: email.definition.fixtures,
1967
+ file: email.file,
1968
+ schema: email.definition.schema,
1969
+ manifest: documentManifest,
1970
+ profile,
1971
+ warnRenderedBytes: config.compatibility.warnRenderedBytes
1972
+ };
1973
+ }
1974
+ async function compileLocales(config, profile, email, catalogs, diagnostics) {
1975
+ if (diagnostics.some((item) => item.severity === "error")) return null;
1976
+ const documents = [];
1977
+ let structure = [];
1978
+ let documentManifest = null;
1979
+ const compiled = await Promise.all(
1980
+ email.locales.map(async (locale) => {
1981
+ const catalog = catalogs[locale] ?? {};
1982
+ const result = await compileEmail({
1983
+ email: {
1984
+ id: email.definition.id,
1985
+ event: email.definition.event,
1986
+ template: email.definition.template
1987
+ },
1988
+ locale,
1989
+ catalog,
1990
+ profile: profile.emission,
1991
+ tailwind: config.tailwind,
1992
+ file: email.file
1993
+ });
1994
+ return { locale, result };
1995
+ })
1996
+ );
1997
+ for (const item of compiled) {
1998
+ if (!item.result.ok) {
1999
+ diagnostics.push(...item.result.diagnostics);
2000
+ continue;
2001
+ }
2002
+ const content = item.result.artifacts[0]?.content ?? "";
2003
+ const digest = item.result.artifacts[0]?.sha256 ?? sha2562(content);
2004
+ documents.push({ locale: item.locale, html: content, sha256: digest });
2005
+ diagnostics.push(...item.result.diagnostics);
2006
+ diagnostics.push(
2007
+ ...diagnoseStyles(content).map((issue) => ({ ...issue, templateId: email.definition.id, locale: item.locale }))
2008
+ );
2009
+ if (content.length > config.compatibility.maxSourceBytes) {
2010
+ diagnostics.push(
2011
+ errorDiagnostic7("SIZE001", `Source exceeds maxSourceBytes (${config.compatibility.maxSourceBytes}).`, {
2012
+ templateId: email.definition.id,
2013
+ locale: item.locale
2014
+ })
2015
+ );
2016
+ }
2017
+ if (item.locale === email.defaultLocale) {
2018
+ structure = item.result.structure;
2019
+ documentManifest = item.result.manifest;
2020
+ }
2021
+ }
2022
+ if (structure.length === 0 && documents[0]) {
2023
+ const first = compiled.find((item) => item.result.ok);
2024
+ if (first?.result.ok) structure = first.result.structure;
2025
+ }
2026
+ return { documents, structure, manifest: documentManifest };
2027
+ }
2028
+ function analyzeContract(email, structure, diagnostics) {
2029
+ diagnostics.push(
2030
+ ...analyzePaths(email.definition.schema, structure).map((issue) => ({
2031
+ ...issue,
2032
+ templateId: email.definition.id
2033
+ }))
2034
+ );
2035
+ const localeIssue = analyzeRootPath(email.definition.schema, email.localePath);
2036
+ if (localeIssue) diagnostics.push({ ...localeIssue, templateId: email.definition.id, path: email.localePath });
2037
+ }
2038
+
2039
+ // src/project/discover.ts
2040
+ import {
2041
+ errorDiagnostic as errorDiagnostic9,
2042
+ isSafeEmailId,
2043
+ parsePath
2044
+ } from "@vtex-email/core";
2045
+ import { access as access2, glob } from "node:fs/promises";
2046
+ import path7 from "node:path";
2047
+
2048
+ // src/project/settings.ts
2049
+ import { errorDiagnostic as errorDiagnostic8 } from "@vtex-email/core";
2050
+ var OUTPUTS = /* @__PURE__ */ new Set(["per-locale", "merged"]);
2051
+ var UNKNOWN_PATH = /* @__PURE__ */ new Set(["error", "warning"]);
2052
+ function parseEmailSettings(value, file) {
2053
+ if (value === void 0) return { ok: true, settings: {} };
2054
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2055
+ return {
2056
+ ok: false,
2057
+ diagnostics: [errorDiagnostic8("CFG001", "export const settings must be an object.", { source: { file } })]
2058
+ };
2059
+ }
2060
+ const record = value;
2061
+ const allowed = /* @__PURE__ */ new Set(["id", "event", "schema", "fixtures", "i18n", "validation"]);
2062
+ const diagnostics = [];
2063
+ for (const key of Object.keys(record)) {
2064
+ if (!allowed.has(key)) {
2065
+ diagnostics.push(errorDiagnostic8("CFG001", `Unknown settings field: ${key}`, { source: { file }, path: key }));
2066
+ }
2067
+ }
2068
+ if (record.id !== void 0 && typeof record.id !== "string") {
2069
+ diagnostics.push(errorDiagnostic8("CFG001", "settings.id must be a string.", { source: { file }, path: "id" }));
2070
+ }
2071
+ if (record.event !== void 0 && typeof record.event !== "string") {
2072
+ diagnostics.push(errorDiagnostic8("CFG001", "settings.event must be a string.", { source: { file }, path: "event" }));
2073
+ }
2074
+ if (record.fixtures !== void 0 && (typeof record.fixtures !== "string" || record.fixtures.length === 0)) {
2075
+ diagnostics.push(
2076
+ errorDiagnostic8("CFG001", "settings.fixtures must be a non-empty string.", {
2077
+ source: { file },
2078
+ path: "fixtures"
2079
+ })
2080
+ );
2081
+ }
2082
+ if (record.schema !== void 0 && !isZodType(record.schema)) {
2083
+ diagnostics.push(
2084
+ errorDiagnostic8("CFG001", "settings.schema must be a Zod schema.", { source: { file }, path: "schema" })
2085
+ );
2086
+ }
2087
+ const i18n = parseI18n(record.i18n, file, diagnostics);
2088
+ const validation = parseValidation(record.validation, file, diagnostics);
2089
+ if (diagnostics.length > 0) return { ok: false, diagnostics };
2090
+ const settings = {
2091
+ ...typeof record.id === "string" ? { id: record.id } : {},
2092
+ ...typeof record.event === "string" ? { event: record.event } : {},
2093
+ ...typeof record.fixtures === "string" ? { fixtures: record.fixtures } : {},
2094
+ ...isZodType(record.schema) ? { schema: record.schema } : {},
2095
+ ...i18n ? { i18n } : {},
2096
+ ...validation ? { validation } : {}
2097
+ };
2098
+ return { ok: true, settings };
2099
+ }
2100
+ function parseI18n(value, file, diagnostics) {
2101
+ if (value === void 0) return void 0;
2102
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2103
+ diagnostics.push(errorDiagnostic8("CFG001", "settings.i18n must be an object.", { source: { file }, path: "i18n" }));
2104
+ return void 0;
2105
+ }
2106
+ const record = value;
2107
+ const allowed = /* @__PURE__ */ new Set(["locales", "defaultLocale", "localePath", "output", "aliases"]);
2108
+ for (const key of Object.keys(record)) {
2109
+ if (!allowed.has(key)) {
2110
+ diagnostics.push(
2111
+ errorDiagnostic8("CFG001", `Unknown settings.i18n field: ${key}`, {
2112
+ source: { file },
2113
+ path: `i18n.${key}`
2114
+ })
2115
+ );
2116
+ }
2117
+ }
2118
+ if (record.locales !== void 0) {
2119
+ if (!Array.isArray(record.locales) || record.locales.length === 0 || record.locales.some((item) => typeof item !== "string")) {
2120
+ diagnostics.push(
2121
+ errorDiagnostic8("CFG001", "settings.i18n.locales must be a non-empty string array.", {
2122
+ source: { file },
2123
+ path: "i18n.locales"
2124
+ })
2125
+ );
2126
+ }
2127
+ }
2128
+ if (record.defaultLocale !== void 0 && typeof record.defaultLocale !== "string") {
2129
+ diagnostics.push(
2130
+ errorDiagnostic8("CFG001", "settings.i18n.defaultLocale must be a string.", {
2131
+ source: { file },
2132
+ path: "i18n.defaultLocale"
2133
+ })
2134
+ );
2135
+ }
2136
+ if (record.localePath !== void 0 && typeof record.localePath !== "string") {
2137
+ diagnostics.push(
2138
+ errorDiagnostic8("CFG001", "settings.i18n.localePath must be a string.", {
2139
+ source: { file },
2140
+ path: "i18n.localePath"
2141
+ })
2142
+ );
2143
+ }
2144
+ if (record.output !== void 0 && (typeof record.output !== "string" || !OUTPUTS.has(record.output))) {
2145
+ diagnostics.push(
2146
+ errorDiagnostic8("CFG001", 'settings.i18n.output must be "per-locale" or "merged".', {
2147
+ source: { file },
2148
+ path: "i18n.output"
2149
+ })
2150
+ );
2151
+ }
2152
+ if (record.aliases !== void 0) {
2153
+ if (!record.aliases || typeof record.aliases !== "object" || Array.isArray(record.aliases)) {
2154
+ diagnostics.push(
2155
+ errorDiagnostic8("CFG001", "settings.i18n.aliases must be an object.", {
2156
+ source: { file },
2157
+ path: "i18n.aliases"
2158
+ })
2159
+ );
2160
+ } else {
2161
+ for (const [alias, locale] of Object.entries(record.aliases)) {
2162
+ if (typeof locale !== "string") {
2163
+ diagnostics.push(
2164
+ errorDiagnostic8("CFG001", `settings.i18n.aliases.${alias} must be a string.`, {
2165
+ source: { file },
2166
+ path: `i18n.aliases.${alias}`
2167
+ })
2168
+ );
2169
+ }
2170
+ }
2171
+ }
2172
+ }
2173
+ return {
2174
+ ...Array.isArray(record.locales) ? { locales: record.locales } : {},
2175
+ ...typeof record.defaultLocale === "string" ? { defaultLocale: record.defaultLocale } : {},
2176
+ ...typeof record.localePath === "string" ? { localePath: record.localePath } : {},
2177
+ ...typeof record.output === "string" && OUTPUTS.has(record.output) ? { output: record.output } : {},
2178
+ ...record.aliases && typeof record.aliases === "object" && !Array.isArray(record.aliases) ? { aliases: record.aliases } : {}
2179
+ };
2180
+ }
2181
+ function parseValidation(value, file, diagnostics) {
2182
+ if (value === void 0) return void 0;
2183
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2184
+ diagnostics.push(
2185
+ errorDiagnostic8("CFG001", "settings.validation must be an object.", {
2186
+ source: { file },
2187
+ path: "validation"
2188
+ })
2189
+ );
2190
+ return void 0;
2191
+ }
2192
+ const record = value;
2193
+ const allowed = /* @__PURE__ */ new Set(["unknownPath", "warningsAsErrors"]);
2194
+ for (const key of Object.keys(record)) {
2195
+ if (!allowed.has(key)) {
2196
+ diagnostics.push(
2197
+ errorDiagnostic8("CFG001", `Unknown settings.validation field: ${key}`, {
2198
+ source: { file },
2199
+ path: `validation.${key}`
2200
+ })
2201
+ );
2202
+ }
2203
+ }
2204
+ if (record.unknownPath !== void 0 && (typeof record.unknownPath !== "string" || !UNKNOWN_PATH.has(record.unknownPath))) {
2205
+ diagnostics.push(
2206
+ errorDiagnostic8("CFG001", 'settings.validation.unknownPath must be "error" or "warning".', {
2207
+ source: { file },
2208
+ path: "validation.unknownPath"
2209
+ })
2210
+ );
2211
+ }
2212
+ if (record.warningsAsErrors !== void 0 && typeof record.warningsAsErrors !== "boolean") {
2213
+ diagnostics.push(
2214
+ errorDiagnostic8("CFG001", "settings.validation.warningsAsErrors must be a boolean.", {
2215
+ source: { file },
2216
+ path: "validation.warningsAsErrors"
2217
+ })
2218
+ );
2219
+ }
2220
+ return {
2221
+ ...typeof record.unknownPath === "string" && UNKNOWN_PATH.has(record.unknownPath) ? { unknownPath: record.unknownPath } : {},
2222
+ ...typeof record.warningsAsErrors === "boolean" ? { warningsAsErrors: record.warningsAsErrors } : {}
2223
+ };
2224
+ }
2225
+ function isZodType(value) {
2226
+ return !!value && typeof value === "object" && "safeParse" in value;
2227
+ }
2228
+
2229
+ // src/project/discover.ts
2230
+ var TEMPLATE_SUFFIX = ".email.tsx";
2231
+ async function discoverEmails(config) {
2232
+ const files = await discoverFiles(config);
2233
+ const emails = [];
2234
+ const diagnostics = [];
2235
+ const fileKeys = /* @__PURE__ */ new Map();
2236
+ for (const file of files) {
2237
+ const fileKey = fileKeyFromPath(file);
2238
+ if (!fileKey) {
2239
+ diagnostics.push(errorDiagnostic9("CFG001", `Email file must end with ${TEMPLATE_SUFFIX}.`, { source: { file } }));
2240
+ continue;
2241
+ }
2242
+ if (!isSafeEmailId(fileKey)) {
2243
+ diagnostics.push(
2244
+ errorDiagnostic9("CFG001", `Invalid email file key: ${fileKey}`, { source: { file }, templateId: fileKey })
2245
+ );
2246
+ continue;
2247
+ }
2248
+ const previous = fileKeys.get(fileKey);
2249
+ if (previous) {
2250
+ diagnostics.push(
2251
+ errorDiagnostic9("CFG001", `Duplicate email file key: ${fileKey}`, {
2252
+ source: { file },
2253
+ templateId: fileKey
2254
+ })
2255
+ );
2256
+ continue;
2257
+ }
2258
+ fileKeys.set(fileKey, file);
2259
+ const entry = await loadEmailEntry(file);
2260
+ if (!entry.ok) {
2261
+ diagnostics.push(...entry.diagnostics);
2262
+ continue;
2263
+ }
2264
+ const template = entry.module.default;
2265
+ if (typeof template !== "function") {
2266
+ diagnostics.push(
2267
+ errorDiagnostic9(
2268
+ "CFG001",
2269
+ "The email module must default-export a React component. Optional overrides go in export const settings.",
2270
+ { source: { file } }
2271
+ )
2272
+ );
2273
+ continue;
2274
+ }
2275
+ const settingsResult = parseEmailSettings(entry.module.settings, file);
2276
+ if (!settingsResult.ok) {
2277
+ diagnostics.push(...settingsResult.diagnostics);
2278
+ continue;
2279
+ }
2280
+ const resolved = await resolveEmail(
2281
+ config,
2282
+ fileKey,
2283
+ template,
2284
+ settingsResult.settings,
2285
+ file,
2286
+ entry.dependencies
2287
+ );
2288
+ if (!resolved.ok) {
2289
+ diagnostics.push(...resolved.diagnostics);
2290
+ continue;
2291
+ }
2292
+ emails.push(resolved.email);
2293
+ }
2294
+ const duplicate = duplicateId(emails.map((email) => email.definition.id));
2295
+ if (duplicate) diagnostics.push(errorDiagnostic9("CFG001", `Duplicate email id: ${duplicate}`));
2296
+ if (diagnostics.length > 0) return { ok: false, diagnostics };
2297
+ return { ok: true, emails };
2298
+ }
2299
+ function fileKeyFromPath(file) {
2300
+ const base = path7.basename(file);
2301
+ if (!base.endsWith(TEMPLATE_SUFFIX)) return null;
2302
+ return base.slice(0, -TEMPLATE_SUFFIX.length);
2303
+ }
2304
+ function schemaPathForKey(config, fileKey) {
2305
+ return path7.resolve(config.configDir, config.schemasDir, `${fileKey}.ts`);
2306
+ }
2307
+ function duplicateId(ids) {
2308
+ const seen = /* @__PURE__ */ new Set();
2309
+ for (const id of ids) {
2310
+ if (seen.has(id)) return id;
2311
+ seen.add(id);
2312
+ }
2313
+ return null;
2314
+ }
2315
+ function readProfile(module) {
2316
+ const candidate = module.profile ?? module.default;
2317
+ if (!candidate || typeof candidate !== "object") return null;
2318
+ const value = candidate;
2319
+ if (typeof value.id !== "string" || typeof value.allowParentSegments !== "boolean" || !Array.isArray(value.capabilities))
2320
+ return null;
2321
+ return {
2322
+ emission: {
2323
+ id: value.id,
2324
+ allowParentSegments: value.allowParentSegments,
2325
+ capabilities: value.capabilities
2326
+ },
2327
+ simulator: { helpers: Array.isArray(value.helpers) ? value.helpers : [] }
2328
+ };
2329
+ }
2330
+ async function discoverFiles(config) {
2331
+ const found = /* @__PURE__ */ new Set();
2332
+ for (const pattern of config.emails) {
2333
+ for await (const entry of glob(pattern, { cwd: config.configDir })) {
2334
+ found.add(path7.resolve(config.configDir, entry));
2335
+ }
2336
+ }
2337
+ return [...found].sort();
2338
+ }
2339
+ async function resolveEmail(config, fileKey, template, settings, file, dependencies) {
2340
+ const diagnostics = [];
2341
+ const id = settings.id ?? fileKey;
2342
+ const event = settings.event ?? fileKey;
2343
+ if (!isSafeEmailId(id)) {
2344
+ diagnostics.push(errorDiagnostic9("CFG001", `Invalid email id: ${id}`, { source: { file }, templateId: id }));
2345
+ }
2346
+ const schemaResult = await resolveSchema(config, fileKey, settings.schema, id, file);
2347
+ if (!schemaResult.ok) diagnostics.push(...schemaResult.diagnostics);
2348
+ const localePath = settings.i18n?.localePath ?? config.localePath;
2349
+ if (!localePath) {
2350
+ diagnostics.push(
2351
+ errorDiagnostic9(
2352
+ "CFG001",
2353
+ `Missing localePath. Set i18n.localePath in defineConfig or settings.i18n.localePath for "${fileKey}".`,
2354
+ { source: { file }, templateId: id }
2355
+ )
2356
+ );
2357
+ } else if (!parsePath(localePath, true).ok) {
2358
+ diagnostics.push(
2359
+ errorDiagnostic9("CFG001", `Invalid locale path: ${localePath}`, { source: { file }, templateId: id })
2360
+ );
2361
+ }
2362
+ const locales = [...settings.i18n?.locales ?? config.locales];
2363
+ for (const locale of locales) {
2364
+ if (!config.locales.includes(locale)) {
2365
+ diagnostics.push(
2366
+ errorDiagnostic9("CFG001", `Locale ${locale} is not enabled by the project.`, {
2367
+ source: { file },
2368
+ templateId: id
2369
+ })
2370
+ );
2371
+ }
2372
+ }
2373
+ const defaultLocale = settings.i18n?.defaultLocale ?? config.defaultLocale;
2374
+ if (!locales.includes(defaultLocale)) {
2375
+ diagnostics.push(
2376
+ errorDiagnostic9("CFG001", "The email default locale is not in its locale list.", {
2377
+ source: { file },
2378
+ templateId: id
2379
+ })
2380
+ );
2381
+ }
2382
+ const aliases = Object.entries(settings.i18n?.aliases ?? {}).map(([alias, locale]) => ({ alias, locale }));
2383
+ for (const alias of aliases) {
2384
+ if (!locales.includes(alias.locale)) {
2385
+ diagnostics.push(
2386
+ errorDiagnostic9("CFG001", `Alias ${alias.alias} points at an unknown locale.`, {
2387
+ source: { file },
2388
+ templateId: id
2389
+ })
2390
+ );
2391
+ }
2392
+ }
2393
+ const fixturesRelative = settings.fixtures ?? path7.posix.join(toPosix2(config.fixturesDir), fileKey);
2394
+ if (diagnostics.length > 0 || !schemaResult.ok || !localePath) {
2395
+ return { ok: false, diagnostics };
2396
+ }
2397
+ const definition = {
2398
+ id,
2399
+ event,
2400
+ template,
2401
+ schema: schemaResult.schema,
2402
+ fixtures: fixturesRelative,
2403
+ i18n: {
2404
+ locales,
2405
+ defaultLocale,
2406
+ localePath,
2407
+ output: settings.i18n?.output ?? "merged",
2408
+ ...settings.i18n?.aliases ? { aliases: settings.i18n.aliases } : {}
2409
+ },
2410
+ ...settings.validation ? { validation: settings.validation } : {}
2411
+ };
2412
+ return {
2413
+ ok: true,
2414
+ email: {
2415
+ definition,
2416
+ file,
2417
+ fileKey,
2418
+ dependencies,
2419
+ locales,
2420
+ defaultLocale,
2421
+ localePath,
2422
+ output: definition.i18n.output ?? "merged",
2423
+ aliases,
2424
+ unknownPath: settings.validation?.unknownPath ?? config.validation.unknownPath,
2425
+ warningsAsErrors: settings.validation?.warningsAsErrors ?? config.validation.warningsAsErrors,
2426
+ unverifiedCapability: config.validation.unverifiedCapability
2427
+ }
2428
+ };
2429
+ }
2430
+ async function resolveSchema(config, fileKey, override, templateId, emailFile) {
2431
+ if (override) return { ok: true, schema: override };
2432
+ const schemaFile = schemaPathForKey(config, fileKey);
2433
+ const relative = toPosix2(path7.relative(config.configDir, schemaFile));
2434
+ if (!await exists2(schemaFile)) {
2435
+ return {
2436
+ ok: false,
2437
+ diagnostics: [
2438
+ errorDiagnostic9(
2439
+ "CFG001",
2440
+ `No schema for file key "${fileKey}". Add ${relative} with export default Zod schema, or set settings.schema.`,
2441
+ { source: { file: emailFile }, templateId }
2442
+ )
2443
+ ]
2444
+ };
2445
+ }
2446
+ try {
2447
+ const module = await importBundled(schemaFile);
2448
+ if (!isZodType2(module.default)) {
2449
+ return {
2450
+ ok: false,
2451
+ diagnostics: [
2452
+ errorDiagnostic9("CFG001", `Schema module ${relative} must default-export a Zod schema.`, {
2453
+ source: { file: schemaFile },
2454
+ templateId
2455
+ })
2456
+ ]
2457
+ };
2458
+ }
2459
+ return { ok: true, schema: module.default };
2460
+ } catch (error) {
2461
+ const message = error instanceof Error ? error.message : `Failed to load schema ${relative}.`;
2462
+ return {
2463
+ ok: false,
2464
+ diagnostics: [errorDiagnostic9("CFG001", message, { source: { file: schemaFile }, templateId })]
2465
+ };
2466
+ }
2467
+ }
2468
+ function isZodType2(value) {
2469
+ return !!value && typeof value === "object" && "safeParse" in value;
2470
+ }
2471
+ async function exists2(file) {
2472
+ try {
2473
+ await access2(file);
2474
+ return true;
2475
+ } catch {
2476
+ return false;
2477
+ }
2478
+ }
2479
+ function toPosix2(value) {
2480
+ return value.replaceAll("\\", "/");
2481
+ }
2482
+
2483
+ // src/project/manifest.ts
2484
+ function projectManifest(profileId, emails) {
2485
+ return {
2486
+ formatVersion: 1,
2487
+ profileId,
2488
+ homologation: "experimental",
2489
+ emails: emails.map((email) => ({
2490
+ id: email.id,
2491
+ event: email.event,
2492
+ output: email.output,
2493
+ locales: email.locales,
2494
+ defaultLocale: email.defaultLocale,
2495
+ files: email.files.map((file) => ({
2496
+ name: file.name,
2497
+ sha256: file.sha256,
2498
+ role: file.role,
2499
+ ...file.locale ? { locale: file.locale } : {}
2500
+ })),
2501
+ capabilities: email.manifest?.capabilities.map((item) => ({ name: item.name, evidence: item.evidence })) ?? [],
2502
+ warnings: email.diagnostics.filter((item) => item.severity === "warning").map((item) => item.message)
2503
+ }))
2504
+ };
2505
+ }
2506
+ function localeInventory(previous, current, locale) {
2507
+ const prior = new Map((previous?.emails ?? []).map((email) => [email.id, email]));
2508
+ const seen = /* @__PURE__ */ new Set();
2509
+ const emails = [];
2510
+ for (const email of current.emails) {
2511
+ seen.add(email.id);
2512
+ const old = prior.get(email.id);
2513
+ const replacement = email.files.filter((file) => file.role === "locale" && file.locale === locale);
2514
+ const kept = (old?.files ?? []).filter((file) => !(file.role === "locale" && file.locale === locale));
2515
+ const files = [...kept, ...replacement];
2516
+ const hasMerged = files.some((file) => file.role === "merged");
2517
+ emails.push({
2518
+ ...email,
2519
+ files,
2520
+ capabilities: mergeCapabilities(old?.capabilities ?? [], email.capabilities, hasMerged)
2521
+ });
2522
+ }
2523
+ for (const email of prior.values()) {
2524
+ if (!seen.has(email.id)) emails.push(email);
2525
+ }
2526
+ return emails;
2527
+ }
2528
+ function mergeCapabilities(previous, incoming, hasMerged) {
2529
+ const map = /* @__PURE__ */ new Map();
2530
+ for (const item of [...previous, ...incoming]) {
2531
+ if (item.name === "eq" && !hasMerged) continue;
2532
+ map.set(item.name, item);
2533
+ }
2534
+ return [...map.values()];
2535
+ }
2536
+
2537
+ // src/project/write-output.ts
2538
+ import { releaseArtifacts } from "@vtex-email/core";
2539
+ import { readFile as readFile3 } from "node:fs/promises";
2540
+ import path8 from "node:path";
2541
+ async function writeOutput(outDir, manifest, emails, onlyId, helperNames, locale) {
2542
+ const manifestPath = path8.join(outDir, "manifest.json");
2543
+ const previous = await readManifest(manifestPath);
2544
+ const nextEmails = locale ? localeInventory(previous, manifest, locale) : onlyId && previous ? [...previous.emails.filter((item) => item.id !== onlyId), ...manifest.emails] : manifest.emails;
2545
+ const next = {
2546
+ formatVersion: 1,
2547
+ profileId: manifest.profileId,
2548
+ homologation: "experimental",
2549
+ emails: nextEmails.sort((left, right) => left.id.localeCompare(right.id))
2550
+ };
2551
+ const selected = new Set(emails.map((email) => email.id));
2552
+ const replacements = emails.flatMap(
2553
+ (email) => email.files.filter((file) => !locale || file.role === "locale" && file.locale === locale)
2554
+ );
2555
+ const kept = new Set(next.emails.flatMap((email) => email.files.map((file) => file.name)));
2556
+ const obsolete = [];
2557
+ for (const email of previous?.emails ?? []) {
2558
+ if (onlyId && email.id !== onlyId) continue;
2559
+ if (locale && !selected.has(email.id)) continue;
2560
+ for (const file of email.files) {
2561
+ if (!kept.has(file.name)) obsolete.push(file.name);
2562
+ }
2563
+ }
2564
+ const issue = await releaseArtifacts({
2565
+ helperNames,
2566
+ directory: outDir,
2567
+ files: [
2568
+ ...replacements.map((file) => ({ name: file.name, content: file.content })),
2569
+ { name: "manifest.json", content: `${JSON.stringify(next, null, 2)}
2570
+ ` }
2571
+ ],
2572
+ remove: obsolete
2573
+ });
2574
+ if (issue) return { ok: false, diagnostic: issue };
2575
+ const wroteNames = new Set(replacements.map((file) => file.name));
2576
+ const preserved = next.emails.flatMap((email) => email.files.map((file) => file.name)).filter((name) => !wroteNames.has(name));
2577
+ return { ok: true, manifest: next, wrote: [...wroteNames, "manifest.json"], preserved };
2578
+ }
2579
+ async function readManifest(file) {
2580
+ try {
2581
+ const parsed2 = JSON.parse(await readFile3(file, "utf8"));
2582
+ if (parsed2.formatVersion !== 1 || !Array.isArray(parsed2.emails)) return null;
2583
+ return parsed2;
2584
+ } catch {
2585
+ return null;
2586
+ }
2587
+ }
2588
+
2589
+ // src/project/build-project.ts
2590
+ async function buildProject(input) {
2591
+ const loaded = await loadProjectConfig(input.configPath);
2592
+ if (!loaded.ok) return emptyProject(exitUsage, loaded.diagnostics);
2593
+ return buildResolved(loaded.config, input);
2594
+ }
2595
+ function validateProject(input) {
2596
+ return buildProject({ ...input, write: false });
2597
+ }
2598
+ async function buildResolved(config, input) {
2599
+ const prepared = await prepareResolved(config, input.onlyId);
2600
+ if (!prepared.ok) return prepared.result;
2601
+ const localeIssue = rejectLocale(config, prepared.emails, input.locale);
2602
+ if (localeIssue) return localeIssue;
2603
+ const emails = input.warningsAsErrors === true ? prepared.emails.map((email) => ({ ...email, warningsAsErrors: true })) : prepared.emails;
2604
+ const compiled = await compileProject(config, prepared.profile, emails);
2605
+ if (!compiled.ok || input.write === false) return compiled;
2606
+ return writeCompiled(
2607
+ config.outDir,
2608
+ compiled,
2609
+ input.onlyId,
2610
+ syntaxHelperNames2(prepared.profile.emission),
2611
+ input.locale
2612
+ );
2613
+ }
2614
+ async function compileProject(config, profile, emails) {
2615
+ const built = [];
2616
+ for (const email of emails) built.push(await compileOne(config, profile, email));
2617
+ const diagnostics = built.flatMap((email) => email.diagnostics);
2618
+ const failed = diagnostics.some((item) => item.severity === "error");
2619
+ const manifest = projectManifest(profile.emission.id, built);
2620
+ if (failed) {
2621
+ return { ok: false, exitCode: exitValidation, diagnostics, manifest, emails: built, wrote: [], preserved: [] };
2622
+ }
2623
+ return { ok: true, exitCode: exitOk, diagnostics, manifest, emails: built, wrote: [], preserved: [] };
2624
+ }
2625
+ async function prepareResolved(config, onlyId) {
2626
+ let profileModule;
2627
+ try {
2628
+ profileModule = await importBundled(config.profilePath);
2629
+ } catch (error) {
2630
+ const message = error instanceof Error ? error.message : "Failed to load the profile.";
2631
+ return { ok: false, result: emptyProject(exitUsage, [errorDiagnostic10("CFG001", message)]) };
2632
+ }
2633
+ const profile = readProfile(profileModule);
2634
+ if (!profile)
2635
+ return { ok: false, result: emptyProject(exitUsage, [errorDiagnostic10("CFG001", "The target profile is invalid.")]) };
2636
+ const discovered = await discoverEmails(config);
2637
+ if (!discovered.ok) return { ok: false, result: emptyProject(exitUsage, discovered.diagnostics) };
2638
+ const selected = onlyId ? discovered.emails.filter((email) => email.definition.id === onlyId) : discovered.emails;
2639
+ if (onlyId && selected.length === 0) {
2640
+ return { ok: false, result: emptyProject(exitUsage, [errorDiagnostic10("CFG001", `Unknown email: ${onlyId}`)]) };
2641
+ }
2642
+ return { ok: true, profile, emails: selected };
2643
+ }
2644
+ function rejectLocale(config, emails, locale) {
2645
+ if (!locale) return null;
2646
+ if (!config.locales.includes(locale)) {
2647
+ return emptyProject(exitUsage, [errorDiagnostic10("CFG001", `Unknown locale: ${locale}`)]);
2648
+ }
2649
+ const diagnostics = emails.filter((email) => !email.locales.includes(locale)).map(
2650
+ (email) => errorDiagnostic10("CFG001", `Locale ${locale} is not enabled for ${email.definition.id}.`, {
2651
+ templateId: email.definition.id
2652
+ })
2653
+ );
2654
+ if (diagnostics.length === 0) return null;
2655
+ return emptyProject(exitUsage, diagnostics);
2656
+ }
2657
+ async function writeCompiled(outDir, compiled, onlyId, helperNames, locale) {
2658
+ if (!compiled.manifest) return compiled;
2659
+ const written = await writeOutput(outDir, compiled.manifest, compiled.emails, onlyId, helperNames, locale);
2660
+ if (!written.ok) {
2661
+ return {
2662
+ ok: false,
2663
+ exitCode: exitValidation,
2664
+ diagnostics: [...compiled.diagnostics, written.diagnostic],
2665
+ manifest: compiled.manifest,
2666
+ emails: compiled.emails,
2667
+ wrote: [],
2668
+ preserved: []
2669
+ };
2670
+ }
2671
+ return {
2672
+ ok: true,
2673
+ exitCode: exitOk,
2674
+ diagnostics: compiled.diagnostics,
2675
+ manifest: written.manifest,
2676
+ emails: compiled.emails,
2677
+ wrote: written.wrote,
2678
+ preserved: written.preserved
2679
+ };
2680
+ }
2681
+
2682
+ // src/commands/project-commands.ts
2683
+ async function runProjectCommand(kind, configPath, configDir, options) {
2684
+ const result = kind === "validate" ? await validateProject({
2685
+ configPath,
2686
+ ...options.warningsAsErrors ? { warningsAsErrors: true } : {}
2687
+ }) : await buildProject({
2688
+ configPath,
2689
+ ...options.emailId ? { onlyId: options.emailId } : {},
2690
+ ...options.locale ? { locale: options.locale } : {},
2691
+ ...options.warningsAsErrors ? { warningsAsErrors: true } : {}
2692
+ });
2693
+ await emitReport(projectReport(kind, result, configDir), options.format);
2694
+ return result.exitCode;
2695
+ }
2696
+ function usageReport(message, configDir) {
2697
+ return buildReport({
2698
+ command: "usage",
2699
+ ok: false,
2700
+ exitCode: exitUsage,
2701
+ diagnostics: [{ code: "CFG001", severity: "error", message }],
2702
+ manifest: null,
2703
+ wrote: [],
2704
+ preserved: [],
2705
+ configDir
2706
+ });
2707
+ }
2708
+ function projectReport(command, result, configDir) {
2709
+ return buildReport({
2710
+ command,
2711
+ ok: result.ok,
2712
+ exitCode: result.exitCode,
2713
+ diagnostics: result.diagnostics,
2714
+ manifest: result.manifest,
2715
+ wrote: result.wrote,
2716
+ preserved: result.preserved,
2717
+ configDir
2718
+ });
2719
+ }
2720
+
2721
+ // src/commands/dev.ts
2722
+ async function startDevCommand(configPath, configDir, options) {
2723
+ const presenter = createDevPresenter({
2724
+ version: options.version,
2725
+ format: options.format
2726
+ });
2727
+ try {
2728
+ const require2 = createRequire(configPath);
2729
+ const resolved = require2.resolve("@vtex-email/preview");
2730
+ const imported = await import(pathToFileURL2(resolved).href);
2731
+ if (!imported.startDev) throw new Error("The preview package does not export startDev.");
2732
+ await presenter.printBanner();
2733
+ return await imported.startDev({
2734
+ configPath,
2735
+ onNotice: (notice) => presenter.handle(notice),
2736
+ ...options.warningsAsErrors ? { warningsAsErrors: true } : {}
2737
+ });
2738
+ } catch (error) {
2739
+ const code2 = error && typeof error === "object" && "code" in error ? String(error.code) : "";
2740
+ const missing = code2 === "MODULE_NOT_FOUND" || code2 === "ERR_MODULE_NOT_FOUND";
2741
+ const message = missing ? "The preview package is not installed for this project." : error instanceof Error ? error.message : "Failed to start the preview.";
2742
+ await emitReport(usageReport(message, configDir), options.format);
2743
+ return exitUsage;
2744
+ }
2745
+ }
2746
+
2747
+ // src/commands/preview-export.ts
2748
+ import path10 from "node:path";
2749
+
2750
+ // src/project/preview-evaluation.ts
2751
+ import {
2752
+ commitArtifacts,
2753
+ errorDiagnostic as errorDiagnostic11,
2754
+ evaluateArtifact,
2755
+ readPathValue,
2756
+ TemplateFailure,
2757
+ withForcedLocale
2758
+ } from "@vtex-email/core";
2759
+ import path9 from "node:path";
2760
+ function previewBuiltEmail(input) {
2761
+ const email = input.email;
2762
+ const fixture = email.fixtures.find((item) => item.id === input.fixtureId && !item.negative);
2763
+ if (!fixture) {
2764
+ return emptyPreview(exitUsage, [errorDiagnostic11("CFG001", `Unknown fixture: ${input.fixtureId}`)]);
2765
+ }
2766
+ const payloadLocale = readPayloadLocale(fixture.data, email.localePath);
2767
+ const merged = email.files.find((file) => file.role === "merged");
2768
+ if (input.mode === "forced") {
2769
+ if (!merged) {
2770
+ return {
2771
+ ...emptyPreview(exitValidation, [
2772
+ errorDiagnostic11("HBS002", "Forced locale uses the merged artifact.", { templateId: email.id })
2773
+ ]),
2774
+ selector: true,
2775
+ locale: input.locale ?? "",
2776
+ payloadLocale
2777
+ };
2778
+ }
2779
+ if (!input.locale) {
2780
+ return {
2781
+ ...emptyPreview(exitUsage, [errorDiagnostic11("CFG001", "Forced locale requires a locale.")]),
2782
+ source: merged.content,
2783
+ selector: true,
2784
+ payloadLocale
2785
+ };
2786
+ }
2787
+ const forced = withForcedLocale(fixture.data, email.localePath, input.locale);
2788
+ if (!forced.ok) {
2789
+ return {
2790
+ ...emptyPreview(exitValidation, [errorDiagnostic11("DATA001", forced.message, { path: email.localePath })]),
2791
+ source: merged.content,
2792
+ selector: true,
2793
+ locale: input.locale,
2794
+ payloadLocale
2795
+ };
2796
+ }
2797
+ return { ...runEvaluation(email, merged.content, forced.data, true, input.locale), payloadLocale };
2798
+ }
2799
+ if (input.mode === "locale" || !merged) {
2800
+ const locale = input.locale ?? readLocale(fixture.data, email) ?? email.defaultLocale;
2801
+ const file = email.files.find((item) => item.role === "locale" && item.locale === locale);
2802
+ if (!file) {
2803
+ return {
2804
+ ...emptyPreview(exitUsage, [errorDiagnostic11("CFG001", `Unknown locale: ${locale}`)]),
2805
+ locale,
2806
+ payloadLocale
2807
+ };
2808
+ }
2809
+ return { ...runEvaluation(email, file.content, fixture.data, false, locale), payloadLocale };
2810
+ }
2811
+ return {
2812
+ ...runEvaluation(email, merged.content, fixture.data, true, readLocale(fixture.data, email) ?? email.defaultLocale),
2813
+ payloadLocale
2814
+ };
2815
+ }
2816
+ async function exportPreview(input) {
2817
+ const loaded = await loadProjectConfig(input.configPath);
2818
+ if (!loaded.ok) return previewFailure(exitUsage, loaded.diagnostics);
2819
+ const outputError = configuredOutputError(loaded.config, input.outDir);
2820
+ if (outputError) return previewFailure(exitUsage, [errorDiagnostic11("CFG001", outputError)]);
2821
+ const preview = previewFromBuild(
2822
+ await buildResolved(loaded.config, {
2823
+ onlyId: input.emailId,
2824
+ write: false,
2825
+ warningsAsErrors: input.warningsAsErrors
2826
+ }),
2827
+ { emailId: input.emailId, fixtureId: input.fixtureId, mode: "runtime" }
2828
+ );
2829
+ if (!preview.ok) return { ...preview, wrote: [] };
2830
+ const name = `${input.emailId}.${input.fixtureId}.html`;
2831
+ await commitArtifacts(path9.resolve(input.outDir), [{ name, content: preview.html }]);
2832
+ return { ...preview, wrote: [name] };
2833
+ }
2834
+ function previewFromBuild(built, input) {
2835
+ if (!built.ok) return emptyPreview(built.exitCode, built.diagnostics);
2836
+ const email = built.emails.find((item) => item.id === input.emailId);
2837
+ if (!email) return emptyPreview(exitUsage, [errorDiagnostic11("CFG001", `Unknown email: ${input.emailId}`)]);
2838
+ return previewBuiltEmail({
2839
+ email,
2840
+ fixtureId: input.fixtureId,
2841
+ mode: input.mode,
2842
+ locale: input.locale
2843
+ });
2844
+ }
2845
+ function previewFailure(exitCode, diagnostics) {
2846
+ return { ...emptyPreview(exitCode, diagnostics), wrote: [] };
2847
+ }
2848
+ function emptyPreview(exitCode, diagnostics) {
2849
+ return { ok: false, exitCode, html: "", source: "", diagnostics, selector: false, locale: "", payloadLocale: null };
2850
+ }
2851
+ function runEvaluation(email, source, data, selector, locale) {
2852
+ try {
2853
+ const html = evaluateArtifact({
2854
+ source,
2855
+ data,
2856
+ profile: email.profile.emission,
2857
+ simulator: email.profile.simulator
2858
+ });
2859
+ const diagnostics = email.diagnostics.slice();
2860
+ if (html.length > email.warnRenderedBytes)
2861
+ diagnostics.push(warningSize(email.id, html.length, email.warnRenderedBytes));
2862
+ return { ok: true, exitCode: exitOk, html, source, diagnostics, selector, locale, payloadLocale: null };
2863
+ } catch (error) {
2864
+ const failure = error instanceof TemplateFailure ? error.diagnostics : [errorDiagnostic11("HBS001", error instanceof Error ? error.message : "Preview failed.")];
2865
+ return {
2866
+ ok: false,
2867
+ exitCode: exitValidation,
2868
+ html: "",
2869
+ source,
2870
+ diagnostics: [...email.diagnostics, ...failure],
2871
+ selector,
2872
+ locale,
2873
+ payloadLocale: null
2874
+ };
2875
+ }
2876
+ }
2877
+ function warningSize(templateId, bytes, limit) {
2878
+ return {
2879
+ code: "SIZE001",
2880
+ severity: "warning",
2881
+ message: `Rendered preview is ${bytes} bytes, above ${limit}. This check does not establish compatibility with email clients.`,
2882
+ templateId
2883
+ };
2884
+ }
2885
+ function readPayloadLocale(data, localePath) {
2886
+ const value = readPathValue(data, localePath);
2887
+ return typeof value === "string" && value.length > 0 ? value : null;
2888
+ }
2889
+ function readLocale(data, email) {
2890
+ const value = readPayloadLocale(data, email.localePath);
2891
+ if (!value || !email.locales.includes(value)) return null;
2892
+ return value;
2893
+ }
2894
+
2895
+ // src/commands/preview-export.ts
2896
+ async function runPreviewExport(configPath, configDir, cwd, options) {
2897
+ const preview = await exportPreview({
2898
+ configPath,
2899
+ emailId: options.emailId,
2900
+ fixtureId: options.fixtureId,
2901
+ outDir: path10.resolve(cwd, options.outDir),
2902
+ ...options.warningsAsErrors ? { warningsAsErrors: true } : {}
2903
+ });
2904
+ await emitReport(
2905
+ buildReport({
2906
+ command: "preview",
2907
+ ok: preview.ok,
2908
+ exitCode: preview.exitCode,
2909
+ diagnostics: preview.diagnostics,
2910
+ manifest: null,
2911
+ wrote: preview.wrote,
2912
+ preserved: [],
2913
+ configDir
2914
+ }),
2915
+ options.format
2916
+ );
2917
+ return preview.exitCode;
2918
+ }
2919
+
2920
+ // src/commands/run.ts
2921
+ async function run(args, cwd, version) {
2922
+ if (args.kind === "help") {
2923
+ await writeStream(process.stdout, helpText());
2924
+ return exitOk;
2925
+ }
2926
+ if (args.kind === "version") {
2927
+ await writeStream(process.stdout, `${version}
2928
+ `);
2929
+ return exitOk;
2930
+ }
2931
+ const configPath = path11.resolve(cwd, args.config ?? "vtex-email.config.ts");
2932
+ const configDir = path11.dirname(configPath);
2933
+ if (args.kind === "dev") {
2934
+ return startDevCommand(configPath, configDir, {
2935
+ warningsAsErrors: args.warningsAsErrors,
2936
+ format: args.format,
2937
+ version
2938
+ });
2939
+ }
2940
+ if (args.kind === "error") {
2941
+ await emitReport(usageReport(args.message, configDir), args.format);
2942
+ return exitUsage;
2943
+ }
2944
+ if (args.kind === "preview") {
2945
+ return runPreviewExport(configPath, configDir, cwd, {
2946
+ emailId: args.emailId,
2947
+ fixtureId: args.fixtureId,
2948
+ outDir: args.outDir,
2949
+ warningsAsErrors: args.warningsAsErrors,
2950
+ format: args.format
2951
+ });
2952
+ }
2953
+ return runProjectCommand(args.kind, configPath, configDir, {
2954
+ format: args.format,
2955
+ warningsAsErrors: args.warningsAsErrors,
2956
+ ...args.kind === "build" && args.emailId ? { emailId: args.emailId } : {},
2957
+ ...args.kind === "build" && args.locale ? { locale: args.locale } : {}
2958
+ });
2959
+ }
2960
+
2961
+ // src/bin.ts
2962
+ var parsed = parseArgs(process.argv);
2963
+ var code = await run(parsed, process.cwd(), packageVersion());
2964
+ process.exit(code);
2965
+ function packageVersion() {
2966
+ const file = fileURLToPath(new URL("../package.json", import.meta.url));
2967
+ const parsedFile = JSON.parse(readFileSync(file, "utf8"));
2968
+ return parsedFile.version ?? "0.0.0";
2969
+ }